Skip to content

Commit 70ec8f4

Browse files
t3dotggclaude
andcommitted
feat(web): show live worktree setup progress in the thread
Starting a worktree thread only showed "Setting up worktree" while git fetched, checked out files, and the setup script ran. Users could not see which step took the time or stop it. The server now tracks each bootstrap stage in memory and streams it over a new subscribeWorktreeSetup RPC. The web timeline renders a card with per stage status, checkout percent from git's progress output, the tail of the setup script terminal, and Cancel and Work locally actions. A worktreeSetup.cancel RPC interrupts the bootstrap fiber and removes the half built worktree. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent e816064 commit 70ec8f4

20 files changed

Lines changed: 1593 additions & 79 deletions

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ export const RPC_REQUIRED_SCOPES = {
109109
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
110110
[WS_METHODS.providerUploadFeedback]: AuthOrchestrationOperateScope,
111111
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
112+
[WS_METHODS.subscribeWorktreeSetup]: AuthOrchestrationReadScope,
113+
[WS_METHODS.worktreeSetupCancel]: AuthOrchestrationOperateScope,
112114
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
113115
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
114116
[WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ export class GitWorkflowService extends Context.Service<
6464
) => Effect.Effect<VcsListRefsResult, GitCommandError>;
6565
readonly createWorktree: (
6666
input: VcsCreateWorktreeInput,
67+
options?: GitVcsDriver.CreateWorktreeOptions,
6768
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
6869
readonly fetchRemote: (input: {
6970
readonly cwd: string;
@@ -308,9 +309,9 @@ export const make = Effect.gen(function* () {
308309
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
309310
),
310311
),
311-
createWorktree: (input) =>
312+
createWorktree: (input, options) =>
312313
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
313-
Effect.andThen(git.createWorktree(input)),
314+
Effect.andThen(git.createWorktree(input, options)),
314315
),
315316
fetchRemote: (input) =>
316317
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(

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

Lines changed: 90 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
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";
33
import * as Effect from "effect/Effect";
44
import * as Layer from "effect/Layer";
55
import * as Option from "effect/Option";
@@ -53,23 +53,24 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
5353
searchThreads: () => Effect.succeed({ matches: [] }),
5454
});
5555

56-
const makeTerminalManagerLayer = (
57-
overrides: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
58-
) =>
56+
type TerminalOverrides = Pick<TerminalManager.TerminalManager["Service"], "open" | "write"> &
57+
Partial<Pick<TerminalManager.TerminalManager["Service"], "subscribe">>;
58+
59+
const makeTerminalManagerLayer = (overrides: TerminalOverrides) =>
5960
Layer.succeed(TerminalManager.TerminalManager, {
60-
...overrides,
6161
attachStream: () => Effect.die(new Error("unused")),
6262
resize: () => Effect.void,
6363
clear: () => Effect.void,
6464
restart: () => Effect.die(new Error("unused")),
6565
close: () => Effect.void,
6666
subscribe: () => Effect.succeed(() => undefined),
6767
subscribeMetadata: () => Effect.succeed(() => undefined),
68+
...overrides,
6869
});
6970

7071
const testLayer = (
7172
project: OrchestrationProject,
72-
terminal: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
73+
terminal: TerminalOverrides,
7374
settings = ServerSettings.layerTest(),
7475
) =>
7576
ProjectSetupScriptRunner.layer.pipe(
@@ -197,6 +198,7 @@ describe("ProjectSetupScriptRunner", () => {
197198
status: "started",
198199
scriptId: "setup",
199200
scriptName: "Setup",
201+
scriptCommand: "bun install",
200202
terminalId: "setup-setup",
201203
cwd: "/repo/worktrees/a",
202204
});
@@ -219,6 +221,88 @@ describe("ProjectSetupScriptRunner", () => {
219221
},
220222
);
221223

224+
it.effect(
225+
"wraps the command with a completion sentinel and resolves the exit code from terminal output",
226+
() => {
227+
const open = vi.fn(() =>
228+
Effect.succeed({
229+
threadId: "thread-1",
230+
terminalId: "setup-setup",
231+
cwd: "/repo/worktrees/a",
232+
worktreePath: "/repo/worktrees/a",
233+
status: "running" as const,
234+
pid: 123,
235+
history: "",
236+
exitCode: null,
237+
exitSignal: null,
238+
label: "setup-setup",
239+
updatedAt: "2026-01-01T00:00:00.000Z",
240+
}),
241+
);
242+
const writes: string[] = [];
243+
const write = vi.fn((input: { data: string }) =>
244+
Effect.sync(() => void writes.push(input.data)),
245+
);
246+
let listener: ((event: TerminalEvent) => Effect.Effect<void>) | null = null;
247+
const subscribe = vi.fn((next: (event: TerminalEvent) => Effect.Effect<void>) => {
248+
listener = next;
249+
return Effect.succeed(() => {
250+
listener = null;
251+
});
252+
});
253+
const project = makeProject([
254+
{
255+
id: "setup",
256+
name: "Setup",
257+
command: "bun install",
258+
icon: "configure",
259+
runOnWorktreeCreate: true,
260+
},
261+
]);
262+
const emit = (data: string) =>
263+
Effect.suspend(() =>
264+
listener
265+
? listener({ threadId: "thread-1", terminalId: "setup-setup", type: "output", data })
266+
: Effect.void,
267+
);
268+
269+
return Effect.gen(function* () {
270+
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
271+
const seen: string[] = [];
272+
const result = yield* runner.runForThread({
273+
threadId: "thread-1",
274+
projectCwd: "/repo/project",
275+
worktreePath: "/repo/worktrees/a",
276+
observeCompletion: {
277+
onOutputLine: (line) => Effect.sync(() => void seen.push(line)),
278+
},
279+
});
280+
expect(result.status).toBe("started");
281+
if (result.status !== "started") return;
282+
expect(result.completion).toBeDefined();
283+
284+
// The subscription is attached before the command is written.
285+
expect(subscribe).toHaveBeenCalledTimes(1);
286+
expect(writes).toHaveLength(1);
287+
expect(writes[0]?.startsWith("( bun install );")).toBe(true);
288+
expect(writes[0]).toContain("__T3_SETUP_DONE__:");
289+
290+
// 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+
yield* emit("\u001b[32mResolving");
294+
yield* emit(" deps\u001b[0m\r\nDone in 2s\r\n");
295+
yield* emit("__T3_SETUP_DONE__:3\r\n");
296+
297+
const completion = yield* result.completion!;
298+
expect(completion.exitCode).toBe(3);
299+
expect(seen).toEqual(["Resolving deps", "Done in 2s"]);
300+
// The subscription is torn down once the sentinel arrives.
301+
expect(listener).toBeNull();
302+
}).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
303+
},
304+
);
305+
222306
it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
223307
const rootCause = new Error("stat failed");
224308
const terminalError = new TerminalManager.TerminalCwdStatError({

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

Lines changed: 145 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import { ProjectId } from "@t3tools/contracts";
2+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
23
import {
34
projectScriptRuntimeEnv,
45
resolveProjectScripts,
56
setupProjectScript,
67
} from "@t3tools/shared/projectScripts";
8+
import * as Clock from "effect/Clock";
79
import * as Context from "effect/Context";
10+
import * as Deferred from "effect/Deferred";
811
import * as Effect from "effect/Effect";
912
import * as Layer from "effect/Layer";
1013
import * as Option from "effect/Option";
@@ -22,8 +25,24 @@ export interface ProjectSetupScriptRunnerResultStarted {
2225
readonly status: "started";
2326
readonly scriptId: string;
2427
readonly scriptName: string;
28+
readonly scriptCommand: string;
2529
readonly terminalId: string;
2630
readonly cwd: string;
31+
/**
32+
* Resolves when the script's shell prints the completion sentinel. The
33+
* exit code is null when the terminal exited or was closed before the
34+
* sentinel arrived. Only present when `observeCompletion` was requested.
35+
*/
36+
readonly completion?: Effect.Effect<ProjectSetupScriptCompletion>;
37+
}
38+
39+
export interface ProjectSetupScriptCompletion {
40+
readonly exitCode: number | null;
41+
readonly durationMs: number;
42+
}
43+
44+
export interface ProjectSetupScriptOutputLine {
45+
readonly line: string;
2746
}
2847

2948
export type ProjectSetupScriptRunnerResult =
@@ -36,6 +55,14 @@ export interface ProjectSetupScriptRunnerInput {
3655
readonly projectCwd?: string;
3756
readonly worktreePath: string;
3857
readonly preferredTerminalId?: string;
58+
/**
59+
* Wrap the command so the shell reports its exit code back through the
60+
* terminal stream, and forward cleaned output lines while it runs. The
61+
* bootstrap flow uses this to drive the worktree setup card.
62+
*/
63+
readonly observeCompletion?: {
64+
readonly onOutputLine?: (line: string) => Effect.Effect<void>;
65+
};
3966
}
4067

4168
export class ProjectSetupScriptOperationError extends Schema.TaggedError<ProjectSetupScriptOperationError>()(
@@ -84,10 +111,112 @@ export class ProjectSetupScriptRunner extends Context.Service<
84111
>()("t3/project/ProjectSetupScriptRunner") {}
85112

86113
/** @public Service construction is part of the canonical Effect module API. */
114+
/** Marker the wrapped setup command echoes so the exit code can be read from the PTY stream. */
115+
const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__:";
116+
const COMPLETION_SENTINEL_PATTERN = /__T3_SETUP_DONE__:(-?\d+)/;
117+
const OUTPUT_LINE_MAX_LENGTH = 400;
118+
119+
/** Removes ANSI escape sequences and cursor controls so lines can be shown as plain text. */
120+
function stripTerminalControl(text: string): string {
121+
return (
122+
text
123+
.replace(
124+
// eslint-disable-next-line no-control-regex
125+
/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,
126+
"",
127+
)
128+
// eslint-disable-next-line no-control-regex
129+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "")
130+
);
131+
}
132+
133+
/**
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.
138+
*/
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"`;
142+
}
143+
return `( ${command} ); printf '\\n${COMPLETION_SENTINEL_PREFIX}%s\\n' "$?"`;
144+
}
145+
87146
export const make = Effect.gen(function* () {
88147
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
89148
const terminalManager = yield* TerminalManager.TerminalManager;
90149
const serverSettings = yield* ServerSettings.ServerSettingsService;
150+
const platform = yield* HostProcessPlatform;
151+
152+
/**
153+
* Watches the setup terminal for the completion sentinel. Terminal output is
154+
* a byte stream, so partial lines are buffered until a newline. The
155+
* subscription is torn down once the sentinel, an exit, or a close arrives.
156+
*/
157+
const observeTerminalCompletion = (input: {
158+
readonly threadId: string;
159+
readonly terminalId: string;
160+
readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
161+
}) =>
162+
Effect.gen(function* () {
163+
const startedAtMs = yield* Clock.currentTimeMillis;
164+
const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
165+
let lineBuffer = "";
166+
let settled = false;
167+
168+
const settle = (exitCode: number | null) =>
169+
Effect.suspend(() => {
170+
if (settled) return Effect.void;
171+
settled = true;
172+
return Clock.currentTimeMillis.pipe(
173+
Effect.flatMap((nowMs) =>
174+
Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),
175+
),
176+
Effect.asVoid,
177+
);
178+
});
179+
180+
const handleLine = (rawLine: string) =>
181+
Effect.suspend(() => {
182+
const sentinel = COMPLETION_SENTINEL_PATTERN.exec(rawLine);
183+
if (sentinel) {
184+
const parsed = Number(sentinel[1]);
185+
return settle(Number.isFinite(parsed) ? parsed : null);
186+
}
187+
const cleaned = stripTerminalControl(rawLine).trimEnd();
188+
// The echoed command line itself contains the sentinel prefix; hide it.
189+
if (
190+
cleaned.length === 0 ||
191+
cleaned.includes(COMPLETION_SENTINEL_PREFIX) ||
192+
input.onOutputLine === undefined
193+
) {
194+
return Effect.void;
195+
}
196+
return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH));
197+
});
198+
199+
const unsubscribe = yield* terminalManager.subscribe((event) => {
200+
if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
201+
return Effect.void;
202+
}
203+
if (event.type === "output") {
204+
lineBuffer += event.data;
205+
const lines = lineBuffer.split(/\r?\n/);
206+
lineBuffer = lines.pop() ?? "";
207+
return Effect.forEach(lines, handleLine, { discard: true });
208+
}
209+
if (event.type === "exited" || event.type === "closed") {
210+
return settle(null);
211+
}
212+
return Effect.void;
213+
});
214+
215+
const completion = Deferred.await(done).pipe(
216+
Effect.ensuring(Effect.sync(() => unsubscribe())),
217+
);
218+
return completion;
219+
});
91220

92221
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
93222
"ProjectSetupScriptRunner.runForThread",
@@ -154,6 +283,10 @@ export const make = Effect.gen(function* () {
154283
project: { cwd: project.workspaceRoot },
155284
worktreePath: input.worktreePath,
156285
});
286+
const observe = input.observeCompletion;
287+
const commandLine = observe
288+
? wrapCommandForCompletion(script.command, platform)
289+
: script.command;
157290

158291
yield* terminalManager
159292
.open({
@@ -173,11 +306,20 @@ export const make = Effect.gen(function* () {
173306
}),
174307
),
175308
);
309+
// Subscribe before writing so the sentinel cannot race past the listener.
310+
const completion = observe
311+
? yield* observeTerminalCompletion({
312+
threadId: input.threadId,
313+
terminalId,
314+
onOutputLine: observe.onOutputLine,
315+
})
316+
: undefined;
317+
176318
yield* terminalManager
177319
.write({
178320
threadId: input.threadId,
179321
terminalId,
180-
data: `${script.command}\r`,
322+
data: `${commandLine}\r`,
181323
})
182324
.pipe(
183325
Effect.mapError(
@@ -194,8 +336,10 @@ export const make = Effect.gen(function* () {
194336
status: "started",
195337
scriptId: script.id,
196338
scriptName: script.name,
339+
scriptCommand: script.command,
197340
terminalId,
198341
cwd,
342+
...(completion ? { completion } : {}),
199343
} as const;
200344
});
201345

0 commit comments

Comments
 (0)