Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3import {
4 OrchestrationDispatchCommandError,
5 ProjectId,
6 projectCloneProgressSummary,
7 type SourceControlCloneProtocol,
8 SourceControlRepositoryError,
9} from "@t3tools/contracts";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as Stream from "effect/Stream";
15import * as TestClock from "effect/testing/TestClock";
16
17import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
18import * as ProjectCloneTracker from "./ProjectCloneTracker.ts";
19import { ProjectConflictError } from "./ProjectService.ts";
20import { parseGitCloneProgressLine } from "./gitCloneProgress.ts";
21
22const projectId = ProjectId.make("project-1");
23const startInput = {
24 projectId,
25 title: "t3code",
26 createdAt: "2026-01-01T00:00:00.000Z",
27 remoteUrl: "git@github.com:octocat/t3code.git",
28 destinationPath: "/workspace/t3code",
29};
30
31function makeHarness(options?: {
32 readonly clone?: SourceControlRepositoryService.SourceControlRepositoryService["Service"]["cloneRepository"];
33}) {
34 const created: Array<{ projectId: ProjectId; workspaceRoot: string }> = [];
35 const cloned: Array<ProjectId> = [];
36 const discarded: Array<string> = [];
37 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
38 createProject: (input) =>
39 Effect.sync(() => {
40 created.push({ projectId: input.projectId, workspaceRoot: input.workspaceRoot });
41 }),
42 onCloned: (input) => Effect.sync(() => void cloned.push(input.projectId)),
43 };
44 const layer = ProjectCloneTracker.layer.pipe(
45 Layer.provide(
46 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
47 prepareClone: (input) =>
48 Effect.succeed({
49 destinationPath: input.destinationPath,
50 remoteUrl: input.remoteUrl ?? "",
51 cloneUrl: input.remoteUrl ?? "",
52 repository: null,
53 }),
54 cloneRepository:
55 options?.clone ??
56 ((input) =>
57 Effect.succeed({
58 cwd: input.destinationPath,
59 remoteUrl: input.remoteUrl ?? "",
60 repository: null,
61 })),
62 discardClone: (destination) => Effect.sync(() => void discarded.push(destination)),
63 }),
64 ),
65 );
66 return { layer, hooks, created, cloned, discarded };
67}
68
69describe("ProjectCloneTracker", () => {
70 it.effect("creates the project first and reports the clone through the stream", () => {
71 const release = Deferred.makeUnsafe<void>();
72 const harness = makeHarness({
73 clone: (input, options) =>
74 Effect.gen(function* () {
75 yield* (
76 options?.onProgress?.({ stage: "receiving", percent: 40, detail: "1 MiB" }) ??
77 Effect.void
78 );
79 yield* Deferred.await(release);
80 return { cwd: input.destinationPath, remoteUrl: input.remoteUrl ?? "", repository: null };
81 }),
82 });
83 return Effect.gen(function* () {
84 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
85 const collected = yield* tracker.stream.pipe(
86 Stream.takeUntil((clones) => clones[0]?.phase === "done"),
87 Stream.runCollect,
88 Effect.forkChild,
89 );
90 yield* Effect.yieldNow;
91
92 const result = yield* tracker.start(startInput, harness.hooks);
93 expect(result.cwd).toBe("/workspace/t3code");
94 expect(harness.created).toEqual([{ projectId, workspaceRoot: "/workspace/t3code" }]);
95
96 yield* Effect.yieldNow;
97 const running = yield* tracker.get(projectId);
98 expect(running).toMatchObject({ phase: "running", stage: "receiving", percent: 40 });
99
100 yield* Deferred.succeed(release, undefined);
101 const lists = yield* Fiber.join(collected);
102 const final = lists.at(-1)?.[0];
103 expect(final).toMatchObject({ phase: "done", percent: 100 });
104 expect(harness.cloned).toEqual([projectId]);
105
106 yield* TestClock.adjust("31 seconds");
107 expect(yield* tracker.get(projectId)).toBeNull();
108 }).pipe(Effect.provide(harness.layer));
109 });
110
111 it.effect("flags a clone stalled when git goes quiet and clears it when git speaks", () => {
112 const release = Deferred.makeUnsafe<void>();
113 const resumed = Deferred.makeUnsafe<void>();
114 const harness = makeHarness({
115 clone: (input, options) =>
116 Effect.gen(function* () {
117 const report = options?.onProgress ?? (() => Effect.void);
118 yield* report({ stage: "receiving", percent: 24, detail: "168.80 MiB | 20.69 MiB/s" });
119 yield* Deferred.await(resumed);
120 yield* report({ stage: "receiving", percent: 25, detail: "170.00 MiB | 1.00 MiB/s" });
121 yield* Deferred.await(release);
122 return { cwd: input.destinationPath, remoteUrl: input.remoteUrl ?? "", repository: null };
123 }),
124 });
125 return Effect.gen(function* () {
126 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
127 yield* tracker.start(startInput, harness.hooks);
128 yield* Effect.yieldNow;
129 expect((yield* tracker.get(projectId))?.stalled).toBe(false);
130
131 yield* TestClock.adjust("19 seconds");
132 expect((yield* tracker.get(projectId))?.stalled).toBe(false);
133 yield* TestClock.adjust("1 second");
134 const stalled = yield* tracker.get(projectId);
135 expect(stalled).toMatchObject({ stalled: true, percent: 24 });
136 expect(projectCloneProgressSummary(stalled!)).toBe("Receiving objects · 24% · Stalled");
137
138 yield* Deferred.succeed(resumed, undefined);
139 yield* Effect.yieldNow;
140 expect(yield* tracker.get(projectId)).toMatchObject({ stalled: false, percent: 25 });
141
142 yield* TestClock.adjust("20 seconds");
143 expect((yield* tracker.get(projectId))?.stalled).toBe(true);
144 yield* Deferred.succeed(release, undefined);
145 yield* Effect.yieldNow;
146 expect(yield* tracker.get(projectId)).toMatchObject({ phase: "done", stalled: false });
147 }).pipe(Effect.provide(harness.layer));
148 });
149
150 it.effect("keeps a failed clone with git's own explanation and retries it", () => {
151 const protocols: Array<SourceControlCloneProtocol | undefined> = [];
152 const harness = makeHarness({
153 clone: (input) =>
154 Effect.suspend(() => {
155 protocols.push(input.protocol);
156 return protocols.length === 1
157 ? Effect.fail(
158 new SourceControlRepositoryError({
159 operation: "cloneRepository",
160 provider: SourceControlProviderKind.make("unknown"),
161 detail: "fatal: repository not found",
162 }),
163 )
164 : Effect.succeed({
165 cwd: input.destinationPath,
166 remoteUrl: input.remoteUrl ?? "",
167 repository: null,
168 });
169 }),
170 });
171 return Effect.gen(function* () {
172 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
173 yield* tracker.start({ ...startInput, protocol: "ssh" }, harness.hooks);
174 yield* Effect.yieldNow;
175 const failed = yield* tracker.get(projectId);
176 expect(failed).toMatchObject({ phase: "failed", error: "fatal: repository not found" });
177
178 expect(yield* tracker.retry(projectId)).toBe(true);
179 expect(harness.discarded).toEqual(["/workspace/t3code"]);
180 yield* Effect.yieldNow;
181 expect((yield* tracker.get(projectId))?.phase).toBe("done");
182 expect(protocols).toEqual(["ssh", "ssh"]);
183 }).pipe(Effect.provide(harness.layer));
184 });
185
186 it.effect("clamps a long failure without splitting a surrogate pair", () => {
187 const harness = makeHarness({
188 clone: () =>
189 Effect.fail(
190 new SourceControlRepositoryError({
191 operation: "cloneRepository",
192 provider: SourceControlProviderKind.make("unknown"),
193 detail: `${"e".repeat(998)}\u{1F680}tail`,
194 }),
195 ),
196 });
197 return Effect.gen(function* () {
198 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
199 yield* tracker.start(startInput, harness.hooks);
200 yield* Effect.yieldNow;
201 expect((yield* tracker.get(projectId))?.error).toBe(`${"e".repeat(998)}…`);
202 }).pipe(Effect.provide(harness.layer));
203 });
204
205 it.effect("cancel interrupts the clone and removes the partial checkout", () => {
206 const harness = makeHarness({ clone: () => Effect.never });
207 return Effect.gen(function* () {
208 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
209 yield* tracker.start(startInput, harness.hooks);
210 yield* Effect.yieldNow;
211
212 expect(yield* tracker.cancel(projectId)).toBe(true);
213 expect((yield* tracker.get(projectId))?.phase).toBe("cancelled");
214 expect(harness.discarded).toEqual(["/workspace/t3code"]);
215 expect(yield* tracker.cancel(projectId)).toBe(false);
216 expect(yield* tracker.retry(projectId)).toBe(true);
217 }).pipe(Effect.provide(harness.layer));
218 });
219
220 it.effect("a cancel that lands after git finished keeps the checkout", () => {
221 const gate = Deferred.makeUnsafe<void>();
222 const harness = makeHarness();
223 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
224 ...harness.hooks,
225 onCloned: () => Deferred.await(gate),
226 };
227 return Effect.gen(function* () {
228 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
229 yield* tracker.start(startInput, hooks);
230 yield* Effect.yieldNow;
231 expect((yield* tracker.get(projectId))?.phase).toBe("done");
232 expect(yield* tracker.cancel(projectId)).toBe(false);
233 expect(harness.discarded).toEqual([]);
234 yield* Deferred.succeed(gate, undefined);
235 }).pipe(Effect.provide(harness.layer));
236 });
237
238 it.effect("hands git the credential-bearing URL while snapshots carry the redacted one", () => {
239 const cloneUrls: Array<string> = [];
240 const harness = makeHarness({
241 clone: (input) =>
242 Effect.sync(() => {
243 cloneUrls.push(input.remoteUrl ?? "");
244 return { cwd: input.destinationPath, remoteUrl: "", repository: null };
245 }),
246 });
247 const layer = ProjectCloneTracker.layer.pipe(
248 Layer.provide(
249 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
250 prepareClone: (input) =>
251 Effect.succeed({
252 destinationPath: input.destinationPath,
253 remoteUrl: "https://github.com/octocat/t3code.git",
254 cloneUrl: "https://user:s3cret@github.com/octocat/t3code.git",
255 repository: null,
256 }),
257 cloneRepository: (input) =>
258 Effect.sync(() => {
259 cloneUrls.push(input.remoteUrl ?? "");
260 return { cwd: input.destinationPath, remoteUrl: "", repository: null };
261 }),
262 discardClone: () => Effect.void,
263 }),
264 ),
265 );
266 return Effect.gen(function* () {
267 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
268 const result = yield* tracker.start(startInput, harness.hooks);
269 yield* Effect.yieldNow;
270 expect(result.remoteUrl).toBe("https://github.com/octocat/t3code.git");
271 expect(cloneUrls).toEqual(["https://user:s3cret@github.com/octocat/t3code.git"]);
272 }).pipe(Effect.provide(layer));
273 });
274
275 it.effect("discard forgets a project's clone when the project is deleted", () => {
276 const harness = makeHarness({ clone: () => Effect.never });
277 return Effect.gen(function* () {
278 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
279 yield* tracker.start(startInput, harness.hooks);
280 yield* Effect.yieldNow;
281 yield* tracker.discard(projectId);
282 expect(yield* tracker.get(projectId)).toBeNull();
283 expect(harness.discarded).toEqual(["/workspace/t3code"]);
284 }).pipe(Effect.provide(harness.layer));
285 });
286
287 it.effect("releases the claim when project creation fails", () => {
288 const harness = makeHarness();
289 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
290 ...harness.hooks,
291 createProject: () =>
292 Effect.fail(new OrchestrationDispatchCommandError({ message: "workspace root exists" })),
293 };
294 return Effect.gen(function* () {
295 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
296 const error = yield* Effect.flip(tracker.start(startInput, hooks));
297 expect(error.message).toContain("workspace root exists");
298 expect(yield* tracker.get(projectId)).toBeNull();
299 yield* tracker.start(startInput, harness.hooks);
300 yield* Effect.yieldNow;
301 expect((yield* tracker.get(projectId))?.phase).toBe("done");
302 }).pipe(Effect.provide(harness.layer));
303 });
304
305 it.effect("clones for the project that already owns the empty destination", () => {
306 const owner = ProjectId.make("project-stranded");
307 const harness = makeHarness();
308 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
309 ...harness.hooks,
310 createProject: (input) =>
311 Effect.fail(
312 new ProjectConflictError({
313 projectId: input.projectId,
314 workspaceRoot: input.workspaceRoot,
315 conflictingProjectId: owner,
316 }),
317 ),
318 };
319 return Effect.gen(function* () {
320 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
321 const result = yield* tracker.start(startInput, hooks);
322 expect(result.projectId).toBe(owner);
323 yield* Effect.yieldNow;
324 expect(yield* tracker.get(owner)).toMatchObject({
325 projectId: owner,
326 destinationPath: "/workspace/t3code",
327 phase: "done",
328 });
329 expect(harness.cloned).toEqual([owner]);
330 expect(yield* tracker.get(projectId)).toBeNull();
331 }).pipe(Effect.provide(harness.layer));
332 });
333
334 it.effect("a fresh clone into a failed clone's destination supersedes it", () => {
335 let attempts = 0;
336 const harness = makeHarness({
337 clone: (input) =>
338 Effect.suspend(() =>
339 ++attempts === 1
340 ? Effect.fail(
341 new SourceControlRepositoryError({
342 operation: "cloneRepository",
343 provider: SourceControlProviderKind.make("unknown"),
344 detail: "fatal: repository not found",
345 }),
346 )
347 : Effect.succeed({
348 cwd: input.destinationPath,
349 remoteUrl: input.remoteUrl ?? "",
350 repository: null,
351 }),
352 ),
353 });
354 // The failed clone's project still owns the destination.
355 const conflictingHooks: ProjectCloneTracker.ProjectCloneHooks = {
356 ...harness.hooks,
357 createProject: (input) =>
358 Effect.fail(
359 new ProjectConflictError({
360 projectId: input.projectId,
361 workspaceRoot: input.workspaceRoot,
362 conflictingProjectId: projectId,
363 }),
364 ),
365 };
366 return Effect.gen(function* () {
367 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
368 yield* tracker.start(startInput, harness.hooks);
369 yield* Effect.yieldNow;
370 expect((yield* tracker.get(projectId))?.phase).toBe("failed");
371
372 const second = ProjectId.make("project-2");
373 const result = yield* tracker.start({ ...startInput, projectId: second }, conflictingHooks);
374 expect(result.projectId).toBe(projectId);
375 yield* Effect.yieldNow;
376 expect((yield* tracker.get(projectId))?.phase).toBe("done");
377 expect(yield* tracker.get(second)).toBeNull();
378 expect(harness.cloned).toEqual([projectId]);
379 }).pipe(Effect.provide(harness.layer));
380 });
381
382 it.effect("refuses a second clone into a destination that is still cloning", () => {
383 const harness = makeHarness({ clone: () => Effect.never });
384 return Effect.gen(function* () {
385 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
386 yield* tracker.start(startInput, harness.hooks);
387 yield* Effect.yieldNow;
388 const error = yield* Effect.flip(
389 tracker.start({ ...startInput, projectId: ProjectId.make("project-2") }, harness.hooks),
390 );
391 expect(error.message).toContain("already in progress");
392 expect((yield* tracker.get(projectId))?.phase).toBe("running");
393 }).pipe(Effect.provide(harness.layer));
394 });
395
396 it.effect("does not create a project when the clone cannot be prepared", () => {
397 const harness = makeHarness();
398 const layer = ProjectCloneTracker.layer.pipe(
399 Layer.provide(
400 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
401 prepareClone: () =>
402 Effect.fail(
403 new SourceControlRepositoryError({
404 operation: "cloneRepository",
405 provider: SourceControlProviderKind.make("unknown"),
406 detail: "Destination path already exists and is not empty.",
407 }),
408 ),
409 }),
410 ),
411 );
412 return Effect.gen(function* () {
413 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
414 const error = yield* Effect.flip(tracker.start(startInput, harness.hooks));
415 expect(error.message).toContain("not empty");
416 expect(harness.created).toEqual([]);
417 expect(yield* tracker.get(projectId)).toBeNull();
418 }).pipe(Effect.provide(layer));
419 });
420});
421
422describe("parseGitCloneProgressLine", () => {
423 it("parses git's transfer counters and ignores other output", () => {
424 expect(
425 parseGitCloneProgressLine("Receiving objects: 45% (4500/10000), 12.30 MiB | 5.00 MiB/s"),
426 ).toEqual({ stage: "receiving", percent: 45, detail: "12.30 MiB | 5.00 MiB/s" });
427 expect(
428 parseGitCloneProgressLine("Receiving objects: 100% (5/5), 40.00 MiB | 1.40 MiB/s, done."),
429 ).toEqual({ stage: "receiving", percent: 100, detail: "40.00 MiB | 1.40 MiB/s" });
430 expect(parseGitCloneProgressLine("Resolving deltas: 100% (700/700), done.")).toEqual({
431 stage: "resolving",
432 percent: 100,
433 detail: null,
434 });
435 expect(parseGitCloneProgressLine("remote: Compressing objects: 12% (3/25)")).toEqual({
436 stage: "counting",
437 percent: 12,
438 detail: null,
439 });
440 expect(parseGitCloneProgressLine("Updating files: 78% (2104/2700)")).toEqual({
441 stage: "checkout",
442 percent: 78,
443 detail: null,
444 });
445 expect(
446 parseGitCloneProgressLine("Filtering content: 66% (2/3), 11.92 MiB | 1009.00 KiB/s"),
447 ).toEqual({ stage: "checkout", percent: 66, detail: "11.92 MiB | 1009.00 KiB/s" });
448 expect(parseGitCloneProgressLine("remote: Enumerating objects: 10, done.")).toEqual({
449 stage: "counting",
450 percent: null,
451 detail: null,
452 });
453 expect(parseGitCloneProgressLine("Cloning into 't3code'...")).toBeNull();
454 expect(parseGitCloneProgressLine("fatal: repository not found")).toBeNull();
455 });
456});