Open History to see the last commit
1import type {
2 ProjectCloneSnapshot,
3 ProjectCloneStage,
4 ProjectCloneStartInput,
5 ProjectCloneStartResult,
6 ProjectId,
7 SourceControlRepositoryInfo,
8} from "@t3tools/contracts";
9import {
10 OrchestrationDispatchCommandError,
11 PROJECT_CLONE_DETAIL_MAX_LENGTH,
12 PROJECT_CLONE_ERROR_MAX_LENGTH,
13 SourceControlRepositoryError,
14} from "@t3tools/contracts";
15import * as Cause from "effect/Cause";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Fiber from "effect/Fiber";
21import * as Layer from "effect/Layer";
22import * as PubSub from "effect/PubSub";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Semaphore from "effect/Semaphore";
27import * as Scope from "effect/Scope";
28import * as Stream from "effect/Stream";
29
30import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
31
32/**
33 * Runs repository clones that back newly added projects and tracks their
34 * progress so clients can show it anywhere, not just in the surface that
35 * started the clone.
36 *
37 * The clone is detached from the request that started it: the palette closes
38 * immediately, the project already exists (pointing at the empty destination),
39 * and the composer can hold a draft for it. Snapshots are memory only. A done
40 * clone is dropped after a short grace window; a failed one stays until it is
41 * retried or the server restarts, since the empty project is the durable
42 * record the user can act on.
43 */
44export class ProjectCloneTracker extends Context.Service<
45 ProjectCloneTracker,
46 {
47 /**
48 * Resolves the remote, creates the project, and starts the clone in the
49 * background. Fails before creating anything when the destination or
50 * repository is unusable so the caller can report it inline.
51 */
52 readonly start: (
53 input: ProjectCloneStartInput,
54 hooks: ProjectCloneHooks,
55 ) => Effect.Effect<
56 ProjectCloneStartResult,
57 SourceControlRepositoryError | OrchestrationDispatchCommandError
58 >;
59 /** Interrupts a running clone and deletes the partial checkout. */
60 readonly cancel: (projectId: ProjectId) => Effect.Effect<boolean>;
61 /** Restarts a failed or cancelled clone into the same destination. */
62 readonly retry: (projectId: ProjectId) => Effect.Effect<boolean, SourceControlRepositoryError>;
63 /**
64 * Stops tracking a project's clone, interrupting it if it still runs and
65 * removing an unfinished checkout. Called when the project is deleted.
66 */
67 readonly discard: (projectId: ProjectId) => Effect.Effect<void>;
68 readonly get: (projectId: ProjectId) => Effect.Effect<ProjectCloneSnapshot | null>;
69 /** Emits every tracked clone first, then the full list after each change. */
70 readonly stream: Stream.Stream<ReadonlyArray<ProjectCloneSnapshot>>;
71 }
72>()("t3/project/ProjectCloneTracker") {}
73
74/**
75 * Orchestration side effects the caller owns. The tracker never depends on the
76 * engine directly: the WebSocket handler dispatches with the client's origin,
77 * and the tracker only needs the outcome.
78 */
79export interface ProjectCloneHooks {
80 readonly createProject: (input: {
81 readonly projectId: ProjectId;
82 readonly title: string;
83 readonly workspaceRoot: string;
84 readonly createdAt: string;
85 }) => Effect.Effect<void, OrchestrationDispatchCommandError>;
86 /** Runs after a successful clone so cached repository identity and git status refresh. */
87 readonly onCloned: (input: {
88 readonly projectId: ProjectId;
89 readonly workspaceRoot: string;
90 }) => Effect.Effect<void>;
91}
92
93/** Finished snapshots stay visible this long so a late subscriber sees the outcome. */
94const DONE_RETENTION = "30 seconds";
95
96function clampText(text: string, maxLength: number): string {
97 return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`;
98}
99
100const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
101
102interface TrackedClone {
103 readonly snapshot: ProjectCloneSnapshot;
104 readonly fiber: Fiber.Fiber<unknown, unknown> | null;
105 readonly hooks: ProjectCloneHooks;
106 readonly input: {
107 /** What git is given; may carry credentials and never leaves the server. */
108 readonly cloneUrl: string;
109 readonly destinationPath: string;
110 readonly repository: SourceControlRepositoryInfo | null;
111 };
112}
113
114/** @public Service construction is part of the canonical Effect module API. */
115export const make = Effect.gen(function* () {
116 const repositories = yield* SourceControlRepositoryService.SourceControlRepositoryService;
117 const clones = yield* Ref.make(new Map<ProjectId, TrackedClone>());
118 const changes = yield* PubSub.unbounded<ReadonlyArray<ProjectCloneSnapshot>>();
119 const retentionFibers = new Map<ProjectId, Fiber.Fiber<unknown, never>>();
120 let sequence = 0;
121 // Clone fibers outlive the RPC that started them but not the server.
122 const cloneScope = yield* Scope.make("parallel");
123 yield* Effect.addFinalizer(() => Scope.close(cloneScope, Exit.void));
124 // start/cancel/retry/discard mutate the same entry and the same directory;
125 // one at a time keeps a double-clicked Retry from racing two clones into it.
126 const actionLock = yield* Semaphore.make(1);
127 const locked = <A, E, R>(effect: Effect.Effect<A, E, R>) => actionLock.withPermits(1)(effect);
128
129 const list = Ref.get(clones).pipe(
130 Effect.map((current) => Array.from(current.values(), (tracked) => tracked.snapshot)),
131 );
132 const publish = list.pipe(Effect.flatMap((snapshots) => PubSub.publish(changes, snapshots)));
133
134 const modify = (
135 projectId: ProjectId,
136 mutate: (tracked: TrackedClone) => TrackedClone,
137 ): Effect.Effect<ProjectCloneSnapshot | null> =>
138 Ref.modify(clones, (current) => {
139 const existing = current.get(projectId);
140 if (!existing) return [null, current] as const;
141 const nextTracked = mutate(existing);
142 const nextSnapshot = { ...nextTracked.snapshot, sequence: ++sequence };
143 const next = new Map(current);
144 next.set(projectId, { ...nextTracked, snapshot: nextSnapshot });
145 return [nextSnapshot, next] as const;
146 }).pipe(Effect.tap((snapshot) => (snapshot ? publish : Effect.void)));
147
148 const clearRetention = (projectId: ProjectId) => {
149 const fiber = retentionFibers.get(projectId);
150 retentionFibers.delete(projectId);
151 return fiber ? Fiber.interrupt(fiber).pipe(Effect.ignore) : Effect.void;
152 };
153
154 const remove = (projectId: ProjectId) =>
155 Ref.update(clones, (current) => {
156 if (!current.has(projectId)) return current;
157 const next = new Map(current);
158 next.delete(projectId);
159 return next;
160 }).pipe(Effect.andThen(publish));
161
162 const scheduleRemoval = (projectId: ProjectId) =>
163 Effect.gen(function* () {
164 yield* clearRetention(projectId);
165 const fiber = yield* remove(projectId).pipe(
166 Effect.delay(DONE_RETENTION),
167 Effect.ensuring(
168 Effect.sync(() => {
169 if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);
170 }),
171 ),
172 Effect.forkDetach,
173 );
174 retentionFibers.set(projectId, fiber);
175 });
176
177 const progress = (
178 projectId: ProjectId,
179 update: {
180 readonly stage: ProjectCloneStage;
181 readonly percent: number | null;
182 readonly detail: string | null;
183 },
184 ) =>
185 modify(projectId, (tracked) => ({
186 ...tracked,
187 snapshot: {
188 ...tracked.snapshot,
189 stage: update.stage,
190 percent: update.percent,
191 detail:
192 update.detail === null ? null : clampText(update.detail, PROJECT_CLONE_DETAIL_MAX_LENGTH),
193 },
194 })).pipe(Effect.asVoid);
195
196 const finish = (
197 projectId: ProjectId,
198 phase: "done" | "failed" | "cancelled",
199 error: string | null,
200 ) =>
201 Effect.gen(function* () {
202 const endedAt = yield* nowIso;
203 yield* modify(projectId, (tracked) => ({
204 ...tracked,
205 fiber: null,
206 snapshot: {
207 ...tracked.snapshot,
208 phase,
209 endedAt,
210 percent: phase === "done" ? 100 : tracked.snapshot.percent,
211 error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH),
212 },
213 }));
214 if (phase === "done") yield* scheduleRemoval(projectId);
215 });
216
217 /**
218 * The clone body. Runs in its own fiber; the tracker records the outcome
219 * through `onExit`, which still runs when the fiber is interrupted (a
220 * `matchCause` handler would be skipped). Once git has finished the clone
221 * is marked done before the post-clone hook runs, so a late Cancel cannot
222 * tear down a complete checkout.
223 */
224 const runClone = (projectId: ProjectId, tracked: TrackedClone) =>
225 repositories
226 .cloneRepository(
227 { remoteUrl: tracked.input.cloneUrl, destinationPath: tracked.input.destinationPath },
228 { onProgress: (update) => progress(projectId, update), timeoutMs: null },
229 )
230 .pipe(
231 Effect.onExit((exit) =>
232 Exit.isSuccess(exit)
233 ? finish(projectId, "done", null)
234 : Cause.hasInterruptsOnly(exit.cause)
235 ? finish(projectId, "cancelled", null)
236 : finish(projectId, "failed", describeCloneFailure(exit.cause)),
237 ),
238 Effect.flatMap(() =>
239 tracked.hooks
240 .onCloned({ projectId, workspaceRoot: tracked.input.destinationPath })
241 .pipe(Effect.ignoreCause({ log: true })),
242 ),
243 Effect.ignoreCause(),
244 );
245
246 const launch = (projectId: ProjectId) =>
247 Effect.gen(function* () {
248 const current = yield* Ref.get(clones);
249 const tracked = current.get(projectId);
250 if (!tracked) return;
251 const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));
252 yield* Ref.update(clones, (map) => {
253 const existing = map.get(projectId);
254 if (!existing) return map;
255 const next = new Map(map);
256 next.set(projectId, { ...existing, fiber });
257 return next;
258 });
259 });
260
261 const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(
262 function* (input, hooks) {
263 const prepared = yield* repositories.prepareClone(input);
264 const startedAt = yield* nowIso;
265 const snapshot: ProjectCloneSnapshot = {
266 projectId: input.projectId,
267 remoteUrl: prepared.remoteUrl,
268 destinationPath: prepared.destinationPath,
269 repository: prepared.repository,
270 phase: "running",
271 stage: "connecting",
272 percent: null,
273 detail: null,
274 error: null,
275 startedAt,
276 endedAt: null,
277 sequence: ++sequence,
278 };
279 const claimed = yield* Ref.modify(clones, (current) => {
280 // A second start for the same project, or for a destination another
281 // clone already owns, must not race two gits into one directory.
282 const conflict = Array.from(current.values()).some(
283 (tracked) =>
284 tracked.snapshot.projectId === input.projectId ||
285 tracked.input.destinationPath === prepared.destinationPath,
286 );
287 if (conflict) return [false, current] as const;
288 const next = new Map(current);
289 next.set(input.projectId, {
290 snapshot,
291 fiber: null,
292 hooks,
293 input: {
294 cloneUrl: prepared.cloneUrl,
295 destinationPath: prepared.destinationPath,
296 repository: prepared.repository,
297 },
298 });
299 return [true, next] as const;
300 });
301 if (!claimed) {
302 return yield* new SourceControlRepositoryError({
303 operation: "cloneRepository",
304 provider: input.provider ?? "unknown",
305 detail: "A clone into this destination is already in progress.",
306 });
307 }
308 // Everything after the claim runs to completion even if the requesting
309 // connection drops: a claimed entry with no fiber could neither be
310 // cancelled nor retried. Any failure in here releases the claim.
311 yield* Effect.uninterruptible(
312 Effect.gen(function* () {
313 yield* clearRetention(input.projectId);
314 // The entry is registered before the project exists so a
315 // thread.create or project.delete racing this call already sees it.
316 yield* hooks.createProject({
317 projectId: input.projectId,
318 title: input.title,
319 workspaceRoot: prepared.destinationPath,
320 createdAt: input.createdAt,
321 });
322 yield* publish;
323 yield* launch(input.projectId);
324 }).pipe(Effect.tapError(() => remove(input.projectId))),
325 );
326 return {
327 projectId: input.projectId,
328 cwd: prepared.destinationPath,
329 remoteUrl: prepared.remoteUrl,
330 repository: prepared.repository,
331 };
332 },
333 );
334
335 const get: ProjectCloneTracker["Service"]["get"] = (projectId) =>
336 Ref.get(clones).pipe(Effect.map((current) => current.get(projectId)?.snapshot ?? null));
337
338 const cancel: ProjectCloneTracker["Service"]["cancel"] = (projectId) =>
339 Effect.gen(function* () {
340 const current = yield* Ref.get(clones);
341 const tracked = current.get(projectId);
342 if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false;
343 // Uninterruptible past this point: a client that disconnects mid-cancel
344 // must not leave a dead fiber behind a "running" snapshot.
345 yield* Effect.uninterruptible(
346 Effect.gen(function* () {
347 yield* Fiber.interrupt(tracked.fiber!);
348 const after = yield* get(projectId);
349 // Git finished in the window before the interrupt landed: keep it.
350 if (after?.phase === "done") return;
351 if (after?.phase === "running") yield* finish(projectId, "cancelled", null);
352 // The partial checkout goes so a retry starts from an empty destination.
353 yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
354 }),
355 );
356 return true;
357 });
358
359 const retry: ProjectCloneTracker["Service"]["retry"] = (projectId) =>
360 Effect.gen(function* () {
361 const current = yield* Ref.get(clones);
362 const tracked = current.get(projectId);
363 if (
364 !tracked ||
365 (tracked.snapshot.phase !== "failed" && tracked.snapshot.phase !== "cancelled")
366 ) {
367 return false;
368 }
369 // A retry into leftover files would fail on the non-empty destination
370 // with a less useful message, so a cleanup failure is the error here.
371 yield* repositories.discardClone(tracked.input.destinationPath);
372 const startedAt = yield* nowIso;
373 yield* modify(projectId, (entry) => ({
374 ...entry,
375 snapshot: {
376 ...entry.snapshot,
377 phase: "running",
378 stage: "connecting",
379 percent: null,
380 detail: null,
381 error: null,
382 startedAt,
383 endedAt: null,
384 },
385 }));
386 yield* launch(projectId);
387 return true;
388 });
389
390 const discard: ProjectCloneTracker["Service"]["discard"] = (projectId) =>
391 Effect.gen(function* () {
392 const current = yield* Ref.get(clones);
393 const tracked = current.get(projectId);
394 if (!tracked) return;
395 if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);
396 // Git may have finished while the interrupt was landing; the project
397 // is going away either way, but a complete checkout is the user's.
398 const after = yield* get(projectId);
399 if (after?.phase !== "done") {
400 yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
401 }
402 yield* clearRetention(projectId);
403 yield* remove(projectId);
404 });
405
406 // One-slot sliding mailbox per subscriber: a slow socket only ever holds the
407 // newest list, and lists are whole states so skipping intermediates is safe.
408 const stream: ProjectCloneTracker["Service"]["stream"] = Stream.callback<
409 ReadonlyArray<ProjectCloneSnapshot>
410 >(
411 (mailbox) =>
412 Effect.gen(function* () {
413 const subscription = yield* PubSub.subscribe(changes);
414 Queue.offerUnsafe(mailbox, yield* list);
415 yield* Stream.fromSubscription(subscription).pipe(
416 Stream.runForEach((snapshots) =>
417 Effect.sync(() => Queue.offerUnsafe(mailbox, snapshots)),
418 ),
419 Effect.forkScoped,
420 );
421 }),
422 { bufferSize: 1, strategy: "sliding" },
423 );
424
425 return ProjectCloneTracker.of({
426 start: (input, hooks) => locked(start(input, hooks)),
427 cancel: (projectId) => locked(cancel(projectId)),
428 retry: (projectId) => locked(retry(projectId)),
429 discard: (projectId) => locked(discard(projectId)),
430 get,
431 stream,
432 });
433});
434
435const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
436
437/**
438 * A project whose clone has not landed has no files to work in. Every
439 * dispatch transport (WebSocket, HTTP) runs this before normalizing so no
440 * client can start a thread on an empty tree, and no attachment copies are
441 * made for a command that is about to be refused.
442 */
443export const rejectCommandsDuringClone = (
444 tracker: ProjectCloneTracker["Service"],
445 command: { readonly type: string; readonly projectId?: ProjectId; readonly bootstrap?: unknown },
446): Effect.Effect<void, OrchestrationDispatchCommandError> =>
447 Effect.gen(function* () {
448 const projectId =
449 command.type === "thread.create"
450 ? (command.projectId ?? null)
451 : command.type === "thread.turn.start"
452 ? bootstrapProjectId(command.bootstrap)
453 : null;
454 if (projectId === null) return;
455 const clone = yield* tracker.get(projectId);
456 if (clone === null || clone.phase === "done") return;
457 return yield* new OrchestrationDispatchCommandError({
458 message:
459 clone.phase === "running"
460 ? "The repository is still being cloned."
461 : "The repository was not cloned. Retry the clone first.",
462 });
463 });
464
465function bootstrapProjectId(bootstrap: unknown): ProjectId | null {
466 if (typeof bootstrap !== "object" || bootstrap === null) return null;
467 const createThread = (bootstrap as { createThread?: { projectId?: ProjectId } }).createThread;
468 return createThread?.projectId ?? null;
469}
470
471function describeCloneFailure(cause: Cause.Cause<unknown>): string {
472 const error = Cause.squash(cause);
473 if (isSourceControlRepositoryError(error)) return error.detail;
474 return error instanceof Error && error.message.trim().length > 0
475 ? error.message
476 : "The repository could not be cloned.";
477}
478
479export const layer = Layer.effect(ProjectCloneTracker, make);