Skip to content

Commit 7a39bff

Browse files
t3dotggclaude
andcommitted
fix(server): make worktree setup progress and cancel robust
Review findings from the first push: - Git separates checkout progress updates with a bare carriage return, so the driver only saw the final line. Line splitting now treats CR as a line break and the driver forwards createWorktree options. - The setup wrapper now closes its block on its own line, so a trailing comment or heredoc in the command cannot swallow the sentinel. It picks fish, PowerShell, or POSIX syntax from the shell TerminalManager will spawn. - A failed terminal write now unsubscribes the completion listener. - cancel waits for the bootstrap fiber to unwind, and closes the setup terminal before removing the worktree. - The tracker stream drops queued snapshots older than the initial one. - The web client keys the setup subscription to the thread it dispatched, holds the last snapshot so a failed card survives, and resends after "Work locally" only once the cancelled dispatch has settled. - knip: restore the @public tag on make, and add tests for the parser and the worktree-setup timeline row. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 70ec8f4 commit 7a39bff

9 files changed

Lines changed: 386 additions & 77 deletions

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

Lines changed: 113 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it, vi } from "@effect/vitest";
22
import { type OrchestrationProject, ProjectId, type TerminalEvent } from "@t3tools/contracts";
3+
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
34
import * as Effect from "effect/Effect";
45
import * as Layer from "effect/Layer";
56
import * as Option from "effect/Option";
@@ -284,12 +285,13 @@ describe("ProjectSetupScriptRunner", () => {
284285
// The subscription is attached before the command is written.
285286
expect(subscribe).toHaveBeenCalledTimes(1);
286287
expect(writes).toHaveLength(1);
287-
expect(writes[0]?.startsWith("( bun install );")).toBe(true);
288-
expect(writes[0]).toContain("__T3_SETUP_DONE__:");
288+
// The block closes on its own line so a trailing comment in the
289+
// command cannot swallow the sentinel.
290+
expect(writes[0]).toBe("( bun install\r); printf '\\n__T3_SETUP_DONE__:%s\\n' \"$?\"\r");
289291

290292
// Output arrives in chunks; partial lines are buffered until a newline,
291-
// control sequences are stripped, and the echoed command is hidden.
292-
yield* emit("( bun install ); printf '\\n__T3_SETUP_DONE__:%s\\n' \"$?\"\r\n");
293+
// control sequences are stripped, and the echoed wrapper is hidden.
294+
yield* emit("( bun install\r\n> ); printf '\\n__T3_SETUP_DONE__:%s\\n' \"$?\"\r\n");
293295
yield* emit("\u001b[32mResolving");
294296
yield* emit(" deps\u001b[0m\r\nDone in 2s\r\n");
295297
yield* emit("__T3_SETUP_DONE__:3\r\n");
@@ -299,10 +301,116 @@ describe("ProjectSetupScriptRunner", () => {
299301
expect(seen).toEqual(["Resolving deps", "Done in 2s"]);
300302
// The subscription is torn down once the sentinel arrives.
301303
expect(listener).toBeNull();
302-
}).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
304+
}).pipe(
305+
Effect.provide(testLayer(project, { open, write, subscribe })),
306+
Effect.provideService(HostProcessPlatform, "linux"),
307+
Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
308+
);
303309
},
304310
);
305311

312+
it.effect("unsubscribes from terminal output when the command cannot be written", () => {
313+
const open = vi.fn(() =>
314+
Effect.succeed({
315+
threadId: "thread-1",
316+
terminalId: "setup-setup",
317+
cwd: "/repo/worktrees/a",
318+
worktreePath: "/repo/worktrees/a",
319+
status: "running" as const,
320+
pid: 123,
321+
history: "",
322+
exitCode: null,
323+
exitSignal: null,
324+
label: "setup-setup",
325+
updatedAt: "2026-01-01T00:00:00.000Z",
326+
}),
327+
);
328+
const write = vi.fn(() =>
329+
Effect.fail(
330+
new TerminalManager.TerminalCwdStatError({ cwd: "/repo/worktrees/a", cause: {} }),
331+
),
332+
);
333+
const unsubscribe = vi.fn();
334+
const subscribe = vi.fn(() => Effect.succeed(unsubscribe));
335+
const project = makeProject([
336+
{
337+
id: "setup",
338+
name: "Setup",
339+
command: "bun install",
340+
icon: "configure",
341+
runOnWorktreeCreate: true,
342+
},
343+
]);
344+
345+
return Effect.gen(function* () {
346+
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
347+
const result = yield* runner
348+
.runForThread({
349+
threadId: "thread-1",
350+
projectCwd: "/repo/project",
351+
worktreePath: "/repo/worktrees/a",
352+
observeCompletion: {},
353+
})
354+
.pipe(Effect.result);
355+
expect(result._tag).toBe("Failure");
356+
expect(unsubscribe).toHaveBeenCalledTimes(1);
357+
}).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
358+
});
359+
360+
it.effect.each([
361+
{
362+
shell: "/usr/bin/fish",
363+
expected: "begin\rbun install\rend; printf '\\n__T3_SETUP_DONE__:%s\\n' $status",
364+
},
365+
{
366+
shell: "/bin/bash",
367+
expected: "( bun install\r); printf '\\n__T3_SETUP_DONE__:%s\\n' \"$?\"",
368+
},
369+
])("wraps the command for the $shell syntax", ({ shell, expected }) => {
370+
const open = vi.fn(() =>
371+
Effect.succeed({
372+
threadId: "thread-1",
373+
terminalId: "setup-setup",
374+
cwd: "/repo/worktrees/a",
375+
worktreePath: "/repo/worktrees/a",
376+
status: "running" as const,
377+
pid: 123,
378+
history: "",
379+
exitCode: null,
380+
exitSignal: null,
381+
label: "setup-setup",
382+
updatedAt: "2026-01-01T00:00:00.000Z",
383+
}),
384+
);
385+
const writes: string[] = [];
386+
const write = vi.fn((input: { data: string }) =>
387+
Effect.sync(() => void writes.push(input.data)),
388+
);
389+
const project = makeProject([
390+
{
391+
id: "setup",
392+
name: "Setup",
393+
command: "bun install",
394+
icon: "configure",
395+
runOnWorktreeCreate: true,
396+
},
397+
]);
398+
return Effect.gen(function* () {
399+
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
400+
yield* runner.runForThread({
401+
threadId: "thread-1",
402+
projectCwd: "/repo/project",
403+
worktreePath: "/repo/worktrees/a",
404+
observeCompletion: {},
405+
});
406+
expect(writes).toEqual([`${expected}\r`]);
407+
}).pipe(
408+
Effect.provide(testLayer(project, { open, write })),
409+
Effect.provideService(HostProcessPlatform, "linux"),
410+
Effect.provideService(HostProcessEnvironment, { SHELL: shell }),
411+
);
412+
});
413+
306414
it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
307415
const rootCause = new Error("stat failed");
308416
const terminalError = new TerminalManager.TerminalCwdStatError({

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

Lines changed: 50 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { ProjectId } from "@t3tools/contracts";
2-
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2+
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
33
import {
44
projectScriptRuntimeEnv,
55
resolveProjectScripts,
@@ -130,24 +130,54 @@ function stripTerminalControl(text: string): string {
130130
);
131131
}
132132

133+
type CompletionShell = "posix" | "fish" | "powershell";
134+
133135
/**
134-
* Builds the shell line for the setup script. On POSIX shells the user's
135-
* command runs in a subshell so `&&` chains and `cd` cannot leak, then the
136-
* exit status is echoed. PowerShell reports `$LASTEXITCODE` or falls back to
137-
* the success flag.
136+
* Predicts the shell TerminalManager will spawn for the setup terminal. The
137+
* manager takes `$SHELL` on POSIX and PowerShell on Windows, falling back to
138+
* other shells only when that one fails to spawn.
138139
*/
139-
function wrapCommandForCompletion(command: string, platform: NodeJS.Platform): string {
140-
if (platform === "win32") {
141-
return `& { ${command} }; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${COMPLETION_SENTINEL_PREFIX}$__t3c"`;
140+
function resolveCompletionShell(
141+
platform: NodeJS.Platform,
142+
env: NodeJS.ProcessEnv,
143+
): CompletionShell {
144+
if (platform === "win32") return "powershell";
145+
const shell = env.SHELL ?? "";
146+
const name = shell.split("/").at(-1) ?? shell;
147+
if (name === "fish") return "fish";
148+
if (name === "pwsh" || name === "powershell") return "powershell";
149+
return "posix";
150+
}
151+
152+
/**
153+
* Builds the shell input for the setup script. The command runs inside a
154+
* block and the block closes on its own line, so a trailing `# comment` or a
155+
* heredoc terminator in the command cannot swallow the sentinel. The shell
156+
* reads the whole block before running any of it, so a script that reads
157+
* stdin cannot consume the sentinel line either. Lines are separated by `\r`
158+
* because that is the Enter key for every shell's line editor.
159+
*/
160+
function wrapCommandForCompletion(command: string, shell: CompletionShell): string {
161+
const body = command.replace(/\r?\n/g, "\r");
162+
switch (shell) {
163+
case "powershell":
164+
return `$global:LASTEXITCODE = $null; & {\r${body}\r}; if ($null -ne $LASTEXITCODE) { $__t3c = $LASTEXITCODE } elseif ($?) { $__t3c = 0 } else { $__t3c = 1 }; Write-Host "${COMPLETION_SENTINEL_PREFIX}$__t3c"`;
165+
case "fish":
166+
return `begin\r${body}\rend; printf '\\n${COMPLETION_SENTINEL_PREFIX}%s\\n' $status`;
167+
case "posix":
168+
return `( ${body}\r); printf '\\n${COMPLETION_SENTINEL_PREFIX}%s\\n' "$?"`;
142169
}
143-
return `( ${command} ); printf '\\n${COMPLETION_SENTINEL_PREFIX}%s\\n' "$?"`;
144170
}
145171

172+
/** @public Service construction is part of the canonical Effect module API. */
146173
export const make = Effect.gen(function* () {
147174
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
148175
const terminalManager = yield* TerminalManager.TerminalManager;
149176
const serverSettings = yield* ServerSettings.ServerSettingsService;
150-
const platform = yield* HostProcessPlatform;
177+
const completionShell = resolveCompletionShell(
178+
yield* HostProcessPlatform,
179+
yield* HostProcessEnvironment,
180+
);
151181

152182
/**
153183
* Watches the setup terminal for the completion sentinel. Terminal output is
@@ -157,6 +187,8 @@ export const make = Effect.gen(function* () {
157187
const observeTerminalCompletion = (input: {
158188
readonly threadId: string;
159189
readonly terminalId: string;
190+
/** The shell echoes typed input; lines ending with these are the wrapper, not output. */
191+
readonly echoedWrapperLines: ReadonlyArray<string>;
160192
readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
161193
}) =>
162194
Effect.gen(function* () {
@@ -185,10 +217,10 @@ export const make = Effect.gen(function* () {
185217
return settle(Number.isFinite(parsed) ? parsed : null);
186218
}
187219
const cleaned = stripTerminalControl(rawLine).trimEnd();
188-
// The echoed command line itself contains the sentinel prefix; hide it.
189220
if (
190221
cleaned.length === 0 ||
191222
cleaned.includes(COMPLETION_SENTINEL_PREFIX) ||
223+
input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||
192224
input.onOutputLine === undefined
193225
) {
194226
return Effect.void;
@@ -215,7 +247,7 @@ export const make = Effect.gen(function* () {
215247
const completion = Deferred.await(done).pipe(
216248
Effect.ensuring(Effect.sync(() => unsubscribe())),
217249
);
218-
return completion;
250+
return { completion, unsubscribe };
219251
});
220252

221253
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
@@ -285,7 +317,7 @@ export const make = Effect.gen(function* () {
285317
});
286318
const observe = input.observeCompletion;
287319
const commandLine = observe
288-
? wrapCommandForCompletion(script.command, platform)
320+
? wrapCommandForCompletion(script.command, completionShell)
289321
: script.command;
290322

291323
yield* terminalManager
@@ -307,10 +339,11 @@ export const make = Effect.gen(function* () {
307339
),
308340
);
309341
// Subscribe before writing so the sentinel cannot race past the listener.
310-
const completion = observe
342+
const observed = observe
311343
? yield* observeTerminalCompletion({
312344
threadId: input.threadId,
313345
terminalId,
346+
echoedWrapperLines: commandLine.split("\r"),
314347
onOutputLine: observe.onOutputLine,
315348
})
316349
: undefined;
@@ -330,6 +363,8 @@ export const make = Effect.gen(function* () {
330363
cause,
331364
}),
332365
),
366+
// Nothing will ever settle the completion if the command never ran.
367+
Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
333368
);
334369

335370
return {
@@ -339,7 +374,7 @@ export const make = Effect.gen(function* () {
339374
scriptCommand: script.command,
340375
terminalId,
341376
cwd,
342-
...(completion ? { completion } : {}),
377+
...(observed ? { completion: observed.completion } : {}),
343378
} as const;
344379
});
345380

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,31 @@ describe("WorktreeSetupTracker", () => {
4747
}),
4848
);
4949

50+
it.effect("stream drops queued changes already folded into the initial snapshot", () =>
51+
Effect.gen(function* () {
52+
const tracker = yield* WorktreeSetupTracker.make;
53+
yield* tracker.begin({
54+
threadId,
55+
branch: null,
56+
baseRef: null,
57+
stages: ["agent"],
58+
fiber: null,
59+
});
60+
yield* tracker.stageStatus(threadId, "agent", "running");
61+
yield* tracker.stageStatus(threadId, "agent", "done");
62+
63+
// A late subscriber sees sequence 2 first and must never see 0 or 1.
64+
const collected = yield* tracker
65+
.stream(threadId)
66+
.pipe(Stream.take(2), Stream.runCollect, Effect.forkChild);
67+
yield* Effect.yieldNow;
68+
yield* tracker.finish(threadId, "done");
69+
70+
const snapshots = yield* Fiber.join(collected);
71+
expect(snapshots.map((snapshot) => snapshot?.sequence)).toEqual([2, 3]);
72+
}),
73+
);
74+
5075
it.effect("stream emits the current snapshot first and then every change", () =>
5176
Effect.gen(function* () {
5277
const tracker = yield* WorktreeSetupTracker.make;
@@ -84,6 +109,7 @@ describe("WorktreeSetupTracker", () => {
84109
yield* tracker.begin({ threadId, branch: null, baseRef: null, stages: ["agent"], fiber });
85110

86111
expect(yield* tracker.cancel(threadId)).toBe(true);
112+
// cancel returns only after the bootstrap fiber has unwound.
87113
const exit = yield* Fiber.await(fiber);
88114
expect(Exit.hasInterrupts(exit)).toBe(true);
89115

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

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,11 @@ export class WorktreeSetupTracker extends Context.Service<
6262
phase: "done" | "failed" | "cancelled",
6363
error?: string | null,
6464
) => Effect.Effect<void>;
65-
/** Interrupts the running bootstrap. Returns false when nothing is running. */
65+
/**
66+
* Interrupts the running bootstrap and waits for it to unwind, so the
67+
* caller's dispatch has already failed and rolled back when this returns.
68+
* Returns false when nothing is running.
69+
*/
6670
readonly cancel: (threadId: ThreadId) => Effect.Effect<boolean>;
6771
readonly get: (threadId: ThreadId) => Effect.Effect<WorktreeSetupSnapshot | null>;
6872
/** Emits the current snapshot (or null) first, then every change until unsubscribed. */
@@ -248,7 +252,7 @@ export const make = Effect.gen(function* () {
248252
if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {
249253
return false;
250254
}
251-
yield* Fiber.interrupt(tracked.fiber).pipe(Effect.forkDetach);
255+
yield* Fiber.interrupt(tracked.fiber);
252256
return true;
253257
});
254258

@@ -260,10 +264,17 @@ export const make = Effect.gen(function* () {
260264
Effect.gen(function* () {
261265
const subscription = yield* PubSub.subscribe(changes);
262266
const initial = yield* get(threadId);
267+
// Changes published between subscribing and reading `initial` are
268+
// already folded into it. Drop them so the client never steps back.
269+
const initialSequence = initial?.sequence ?? -1;
263270
return Stream.concat(
264271
Stream.make(initial),
265272
Stream.fromSubscription(subscription).pipe(
266-
Stream.filter((change) => change.threadId === threadId),
273+
Stream.filter(
274+
(change) =>
275+
change.threadId === threadId &&
276+
(change.snapshot === null || change.snapshot.sequence > initialSequence),
277+
),
267278
Stream.map((change) => change.snapshot),
268279
),
269280
);

0 commit comments

Comments
 (0)