Skip to content

Commit 37452ee

Browse files
fix(server): cloning into a stranded clone project's empty folder reuses that project (pingdotgg#33439)
1 parent a03d9bc commit 37452ee

9 files changed

Lines changed: 119 additions & 49 deletions

File tree

‎apps/mobile/src/features/projects/AddProjectScreen.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,12 +1424,11 @@ export function AddProjectDestinationScreen(props: {
14241424

14251425
const originRoute = getActiveRoute(navigation);
14261426
setIsSubmitting(true);
1427-
const projectId = ProjectId.make(uuidv4());
14281427
const title = inferProjectTitleFromPath(resolved.path);
14291428
const startResult = await startProjectClone({
14301429
environmentId: environment.environmentId,
14311430
input: {
1432-
projectId,
1431+
projectId: ProjectId.make(uuidv4()),
14331432
title,
14341433
createdAt: new Date().toISOString(),
14351434
remoteUrl,
@@ -1440,6 +1439,7 @@ export function AddProjectDestinationScreen(props: {
14401439
setError(errorMessage(Cause.squash(startResult.cause)));
14411440
} else {
14421441
void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl);
1442+
const { projectId } = startResult.value;
14431443
// Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls.
14441444
const project = await waitForProject(
14451445
{ environmentId: environment.environmentId, projectId },

‎apps/server/src/project/ProjectCloneTracker.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as TestClock from "effect/testing/TestClock";
1616

1717
import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
1818
import * as ProjectCloneTracker from "./ProjectCloneTracker.ts";
19+
import { ProjectConflictError } from "./ProjectService.ts";
1920
import { parseGitCloneProgressLine } from "./gitCloneProgress.ts";
2021

2122
const projectId = ProjectId.make("project-1");
@@ -282,6 +283,35 @@ describe("ProjectCloneTracker", () => {
282283
}).pipe(Effect.provide(harness.layer));
283284
});
284285

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+
285315
it.effect("does not create a project when the clone cannot be prepared", () => {
286316
const harness = makeHarness();
287317
const layer = ProjectCloneTracker.layer.pipe(

‎apps/server/src/project/ProjectCloneTracker.ts‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import * as Scope from "effect/Scope";
3131
import * as Stream from "effect/Stream";
3232

3333
import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
34+
import type { ProjectConflictError } from "./ProjectService.ts";
3435

3536
export class ProjectCloneTracker extends Context.Service<
3637
ProjectCloneTracker,
@@ -53,12 +54,13 @@ export class ProjectCloneTracker extends Context.Service<
5354
>()("t3/project/ProjectCloneTracker") {}
5455

5556
export interface ProjectCloneHooks {
57+
/** Fails with `ProjectConflictError` when another project already owns the destination. */
5658
readonly createProject: (input: {
5759
readonly projectId: ProjectId;
5860
readonly title: string;
5961
readonly workspaceRoot: string;
6062
readonly createdAt: string;
61-
}) => Effect.Effect<void, OrchestrationDispatchCommandError>;
63+
}) => Effect.Effect<void, OrchestrationDispatchCommandError | ProjectConflictError>;
6264
readonly onCloned: (input: {
6365
readonly projectId: ProjectId;
6466
readonly workspaceRoot: string;
@@ -266,6 +268,16 @@ export const make = Effect.gen(function* () {
266268
});
267269
});
268270

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+
269281
const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(
270282
function* (input, hooks) {
271283
const prepared = yield* repositories.prepareClone(input);
@@ -306,30 +318,44 @@ export const make = Effect.gen(function* () {
306318
});
307319
return [true, next] as const;
308320
});
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;
316327
// 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(
318329
Effect.gen(function* () {
319330
yield* clearRetention(input.projectId);
320331
// 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+
);
327352
yield* publish;
328-
yield* launch(input.projectId);
353+
yield* launch(projectId);
354+
return projectId;
329355
}).pipe(Effect.tapError(() => remove(input.projectId))),
330356
);
331357
return {
332-
projectId: input.projectId,
358+
projectId,
333359
cwd: prepared.destinationPath,
334360
remoteUrl: prepared.remoteUrl,
335361
repository: prepared.repository,

‎apps/server/src/ws.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2896,12 +2896,13 @@ export const layerWsRpc = (
28962896
})
28972897
.pipe(
28982898
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+
}),
29052906
),
29062907
),
29072908
onCloned: (project) =>

‎apps/web/src/components/AddProjectToMachineDialog.tsx‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,16 +186,15 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
186186
}
187187
setSubmitting(true);
188188
setError(null);
189-
const projectId = newProjectId();
190189
try {
191-
await addProjectToMachine({
190+
const projectId = await addProjectToMachine({
192191
source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
193192
subdirectory: projectSubdirectory(
194193
project.repositoryIdentity?.rootPath,
195194
project.workspaceRoot,
196195
),
197196
target: { environmentId: target.environmentId, label: target.label },
198-
projectId,
197+
projectId: newProjectId(),
199198
title: project.title,
200199
remoteUrl,
201200
destinationPath: destinationPath.trim(),

‎apps/web/src/components/CommandPalette.composition.browser.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ vi.mock("../hooks/useHandleNewThread", () => ({
4545
vi.mock("../hooks/useOpenPanelPullRequestUrl", () => ({ useOpenPanelPullRequestUrl: () => null }));
4646
vi.mock("../connection/useDesktopLocalBootstraps", () => ({ useDesktopLocalBootstraps: () => [] }));
4747
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" } }),
4950
}));
5051
vi.mock("../state/use-atom-query-runner", () => ({
5152
useAtomQueryRunner: () => async () => ({ _tag: "Success", value: undefined }),

‎apps/web/src/components/CommandPalette.tsx‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2166,12 +2166,11 @@ function OpenCommandPaletteDialog(props: {
21662166
return;
21672167
}
21682168

2169-
const projectId = newProjectId();
21702169
setIsRemoteProjectCloning(true);
21712170
const startResult = await startProjectClone({
21722171
environmentId: addProjectCloneFlow.environmentId,
21732172
input: {
2174-
projectId,
2173+
projectId: newProjectId(),
21752174
title: inferProjectTitleFromPath(destinationPath),
21762175
// oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
21772176
createdAt: new Date().toISOString(),
@@ -2197,7 +2196,10 @@ function OpenCommandPaletteDialog(props: {
21972196
addProjectCloneFlow.environmentId,
21982197
addProjectCloneFlow.remoteUrl,
21992198
);
2200-
const projectRef = scopeProjectRef(addProjectCloneFlow.environmentId, projectId);
2199+
const projectRef = scopeProjectRef(
2200+
addProjectCloneFlow.environmentId,
2201+
startResult.value.projectId,
2202+
);
22012203
await waitForProject(projectRef, 3_000).catch(() => null);
22022204
const navigationResult = await settlePromise(() => handleNewThread(projectRef));
22032205
if (navigationResult._tag === "Failure") {

‎apps/web/src/components/promptLinks/NewThreadLinkView.tsx‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -213,13 +213,12 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
213213
return;
214214
}
215215
setState({ status: "opening" });
216-
const projectId = newProjectId();
217216
const remoteUrl = `https://github.com/${repository.owner}/${repository.name}.git`;
218217
const settings = serverConfig.settings;
219218
const result = await startProjectClone({
220219
environmentId,
221220
input: {
222-
projectId,
221+
projectId: newProjectId(),
223222
title: repository.name,
224223
createdAt: new Date().toISOString(),
225224
remoteUrl,
@@ -249,9 +248,10 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) {
249248
environmentId,
250249
`https://github.com/${repository.owner}/${repository.name}.git`,
251250
);
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);
255255
if (project === null) {
256256
setState({ status: "failed", message: "The clone started, but its project did not appear." });
257257
return;

‎apps/web/src/lib/addProjectToMachine.ts‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,11 @@ export function dismissProjectFileCopy(ref: ScopedProjectRef) {
9797
}
9898

9999
/**
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.
104103
*/
105-
export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
104+
export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<ProjectId> {
106105
// Read first, so the copy reflects the files as they were when the user asked.
107106
const reads = await Promise.all(
108107
input.files.map(async (relativePath) => {
@@ -120,11 +119,11 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
120119
}),
121120
);
122121

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);
125124
// 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" });
128127
const started = await runAtomCommand(
129128
appAtomRegistry,
130129
sourceControlEnvironment.startProjectClone,
@@ -141,14 +140,25 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
141140
{ label: "Add project to machine", reportFailure: false },
142141
);
143142
if (started._tag === "Failure") {
144-
setFileCopy(copyKey, null);
143+
setFileCopy(requestedKey, null);
145144
throw new Error(failureMessage(started));
146145
}
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+
}
147157
void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl);
148-
if (reads.length === 0) return;
158+
if (reads.length === 0) return projectId;
149159

150160
void (async () => {
151-
const clone = await waitForClone(input.target.environmentId, input.projectId);
161+
const clone = await waitForClone(input.target.environmentId, projectId);
152162
if (!clone) {
153163
setFileCopy(copyKey, null);
154164
return;
@@ -188,4 +198,5 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom
188198
},
189199
);
190200
})();
201+
return projectId;
191202
}

0 commit comments

Comments
 (0)