From 3d5c2420b5dba7f13b11eaf33c76fadd0919727e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 19:43:18 +0000 Subject: [PATCH] fix(mobile): adding a folder that is already a project opens it A path typed as ~/... was compared unexpanded against registered roots, which are absolute, so Local folder tried to create a duplicate and the server rejected it. Clone destination never looked for a registered project at all. Ask the host for its home folder, expand the typed path the way the host does, and match on that. Both screens share the lookup. A clone opens the registered project only when it is the same repository, and keeps the prompt. Co-Authored-By: Claude Fable 5.2 --- .../projects/AddProjectScreen.test.ts | 139 ++++++++++++++++- .../features/projects/AddProjectScreen.tsx | 146 +++++++++++++----- .../src/operations/projects.test.ts | 14 ++ .../client-runtime/src/operations/projects.ts | 11 ++ 4 files changed, 266 insertions(+), 44 deletions(-) diff --git a/apps/mobile/src/features/projects/AddProjectScreen.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.test.ts index ab331d0149e15..23d43eacc1f0a 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.test.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.test.ts @@ -6,7 +6,11 @@ import * as NodeModule from "node:module"; import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { workspaceDetailRouter } from "../layout/workspace/workspace-detail-selection"; import type { NavigationState } from "@react-navigation/native"; -import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts"; +import { + AuthFilesystemReadScope, + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, +} from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { act, createElement, isValidElement, type ReactNode } from "react"; @@ -22,7 +26,9 @@ const state = vi.hoisted(() => ({ id: string; title: string; workspaceRoot: string; + repositoryIdentity?: { canonicalKey: string }; }[], + cloneDestinations: [] as string[], createResult: null as Promise | null, createNewResult: null as Promise | null, startCloneResult: null as Promise | null, @@ -134,16 +140,36 @@ vi.mock("../../state/use-remote-environment-registry", () => ({ }), })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); -vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} })); +vi.mock("../../state/use-atom-query-runner", () => ({ + useAtomQueryRunner: + () => + async ({ input }: { input: { partialPath: string } }) => { + // The host's filesystem.browse: expand `~`, then list the directory the path names. + const partialPath = input.partialPath; + const resolved = NodePath.posix.resolve( + partialPath === "~" || partialPath.startsWith("~/") || partialPath.startsWith("~\\") + ? NodePath.posix.join("/home/tester", partialPath.slice(2)) + : partialPath, + ); + const listsDirectory = /[\\/]$/.test(partialPath) || partialPath === "~"; + return AsyncResult.success({ + parentPath: listsDirectory ? resolved : NodePath.posix.dirname(resolved), + entries: [], + }); + }, +})); vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) })); vi.mock("../../state/presentation", () => ({ useEnvironmentPresentation: () => ({ isReady: true, presentation: null }), })); -vi.mock("../../state/filesystem", () => ({ filesystemEnvironment: {} })); +vi.mock("../../state/filesystem", () => ({ + filesystemEnvironment: { browse: (target: unknown) => target }, +})); vi.mock("../../state/sourceControl", () => ({ sourceControlEnvironment: { discovery: (input: unknown) => input, startProjectClone: async ({ input }: { input: { destinationPath: string } }) => { + state.cloneDestinations.push(input.destinationPath); if (state.startCloneResult) return state.startCloneResult; NodeFS.mkdirSync(input.destinationPath); return AsyncResult.success(undefined); @@ -756,3 +782,110 @@ describe("local folder path", () => { expect(screen.path).toBe("~/code/app"); }); }); + +describe("adding a folder that is already a project", () => { + function setup(input: { path: string; root: string; canonicalKey?: string }) { + state.navigationState = undefined; + state.scopes = new Set([ + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, + AuthFilesystemReadScope, + ]); + state.baseDirectory = input.path; + state.existingProjects = [ + { + environmentId: "environment", + id: "existing-project", + title: "Bike documents", + workspaceRoot: input.root, + ...(input.canonicalKey ? { repositoryIdentity: { canonicalKey: input.canonicalKey } } : {}), + }, + ]; + state.projects = []; + state.cloneDestinations = []; + state.createResult = null; + state.startCloneResult = Promise.resolve( + AsyncResult.failure(Cause.fail(new Error("Destination is not empty"))), + ); + state.dispatch.mockReset(); + state.alert.mockReset(); + state.waitForProject.mockReset(); + state.waitForProject.mockResolvedValue(null); + return { + navigation: mountProjectFlow(false), + [Symbol.dispose]: () => { + state.existingProjects = []; + state.startCloneResult = null; + }, + }; + } + + it.each([ + { path: "~/repro/bike-documents/", root: "/home/tester/repro/bike-documents", created: [] }, + // `work\repo` is one folder on POSIX, not the registered `work\` > `repo`. + { path: "~/work\\repo", root: "/home/tester/work\\/repo", created: ["~/work\\repo"] }, + ])("matches local folder $path against registered roots", async ({ path, root, created }) => { + using flow = setup({ path, root }); + const submit = findAction( + renderScreen(() => AddProjectLocalFolderScreen({ environmentId: "environment" })), + "Add project", + ); + if (!submit) throw new Error("Add project action missing"); + await submit(); + + expect(state.projects).toEqual(created); + const opened = flow.navigation.getState().routes.at(-1)?.params; + if (created.length === 0) { + expect(state.alert.mock.calls).toEqual([ + expect.arrayContaining(["Project already exists", "Bike documents"]), + ]); + expect(opened).toEqual({ + draft: { + environmentId: "environment", + projectId: "existing-project", + title: "Bike documents", + }, + }); + } else { + expect(opened).toBeUndefined(); + } + }); + + it.each([ + { canonicalKey: "example.com/owner/bike-documents", cloned: [] }, + { canonicalKey: "example.com/owner/other", cloned: ["~/repro/bike-documents"] }, + ])("clones into a registered folder only for another repository ($canonicalKey)", async (row) => { + using flow = setup({ + path: "~/repro", + root: "/home/tester/repro/bike-documents", + canonicalKey: row.canonicalKey, + }); + const submit = findAction( + renderScreen(() => + AddProjectDestinationScreen({ + environmentId: "environment", + remoteUrl: "https://example.com/owner/bike-documents.git", + repositoryName: "bike-documents", + prompt: "Fix the bike", + }), + ), + "Clone project", + ); + if (!submit) throw new Error("Clone action missing"); + await submit(); + + expect(state.cloneDestinations).toEqual(row.cloned); + expect(flow.navigation.getState().routes.at(-1)?.params).toEqual( + row.cloned.length === 0 + ? { + draft: { + environmentId: "environment", + projectId: "existing-project", + title: "Bike documents", + draftId: "prompt-draft", + }, + } + : undefined, + ); + }); +}); diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 33b7de17c3914..ea14312fe9049 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -13,6 +13,7 @@ import { buildAddProjectRemoteSourceReadiness, buildProjectCreateCommand, canCreateProjectInEnvironment, + expandHomeProjectPath, findExistingAddProject, getAddProjectInitialQuery, getCloneDestinationBrowsePath, @@ -379,6 +380,24 @@ function useBrowsePathInput( return committed; }; + // Only the host knows its home folder; browsing `~/` reports it as the listed directory. + const resolveHomePath = async (path: string): Promise => { + if ( + !environment || + !readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) || + !canPreloadBrowsePath(environmentRuntime?.connectionState) + ) { + return path; + } + const home = await loadBrowsePath({ + environmentId: environment.environmentId, + input: { partialPath: "~/" }, + }); + return AsyncResult.isSuccess(home) && home.value + ? expandHomeProjectPath(path, home.value.parentPath) + : path; + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- invalidates the browse navigation coordinator on unmount so in-flight browses do not commit useEffect( () => () => { @@ -387,7 +406,7 @@ function useBrowsePathInput( [browseNavigation], ); - return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath }; + return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath, resolveHomePath }; } function useEnvironmentOptions( @@ -730,16 +749,73 @@ async function draftWithPrompt( return draftId; } -function useCreateProject(environment: EnvironmentOption | null) { +function useOpenExistingProject(environment: EnvironmentOption | null) { const openNewTaskDraft = useOpenNewTaskDraft(); - const navigation = useNavigation(); - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const updateProject = useAtomCommand(projectEnvironment.update, { label: "project unarchive", }); const projects = useProjects(); - return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => { + /** Opens the project registered at `path`, if any. Rejects when the prompt cannot be stored. */ + return async ( + path: string, + originRoute: ReturnType, + clone?: { readonly remoteUrl: string; readonly prompt: string | null }, + ): Promise => { + if (!environment) return false; + const existing = findExistingAddProject({ + projects, + environmentId: environment.environmentId, + path, + }); + if (!existing) return false; + // A folder holding another repository is not this clone; the clone reports it occupied. + if ( + clone && + existing.repositoryIdentity?.canonicalKey !== + sourceControlClients.repositoryKeyFromRemote(clone.remoteUrl) + ) { + return false; + } + const draftId = clone?.prompt + ? await draftWithPrompt(existing.environmentId, existing.id, clone.prompt) + : null; + // Adding an archived project's folder again brings the project back. + const unarchived = + existing.archivedAt == null || + ( + await updateProject({ + environmentId: existing.environmentId, + input: { projectId: existing.id, archived: false }, + }) + )._tag === "Success"; + Dialog.alert( + "Project already exists", + unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, + ); + openNewTaskDraft( + { + environmentId: existing.environmentId, + projectId: existing.id, + title: existing.title, + ...(draftId === null ? {} : { draftId }), + }, + originRoute, + ); + return true; + }; +} + +function useCreateProject(environment: EnvironmentOption | null) { + const openNewTaskDraft = useOpenNewTaskDraft(); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const openExistingProject = useOpenExistingProject(environment); + + return async ( + workspaceRoot: string, + lookupPath: string, + originRoute: ReturnType, + ) => { if ( !environment || !canCreateProjectInEnvironment(environment.connectionState) || @@ -752,35 +828,7 @@ function useCreateProject(environment: EnvironmentOption | null) { return; } - const existing = findExistingAddProject({ - projects, - environmentId: environment.environmentId, - path: workspaceRoot, - }); - if (existing) { - // Adding an archived project's folder again brings the project back. - const unarchived = - existing.archivedAt == null || - ( - await updateProject({ - environmentId: existing.environmentId, - input: { projectId: existing.id, archived: false }, - }) - )._tag === "Success"; - Dialog.alert( - "Project already exists", - unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, - ); - openNewTaskDraft( - { - environmentId: existing.environmentId, - projectId: existing.id, - title: existing.title, - }, - originRoute, - ); - return; - } + if (await openExistingProject(lookupPath, originRoute)) return; const projectId = ProjectId.make(uuidv4()); const command = buildProjectCreateCommand({ @@ -1313,8 +1361,9 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st environment?.environmentId ?? null, AuthOrchestrationOperateScope, ); + const navigation = useNavigation(); const createProject = useCreateProject(environment); - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = + const { isBrowseNavigating, navigateToBrowsePath, pathInput, resolveHomePath, setPathInput } = useBrowsePathInput(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1332,8 +1381,13 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st return; } + const originRoute = getActiveRoute(navigation); setIsSubmitting(true); - const result = await createProject(resolved.path); + const result = await createProject( + resolved.path, + resolved.path.startsWith("~") ? await resolveHomePath(resolved.path) : resolved.path, + originRoute, + ); if (result && AsyncResult.isFailure(result)) { setError(errorMessage(Cause.squash(result.cause))); } @@ -1404,11 +1458,9 @@ export function AddProjectDestinationScreen(props: { ? getCloneDirectoryPath(remoteUrl, true, repositoryName) : null; const cloneDirectoryName = ghqDirectoryPath?.split("/").at(-1) ?? repositoryName; - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput( - environment, - cloneDirectoryName, - ghqDirectoryPath ?? repositoryName, - ); + const { isBrowseNavigating, navigateToBrowsePath, pathInput, resolveHomePath, setPathInput } = + useBrowsePathInput(environment, cloneDirectoryName, ghqDirectoryPath ?? repositoryName); + const openExistingProject = useOpenExistingProject(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1436,6 +1488,18 @@ export function AddProjectDestinationScreen(props: { const originRoute = getActiveRoute(navigation); setIsSubmitting(true); + const handled = await openExistingProject( + resolved.path.startsWith("~") ? await resolveHomePath(resolved.path) : resolved.path, + originRoute, + { remoteUrl, prompt }, + ).catch((cause: unknown) => { + setError(errorMessage(cause)); + return true; + }); + if (handled) { + setIsSubmitting(false); + return; + } const title = inferProjectTitleFromPath(resolved.path); const startResult = await startProjectClone({ environmentId: environment.environmentId, diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts index 070ae5fbc53fb..364fee32d9390 100644 --- a/packages/client-runtime/src/operations/projects.test.ts +++ b/packages/client-runtime/src/operations/projects.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId, ProjectId } from "@t3tools/contracts"; import { + expandHomeProjectPath, findExistingAddProject, getCloneDestinationForPickedFolder, getCloneDestinationPath, @@ -221,4 +222,17 @@ describe("add project shared logic", () => { "project", ); }); + + it.each([ + { path: "~/work/repo", home: "/home/tester", expanded: "/home/tester/work/repo" }, + { path: "~", home: "/home/tester", expanded: "/home/tester/" }, + // On POSIX a backslash is part of the folder name, not a separator. + { path: "~/work\\repo", home: "/home/tester", expanded: "/home/tester/work\\repo" }, + { path: "~\\work\\repo", home: "C:\\Users\\tester", expanded: "C:\\Users\\tester\\work\\repo" }, + { path: "~/repo", home: "/", expanded: "/repo" }, + { path: "~work/repo", home: "/home/tester", expanded: "~work/repo" }, + { path: "/srv/~/repo", home: "/home/tester", expanded: "/srv/~/repo" }, + ])("expands $path below the home folder $home", ({ path, home, expanded }) => { + expect(expandHomeProjectPath(path, home)).toBe(expanded); + }); }); diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 8f7fcb7d1b424..57d406f95de37 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -355,6 +355,17 @@ export function resolveAddProjectPath(input: { return path.length === 0 ? { ok: false, error: "Enter a project path." } : { ok: true, path }; } +/** + * Mirrors the host's `~` expansion so a typed path can be matched against registered roots, which + * are absolute. The rest of the path is kept verbatim: `\\` is a file name character on POSIX. + */ +export function expandHomeProjectPath(path: string, homeDirectory: string): string { + if (path !== "~" && !path.startsWith("~/") && !path.startsWith("~\\")) { + return path; + } + return `${ensureBrowseDirectoryPath(homeDirectory)}${path.slice(2)}`; +} + export function findExistingAddProject(input: { readonly projects: ReadonlyArray; readonly environmentId: EnvironmentId;