@devries-cameron20 / t3code Mirror · read-only / commits / 707dcdaa16
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 04:30 UTC

feat: optionally clone repos into ghq-style <host>/<owner>/<repo> folders (#24904)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

shivam committed Nov 5, 2026 at 06:51 UTC 707dcdaa16b749ef73513187829cb71564d8628a
19 files changed +308 -29
apps/mobile/src/features/projects/AddProjectScreen.logic.ts
+17 -1
@@ -1,6 +1,22 @@
1 import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
2 import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
3 -import type { EnvironmentId } from "@t3tools/contracts";
3 +import { type EnvironmentId, FilesystemBrowseError } from "@t3tools/contracts";
4 +import * as Schema from "effect/Schema";
5 +
6 +const isFilesystemBrowseError = Schema.is(FilesystemBrowseError);
7 +
8 +/** Clone destinations may name folders that do not exist yet; cloning creates them. */
9 +export function isMissingCloneParentBrowseFailure(input: {
10 + readonly cloning: boolean;
11 + readonly failure: unknown;
12 +}): boolean {
13 + return (
14 + input.cloning &&
15 + isFilesystemBrowseError(input.failure) &&
16 + input.failure.failure === "read_directory_failed" &&
17 + input.failure.pathMissing === true
18 + );
19 +}
20
21 export function resolveAddProjectEnvironment<
22 T extends {
apps/mobile/src/features/projects/AddProjectScreen.tsx
+33 -6
@@ -17,6 +17,7 @@ import {
17 getAddProjectInitialQuery,
18 getCloneDestinationBrowsePath,
19 getCloneDestinationPath,
20 + getCloneDirectoryPath,
21 getCloneDirectoryName,
22 getDefaultCloneUrl,
23 getNewProjectPathPreview,
@@ -96,7 +97,10 @@ import {
97 useRemoteEnvironmentRuntime,
98 useSavedRemoteConnections,
99 } from "../../state/use-remote-environment-registry";
99 -import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
100 +import {
101 + isMissingCloneParentBrowseFailure,
102 + resolveAddProjectEnvironment,
103 +} from "./AddProjectScreen.logic";
104 import {
105 createNewTaskDraft,
106 setComposerDraftText,
@@ -113,6 +117,7 @@ interface EnvironmentOption {
117 readonly connectionState: EnvironmentConnectionPhase;
118 readonly connectionError: string | null;
119 readonly connectionErrorTraceId: string | null;
120 + readonly ghqCloneLayout: boolean;
121 }
122
123 const environmentOptionOrder = Order.mapInput(
@@ -290,13 +295,17 @@ function ProjectPathInput(props: {
295 );
296 }
297
293 -function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
298 +function useBrowsePathInput(
299 + environment: EnvironmentOption | null,
300 + pinnedDirectoryName = "",
301 + cloneDirectoryPath = pinnedDirectoryName,
302 +) {
303 const environmentId = environment?.environmentId ?? null;
304 const environmentBaseDirectory = environment?.baseDirectory ?? null;
305 const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
306 const seedPath = getCloneDestinationPath(
307 getAddProjectInitialQuery(environmentBaseDirectory),
299 - pinnedDirectoryName,
308 + cloneDirectoryPath,
309 );
310 // Each host keeps the path last typed or browsed for it, and shows its own default until then,
311 // so switching hosts and back loses nothing. With no host selected (one dropping out briefly),
@@ -403,6 +412,7 @@ function useEnvironmentOptions(
412 connectionState: runtime?.connectionState ?? "available",
413 connectionError: runtime?.connectionError ?? null,
414 connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
415 + ghqCloneLayout: config?.settings.ghqCloneLayout === true,
416 };
417 });
418 return Arr.sort(
@@ -914,6 +924,7 @@ function FolderBrowser(props: {
924 readonly selectedDirectoryName?: string;
925 }) => Promise<boolean>;
926 readonly pinnedDirectoryName?: string;
927 + readonly cloning?: boolean;
928 }) {
929 const browsePath = getFilesystemBrowsePath(props.pathInput, props.environment.platform);
930 const browseInput =
@@ -953,7 +964,16 @@ function FolderBrowser(props: {
964 {!canReadFiles && !fileAccess.isPending ? (
965 <ErrorBanner message={fileAccess.error ?? "This connection cannot browse host folders."} />
966 ) : null}
956 - {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
967 + {browseState.error === null ? null : isMissingCloneParentBrowseFailure({
968 + cloning: props.cloning === true,
969 + failure: browseState.failure,
970 + }) ? (
971 + <Text className="text-sm text-foreground-muted">
972 + This folder does not exist yet. Cloning creates it.
973 + </Text>
974 + ) : (
975 + <ErrorBanner message={browseState.error} />
976 + )}
977 <ListSection>
978 {fileAccess.isPending || (browseState.isPending && browseState.data === null) ? (
979 <View className="items-center py-5">
@@ -1367,9 +1387,15 @@ export function AddProjectDestinationScreen(props: {
1387 const repositoryTitle = stringParam(props.repositoryTitle);
1388 const prompt = stringParam(props.prompt);
1389 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
1390 + const ghqDirectoryPath =
1391 + remoteUrl && environment?.ghqCloneLayout
1392 + ? getCloneDirectoryPath(remoteUrl, true, repositoryName)
1393 + : null;
1394 + const cloneDirectoryName = ghqDirectoryPath?.split("/").at(-1) ?? repositoryName;
1395 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
1396 environment,
1372 - repositoryName,
1397 + cloneDirectoryName,
1398 + ghqDirectoryPath ?? repositoryName,
1399 );
1400 const [isSubmitting, setIsSubmitting] = useState(false);
1401 const [error, setError] = useState<string | null>(null);
@@ -1474,7 +1500,8 @@ export function AddProjectDestinationScreen(props: {
1500 navigateToBrowsePath={navigateToBrowsePath}
1501 pathInput={pathInput}
1502 setPathInput={setPathInput}
1477 - pinnedDirectoryName={repositoryName}
1503 + pinnedDirectoryName={cloneDirectoryName}
1504 + cloning={Boolean(remoteUrl)}
1505 />
1506 </>
1507 ) : (
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+10
@@ -437,6 +437,16 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
437 onValueChange={(value) => write({ defaultAutoPull: value })}
438 />
439 </SettingsSection>
440 + <SettingsSection title="Clones">
441 + <SettingsSwitchRow
442 + icon="folder"
443 + label="Clone into host folders"
444 + subtitle="Clones go to github.com/owner/repo under the Add project folder, like ghq."
445 + value={uniform("ghqCloneLayout")}
446 + disabled={disabledFor("ghqCloneLayout")}
447 + onValueChange={(value) => write({ ghqCloneLayout: value })}
448 + />
449 + </SettingsSection>
450 </>
451 ) : null}
452
apps/mobile/src/features/settings/settings-search.ts
+2
@@ -75,6 +75,8 @@ const SETTINGS_SEARCH_TERMS = {
75 "agent credits",
76 "default branch",
77 "automatically pull",
78 + "clone into host folders",
79 + "ghq",
80 ],
81 SettingsWorktrees: [
82 "worktree",
apps/server/src/workspace/WorkspaceEntries.test.ts
+25
@@ -789,5 +789,30 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
789 });
790 }),
791 );
792 +
793 + it.effect("marks only a missing directory as missing when browsing fails", () =>
794 + Effect.gen(function* () {
795 + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
796 + const path = yield* Path.Path;
797 + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-missing-" });
798 + yield* writeTextFile(cwd, "file.txt", "");
799 +
800 + const missing = yield* workspaceEntries
801 + .browse({ partialPath: `${path.join(cwd, "absent", "nested")}${path.sep}` })
802 + .pipe(Effect.flip);
803 + const underFile = yield* workspaceEntries
804 + .browse({ partialPath: `${path.join(cwd, "file.txt")}${path.sep}` })
805 + .pipe(Effect.flip);
806 +
807 + expect(missing).toMatchObject({
808 + _tag: "WorkspaceEntriesReadDirectoryError",
809 + pathMissing: true,
810 + });
811 + expect(underFile).toMatchObject({
812 + _tag: "WorkspaceEntriesReadDirectoryError",
813 + pathMissing: false,
814 + });
815 + }),
816 + );
817 });
818 });
apps/server/src/workspace/WorkspaceEntries.ts
+4
@@ -64,6 +64,10 @@ export class WorkspaceEntriesReadDirectoryError extends Schema.TaggedError<Works
64 cause: Schema.Defect(),
65 },
66 ) {
67 + get pathMissing(): boolean {
68 + return (this.cause as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
69 + }
70 +
71 override get message(): string {
72 const cwd = this.cwd ? ` from '${this.cwd}'` : "";
73 return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;
apps/server/src/ws.ts
+6 -1
@@ -561,6 +561,7 @@ function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntries
561 readonly failure: FilesystemBrowseFailure;
562 readonly parentPath?: string;
563 readonly platform?: string;
564 + readonly pathMissing?: boolean;
565 } {
566 switch (error._tag) {
567 case "WorkspaceEntriesWindowsPathUnsupportedError":
@@ -568,7 +569,11 @@ function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntries
569 case "WorkspaceEntriesCurrentProjectRequiredError":
570 return { failure: "current_project_required" };
571 case "WorkspaceEntriesReadDirectoryError":
571 - return { failure: "read_directory_failed", parentPath: error.parentPath };
572 + return {
573 + failure: "read_directory_failed",
574 + parentPath: error.parentPath,
575 + ...(error.pathMissing ? { pathMissing: true } : {}),
576 + };
577 default:
578 return unexpectedCompatibilityError(error);
579 }
apps/web/src/components/AddProjectToMachineDialog.tsx
+5 -2
@@ -3,7 +3,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3 import {
4 getAddProjectInitialQuery,
5 getCloneDestinationPath,
6 - getCloneDirectoryName,
6 + getCloneDirectoryPath,
7 } from "@t3tools/client-runtime/operations/projects";
8 import { resolvePastedPath } from "@t3tools/shared/path";
9 import {
@@ -113,7 +113,10 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
113 const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
114 const defaultPath = getCloneDestinationPath(
115 getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
116 - getCloneDirectoryName(sourceUrl),
116 + getCloneDirectoryPath(
117 + sourceUrl,
118 + targetEnvironment?.serverConfig?.settings.ghqCloneLayout === true,
119 + ),
120 );
121 const [pathOverride, setPathOverride] = useState<string | null>(null);
122 const destinationPath = pathOverride ?? defaultPath;
apps/web/src/components/CommandPalette.tsx
+33 -12
@@ -10,7 +10,8 @@ import {
10 canCreateProjectInEnvironment,
11 getCloneDestinationBrowsePath,
12 getCloneDestinationPath,
13 - getCloneDirectoryName,
13 + getCloneDirectoryLeafName,
14 + getCloneDirectoryPath,
15 getDefaultCloneUrl,
16 getNewProjectPathPreview,
17 getNewProjectPublishTarget,
@@ -638,7 +639,11 @@ function OpenCommandPaletteDialog(props: {
639 const isRemoteProjectRepositoryStep = addProjectCloneFlow?.step === "repository";
640 const pinnedCloneDirectoryName =
641 addProjectCloneFlow?.step === "confirm"
641 - ? getCloneDirectoryName(
642 + ? getCloneDirectoryLeafName(
643 + addProjectCloneFlow.remoteUrl,
644 + environments.find(
645 + (candidate) => candidate.environmentId === addProjectCloneFlow.environmentId,
646 + )?.serverConfig?.settings.ghqCloneLayout === true,
647 addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.remoteUrl,
648 )
649 : "";
@@ -1940,8 +1945,20 @@ function OpenCommandPaletteDialog(props: {
1945 if (created.value) setOpen(false);
1946 }
1947
1943 - function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
1944 - return getAddProjectInitialQueryForEnvironment(environmentId);
1948 + function getDefaultCloneDestination(
1949 + environmentId: EnvironmentId,
1950 + remoteUrl: string,
1951 + repository: string,
1952 + ): string {
1953 + const environment = environments.find((candidate) => candidate.environmentId === environmentId);
1954 + return getCloneDestinationPath(
1955 + getAddProjectInitialQueryForEnvironment(environmentId),
1956 + getCloneDirectoryPath(
1957 + remoteUrl,
1958 + environment?.serverConfig?.settings.ghqCloneLayout === true,
1959 + repository,
1960 + ),
1961 + );
1962 }
1963
1964 async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
@@ -1982,9 +1999,11 @@ function OpenCommandPaletteDialog(props: {
1999
2000 const provider = addProjectRemoteSourceProvider(addProjectCloneFlow.source);
2001 if (!provider) {
1985 - const destinationPath = getCloneDestinationPath(
1986 - getDefaultCloneParentPath(addProjectCloneFlow.environmentId),
1987 - getCloneDirectoryName(rawRepository),
2002 + const remoteUrl = normalizePastedCloneUrl(rawRepository);
2003 + const destinationPath = getDefaultCloneDestination(
2004 + addProjectCloneFlow.environmentId,
2005 + remoteUrl,
2006 + rawRepository,
2007 );
2008 setAddProjectCloneFlow({
2009 step: "confirm",
@@ -1992,7 +2011,7 @@ function OpenCommandPaletteDialog(props: {
2011 source: addProjectCloneFlow.source,
2012 repositoryInput: rawRepository,
2013 repository: null,
1995 - remoteUrl: normalizePastedCloneUrl(rawRepository),
2014 + remoteUrl,
2015 });
2016 setHighlightedItemValue(null);
2017 setQuery(destinationPath);
@@ -2024,9 +2043,11 @@ function OpenCommandPaletteDialog(props: {
2043 return;
2044 }
2045 const repository = lookupResult.value;
2027 - const destinationPath = getCloneDestinationPath(
2028 - getDefaultCloneParentPath(addProjectCloneFlow.environmentId),
2029 - getCloneDirectoryName(repository.nameWithOwner),
2046 + const remoteUrl = getDefaultCloneUrl(repository);
2047 + const destinationPath = getDefaultCloneDestination(
2048 + addProjectCloneFlow.environmentId,
2049 + remoteUrl,
2050 + repository.nameWithOwner,
2051 );
2052 setAddProjectCloneFlow({
2053 step: "confirm",
@@ -2034,7 +2055,7 @@ function OpenCommandPaletteDialog(props: {
2055 source: addProjectCloneFlow.source,
2056 repositoryInput: rawRepository,
2057 repository,
2037 - remoteUrl: getDefaultCloneUrl(repository),
2058 + remoteUrl,
2059 });
2060 setHighlightedItemValue(null);
2061 setQuery(destinationPath);
apps/web/src/components/promptLinks/NewThreadLinkView.tsx
+17 -5
@@ -1,5 +1,9 @@
1 import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2 -import { getCloneDestinationPath } from "@t3tools/client-runtime/operations/projects";
2 +import {
3 + getAddProjectInitialQuery,
4 + getCloneDestinationPath,
5 + getCloneDirectoryPath,
6 +} from "@t3tools/client-runtime/operations/projects";
7 import {
8 findPromptLinkProjects,
9 findPromptLinkPullRequestThread,
@@ -198,8 +202,9 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
202 const cloneRepository = async (repository: PromptLinkRepository) => {
203 const environmentId = lastActiveEnvironmentId();
204 const environment = environments.find((entry) => entry.environmentId === environmentId);
201 - const newProjectsRoot = environment?.serverConfig?.newProjectsRoot ?? null;
202 - if (environmentId === null || newProjectsRoot === null) {
205 + const serverConfig = environment?.serverConfig ?? null;
206 + const newProjectsRoot = serverConfig?.newProjectsRoot ?? null;
207 + if (environmentId === null || serverConfig === null || newProjectsRoot === null) {
208 setState({
209 status: "failed",
210 message:
@@ -209,14 +214,21 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
214 }
215 setState({ status: "opening" });
216 const projectId = newProjectId();
217 + const remoteUrl = `https://github.com/${repository.owner}/${repository.name}.git`;
218 + const settings = serverConfig.settings;
219 const result = await startProjectClone({
220 environmentId,
221 input: {
222 projectId,
223 title: repository.name,
224 createdAt: new Date().toISOString(),
218 - remoteUrl: `https://github.com/${repository.owner}/${repository.name}.git`,
219 - destinationPath: getCloneDestinationPath(newProjectsRoot, repository.name),
225 + remoteUrl,
226 + destinationPath: getCloneDestinationPath(
227 + settings.ghqCloneLayout
228 + ? getAddProjectInitialQuery(settings.addProjectBaseDirectory)
229 + : newProjectsRoot,
230 + getCloneDirectoryPath(remoteUrl, settings.ghqCloneLayout === true),
231 + ),
232 },
233 });
234 if (result._tag === "Failure") {
apps/web/src/components/settings/SettingsPanels.tsx
+28
@@ -552,6 +552,9 @@ export function useSettingsRestore(onRestored?: () => void) {
552 ...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
553 ? ["Add project base directory"]
554 : []),
555 + ...(settings.ghqCloneLayout !== DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout
556 + ? ["Clone into host folders"]
557 + : []),
558 ...(settings.confirmThreadUnpin !== DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin
559 ? ["Unpin confirmation"]
560 : []),
@@ -665,6 +668,7 @@ export function useSettingsRestore(onRestored?: () => void) {
668 defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
669 newWorktreesStartFromOrigin: DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin,
670 addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
671 + ghqCloneLayout: DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout,
672 confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
673 confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
674 confirmThreadUnpin: DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin,
@@ -1585,6 +1589,30 @@ export function ThreadsSettingsPanel() {
1589 />
1590 }
1591 />
1592 + <SettingsRow
1593 + serverScoped
1594 + settingKeys={["ghqCloneLayout"]}
1595 + {...searchableSetting("ghq-clone-layout")}
1596 + description="Clones go to github.com/owner/repo under the folder above, like ghq."
1597 + resetAction={
1598 + settings.ghqCloneLayout !== DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout ? (
1599 + <SettingResetButton
1600 + label="clone into host folders"
1601 + onClick={() =>
1602 + updateSettings({ ghqCloneLayout: DEFAULT_UNIFIED_SETTINGS.ghqCloneLayout })
1603 + }
1604 + />
1605 + ) : null
1606 + }
1607 + control={
1608 + <ScopedSwitch
1609 + settingKeys={["ghqCloneLayout"]}
1610 + checked={settings.ghqCloneLayout}
1611 + onCheckedChange={(checked) => updateSettings({ ghqCloneLayout: Boolean(checked) })}
1612 + aria-label="Clone into host folders"
1613 + />
1614 + }
1615 + />
1616 </SettingsSection>
1617
1618 <ProjectDefaultsSettings category="general" />
apps/web/src/components/settings/settingsSearch.ts
+7
@@ -655,6 +655,13 @@ export const SETTINGS_SEARCH_ITEMS = [
655 scope: "environment-defaults",
656 searchTerms: ["base directory folder browser path home"],
657 },
658 + {
659 + id: "ghq-clone-layout",
660 + title: "Clone into host folders",
661 + to: "/settings/threads",
662 + scope: "environment-defaults",
663 + searchTerms: ["ghq clone destination host owner repository root layout"],
664 + },
665 {
666 id: "unpin-confirmation",
667 title: "Unpin confirmation",
docs/user/source-control.md
+5
@@ -148,6 +148,11 @@ toast or from the banner above the composer. When the host refuses the machine's
148 clones over HTTPS with Git's credentials for that host instead, and the project's remote uses the
149 HTTPS URL.
150
151 +To lay clones out like [ghq](https://github.com/x-motemen/ghq), turn on **Clone into host folders**
152 +under **Settings → Threads** (or **Source control** on mobile). Clones then default to
153 +`<host>/<owner>/<repo>` under **Add project starts in**, so set that to `~/ghq` to share ghq's
154 +folders. You can still change the destination before cloning.
155 +
156 For a local Git repository without a remote, **Publish Repository** creates a hosted repository,
157 adds it as `origin`, and pushes your commits. If there are no commits yet, it creates the remote;
158 make your first commit before pushing.
packages/client-runtime/src/operations/projects.test.ts
+35
@@ -4,7 +4,10 @@ import { EnvironmentId, ProjectId } from "@t3tools/contracts";
4
5 import {
6 findExistingAddProject,
7 + getCloneDestinationPath,
8 + getCloneDirectoryLeafName,
9 getCloneDirectoryName,
10 + getCloneDirectoryPath,
11 getDefaultCloneUrl,
12 githubIncompleteOwnerRepositoryMessage,
13 normalizePastedCloneUrl,
@@ -94,6 +97,38 @@ describe("add project shared logic", () => {
97 expect(getCloneDirectoryName(" https://github.com/owner/repo.git ")).toBe("repo");
98 });
99
100 + it("lays clone folders out like ghq only when asked, and only when the URL is safe", () => {
101 + expect(getCloneDirectoryPath("git@github.com:owner/repo.git", false)).toBe("repo");
102 + expect(getCloneDirectoryPath("git@github.com:owner/repo.git", true)).toBe(
103 + "github.com/owner/repo",
104 + );
105 + expect(getCloneDirectoryPath("ssh://git@gitlab.com:2222/group/sub/repo.git", true)).toBe(
106 + "gitlab.com/group/sub/repo",
107 + );
108 + expect(getCloneDirectoryPath("https://github.com/owner/../../repo", true)).toBe("repo");
109 + expect(getCloneDirectoryPath("/srv/git/repo.git", true)).toBe("repo");
110 + expect(
111 + getCloneDirectoryPath(
112 + "git@ssh.dev.azure.com:v3/org/Project/My%20Repo",
113 + false,
114 + "Project/My Repo",
115 + ),
116 + ).toBe("My Repo");
117 + expect(
118 + getCloneDirectoryLeafName(
119 + "git@ssh.dev.azure.com:v3/org/Project/My%20Repo",
120 + true,
121 + "Project/My Repo",
122 + ),
123 + ).toBe("My%20Repo");
124 + expect(
125 + getCloneDestinationPath(
126 + "C:\\Users\\me\\ghq",
127 + getCloneDirectoryPath("git@github.com:owner/repo.git", true),
128 + ),
129 + ).toBe("C:\\Users\\me\\ghq\\github.com\\owner\\repo");
130 + });
131 +
132 it("keeps a numeric repository name that sits on a path", () => {
133 expect(getCloneDirectoryName("https://github.com/acme/123.git")).toBe("123");
134 expect(getCloneDirectoryName("https://github.com/acme/123")).toBe("123");
packages/client-runtime/src/operations/projects.ts
+23 -1
@@ -9,6 +9,7 @@ import type {
9 SourceControlRepositoryInfo,
10 } from "@t3tools/contracts";
11 import { SourceControlProviderKind } from "@t3tools/contracts";
12 +import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl";
13 import { newProjectFolderName } from "@t3tools/shared/path";
14 import * as Arr from "effect/Array";
15 import * as Option from "effect/Option";
@@ -207,6 +208,26 @@ export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | und
208 return lastSegment.endsWith(".git") ? lastSegment.slice(0, -".git".length) : lastSegment;
209 }
210
211 +/** The folder a clone gets below its base: `<repo>`, or `<host>/<owner>/<repo>` like ghq. */
212 +export function getCloneDirectoryPath(
213 + remoteUrl: string,
214 + ghqCloneLayout: boolean,
215 + repository = remoteUrl,
216 +): string {
217 + return (
218 + (ghqCloneLayout ? cloneUrlRepositoryPath(remoteUrl) : null) ?? getCloneDirectoryName(repository)
219 + );
220 +}
221 +
222 +/** The clone's own folder, which folder browsing keeps at the end of the destination. */
223 +export function getCloneDirectoryLeafName(
224 + remoteUrl: string,
225 + ghqCloneLayout: boolean,
226 + repository = remoteUrl,
227 +): string {
228 + return getCloneDirectoryPath(remoteUrl, ghqCloneLayout, repository).split("/").at(-1) ?? "";
229 +}
230 +
231 export function getCloneDestinationPath(
232 directoryPath: string,
233 directoryName: string | null | undefined,
@@ -215,7 +236,8 @@ export function getCloneDestinationPath(
236 if (name.length === 0) {
237 return directoryPath;
238 }
218 - return `${ensureBrowseDirectoryPath(directoryPath)}${name}`;
239 + const base = ensureBrowseDirectoryPath(directoryPath);
240 + return `${base}${base.endsWith("\\") ? name.replaceAll("/", "\\") : name}`;
241 }
242
243 export function getNewProjectPathPreview(newProjectsRoot: string, name: string): string {
packages/contracts/src/filesystem.ts
+3
@@ -64,6 +64,8 @@ export class FilesystemBrowseError extends Schema.TaggedError<FilesystemBrowseEr
64 failure: Schema.optional(FilesystemBrowseFailure),
65 parentPath: Schema.optional(TrimmedNonEmptyString),
66 platform: Schema.optional(TrimmedNonEmptyString),
67 + /** Set when the directory does not exist; older clients ignore it. */
68 + pathMissing: Schema.optional(Schema.Boolean),
69 message: TrimmedNonEmptyString,
70 cause: Schema.optional(Schema.Defect()),
71 },
@@ -75,6 +77,7 @@ export class FilesystemBrowseError extends Schema.TaggedError<FilesystemBrowseEr
77 readonly failure: FilesystemBrowseFailure;
78 readonly parentPath?: string;
79 readonly platform?: string;
80 + readonly pathMissing?: boolean;
81 readonly cause?: unknown;
82 }) {
83 const cwd = props.cwd === undefined ? "" : ` from '${props.cwd}'`;
packages/contracts/src/settings.ts
+3
@@ -1315,6 +1315,8 @@ export const ServerSettings = Schema.Struct({
1315 Schema.withDecodingDefault(Effect.succeed(null)),
1316 ),
1317 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
1318 + /** Clones default to `<addProjectBaseDirectory>/<host>/<owner>/<repo>`, like ghq. */
1319 + ghqCloneLayout: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1320 textGenerationModelSelection: ModelSelection.pipe(
1321 Schema.withDecodingDefault(
1322 Effect.succeed({
@@ -1675,6 +1677,7 @@ export const ServerSettingsPatch = Schema.Struct({
1677 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
1678 worktreeSubmodules: Schema.optionalKey(Schema.NullOr(WorktreeSubmodules)),
1679 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
1680 + ghqCloneLayout: Schema.optionalKey(Schema.Boolean),
1681 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
1682 threadTitleInstructions: Schema.optionalKey(TrimmedString),
1683 branchNamingMode: Schema.optionalKey(BranchNamingMode),
packages/shared/src/cloneUrl.test.ts
+27 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { cloneUrlForProtocol, cloneUrlProtocol } from "./cloneUrl.ts";
3 +import { cloneUrlForProtocol, cloneUrlProtocol, cloneUrlRepositoryPath } from "./cloneUrl.ts";
4
5 describe("cloneUrlForProtocol", () => {
6 it.each([
@@ -138,3 +138,29 @@ describe("cloneUrlForProtocol", () => {
138 expect(cloneUrlProtocol("file:///srv/git/repo.git")).toBeNull();
139 });
140 });
141 +
142 +describe("cloneUrlRepositoryPath", () => {
143 + it("rejects Windows device names and trailing dots or spaces in every folder", () => {
144 + for (const segment of [
145 + "CON",
146 + "nul.txt",
147 + "COM1",
148 + "LPT0",
149 + "com¹",
150 + "CONIN$",
151 + "conout$",
152 + "aux .txt",
153 + "repo.",
154 + "repo ",
155 + ]) {
156 + expect(cloneUrlRepositoryPath(`https://github.com/${segment}/repo.git`)).toBeNull();
157 + expect(cloneUrlRepositoryPath(`https://${segment}/owner/repo.git`)).toBeNull();
158 + expect(cloneUrlRepositoryPath(`https://github.com/owner/${segment}.git`)).toBeNull();
159 + }
160 + expect(cloneUrlRepositoryPath("https://github.com/acme/repo.git")).toBe("github.com/acme/repo");
161 + expect(cloneUrlRepositoryPath("ssh://git@gitlab.com:2222/group/sub/repo.git")).toBe(
162 + "gitlab.com/group/sub/repo",
163 + );
164 + expect(cloneUrlRepositoryPath("C:/repos/project.git")).toBeNull();
165 + });
166 +});
packages/shared/src/cloneUrl.ts
+25
@@ -1,3 +1,5 @@
1 +import { isWindowsDrivePath } from "./path.ts";
2 +
3 export type CloneProtocol = "ssh" | "https";
4
5 const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
@@ -46,3 +48,26 @@ export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): strin
48 ? `git@${parsed.host}:${parsed.path}`
49 : `https://${parsed.host}/${parsed.path}`;
50 }
51 +
52 +const UNSAFE_SEGMENT = /^\.{1,2}$|[\\:*?"<>|\p{Cc}]|[ .]$/u;
53 +const WINDOWS_DEVICE_NAME =
54 + /^(?:con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(?: *\.| *$)/i;
55 +
56 +/**
57 + * The `<host>/<owner>/<repo>` folders ghq clones a URL into, or null for local paths and
58 + * anything with a folder that could leave the root.
59 + */
60 +export function cloneUrlRepositoryPath(url: string): string | null {
61 + if (isWindowsDrivePath(url.trim())) return null;
62 + const parsed = parseCloneUrl(url);
63 + if (!parsed) return null;
64 + const segments = [parsed.host, ...parsed.path.split(/[?#]/)[0]!.split("/").filter(Boolean)];
65 + const last = segments.at(-1)!;
66 + if (last.endsWith(".git")) segments[segments.length - 1] = last.slice(0, -".git".length);
67 + if (
68 + segments.length < 2 ||
69 + segments.some((s) => s === "" || UNSAFE_SEGMENT.test(s) || WINDOWS_DEVICE_NAME.test(s))
70 + )
71 + return null;
72 + return segments.join("/");
73 +}