Skip to content

Commit 73b206f

Browse files
authored
feat(web): show each worktree setup step and let users cancel it (#11372)
Starting a thread in a new worktree showed one static "Setting up worktree" line while git fetched, checked out files, and the setup script ran. Users could not tell which step was slow, see setup script output without hunting for the terminal, or stop a setup that was going wrong. The timeline now shows a card with each step and its elapsed time. Check out files has a percent bar fed by git's own progress output. The setup script step shows the last lines of its terminal inline and links to the full terminal. Cancel stops the bootstrap and removes the half built worktree. Work locally cancels, switches the draft to the project checkout, and resends. The server keeps an in-memory per-thread snapshot of the bootstrap stages and streams it over a new subscribeWorktreeSetup RPC. The bootstrap runs as a child fiber so worktreeSetup.cancel can interrupt it, and the turn handoff is uninterruptible. The setup script's exit code comes from a per-run sentinel echoed after the command in the setup PTY. Created with Claude Fable 5.1 in Claude Code.
1 parent b70015b commit 73b206f

24 files changed

Lines changed: 2352 additions & 79 deletions

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ export const RPC_REQUIRED_SCOPES = {
111111
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
112112
[WS_METHODS.providerUploadFeedback]: AuthOrchestrationOperateScope,
113113
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
114+
[WS_METHODS.subscribeWorktreeSetup]: AuthOrchestrationReadScope,
115+
[WS_METHODS.worktreeSetupCancel]: AuthOrchestrationOperateScope,
114116
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
115117
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
116118
[WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,

‎apps/server/src/git/GitWorkflowService.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export class GitWorkflowService extends Context.Service<
6969
) => Effect.Effect<VcsListRefsResult, GitCommandError>;
7070
readonly createWorktree: (
7171
input: VcsCreateWorktreeInput,
72+
options?: GitVcsDriver.CreateWorktreeOptions,
7273
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
7374
readonly fetchRemote: (input: {
7475
readonly cwd: string;
@@ -338,9 +339,9 @@ export const make = Effect.gen(function* () {
338339
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
339340
),
340341
),
341-
createWorktree: (input) =>
342+
createWorktree: (input, options) =>
342343
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
343-
Effect.andThen(git.createWorktree(input)),
344+
Effect.andThen(git.createWorktree(input, options)),
344345
),
345346
fetchRemote: (input) =>
346347
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(

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

Lines changed: 212 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it, vi } from "@effect/vitest";
2-
import { type OrchestrationProject, ProjectId } from "@t3tools/contracts";
2+
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";
@@ -54,23 +55,24 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
5455
searchThreads: () => Effect.succeed({ matches: [] }),
5556
});
5657

57-
const makeTerminalManagerLayer = (
58-
overrides: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
59-
) =>
58+
type TerminalOverrides = Pick<TerminalManager.TerminalManager["Service"], "open" | "write"> &
59+
Partial<Pick<TerminalManager.TerminalManager["Service"], "subscribe">>;
60+
61+
const makeTerminalManagerLayer = (overrides: TerminalOverrides) =>
6062
Layer.succeed(TerminalManager.TerminalManager, {
61-
...overrides,
6263
attachStream: () => Effect.die(new Error("unused")),
6364
resize: () => Effect.void,
6465
clear: () => Effect.void,
6566
restart: () => Effect.die(new Error("unused")),
6667
close: () => Effect.void,
6768
subscribe: () => Effect.succeed(() => undefined),
6869
subscribeMetadata: () => Effect.succeed(() => undefined),
70+
...overrides,
6971
});
7072

7173
const testLayer = (
7274
project: OrchestrationProject,
73-
terminal: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
75+
terminal: TerminalOverrides,
7476
settings = ServerSettings.layerTest(),
7577
) =>
7678
ProjectSetupScriptRunner.layer.pipe(
@@ -198,6 +200,7 @@ describe("ProjectSetupScriptRunner", () => {
198200
status: "started",
199201
scriptId: "setup",
200202
scriptName: "Setup",
203+
scriptCommand: "bun install",
201204
terminalId: "setup-setup",
202205
cwd: "/repo/worktrees/a",
203206
});
@@ -220,6 +223,209 @@ describe("ProjectSetupScriptRunner", () => {
220223
},
221224
);
222225

226+
it.effect(
227+
"wraps the command with a completion sentinel and resolves the exit code from terminal output",
228+
() => {
229+
const open = vi.fn(() =>
230+
Effect.succeed({
231+
threadId: "thread-1",
232+
terminalId: "setup-setup",
233+
cwd: "/repo/worktrees/a",
234+
worktreePath: "/repo/worktrees/a",
235+
status: "running" as const,
236+
pid: 123,
237+
history: "",
238+
exitCode: null,
239+
exitSignal: null,
240+
label: "setup-setup",
241+
updatedAt: "2026-01-01T00:00:00.000Z",
242+
}),
243+
);
244+
const writes: string[] = [];
245+
const write = vi.fn((input: { data: string }) =>
246+
Effect.sync(() => void writes.push(input.data)),
247+
);
248+
let listener: ((event: TerminalEvent) => Effect.Effect<void>) | null = null;
249+
const subscribe = vi.fn((next: (event: TerminalEvent) => Effect.Effect<void>) => {
250+
listener = next;
251+
return Effect.succeed(() => {
252+
listener = null;
253+
});
254+
});
255+
const project = makeProject([
256+
{
257+
id: "setup",
258+
name: "Setup",
259+
command: "bun install",
260+
icon: "configure",
261+
runOnWorktreeCreate: true,
262+
},
263+
]);
264+
const emit = (data: string) =>
265+
Effect.suspend(() =>
266+
listener
267+
? listener({ threadId: "thread-1", terminalId: "setup-setup", type: "output", data })
268+
: Effect.void,
269+
);
270+
271+
return Effect.gen(function* () {
272+
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
273+
const seen: string[] = [];
274+
const result = yield* runner.runForThread({
275+
threadId: "thread-1",
276+
projectCwd: "/repo/project",
277+
worktreePath: "/repo/worktrees/a",
278+
observeCompletion: {
279+
onOutputLine: (line) => Effect.sync(() => void seen.push(line)),
280+
},
281+
});
282+
expect(result.status).toBe("started");
283+
if (result.status !== "started") return;
284+
expect(result.completion).toBeDefined();
285+
286+
// The subscription is attached before the command is written.
287+
expect(subscribe).toHaveBeenCalledTimes(1);
288+
expect(writes).toHaveLength(1);
289+
// The block closes on its own line so a trailing comment in the
290+
// command cannot swallow the sentinel, and the sentinel carries a
291+
// per-run token so script output cannot spoof it.
292+
const written = writes[0] ?? "";
293+
const sentinel = /__T3_SETUP_DONE___[0-9a-f]{32}:/.exec(written)?.[0];
294+
expect(sentinel).toBeDefined();
295+
expect(written).toBe(`( bun install\r); printf '\\n${sentinel}%s\\n' "$?"\r`);
296+
297+
// Output arrives in chunks; partial lines are buffered until a newline,
298+
// control sequences are stripped, and the echoed wrapper is hidden.
299+
yield* emit(`( bun install\r\n> ); printf '\\n${sentinel}%s\\n' "$?"\r\n`);
300+
yield* emit("\u001b[32mResolving");
301+
yield* emit(" deps\u001b[0m\r\nDone in 2s\r\n");
302+
// A spoofed sentinel from the script itself must not settle completion.
303+
yield* emit("__T3_SETUP_DONE__:0\r\n");
304+
yield* emit(`__T3_SETUP_DONE___${"0".repeat(32)}:0\r\n`);
305+
yield* emit(`${sentinel}3\r\n`);
306+
307+
const completion = yield* result.completion!;
308+
expect(completion.exitCode).toBe(3);
309+
expect(seen).toEqual([
310+
"Resolving deps",
311+
"Done in 2s",
312+
"__T3_SETUP_DONE__:0",
313+
`__T3_SETUP_DONE___${"0".repeat(32)}:0`,
314+
]);
315+
// The subscription is torn down once the sentinel arrives.
316+
expect(listener).toBeNull();
317+
}).pipe(
318+
Effect.provide(testLayer(project, { open, write, subscribe })),
319+
Effect.provideService(HostProcessPlatform, "linux"),
320+
Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
321+
);
322+
},
323+
);
324+
325+
it.effect("unsubscribes from terminal output when the command cannot be written", () => {
326+
const open = vi.fn(() =>
327+
Effect.succeed({
328+
threadId: "thread-1",
329+
terminalId: "setup-setup",
330+
cwd: "/repo/worktrees/a",
331+
worktreePath: "/repo/worktrees/a",
332+
status: "running" as const,
333+
pid: 123,
334+
history: "",
335+
exitCode: null,
336+
exitSignal: null,
337+
label: "setup-setup",
338+
updatedAt: "2026-01-01T00:00:00.000Z",
339+
}),
340+
);
341+
const write = vi.fn(() =>
342+
Effect.fail(
343+
new TerminalManager.TerminalCwdStatError({ cwd: "/repo/worktrees/a", cause: {} }),
344+
),
345+
);
346+
const unsubscribe = vi.fn();
347+
const subscribe = vi.fn(() => Effect.succeed(unsubscribe));
348+
const project = makeProject([
349+
{
350+
id: "setup",
351+
name: "Setup",
352+
command: "bun install",
353+
icon: "configure",
354+
runOnWorktreeCreate: true,
355+
},
356+
]);
357+
358+
return Effect.gen(function* () {
359+
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
360+
const result = yield* runner
361+
.runForThread({
362+
threadId: "thread-1",
363+
projectCwd: "/repo/project",
364+
worktreePath: "/repo/worktrees/a",
365+
observeCompletion: {},
366+
})
367+
.pipe(Effect.result);
368+
expect(result._tag).toBe("Failure");
369+
expect(unsubscribe).toHaveBeenCalledTimes(1);
370+
}).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
371+
});
372+
373+
it.effect.each([
374+
{
375+
shell: "/usr/bin/fish",
376+
expected:
377+
/^begin\rbun install\rend; printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' \$status\r$/,
378+
},
379+
{
380+
shell: "/bin/bash",
381+
expected: /^\( bun install\r\); printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' "\$\?"\r$/,
382+
},
383+
])("wraps the command for the $shell syntax", ({ shell, expected }) => {
384+
const open = vi.fn(() =>
385+
Effect.succeed({
386+
threadId: "thread-1",
387+
terminalId: "setup-setup",
388+
cwd: "/repo/worktrees/a",
389+
worktreePath: "/repo/worktrees/a",
390+
status: "running" as const,
391+
pid: 123,
392+
history: "",
393+
exitCode: null,
394+
exitSignal: null,
395+
label: "setup-setup",
396+
updatedAt: "2026-01-01T00:00:00.000Z",
397+
}),
398+
);
399+
const writes: string[] = [];
400+
const write = vi.fn((input: { data: string }) =>
401+
Effect.sync(() => void writes.push(input.data)),
402+
);
403+
const project = makeProject([
404+
{
405+
id: "setup",
406+
name: "Setup",
407+
command: "bun install",
408+
icon: "configure",
409+
runOnWorktreeCreate: true,
410+
},
411+
]);
412+
return Effect.gen(function* () {
413+
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
414+
yield* runner.runForThread({
415+
threadId: "thread-1",
416+
projectCwd: "/repo/project",
417+
worktreePath: "/repo/worktrees/a",
418+
observeCompletion: {},
419+
});
420+
expect(writes).toHaveLength(1);
421+
expect(writes[0]).toMatch(expected);
422+
}).pipe(
423+
Effect.provide(testLayer(project, { open, write })),
424+
Effect.provideService(HostProcessPlatform, "linux"),
425+
Effect.provideService(HostProcessEnvironment, { SHELL: shell }),
426+
);
427+
});
428+
223429
it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
224430
const rootCause = new Error("stat failed");
225431
const terminalError = new TerminalManager.TerminalCwdStatError({

0 commit comments

Comments
 (0)