From a28aafae22052fc386691f29967eee250e02174a Mon Sep 17 00:00:00 2001 From: Amp Date: Sat, 21 Nov 2026 20:46:30 +0000 Subject: [PATCH 1/4] feat(web): offer to add an existing folder when moving a project to another machine Adding a project to another machine failed with "Destination path already exists and is not empty" when that machine already had a checkout at the destination, leaving the user at a dead end. The server now tags that clone failure with reason "destination-not-empty". The Add to another machine dialog reads it and offers "Add existing folder", which adds the folder on that machine as the project without copying any files. Changing the folder or machine returns the dialog to cloning. Model and harness: Claude Opus 5.5 in Amp. Amp-Thread-ID: https://ampcode.com/threads/T-01a1ff98-adfc-71e2-831e-72f58c684e8a Co-authored-by: Marcel Ruhf --- .../SourceControlRepositoryService.test.ts | 18 +++ .../SourceControlRepositoryService.ts | 1 + ...AddProjectToMachineDialog.browser.test.tsx | 77 +++++++++++- .../components/AddProjectToMachineDialog.tsx | 117 ++++++++++++++---- apps/web/src/i18n/translations/de.json | 4 + apps/web/src/i18n/translations/en.json | 4 + apps/web/src/i18n/translations/es.json | 4 + apps/web/src/i18n/translations/fr.json | 4 + apps/web/src/i18n/translations/ja.json | 4 + apps/web/src/i18n/translations/ko.json | 4 + apps/web/src/i18n/translations/pt-BR.json | 4 + apps/web/src/i18n/translations/ru.json | 4 + apps/web/src/i18n/translations/sv.json | 4 + apps/web/src/i18n/translations/zh.json | 4 + apps/web/src/lib/addProjectToMachine.ts | 4 +- packages/contracts/src/sourceControl.ts | 2 + 16 files changed, 229 insertions(+), 30 deletions(-) diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts index f0cc6a8066f32..c2694f0d96df6 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts @@ -201,6 +201,24 @@ it.effect("clones a looked-up repository after creating missing parent directori }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); +it.effect("marks a non-empty destination so clients can offer to add the folder instead", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const destinationPath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-existing-" }); + yield* fs.writeFileString(path.join(destinationPath, "README.md"), "already here"); + + const error = yield* Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + return yield* service + .prepareClone({ remoteUrl: CLONE_URLS.url, destinationPath }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layer({}))); + + assert.strictEqual(error.reason, "destination-not-empty"); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + it.effect.each(["--bare", "source.git"])( "clones a local repository named %s as a working tree", (repositoryName) => diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts index 49a9edfdde0f7..83ba66b844d46 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts @@ -279,6 +279,7 @@ export const make = Effect.gen(function* () { operation: "cloneRepository", provider: SourceControlProviderKind.make("unknown"), detail: "Destination path already exists and is not empty.", + reason: "destination-not-empty", }); } } else { diff --git a/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx b/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx index 1ca6c0422c560..79eb8b0f3b0f1 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.browser.test.tsx @@ -1,6 +1,12 @@ -import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { + EnvironmentId, + ProjectId, + SourceControlProviderKind, + SourceControlRepositoryError, +} from "@t3tools/contracts"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import { act, render } from "../../test/render"; @@ -25,6 +31,24 @@ const project = vi.hoisted(() => { }; }); +const machine = vi.hoisted(() => { + let targets: ReadonlyArray = []; + let clone = (): Promise => Promise.resolve(null); + const createProject = vi.fn<(value: unknown) => Promise>(); + return { + // Each test chooses the machines it can clone to and how the clone answers. + setup: (next: { targets: ReadonlyArray; clone: () => Promise }) => { + targets = next.targets; + clone = next.clone; + createProject.mockReset(); + createProject.mockResolvedValue({ _tag: "Success" }); + }, + targets: () => targets, + clone: () => clone(), + createProject, + }; +}); + vi.mock(import("../state/entities"), async (original) => { const { useSyncExternalStore } = await import("react"); return { @@ -45,13 +69,22 @@ vi.mock(import("../hooks/useHandleNewThread"), async (original) => ({ })); vi.mock(import("../hooks/useAddProjectTargets"), async (original) => ({ ...(await original()), - useAddProjectTargets: (() => []) as never, + useAddProjectTargets: (() => machine.targets()) as never, })); vi.mock(import("../hooks/useLogicalProjectEnvironments"), async (original) => ({ ...(await original()), useLogicalProjectEnvironments: (() => []) as never, })); +vi.mock(import("../lib/addProjectToMachine"), async (original) => ({ + ...(await original()), + addProjectToMachine: (() => machine.clone()) as never, +})); +vi.mock(import("../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: (() => machine.createProject) as never, +})); + import { AddProjectToMachineDialogHost, openAddProjectToMachine, @@ -68,8 +101,47 @@ const PROJECT = { }; describe("AddProjectToMachineDialog", () => { + it("offers to add the folder as the project while the clone destination is taken", async () => { + project.setup(PROJECT); + const laptop = EnvironmentId.make("laptop"); + machine.setup({ + targets: [{ environmentId: laptop, label: "Laptop", machine: "laptop" }], + clone: () => + Promise.reject( + new SourceControlRepositoryError({ + provider: SourceControlProviderKind.make("unknown"), + operation: "cloneRepository", + detail: "Destination path already exists and is not empty.", + reason: "destination-not-empty", + }), + ), + }); + await using screen = await render(); + await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: laptop })); + const folder = screen.getByLabelText("Folder on Laptop"); + await userEvent.fill(folder, "~/code/repo"); + + await userEvent.keyboard("{Enter}"); + await expect.element(screen.getByRole("button", { name: "Add existing folder" })).toBeVisible(); + await userEvent.fill(folder, "~/code/other"); + await expect.element(screen.getByRole("button", { name: "Clone to Laptop" })).toBeVisible(); + await userEvent.fill(folder, "~/code/repo"); + await userEvent.keyboard("{Enter}"); + + await vi.waitFor(() => + expect(machine.createProject).toHaveBeenCalledWith({ + environmentId: laptop, + input: expect.objectContaining({ + workspaceRoot: "~/code/repo", + createWorkspaceRootIfMissing: false, + }), + }), + ); + }); + it("closes when its project goes away", async () => { project.setup(PROJECT); + machine.setup({ targets: [], clone: () => Promise.resolve(null) }); await using screen = await render(); await act(() => openAddProjectToMachine({ projectRef, targetEnvironmentId: null })); @@ -82,6 +154,7 @@ describe("AddProjectToMachineDialog", () => { it("does not reopen for a project that vanished before the dialog showed", async () => { project.setup(PROJECT); + machine.setup({ targets: [], clone: () => Promise.resolve(null) }); await using screen = await render(); await act(() => { diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 0982ab1e1ccab..db8109bb65ccc 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -12,8 +12,11 @@ import { type EnvironmentId, type ProjectIgnoredFile, type ScopedProjectRef, + SourceControlRepositoryError, resolveEnvironmentMachineKind, } from "@t3tools/contracts"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import * as Schema from "effect/Schema"; import { type CloneProtocol, cloneUrlForProtocol, @@ -42,6 +45,7 @@ import { useEnvironments } from "../state/environments"; import { projectEnvironment } from "../state/projects"; import { useDebouncedValue } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; +import { useAtomCommand } from "../state/use-atom-command"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { Button } from "./ui/button"; import { Checkbox } from "./ui/checkbox"; @@ -60,6 +64,8 @@ import { MiddleTruncate } from "./ui/middle-truncate"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; import { Toggle, ToggleGroup } from "./ui/toggle-group"; +const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError); + interface AddProjectToMachineRequest { readonly projectRef: ScopedProjectRef; readonly targetEnvironmentId: EnvironmentId | null; @@ -165,6 +171,16 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + // A clone refused because the folder is taken; editing the path or machine clears the offer. + const [occupiedFolder, setOccupiedFolder] = useState<{ + readonly environmentId: EnvironmentId; + readonly path: string; + } | null>(null); + const folderOccupied = + occupiedFolder !== null && + occupiedFolder.environmentId === target?.environmentId && + occupiedFolder.path === destinationPath.trim(); // The project or every target can vanish while the dialog is open. Submitting // before the file list loads would silently skip the default .env copies. @@ -220,6 +236,31 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe } setSubmitting(true); setError(null); + if (folderOccupied) { + // The folder is the user's own checkout, so its files stay as they are and nothing is copied. + const projectId = newProjectId(); + const result = await createProject({ + environmentId: target.environmentId, + input: { + projectId, + title: project.title, + workspaceRoot: destinationPath.trim(), + createWorkspaceRootIfMissing: false, + defaultModelSelection: null, + }, + }); + if (result._tag === "Failure") { + setError( + thrownErrorMessage(squashAtomCommandFailure(result), m) ?? + gt("Could not add the folder."), + ); + setSubmitting(false); + return; + } + close(); + openClonedProject(scopeProjectRef(target.environmentId, projectId)); + return; + } try { const projectId = await addProjectToMachine({ source: { environmentId: project.environmentId, cwd: project.workspaceRoot }, @@ -237,7 +278,11 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe close(); openClonedProject(scopeProjectRef(target.environmentId, projectId)); } catch (cause) { - setError(thrownErrorMessage(cause, m) ?? gt("Could not start the clone.")); + if (isSourceControlRepositoryError(cause) && cause.reason === "destination-not-empty") { + setOccupiedFolder({ environmentId: target.environmentId, path: destinationPath.trim() }); + } else { + setError(thrownErrorMessage(cause, m) ?? gt("Could not start the clone.")); + } setSubmitting(false); } }; @@ -283,14 +328,18 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
- {/* oxlint-disable-next-line t3code/no-untranslated-copy -- git command name */} - git clone + {folderOccupied ? ( + {gt("existing folder")} + ) : ( + // oxlint-disable-next-line t3code/no-untranslated-copy -- git command name + git clone + )} - {selectedFiles.size === 0 + {folderOccupied || selectedFiles.size === 0 ? gt("no files") : gt("{count, plural, one {+ {count} file} other {+ {count} files}}", { count: selectedFiles.size, @@ -337,25 +386,29 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
-
- - {sshUrl && httpsUrl ? ( - { - const value = next[0]; - if (value === "ssh" || value === "https") setProtocol(value); - }} - > - SSH - HTTPS - - ) : null} - {remoteUrl} -
+ {folderOccupied ? null : ( +
+ + {sshUrl && httpsUrl ? ( + { + const value = next[0]; + if (value === "ssh" || value === "https") setProtocol(value); + }} + > + SSH + HTTPS + + ) : null} + + {remoteUrl} + +
+ )}
- {canListFiles ? ( + {canListFiles && !folderOccupied ? (
- {folderOccupied ? ( + {occupied ? ( {gt("existing folder")} ) : ( // oxlint-disable-next-line t3code/no-untranslated-copy -- git command name @@ -339,7 +364,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe - {folderOccupied || selectedFiles.size === 0 + {occupied || selectedFiles.size === 0 ? gt("no files") : gt("{count, plural, one {+ {count} file} other {+ {count} files}}", { count: selectedFiles.size, @@ -386,7 +411,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
- {folderOccupied ? null : ( + {occupied ? null : (
- {canListFiles && !folderOccupied ? ( + {canListFiles && !occupied ? (
{canListFiles && !occupied ? ( @@ -551,7 +552,9 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe