Skip to content

Commit 5ea6439

Browse files
feat(web): inline worktree setup rows and async setup scripts (pingdotgg#11832)
Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 6dbea7e commit 5ea6439

18 files changed

Lines changed: 590 additions & 144 deletions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ describe("ProjectSetupScriptRunner", () => {
203203
scriptCommand: "bun install",
204204
terminalId: "setup-setup",
205205
cwd: "/repo/worktrees/a",
206+
async: true,
206207
});
207208
expect(open).toHaveBeenCalledWith({
208209
threadId: "thread-1",

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ export interface ProjectSetupScriptRunnerResultStarted {
3030
readonly scriptCommand: string;
3131
readonly terminalId: string;
3232
readonly cwd: string;
33+
/** False when the script's `async` flag asks the agent to wait for it. */
34+
readonly async: boolean;
3335
/**
3436
* Resolves when the script's shell prints the completion sentinel. The
3537
* exit code is null when the terminal exited or was closed before the
@@ -410,6 +412,7 @@ export const make = Effect.gen(function* () {
410412
scriptCommand: script.command,
411413
terminalId,
412414
cwd,
415+
async: script.async !== false,
413416
...(observed ? { completion: observed.completion } : {}),
414417
} as const;
415418
});

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

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ import {
4444
WS_METHODS,
4545
WsRpcGroup,
4646
EditorId,
47+
type WorktreeSetupSnapshot,
48+
type WorktreeSetupStageId,
4749
} from "@t3tools/contracts";
4850
import {
4951
computeDpopAccessTokenHash,
@@ -10759,6 +10761,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
1075910761
scriptCommand: "npm install",
1076010762
terminalId: "setup-setup",
1076110763
cwd: "/tmp/bootstrap-worktree",
10764+
async: true,
1076210765
}),
1076310766
);
1076410767

@@ -11324,6 +11327,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
1132411327
scriptCommand: "npm install",
1132511328
terminalId: "setup-setup",
1132611329
cwd: "/tmp/bootstrap-worktree",
11330+
async: true,
1132711331
}),
1132811332
);
1132911333
let setupActivityAppendAttempt = 0;
@@ -11427,6 +11431,153 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
1142711431
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
1142811432
);
1142911433

11434+
it.effect.each([
11435+
{ caseName: "async setup scripts let the turn start before the script exits", async: true },
11436+
{ caseName: "sync setup scripts hold the turn until the script exits", async: false },
11437+
])("$caseName", ({ async }) =>
11438+
Effect.gen(function* () {
11439+
const dispatchedCommands: Array<OrchestrationCommand> = [];
11440+
const scriptExit = yield* Deferred.make<void>();
11441+
const runForThread = vi.fn(
11442+
(
11443+
_: Parameters<
11444+
ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]
11445+
>[0],
11446+
) =>
11447+
Effect.succeed({
11448+
status: "started" as const,
11449+
scriptId: "setup",
11450+
scriptName: "Setup",
11451+
scriptCommand: "npm install",
11452+
terminalId: "setup-setup",
11453+
cwd: "/tmp/bootstrap-worktree",
11454+
async,
11455+
completion: Deferred.await(scriptExit).pipe(Effect.as({ exitCode: 0, durationMs: 1 })),
11456+
}),
11457+
);
11458+
11459+
yield* buildAppUnderTest({
11460+
layers: {
11461+
vcsDriver: {
11462+
isInsideWorkTree: () => Effect.succeed(true),
11463+
},
11464+
gitVcsDriver: {
11465+
execute: () => Effect.succeed(SUCCESSFUL_GIT_EXECUTION),
11466+
createWorktree: () =>
11467+
Effect.succeed({
11468+
worktree: {
11469+
refName: "t3code/bootstrap-refName",
11470+
path: "/tmp/bootstrap-worktree",
11471+
},
11472+
}),
11473+
},
11474+
orchestrationEngine: {
11475+
dispatch: (command) =>
11476+
Effect.sync(() => {
11477+
dispatchedCommands.push(command);
11478+
return { sequence: dispatchedCommands.length };
11479+
}),
11480+
readEvents: () => Stream.empty,
11481+
},
11482+
projectSetupScriptRunner: {
11483+
runForThread,
11484+
},
11485+
},
11486+
});
11487+
11488+
const createdAt = "2026-01-01T00:00:00.000Z";
11489+
const threadId = ThreadId.make(`thread-bootstrap-${async ? "async" : "sync"}-setup`);
11490+
const wsUrl = yield* getWsServerUrl("/ws");
11491+
const dispatchFiber = yield* Effect.scoped(
11492+
withWsRpcClient(wsUrl, (client) =>
11493+
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
11494+
type: "thread.turn.start",
11495+
commandId: CommandId.make(`cmd-bootstrap-${async ? "async" : "sync"}-setup`),
11496+
threadId,
11497+
message: {
11498+
messageId: MessageId.make("msg-bootstrap-setup"),
11499+
role: "user",
11500+
text: "hello",
11501+
attachments: [],
11502+
},
11503+
modelSelection: defaultModelSelection,
11504+
runtimeMode: "full-access",
11505+
interactionMode: "default",
11506+
bootstrap: {
11507+
createThread: {
11508+
projectId: defaultProjectId,
11509+
title: "Bootstrap Thread",
11510+
modelSelection: defaultModelSelection,
11511+
runtimeMode: "full-access",
11512+
interactionMode: "default",
11513+
branch: "main",
11514+
worktreePath: null,
11515+
createdAt,
11516+
},
11517+
prepareWorktree: {
11518+
projectCwd: "/tmp/project",
11519+
baseBranch: "main",
11520+
branch: "t3code/bootstrap-refName",
11521+
},
11522+
runSetupScript: true,
11523+
},
11524+
createdAt,
11525+
}),
11526+
),
11527+
).pipe(Effect.forkChild);
11528+
11529+
const turnStarted = () =>
11530+
dispatchedCommands.some((command) => command.type === "thread.turn.start");
11531+
const snapshotWhere = (predicate: (snapshot: WorktreeSetupSnapshot) => boolean) =>
11532+
Effect.scoped(
11533+
withWsRpcClient(wsUrl, (client) =>
11534+
client[WS_METHODS.subscribeWorktreeSetup]({ threadId }).pipe(
11535+
Stream.filter(
11536+
(snapshot): snapshot is WorktreeSetupSnapshot =>
11537+
snapshot !== null && predicate(snapshot),
11538+
),
11539+
Stream.runHead,
11540+
Effect.map(Option.getOrThrow),
11541+
),
11542+
),
11543+
);
11544+
const stageStatus = (snapshot: WorktreeSetupSnapshot, id: WorktreeSetupStageId) =>
11545+
snapshot.stages.find((stage) => stage.id === id)?.status;
11546+
11547+
if (async) {
11548+
// The turn is dispatched while the script is still running.
11549+
const started = yield* snapshotWhere(
11550+
(snapshot) => stageStatus(snapshot, "agent") === "done",
11551+
);
11552+
assertTrue(turnStarted());
11553+
assert.equal(started.phase, "running");
11554+
assert.equal(stageStatus(started, "setup-script"), "running");
11555+
yield* Fiber.join(dispatchFiber);
11556+
11557+
yield* Deferred.succeed(scriptExit, undefined);
11558+
const settled = yield* snapshotWhere((snapshot) => snapshot.phase !== "running");
11559+
assert.equal(settled.phase, "done");
11560+
assert.equal(stageStatus(settled, "setup-script"), "done");
11561+
return;
11562+
}
11563+
11564+
// The script is running and the turn has not been dispatched yet.
11565+
const running = yield* snapshotWhere(
11566+
(snapshot) => stageStatus(snapshot, "setup-script") === "running",
11567+
);
11568+
assert.equal(stageStatus(running, "agent"), "pending");
11569+
assert.isFalse(turnStarted());
11570+
11571+
yield* Deferred.succeed(scriptExit, undefined);
11572+
yield* Fiber.join(dispatchFiber);
11573+
assertTrue(turnStarted());
11574+
const settled = yield* snapshotWhere((snapshot) => snapshot.phase !== "running");
11575+
assert.equal(settled.phase, "done");
11576+
assert.equal(stageStatus(settled, "setup-script"), "done");
11577+
assert.equal(stageStatus(settled, "agent"), "done");
11578+
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
11579+
);
11580+
1143011581
it.effect("cleans up created bootstrap threads when worktree creation defects", () =>
1143111582
Effect.gen(function* () {
1143211583
const dispatchedCommands: Array<OrchestrationCommand> = [];

‎apps/server/src/ws.ts‎

Lines changed: 49 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1112,15 +1112,16 @@ const makeWsRpcLayer = (
11121112
const threadId = command.threadId;
11131113
const track = (effect: Effect.Effect<void>) => (tracked ? effect : Effect.void);
11141114

1115-
// Runs the setup script and, for tracked bootstraps, waits for it to
1116-
// exit so the card can show the exit code and the agent stage never
1117-
// starts on a half-installed tree. Untracked callers keep the old
1118-
// fire-and-forget behavior.
1115+
// Starts the setup script. For tracked bootstraps it returns the
1116+
// effect that waits for the script to exit and records the outcome
1117+
// on the card; whether the agent stage waits on it depends on the
1118+
// script's `async` flag. Returns null when nothing is left to await.
1119+
// Untracked callers keep the old fire-and-forget behavior.
11191120
const runSetupProgram = () =>
11201121
Effect.gen(function* () {
11211122
if (!bootstrap?.runSetupScript || !targetWorktreePath) {
11221123
yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "skipped"));
1123-
return;
1124+
return null;
11241125
}
11251126
const worktreePath = targetWorktreePath;
11261127
const requestedAt = yield* nowIso;
@@ -1197,21 +1198,38 @@ const makeWsRpcLayer = (
11971198
}),
11981199
);
11991200
if (!tracked || !setupResult?.completion) {
1200-
return;
1201+
return null;
12011202
}
12021203
// The setup script is best effort, like the untracked path: a
12031204
// failed install must not throw away the worktree the user just
12041205
// waited for. The card keeps the failed stage and its terminal.
1205-
const completion = yield* setupResult.completion;
1206-
if (completion.exitCode === 0) {
1207-
yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "done");
1208-
return;
1206+
// Forked right away so the terminal listener behind `completion`
1207+
// is always consumed, even when the turn dispatch fails before
1208+
// anyone would otherwise wait on it. The tracker update is a
1209+
// no-op once the snapshot has been dropped.
1210+
const completionFiber = yield* setupResult.completion.pipe(
1211+
Effect.flatMap((completion) => {
1212+
if (completion.exitCode === 0) {
1213+
return worktreeSetupTracker.stageStatus(threadId, "setup-script", "done");
1214+
}
1215+
const detail =
1216+
completion.exitCode === null
1217+
? "terminal closed before the script finished"
1218+
: `exit ${completion.exitCode}`;
1219+
return worktreeSetupTracker.stageStatus(
1220+
threadId,
1221+
"setup-script",
1222+
"failed",
1223+
detail,
1224+
);
1225+
}),
1226+
Effect.forkDetach,
1227+
);
1228+
if (!setupResult.async) {
1229+
yield* Fiber.join(completionFiber);
1230+
return null;
12091231
}
1210-
const detail =
1211-
completion.exitCode === null
1212-
? "terminal closed before the script finished"
1213-
: `exit ${completion.exitCode}`;
1214-
yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "failed", detail);
1232+
return completionFiber;
12151233
});
12161234

12171235
const bootstrapProgram = Effect.gen(function* () {
@@ -1414,7 +1432,7 @@ const makeWsRpcLayer = (
14141432
yield* refreshGitStatus(targetWorktreePath);
14151433
}
14161434

1417-
yield* runSetupProgram();
1435+
const pendingSetupScript = yield* runSetupProgram();
14181436

14191437
yield* track(worktreeSetupTracker.stageStatus(threadId, "agent", "running"));
14201438
// Past this point a cancel would roll back a thread whose turn has
@@ -1423,11 +1441,21 @@ const makeWsRpcLayer = (
14231441
const started = yield* Effect.uninterruptible(
14241442
dispatchFromClient(finalTurnStartCommand),
14251443
);
1426-
yield* track(
1427-
worktreeSetupTracker
1428-
.stageStatus(threadId, "agent", "done")
1429-
.pipe(Effect.andThen(worktreeSetupTracker.finish(threadId, "done"))),
1430-
);
1444+
yield* track(worktreeSetupTracker.stageStatus(threadId, "agent", "done"));
1445+
// An async setup script outlives the handoff: the snapshot stays
1446+
// running so the client keeps its row next to the agent's work,
1447+
// and settles when the script exits. The turn already started, so
1448+
// the wait cannot fail the dispatch.
1449+
const settle = track(worktreeSetupTracker.finish(threadId, "done"));
1450+
if (pendingSetupScript) {
1451+
yield* Fiber.join(pendingSetupScript).pipe(
1452+
Effect.ignoreCause({ log: true }),
1453+
Effect.andThen(settle),
1454+
Effect.forkDetach,
1455+
);
1456+
} else {
1457+
yield* settle;
1458+
}
14311459
return started;
14321460
});
14331461

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1430,6 +1430,16 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | n
14301430
return current.messageId === null ? current : { ...current, messageId: null };
14311431
}
14321432

1433+
/**
1434+
* Worktree setups whose async setup script may still be running after the
1435+
* draft route hands off to the created thread. Keyed by scoped thread key;
1436+
* entries are removed once the setup settles.
1437+
*/
1438+
const pendingWorktreeSetupByThreadKey = new Map<
1439+
string,
1440+
{ environmentId: EnvironmentId; threadId: ThreadId }
1441+
>();
1442+
14331443
export default function ChatView(props: ChatViewProps) {
14341444
const {
14351445
environmentId,
@@ -1659,7 +1669,12 @@ export default function ChatView(props: ChatViewProps) {
16591669
environmentId: EnvironmentId;
16601670
threadId: ThreadId;
16611671
ownerKey: string;
1662-
} | null>(null);
1672+
} | null>(() => {
1673+
// The draft route unmounts when it promotes to the created thread, while an
1674+
// async setup script may still be running. Adopt the ref the draft left.
1675+
const handed = pendingWorktreeSetupByThreadKey.get(routeThreadKey);
1676+
return handed ? { ...handed, ownerKey: routeThreadKey } : null;
1677+
});
16631678
const [heldWorktreeSetup, setHeldWorktreeSetup] = useState<WorktreeSetupSnapshot | null>(null);
16641679
// Set by "Work locally": the draft whose restored message should be resent
16651680
// once the cancelled dispatch has settled and the draft is in local mode.
@@ -3500,14 +3515,28 @@ export default function ChatView(props: ChatViewProps) {
35003515
? heldWorktreeSetup
35013516
: null;
35023517
// A finished card is dropped once the agent's turn shows in the timeline:
3503-
// the card belongs to the send, and the agent takes over from there.
3518+
// the card belongs to the send, and the agent takes over from there. An
3519+
// async setup script keeps the snapshot running past the handoff and its
3520+
// row leaves the moment the script exits cleanly; a failed script stays
3521+
// for the rest of the turn so the exit code and terminal remain reachable.
35043522
const worktreeSetupDoneAndTurnVisible =
3505-
worktreeSetup?.phase === "done" && activeThread?.latestTurn?.startedAt != null;
3523+
worktreeSetup?.phase === "done" &&
3524+
activeThread?.latestTurn?.startedAt != null &&
3525+
(!isWorking || !worktreeSetup.stages.some((stage) => stage.status === "failed"));
35063526
useEffect(() => {
35073527
if (!worktreeSetupDoneAndTurnVisible) return;
35083528
setWorktreeSetupRef(null);
35093529
setHeldWorktreeSetup(null);
35103530
}, [worktreeSetupDoneAndTurnVisible]);
3531+
// The handoff entry only matters while the setup is still running: once it
3532+
// settles in any phase, a later mount of the thread must not adopt it.
3533+
const worktreeSetupSettledKey =
3534+
worktreeSetup && worktreeSetup.phase !== "running" && worktreeSetupRef
3535+
? scopedThreadKey(scopeThreadRef(worktreeSetupRef.environmentId, worktreeSetupRef.threadId))
3536+
: null;
3537+
useEffect(() => {
3538+
if (worktreeSetupSettledKey) pendingWorktreeSetupByThreadKey.delete(worktreeSetupSettledKey);
3539+
}, [worktreeSetupSettledKey]);
35113540
const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
35123541
reportFailure: false,
35133542
});
@@ -7515,6 +7544,12 @@ export default function ChatView(props: ChatViewProps) {
75157544
? { environmentId, threadId: threadIdForSend, ownerKey: worktreeSetupOwnerKey }
75167545
: null,
75177546
);
7547+
if (baseBranchForWorktree) {
7548+
pendingWorktreeSetupByThreadKey.set(
7549+
scopedThreadKey(scopeThreadRef(environmentId, threadIdForSend)),
7550+
{ environmentId, threadId: threadIdForSend },
7551+
);
7552+
}
75187553

75197554
const messageIdForSend = newMessageId();
75207555
const messageCreatedAt = new Date().toISOString();

‎apps/web/src/components/ProjectScriptsControl.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ export default function ProjectScriptsControl({
113113
command: fileScript.command,
114114
icon: fileScript.icon ?? "play",
115115
runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
116+
waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
116117
keybinding: null,
117118
previewUrl: fileScript.previewUrl ?? null,
118119
autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,

0 commit comments

Comments
 (0)