Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectCloneTracker.test.ts

303 lines12.0 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 OrchestrationDispatchCommandError,
4 ProjectId,
5 SourceControlRepositoryError,
6} from "@t3tools/contracts";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Layer from "effect/Layer";
11import * as Stream from "effect/Stream";
12import * as TestClock from "effect/testing/TestClock";
13​
14import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
15import * as ProjectCloneTracker from "./ProjectCloneTracker.ts";
16import { parseGitCloneProgressLine } from "./gitCloneProgress.ts";
17​
18const projectId = ProjectId.make("project-1");
19const startInput = {
20 projectId,
21 title: "t3code",
22 createdAt: "2026-01-01T00:00:00.000Z",
23 remoteUrl: "git@github.com:octocat/t3code.git",
24 destinationPath: "/workspace/t3code",
25};
26​
27function makeHarness(options?: {
28 readonly clone?: SourceControlRepositoryService.SourceControlRepositoryService["Service"]["cloneRepository"];
29}) {
30 const created: Array<{ projectId: ProjectId; workspaceRoot: string }> = [];
31 const cloned: Array<ProjectId> = [];
32 const discarded: Array<string> = [];
33 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
34 createProject: (input) =>
35 Effect.sync(() => {
36 created.push({ projectId: input.projectId, workspaceRoot: input.workspaceRoot });
37 }),
38 onCloned: (input) => Effect.sync(() => void cloned.push(input.projectId)),
39 };
40 const layer = ProjectCloneTracker.layer.pipe(
41 Layer.provide(
42 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
43 prepareClone: (input) =>
44 Effect.succeed({
45 destinationPath: input.destinationPath,
46 remoteUrl: input.remoteUrl ?? "",
47 cloneUrl: input.remoteUrl ?? "",
48 repository: null,
49 }),
50 cloneRepository:
51 options?.clone ??
52 ((input) =>
53 Effect.succeed({
54 cwd: input.destinationPath,
55 remoteUrl: input.remoteUrl ?? "",
56 repository: null,
57 })),
58 discardClone: (destination) => Effect.sync(() => void discarded.push(destination)),
59 }),
60 ),
61 );
62 return { layer, hooks, created, cloned, discarded };
64​
65describe("ProjectCloneTracker", () => {
66 it.effect("creates the project first and reports the clone through the stream", () => {
67 const release = Deferred.makeUnsafe<void>();
68 const harness = makeHarness({
69 clone: (input, options) =>
70 Effect.gen(function* () {
71 yield* (
72 options?.onProgress?.({ stage: "receiving", percent: 40, detail: "1 MiB" }) ??
73 Effect.void
74 );
75 yield* Deferred.await(release);
76 return { cwd: input.destinationPath, remoteUrl: input.remoteUrl ?? "", repository: null };
77 }),
78 });
79 return Effect.gen(function* () {
80 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
81 const collected = yield* tracker.stream.pipe(
82 Stream.takeUntil((clones) => clones[0]?.phase === "done"),
83 Stream.runCollect,
84 Effect.forkChild,
85 );
86 yield* Effect.yieldNow;
87​
88 const result = yield* tracker.start(startInput, harness.hooks);
89 expect(result.cwd).toBe("/workspace/t3code");
90 // The project exists before git runs so the draft can open immediately.
91 expect(harness.created).toEqual([{ projectId, workspaceRoot: "/workspace/t3code" }]);
92​
93 yield* Effect.yieldNow;
94 const running = yield* tracker.get(projectId);
95 expect(running).toMatchObject({ phase: "running", stage: "receiving", percent: 40 });
96​
97 yield* Deferred.succeed(release, undefined);
98 const lists = yield* Fiber.join(collected);
99 const final = lists.at(-1)?.[0];
100 expect(final).toMatchObject({ phase: "done", percent: 100 });
101 expect(harness.cloned).toEqual([projectId]);
102​
103 // Done clones drop out after the grace window so the toast can settle.
104 yield* TestClock.adjust("31 seconds");
105 expect(yield* tracker.get(projectId)).toBeNull();
106 }).pipe(Effect.provide(harness.layer));
107 });
108​
109 it.effect("keeps a failed clone with git's own explanation and retries it", () => {
110 let attempts = 0;
111 const harness = makeHarness({
112 clone: (input) =>
113 Effect.suspend(() => {
114 attempts += 1;
115 return attempts === 1
116 ? Effect.fail(
117 new SourceControlRepositoryError({
118 operation: "cloneRepository",
119 provider: "unknown",
120 detail: "fatal: repository not found",
121 }),
122 )
123 : Effect.succeed({
124 cwd: input.destinationPath,
125 remoteUrl: input.remoteUrl ?? "",
126 repository: null,
127 });
128 }),
129 });
130 return Effect.gen(function* () {
131 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
132 yield* tracker.start(startInput, harness.hooks);
133 yield* Effect.yieldNow;
134 const failed = yield* tracker.get(projectId);
135 expect(failed).toMatchObject({ phase: "failed", error: "fatal: repository not found" });
136​
137 expect(yield* tracker.retry(projectId)).toBe(true);
138 // The partial checkout is cleared so git sees an empty destination.
139 expect(harness.discarded).toEqual(["/workspace/t3code"]);
140 yield* Effect.yieldNow;
141 expect((yield* tracker.get(projectId))?.phase).toBe("done");
142 expect(attempts).toBe(2);
143 }).pipe(Effect.provide(harness.layer));
144 });
145​
146 it.effect("cancel interrupts the clone and removes the partial checkout", () => {
147 const harness = makeHarness({ clone: () => Effect.never });
148 return Effect.gen(function* () {
149 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
150 yield* tracker.start(startInput, harness.hooks);
151 yield* Effect.yieldNow;
152​
153 expect(yield* tracker.cancel(projectId)).toBe(true);
154 expect((yield* tracker.get(projectId))?.phase).toBe("cancelled");
155 expect(harness.discarded).toEqual(["/workspace/t3code"]);
156 // Nothing left to cancel; retry is what brings it back.
157 expect(yield* tracker.cancel(projectId)).toBe(false);
158 expect(yield* tracker.retry(projectId)).toBe(true);
159 }).pipe(Effect.provide(harness.layer));
160 });
161​
162 it.effect("a cancel that lands after git finished keeps the checkout", () => {
163 const gate = Deferred.makeUnsafe<void>();
164 const harness = makeHarness();
165 // The clone itself completes instantly; the post-clone hook is what hangs.
166 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
167 ...harness.hooks,
168 onCloned: () => Deferred.await(gate),
169 };
170 return Effect.gen(function* () {
171 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
172 yield* tracker.start(startInput, hooks);
173 yield* Effect.yieldNow;
174 expect((yield* tracker.get(projectId))?.phase).toBe("done");
175 expect(yield* tracker.cancel(projectId)).toBe(false);
176 expect(harness.discarded).toEqual([]);
177 yield* Deferred.succeed(gate, undefined);
178 }).pipe(Effect.provide(harness.layer));
179 });
180​
181 it.effect("hands git the credential-bearing URL while snapshots carry the redacted one", () => {
182 const cloneUrls: Array<string> = [];
183 const harness = makeHarness({
184 clone: (input) =>
185 Effect.sync(() => {
186 cloneUrls.push(input.remoteUrl ?? "");
187 return { cwd: input.destinationPath, remoteUrl: "", repository: null };
188 }),
189 });
190 const layer = ProjectCloneTracker.layer.pipe(
191 Layer.provide(
192 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
193 prepareClone: (input) =>
194 Effect.succeed({
195 destinationPath: input.destinationPath,
196 remoteUrl: "https://github.com/octocat/t3code.git",
197 cloneUrl: "https://user:s3cret@github.com/octocat/t3code.git",
198 repository: null,
199 }),
200 cloneRepository: (input) =>
201 Effect.sync(() => {
202 cloneUrls.push(input.remoteUrl ?? "");
203 return { cwd: input.destinationPath, remoteUrl: "", repository: null };
204 }),
205 discardClone: () => Effect.void,
206 }),
207 ),
208 );
209 return Effect.gen(function* () {
210 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
211 const result = yield* tracker.start(startInput, harness.hooks);
212 yield* Effect.yieldNow;
213 expect(result.remoteUrl).toBe("https://github.com/octocat/t3code.git");
214 expect(cloneUrls).toEqual(["https://user:s3cret@github.com/octocat/t3code.git"]);
215 }).pipe(Effect.provide(layer));
216 });
217​
218 it.effect("discard forgets a project's clone when the project is deleted", () => {
219 const harness = makeHarness({ clone: () => Effect.never });
220 return Effect.gen(function* () {
221 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
222 yield* tracker.start(startInput, harness.hooks);
223 yield* Effect.yieldNow;
224 yield* tracker.discard(projectId);
225 expect(yield* tracker.get(projectId)).toBeNull();
226 expect(harness.discarded).toEqual(["/workspace/t3code"]);
227 }).pipe(Effect.provide(harness.layer));
228 });
229​
230 it.effect("releases the claim when project creation fails", () => {
231 const harness = makeHarness();
232 const hooks: ProjectCloneTracker.ProjectCloneHooks = {
233 ...harness.hooks,
234 createProject: () =>
235 Effect.fail(new OrchestrationDispatchCommandError({ message: "workspace root exists" })),
236 };
237 return Effect.gen(function* () {
238 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
239 const error = yield* Effect.flip(tracker.start(startInput, hooks));
240 expect(error.message).toContain("workspace root exists");
241 expect(yield* tracker.get(projectId)).toBeNull();
242 // The destination is free again for a corrected attempt.
243 yield* tracker.start(startInput, harness.hooks);
244 yield* Effect.yieldNow;
245 expect((yield* tracker.get(projectId))?.phase).toBe("done");
246 }).pipe(Effect.provide(harness.layer));
247 });
248​
249 it.effect("does not create a project when the clone cannot be prepared", () => {
250 const harness = makeHarness();
251 const layer = ProjectCloneTracker.layer.pipe(
252 Layer.provide(
253 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
254 prepareClone: () =>
255 Effect.fail(
256 new SourceControlRepositoryError({
257 operation: "cloneRepository",
258 provider: "unknown",
259 detail: "Destination path already exists and is not empty.",
260 }),
261 ),
262 }),
263 ),
264 );
265 return Effect.gen(function* () {
266 const tracker = yield* ProjectCloneTracker.ProjectCloneTracker;
267 const error = yield* Effect.flip(tracker.start(startInput, harness.hooks));
268 expect(error.message).toContain("not empty");
269 expect(harness.created).toEqual([]);
270 expect(yield* tracker.get(projectId)).toBeNull();
271 }).pipe(Effect.provide(layer));
272 });
273});
274​
275describe("parseGitCloneProgressLine", () => {
276 it("parses git's transfer counters and ignores other output", () => {
277 expect(
278 parseGitCloneProgressLine("Receiving objects: 45% (4500/10000), 12.30 MiB | 5.00 MiB/s"),
279 ).toEqual({ stage: "receiving", percent: 45, detail: "12.30 MiB | 5.00 MiB/s" });
280 expect(parseGitCloneProgressLine("Resolving deltas: 100% (700/700), done.")).toEqual({
281 stage: "resolving",
282 percent: 100,
283 detail: null,
284 });
285 expect(parseGitCloneProgressLine("remote: Compressing objects: 12% (3/25)")).toEqual({
286 stage: "counting",
287 percent: 12,
288 detail: null,
289 });
290 expect(parseGitCloneProgressLine("Updating files: 78% (2104/2700)")).toEqual({
291 stage: "checkout",
292 percent: 78,
293 detail: null,
294 });
295 expect(parseGitCloneProgressLine("remote: Enumerating objects: 10, done.")).toEqual({
296 stage: "counting",
297 percent: null,
298 detail: null,
299 });
300 expect(parseGitCloneProgressLine("Cloning into 't3code'...")).toBeNull();
301 expect(parseGitCloneProgressLine("fatal: repository not found")).toBeNull();
302 });
303});