@devries-cameron20 / t3code-1 / commits / 37452eeaa3
Fork 0

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

fix(server): cloning into a stranded clone project's empty folder reuses that project (#33439)

Julius Marminge committed Nov 10, 2026 at 22:45 UTC 37452eeaa37fa19f29f3aae0f488de7172dcaa4e
9 files changed +119 -49
apps/mobile/src/features/projects/AddProjectScreen.tsx
+2 -2
@@ -1424,12 +1424,11 @@ export function AddProjectDestinationScreen(props: {
1424
1425 const originRoute = getActiveRoute(navigation);
1426 setIsSubmitting(true);
1427 - const projectId = ProjectId.make(uuidv4());
1427 const title = inferProjectTitleFromPath(resolved.path);
1428 const startResult = await startProjectClone({
1429 environmentId: environment.environmentId,
1430 input: {
1432 - projectId,
1431 + projectId: ProjectId.make(uuidv4()),
1432 title,
1433 createdAt: new Date().toISOString(),
1434 remoteUrl,
@@ -1440,6 +1439,7 @@ export function AddProjectDestinationScreen(props: {
1439 setError(errorMessage(Cause.squash(startResult.cause)));
1440 } else {
1441 void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl);
1442 + const { projectId } = startResult.value;
1443 // Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls.
1444 const project = await waitForProject(
1445 { environmentId: environment.environmentId, projectId },
apps/server/src/project/ProjectCloneTracker.test.ts
+30
@@ -16,6 +16,7 @@ import * as TestClock from "effect/testing/TestClock";
16
17 import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
18 import * as ProjectCloneTracker from "./ProjectCloneTracker.ts";
19 +import { ProjectConflictError } from "./ProjectService.ts";
20 import { parseGitCloneProgressLine } from "./gitCloneProgress.ts";
21
22 const projectId = ProjectId.make("project-1");
@@ -282,6 +283,35 @@ describe("ProjectCloneTracker", () => {
283 }).pipe(Effect.provide(harness.layer));
284 });
285
286 + it.effect("clones for the project that already owns the empty destination", () => {
287 + const owner = ProjectId.make("project-stranded");
288 + const harness = makeHarness();
289 + const hooks: ProjectCloneTracker.ProjectCloneHooks = {
290 + ...harness.hooks,
291 + createProject: (input) =>
292 + Effect.fail(
293 + new ProjectConflictError({
294 + projectId: input.projectId,
295 + workspaceRoot: input.workspaceRoot,
296 + conflictingProjectId: owner,
297 + }),
298 + ),
299 + };
300 + return Effect.gen(function* () {
301 + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
302 + const result = yield* tracker.start(startInput, hooks);
303 + expect(result.projectId).toBe(owner);
304 + yield* Effect.yieldNow;
305 + expect(yield* tracker.get(owner)).toMatchObject({
306 + projectId: owner,
307 + destinationPath: "/workspace/t3code",
308 + phase: "done",
309 + });
310 + expect(harness.cloned).toEqual([owner]);
311 + expect(yield* tracker.get(projectId)).toBeNull();
312 + }).pipe(Effect.provide(harness.layer));
313 + });
314 +
315 it.effect("does not create a project when the clone cannot be prepared", () => {
316 const harness = makeHarness();
317 const layer = ProjectCloneTracker.layer.pipe(
apps/server/src/project/ProjectCloneTracker.ts
+43 -17
@@ -31,6 +31,7 @@ import * as Scope from "effect/Scope";
31 import * as Stream from "effect/Stream";
32
33 import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
34 +import type { ProjectConflictError } from "./ProjectService.ts";
35
36 export class ProjectCloneTracker extends Context.Service<
37 ProjectCloneTracker,
@@ -53,12 +54,13 @@ export class ProjectCloneTracker extends Context.Service<
54 >()("t3/project/ProjectCloneTracker") {}
55
56 export interface ProjectCloneHooks {
57 + /** Fails with `ProjectConflictError` when another project already owns the destination. */
58 readonly createProject: (input: {
59 readonly projectId: ProjectId;
60 readonly title: string;
61 readonly workspaceRoot: string;
62 readonly createdAt: string;
61 - }) => Effect.Effect<void, OrchestrationDispatchCommandError>;
63 + }) => Effect.Effect<void, OrchestrationDispatchCommandError | ProjectConflictError>;
64 readonly onCloned: (input: {
65 readonly projectId: ProjectId;
66 readonly workspaceRoot: string;
@@ -266,6 +268,16 @@ export const make = Effect.gen(function* () {
268 });
269 });
270
271 + const moveClaim = (from: ProjectId, to: ProjectId) =>
272 + Ref.modify(clones, (current) => {
273 + const claim = current.get(from);
274 + if (!claim || current.has(to)) return [false, current] as const;
275 + const next = new Map(current);
276 + next.delete(from);
277 + next.set(to, { ...claim, snapshot: { ...claim.snapshot, projectId: to } });
278 + return [true, next] as const;
279 + });
280 +
281 const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(
282 function* (input, hooks) {
283 const prepared = yield* repositories.prepareClone(input);
@@ -306,30 +318,44 @@ export const make = Effect.gen(function* () {
318 });
319 return [true, next] as const;
320 });
309 - if (!claimed) {
310 - return yield* new SourceControlRepositoryError({
311 - operation: "cloneRepository",
312 - provider: input.provider ?? SourceControlProviderKind.make("unknown"),
313 - detail: "A clone into this destination is already in progress.",
314 - });
315 - }
321 + const alreadyInProgress = new SourceControlRepositoryError({
322 + operation: "cloneRepository",
323 + provider: input.provider ?? SourceControlProviderKind.make("unknown"),
324 + detail: "A clone into this destination is already in progress.",
325 + });
326 + if (!claimed) return yield* alreadyInProgress;
327 // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried.
317 - yield* Effect.uninterruptible(
328 + const projectId = yield* Effect.uninterruptible(
329 Effect.gen(function* () {
330 yield* clearRetention(input.projectId);
331 // Register before creation so racing thread.create and project.delete see the clone.
321 - yield* hooks.createProject({
322 - projectId: input.projectId,
323 - title: input.title,
324 - workspaceRoot: prepared.destinationPath,
325 - createdAt: input.createdAt,
326 - });
332 + const projectId = yield* hooks
333 + .createProject({
334 + projectId: input.projectId,
335 + title: input.title,
336 + workspaceRoot: prepared.destinationPath,
337 + createdAt: input.createdAt,
338 + })
339 + .pipe(
340 + Effect.as(input.projectId),
341 + // A failed clone's project still owns its empty folder after a restart
342 + // forgets the clone; clone for that project instead.
343 + Effect.catchTags({
344 + ProjectConflictError: (conflict) =>
345 + moveClaim(input.projectId, conflict.conflictingProjectId).pipe(
346 + Effect.flatMap((moved) =>
347 + moved ? Effect.succeed(conflict.conflictingProjectId) : alreadyInProgress,
348 + ),
349 + ),
350 + }),
351 + );
352 yield* publish;
328 - yield* launch(input.projectId);
353 + yield* launch(projectId);
354 + return projectId;
355 }).pipe(Effect.tapError(() => remove(input.projectId))),
356 );
357 return {
332 - projectId: input.projectId,
358 + projectId,
359 cwd: prepared.destinationPath,
360 remoteUrl: prepared.remoteUrl,
361 repository: prepared.repository,
apps/server/src/ws.ts
+7 -6
@@ -2896,12 +2896,13 @@ export const layerWsRpc = (
2896 })
2897 .pipe(
2898 Effect.asVoid,
2899 - Effect.mapError(
2900 - (cause) =>
2901 - new OrchestrationDispatchCommandError({
2902 - message: "Failed to create clone project.",
2903 - cause,
2904 - }),
2899 + Effect.mapError((cause) =>
2900 + cause._tag === "ProjectConflictError"
2901 + ? cause
2902 + : new OrchestrationDispatchCommandError({
2903 + message: "Failed to create clone project.",
2904 + cause,
2905 + }),
2906 ),
2907 ),
2908 onCloned: (project) =>
apps/web/src/components/AddProjectToMachineDialog.tsx
+2 -3
@@ -186,16 +186,15 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
186 }
187 setSubmitting(true);
188 setError(null);
189 - const projectId = newProjectId();
189 try {
191 - await addProjectToMachine({
190 + const projectId = await addProjectToMachine({
191 source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
192 subdirectory: projectSubdirectory(
193 project.repositoryIdentity?.rootPath,
194 project.workspaceRoot,
195 ),
196 target: { environmentId: target.environmentId, label: target.label },
198 - projectId,
197 + projectId: newProjectId(),
198 title: project.title,
199 remoteUrl,
200 destinationPath: destinationPath.trim(),
apps/web/src/components/CommandPalette.composition.browser.test.tsx
+2 -1
@@ -45,7 +45,8 @@ vi.mock("../hooks/useHandleNewThread", () => ({
45 vi.mock("../hooks/useOpenPanelPullRequestUrl", () => ({ useOpenPanelPullRequestUrl: () => null }));
46 vi.mock("../connection/useDesktopLocalBootstraps", () => ({ useDesktopLocalBootstraps: () => [] }));
47 vi.mock("../state/use-atom-command", () => ({
48 - useAtomCommand: () => async () => ({ _tag: "Success", value: undefined }),
48 + // The add-project destination step starts a clone and follows its project id.
49 + useAtomCommand: () => async () => ({ _tag: "Success", value: { projectId: "project-cloned" } }),
50 }));
51 vi.mock("../state/use-atom-query-runner", () => ({
52 useAtomQueryRunner: () => async () => ({ _tag: "Success", value: undefined }),
apps/web/src/components/CommandPalette.tsx
+5 -3
@@ -2166,12 +2166,11 @@ function OpenCommandPaletteDialog(props: {
2166 return;
2167 }
2168
2169 - const projectId = newProjectId();
2169 setIsRemoteProjectCloning(true);
2170 const startResult = await startProjectClone({
2171 environmentId: addProjectCloneFlow.environmentId,
2172 input: {
2174 - projectId,
2173 + projectId: newProjectId(),
2174 title: inferProjectTitleFromPath(destinationPath),
2175 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
2176 createdAt: new Date().toISOString(),
@@ -2197,7 +2196,10 @@ function OpenCommandPaletteDialog(props: {
2196 addProjectCloneFlow.environmentId,
2197 addProjectCloneFlow.remoteUrl,
2198 );
2200 - const projectRef = scopeProjectRef(addProjectCloneFlow.environmentId, projectId);
2199 + const projectRef = scopeProjectRef(
2200 + addProjectCloneFlow.environmentId,
2201 + startResult.value.projectId,
2202 + );
2203 await waitForProject(projectRef, 3_000).catch(() => null);
2204 const navigationResult = await settlePromise(() => handleNewThread(projectRef));
2205 if (navigationResult._tag === "Failure") {
apps/web/src/components/promptLinks/NewThreadLinkView.tsx
+5 -5
@@ -213,13 +213,12 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
213 return;
214 }
215 setState({ status: "opening" });
216 - const projectId = newProjectId();
216 const remoteUrl = `https://github.com/${repository.owner}/${repository.name}.git`;
217 const settings = serverConfig.settings;
218 const result = await startProjectClone({
219 environmentId,
220 input: {
222 - projectId,
221 + projectId: newProjectId(),
222 title: repository.name,
223 createdAt: new Date().toISOString(),
224 remoteUrl,
@@ -249,9 +248,10 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
248 environmentId,
249 `https://github.com/${repository.owner}/${repository.name}.git`,
250 );
252 - const project = await waitForProject(scopeProjectRef(environmentId, projectId), 5_000).catch(
253 - () => null,
254 - );
251 + const project = await waitForProject(
252 + scopeProjectRef(environmentId, result.value.projectId),
253 + 5_000,
254 + ).catch(() => null);
255 if (project === null) {
256 setState({ status: "failed", message: "The clone started, but its project did not appear." });
257 return;
apps/web/src/lib/addProjectToMachine.ts
+23 -12
@@ -97,12 +97,11 @@ export function dismissProjectFileCopy(ref: ScopedProjectRef) {
97 }
98
99 /**
100 - * Clones a project onto another machine, then copies the chosen ignored files
101 - * from the source. The client relays the files because the two servers never
102 - * talk to each other. Resolves once the clone starts. The caller opens the new
103 - * project, whose composer shows the clone and copy progress, so nothing toasts.
100 + * Clones onto another machine, then relays the chosen ignored files, since the
101 + * two servers never talk. Resolves with the cloning project once it starts; the
102 + * caller opens it, and its composer shows progress, so nothing toasts.
103 */
105 -export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
104 +export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<ProjectId> {
105 // Read first, so the copy reflects the files as they were when the user asked.
106 const reads = await Promise.all(
107 input.files.map(async (relativePath) => {
@@ -120,11 +119,11 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
119 }),
120 );
121
123 - const targetRef = { environmentId: input.target.environmentId, projectId: input.projectId };
124 - const copyKey = scopedProjectKey(targetRef);
122 + const requestedRef = { environmentId: input.target.environmentId, projectId: input.projectId };
123 + const requestedKey = scopedProjectKey(requestedRef);
124 // Marked before the start request, since the clone list can arrive before its reply.
126 - silenceProjectCloneToasts(targetRef);
127 - if (reads.length > 0) setFileCopy(copyKey, { phase: "copying" });
125 + silenceProjectCloneToasts(requestedRef);
126 + if (reads.length > 0) setFileCopy(requestedKey, { phase: "copying" });
127 const started = await runAtomCommand(
128 appAtomRegistry,
129 sourceControlEnvironment.startProjectClone,
@@ -141,14 +140,25 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
140 { label: "Add project to machine", reportFailure: false },
141 );
142 if (started._tag === "Failure") {
144 - setFileCopy(copyKey, null);
143 + setFileCopy(requestedKey, null);
144 throw new Error(failureMessage(started));
145 }
146 + // The server clones for the existing project when one already owns the empty destination.
147 + const { projectId } = started.value;
148 + const targetRef = { environmentId: input.target.environmentId, projectId };
149 + const copyKey = scopedProjectKey(targetRef);
150 + if (projectId !== input.projectId) {
151 + silenceProjectCloneToasts(targetRef);
152 + if (reads.length > 0) {
153 + setFileCopy(copyKey, { phase: "copying" });
154 + setFileCopy(requestedKey, null);
155 + }
156 + }
157 void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl);
148 - if (reads.length === 0) return;
158 + if (reads.length === 0) return projectId;
159
160 void (async () => {
151 - const clone = await waitForClone(input.target.environmentId, input.projectId);
161 + const clone = await waitForClone(input.target.environmentId, projectId);
162 if (!clone) {
163 setFileCopy(copyKey, null);
164 return;
@@ -188,4 +198,5 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
198 },
199 );
200 })();
201 + return projectId;
202 }