TypeScript
feat(web): inline worktree setup rows and async setup scripts (#11832)
Julius Marminge5ea643981647
diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.tsindex c0d15f105af..d9d74d92671 100644--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts@@ -203,6 +203,7 @@ describe("ProjectSetupScriptRunner", () => {scriptCommand: "bun install",terminalId: "setup-setup",cwd: "/repo/worktrees/a",+ async: true,});expect(open).toHaveBeenCalledWith({threadId: "thread-1",diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.tsindex c80dd535f51..d69198e3091 100644--- a/apps/server/src/project/ProjectSetupScriptRunner.ts+++ b/apps/server/src/project/ProjectSetupScriptRunner.ts@@ -30,6 +30,8 @@ export interface ProjectSetupScriptRunnerResultStarted {readonly scriptCommand: string;readonly terminalId: string;readonly cwd: string;+ /** False when the script's `async` flag asks the agent to wait for it. */+ readonly async: boolean;/*** Resolves when the script's shell prints the completion sentinel. The* exit code is null when the terminal exited or was closed before the@@ -410,6 +412,7 @@ export const make = Effect.gen(function* () {scriptCommand: script.command,terminalId,cwd,+ async: script.async !== false,...(observed ? { completion: observed.completion } : {}),} as const;});diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 0411a082696..b21d18de6b1 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -44,6 +44,8 @@ import {WS_METHODS,WsRpcGroup,EditorId,+ type WorktreeSetupSnapshot,+ type WorktreeSetupStageId,} from "@t3tools/contracts";import {computeDpopAccessTokenHash,@@ -10759,6 +10761,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {scriptCommand: "npm install",terminalId: "setup-setup",cwd: "/tmp/bootstrap-worktree",+ async: true,}),);@@ -11324,6 +11327,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {scriptCommand: "npm install",terminalId: "setup-setup",cwd: "/tmp/bootstrap-worktree",+ async: true,}),);let setupActivityAppendAttempt = 0;@@ -11427,6 +11431,153 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);+ it.effect.each([+ { caseName: "async setup scripts let the turn start before the script exits", async: true },+ { caseName: "sync setup scripts hold the turn until the script exits", async: false },+ ])("$caseName", ({ async }) =>+ Effect.gen(function* () {+ const dispatchedCommands: Array<OrchestrationCommand> = [];+ const scriptExit = yield* Deferred.make<void>();+ const runForThread = vi.fn(+ (+ _: Parameters<+ ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"]+ >[0],+ ) =>+ Effect.succeed({+ status: "started" as const,+ scriptId: "setup",+ scriptName: "Setup",+ scriptCommand: "npm install",+ terminalId: "setup-setup",+ cwd: "/tmp/bootstrap-worktree",+ async,+ completion: Deferred.await(scriptExit).pipe(Effect.as({ exitCode: 0, durationMs: 1 })),+ }),+ );++ yield* buildAppUnderTest({+ layers: {+ vcsDriver: {+ isInsideWorkTree: () => Effect.succeed(true),+ },+ gitVcsDriver: {+ execute: () => Effect.succeed(SUCCESSFUL_GIT_EXECUTION),+ createWorktree: () =>+ Effect.succeed({+ worktree: {+ refName: "t3code/bootstrap-refName",+ path: "/tmp/bootstrap-worktree",+ },+ }),+ },+ orchestrationEngine: {+ dispatch: (command) =>+ Effect.sync(() => {+ dispatchedCommands.push(command);+ return { sequence: dispatchedCommands.length };+ }),+ readEvents: () => Stream.empty,+ },+ projectSetupScriptRunner: {+ runForThread,+ },+ },+ });++ const createdAt = "2026-01-01T00:00:00.000Z";+ const threadId = ThreadId.make(`thread-bootstrap-${async ? "async" : "sync"}-setup`);+ const wsUrl = yield* getWsServerUrl("/ws");+ const dispatchFiber = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.dispatchCommand]({+ type: "thread.turn.start",+ commandId: CommandId.make(`cmd-bootstrap-${async ? "async" : "sync"}-setup`),+ threadId,+ message: {+ messageId: MessageId.make("msg-bootstrap-setup"),+ role: "user",+ text: "hello",+ attachments: [],+ },+ modelSelection: defaultModelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ bootstrap: {+ createThread: {+ projectId: defaultProjectId,+ title: "Bootstrap Thread",+ modelSelection: defaultModelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: "main",+ worktreePath: null,+ createdAt,+ },+ prepareWorktree: {+ projectCwd: "/tmp/project",+ baseBranch: "main",+ branch: "t3code/bootstrap-refName",+ },+ runSetupScript: true,+ },+ createdAt,+ }),+ ),+ ).pipe(Effect.forkChild);++ const turnStarted = () =>+ dispatchedCommands.some((command) => command.type === "thread.turn.start");+ const snapshotWhere = (predicate: (snapshot: WorktreeSetupSnapshot) => boolean) =>+ Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[WS_METHODS.subscribeWorktreeSetup]({ threadId }).pipe(+ Stream.filter(+ (snapshot): snapshot is WorktreeSetupSnapshot =>+ snapshot !== null && predicate(snapshot),+ ),+ Stream.runHead,+ Effect.map(Option.getOrThrow),+ ),+ ),+ );+ const stageStatus = (snapshot: WorktreeSetupSnapshot, id: WorktreeSetupStageId) =>+ snapshot.stages.find((stage) => stage.id === id)?.status;++ if (async) {+ // The turn is dispatched while the script is still running.+ const started = yield* snapshotWhere(+ (snapshot) => stageStatus(snapshot, "agent") === "done",+ );+ assertTrue(turnStarted());+ assert.equal(started.phase, "running");+ assert.equal(stageStatus(started, "setup-script"), "running");+ yield* Fiber.join(dispatchFiber);++ yield* Deferred.succeed(scriptExit, undefined);+ const settled = yield* snapshotWhere((snapshot) => snapshot.phase !== "running");+ assert.equal(settled.phase, "done");+ assert.equal(stageStatus(settled, "setup-script"), "done");+ return;+ }++ // The script is running and the turn has not been dispatched yet.+ const running = yield* snapshotWhere(+ (snapshot) => stageStatus(snapshot, "setup-script") === "running",+ );+ assert.equal(stageStatus(running, "agent"), "pending");+ assert.isFalse(turnStarted());++ yield* Deferred.succeed(scriptExit, undefined);+ yield* Fiber.join(dispatchFiber);+ assertTrue(turnStarted());+ const settled = yield* snapshotWhere((snapshot) => snapshot.phase !== "running");+ assert.equal(settled.phase, "done");+ assert.equal(stageStatus(settled, "setup-script"), "done");+ assert.equal(stageStatus(settled, "agent"), "done");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );+it.effect("cleans up created bootstrap threads when worktree creation defects", () =>Effect.gen(function* () {const dispatchedCommands: Array<OrchestrationCommand> = [];diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex cec94e35887..2286387cadc 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -1112,15 +1112,16 @@ const makeWsRpcLayer = (const threadId = command.threadId;const track = (effect: Effect.Effect<void>) => (tracked ? effect : Effect.void);- // Runs the setup script and, for tracked bootstraps, waits for it to- // exit so the card can show the exit code and the agent stage never- // starts on a half-installed tree. Untracked callers keep the old- // fire-and-forget behavior.+ // Starts the setup script. For tracked bootstraps it returns the+ // effect that waits for the script to exit and records the outcome+ // on the card; whether the agent stage waits on it depends on the+ // script's `async` flag. Returns null when nothing is left to await.+ // Untracked callers keep the old fire-and-forget behavior.const runSetupProgram = () =>Effect.gen(function* () {if (!bootstrap?.runSetupScript || !targetWorktreePath) {yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "skipped"));- return;+ return null;}const worktreePath = targetWorktreePath;const requestedAt = yield* nowIso;@@ -1197,21 +1198,38 @@ const makeWsRpcLayer = (}),);if (!tracked || !setupResult?.completion) {- return;+ return null;}// The setup script is best effort, like the untracked path: a// failed install must not throw away the worktree the user just// waited for. The card keeps the failed stage and its terminal.- const completion = yield* setupResult.completion;- if (completion.exitCode === 0) {- yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "done");- return;+ // Forked right away so the terminal listener behind `completion`+ // is always consumed, even when the turn dispatch fails before+ // anyone would otherwise wait on it. The tracker update is a+ // no-op once the snapshot has been dropped.+ const completionFiber = yield* setupResult.completion.pipe(+ Effect.flatMap((completion) => {+ if (completion.exitCode === 0) {+ return worktreeSetupTracker.stageStatus(threadId, "setup-script", "done");+ }+ const detail =+ completion.exitCode === null+ ? "terminal closed before the script finished"+ : `exit ${completion.exitCode}`;+ return worktreeSetupTracker.stageStatus(+ threadId,+ "setup-script",+ "failed",+ detail,+ );+ }),+ Effect.forkDetach,+ );+ if (!setupResult.async) {+ yield* Fiber.join(completionFiber);+ return null;}- const detail =- completion.exitCode === null- ? "terminal closed before the script finished"- : `exit ${completion.exitCode}`;- yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "failed", detail);+ return completionFiber;});const bootstrapProgram = Effect.gen(function* () {@@ -1414,7 +1432,7 @@ const makeWsRpcLayer = (yield* refreshGitStatus(targetWorktreePath);}- yield* runSetupProgram();+ const pendingSetupScript = yield* runSetupProgram();yield* track(worktreeSetupTracker.stageStatus(threadId, "agent", "running"));// Past this point a cancel would roll back a thread whose turn has@@ -1423,11 +1441,21 @@ const makeWsRpcLayer = (const started = yield* Effect.uninterruptible(dispatchFromClient(finalTurnStartCommand),);- yield* track(- worktreeSetupTracker- .stageStatus(threadId, "agent", "done")- .pipe(Effect.andThen(worktreeSetupTracker.finish(threadId, "done"))),- );+ yield* track(worktreeSetupTracker.stageStatus(threadId, "agent", "done"));+ // An async setup script outlives the handoff: the snapshot stays+ // running so the client keeps its row next to the agent's work,+ // and settles when the script exits. The turn already started, so+ // the wait cannot fail the dispatch.+ const settle = track(worktreeSetupTracker.finish(threadId, "done"));+ if (pendingSetupScript) {+ yield* Fiber.join(pendingSetupScript).pipe(+ Effect.ignoreCause({ log: true }),+ Effect.andThen(settle),+ Effect.forkDetach,+ );+ } else {+ yield* settle;+ }return started;});diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 303427ebd2e..6b8c65410ed 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1430,6 +1430,16 @@ function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | nreturn current.messageId === null ? current : { ...current, messageId: null };}+/**+ * Worktree setups whose async setup script may still be running after the+ * draft route hands off to the created thread. Keyed by scoped thread key;+ * entries are removed once the setup settles.+ */+const pendingWorktreeSetupByThreadKey = new Map<+ string,+ { environmentId: EnvironmentId; threadId: ThreadId }+>();+export default function ChatView(props: ChatViewProps) {const {environmentId,@@ -1659,7 +1669,12 @@ export default function ChatView(props: ChatViewProps) {environmentId: EnvironmentId;threadId: ThreadId;ownerKey: string;- } | null>(null);+ } | null>(() => {+ // The draft route unmounts when it promotes to the created thread, while an+ // async setup script may still be running. Adopt the ref the draft left.+ const handed = pendingWorktreeSetupByThreadKey.get(routeThreadKey);+ return handed ? { ...handed, ownerKey: routeThreadKey } : null;+ });const [heldWorktreeSetup, setHeldWorktreeSetup] = useState<WorktreeSetupSnapshot | null>(null);// Set by "Work locally": the draft whose restored message should be resent// once the cancelled dispatch has settled and the draft is in local mode.@@ -3500,14 +3515,28 @@ export default function ChatView(props: ChatViewProps) {? heldWorktreeSetup: null;// A finished card is dropped once the agent's turn shows in the timeline:- // the card belongs to the send, and the agent takes over from there.+ // the card belongs to the send, and the agent takes over from there. An+ // async setup script keeps the snapshot running past the handoff and its+ // row leaves the moment the script exits cleanly; a failed script stays+ // for the rest of the turn so the exit code and terminal remain reachable.const worktreeSetupDoneAndTurnVisible =- worktreeSetup?.phase === "done" && activeThread?.latestTurn?.startedAt != null;+ worktreeSetup?.phase === "done" &&+ activeThread?.latestTurn?.startedAt != null &&+ (!isWorking || !worktreeSetup.stages.some((stage) => stage.status === "failed"));useEffect(() => {if (!worktreeSetupDoneAndTurnVisible) return;setWorktreeSetupRef(null);setHeldWorktreeSetup(null);}, [worktreeSetupDoneAndTurnVisible]);+ // The handoff entry only matters while the setup is still running: once it+ // settles in any phase, a later mount of the thread must not adopt it.+ const worktreeSetupSettledKey =+ worktreeSetup && worktreeSetup.phase !== "running" && worktreeSetupRef+ ? scopedThreadKey(scopeThreadRef(worktreeSetupRef.environmentId, worktreeSetupRef.threadId))+ : null;+ useEffect(() => {+ if (worktreeSetupSettledKey) pendingWorktreeSetupByThreadKey.delete(worktreeSetupSettledKey);+ }, [worktreeSetupSettledKey]);const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {reportFailure: false,});@@ -7515,6 +7544,12 @@ export default function ChatView(props: ChatViewProps) {? { environmentId, threadId: threadIdForSend, ownerKey: worktreeSetupOwnerKey }: null,);+ if (baseBranchForWorktree) {+ pendingWorktreeSetupByThreadKey.set(+ scopedThreadKey(scopeThreadRef(environmentId, threadIdForSend)),+ { environmentId, threadId: threadIdForSend },+ );+ }const messageIdForSend = newMessageId();const messageCreatedAt = new Date().toISOString();diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsxindex 304922909b0..15cca412ba4 100644--- a/apps/web/src/components/ProjectScriptsControl.tsx+++ b/apps/web/src/components/ProjectScriptsControl.tsx@@ -113,6 +113,7 @@ export default function ProjectScriptsControl({command: fileScript.command,icon: fileScript.icon ?? "play",runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,+ waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,keybinding: null,previewUrl: fileScript.previewUrl ?? null,autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.tsindex 59b4a0c9856..39cd8f8318a 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts@@ -1148,17 +1148,18 @@ describe("deriveMessagesTimelineRows", () => {id: WORKTREE_SETUP_ROW_ID,createdAt: "2026-01-01T00:00:00Z",snapshot,+ embedded: false,},]);- // Once the agent has replied the finished card stays under the send.+ // A failed setup never handed off, so the card stays under the send.const withMessages = deriveMessagesTimelineRows({timelineEntries: [userEntry, assistantEntry],isWorking: true,activeTurnStartedAt: "2026-01-01T00:00:00Z",turnDiffSummaries: [],supportsConversationRollback: false,- worktreeSetup: { ...snapshot, phase: "done" },+ worktreeSetup: { ...snapshot, phase: "failed" },});expect(withMessages.map((row) => row.kind)).toEqual(["message",@@ -1166,6 +1167,73 @@ describe("deriveMessagesTimelineRows", () => {"working","message",]);++ // Once the agent stage is done the setup script may still be running in+ // the background: the turn owns the header and the script row follows it.+ const stage = (id: "agent" | "setup-script", status: "done" | "running") =>+ ({+ id,+ status,+ startedAt: "2026-01-01T00:00:10Z",+ endedAt: status === "done" ? "2026-01-01T00:00:11Z" : null,+ percent: null,+ detail: null,+ tail: [],+ }) as const;+ const asyncSnapshot: WorktreeSetupSnapshot = {+ ...snapshot,+ stages: [stage("setup-script", "running"), stage("agent", "done")],+ };+ const liveTurn = {+ turnId: "turn-1" as never,+ state: "running",+ startedAt: "2026-01-01T00:00:11Z",+ completedAt: null,+ } as const;+ const asyncRows = deriveMessagesTimelineRows({+ timelineEntries: [userEntry],+ latestTurn: liveTurn,+ isWorking: true,+ activeTurnStartedAt: "2026-01-01T00:00:00Z",+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ worktreeSetup: asyncSnapshot,+ });+ expect(asyncRows.map((row) => row.kind)).toEqual([+ "message",+ "working",+ "worktree-setup",+ "thinking",+ ]);+ expect(asyncRows[2]).toMatchObject({ kind: "worktree-setup", embedded: true });++ // Dispatched but not yet visible as a turn: the full card stays put so+ // nothing collapses during the handoff.+ const handoffRows = deriveMessagesTimelineRows({+ timelineEntries: [userEntry],+ isWorking: true,+ activeTurnStartedAt: "2026-01-01T00:00:00Z",+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ worktreeSetup: asyncSnapshot,+ });+ expect(handoffRows.map((row) => row.kind)).toEqual(["message", "worktree-setup"]);+ expect(handoffRows[1]).toMatchObject({ kind: "worktree-setup", embedded: false });++ // A script that already finished has nothing left to show once the turn is live.+ const finishedRows = deriveMessagesTimelineRows({+ timelineEntries: [userEntry],+ latestTurn: liveTurn,+ isWorking: true,+ activeTurnStartedAt: "2026-01-01T00:00:00Z",+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ worktreeSetup: {+ ...asyncSnapshot,+ stages: [stage("setup-script", "done"), stage("agent", "done")],+ },+ });+ expect(finishedRows.map((row) => row.kind)).toEqual(["message", "working", "thinking"]);});it("keeps context compaction visible outside folded work", () => {diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex 3d7b1e12284..89bcf214783 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -400,6 +400,8 @@ export type MessagesTimelineRow =id: string;createdAt: string | null;snapshot: WorktreeSetupSnapshot;+ /** The agent already started; render only the script row under the turn header. */+ embedded: boolean;};export interface StableMessagesTimelineRowsState {@@ -1260,15 +1262,23 @@ export function deriveMessagesTimelineRows(input: {});}- // The setup card takes the place of the working and thinking placeholders- // while a worktree is being prepared. It stays after the setup settles so a- // failure and its actions remain visible until the thread state moves on.- if (input.worktreeSetup) {+ // Until the agent's turn is live, the setup card takes the place of the+ // working and thinking placeholders. It stays after a failed or cancelled+ // setup so the outcome and its actions remain visible until the thread+ // state moves on. "Live" means the turn is in the timeline, not just that+ // the server dispatched it: the card must not collapse in the gap between.+ const setupHandedOff =+ input.worktreeSetup !== null &&+ input.worktreeSetup !== undefined &&+ worktreeSetupAgentStarted(input.worktreeSetup) &&+ input.latestTurn?.startedAt != null;+ if (input.worktreeSetup && !setupHandedOff) {const setupRow = {kind: "worktree-setup",id: WORKTREE_SETUP_ROW_ID,createdAt: input.worktreeSetup.startedAt,snapshot: input.worktreeSetup,+ embedded: false,} as const;// Sit directly under the first user message: a finished snapshot can// outlive the first assistant reply, and it belongs to the send, not the@@ -1287,6 +1297,31 @@ export function deriveMessagesTimelineRows(input: {if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {appendWorkingRow();}+ // An async setup script outlives the handoff. The turn owns the header, so+ // the script's row sits first under it, ahead of the agent's own work. A+ // script that already finished (or never ran) has nothing left to show.+ const setupScriptStage = input.worktreeSetup?.stages.find((stage) => stage.id === "setup-script");+ if (+ input.worktreeSetup &&+ setupHandedOff &&+ (setupScriptStage?.status === "running" || setupScriptStage?.status === "failed")+ ) {+ const setupRow = {+ kind: "worktree-setup",+ id: WORKTREE_SETUP_ROW_ID,+ createdAt: input.worktreeSetup.startedAt,+ snapshot: input.worktreeSetup,+ embedded: true,+ } as const;+ const workingRowIndex = nextRows.findIndex((row) => row.kind === "working");+ if (workingRowIndex >= 0) {+ nextRows.splice(workingRowIndex + 1, 0, setupRow);+ } else {+ // The turn already finished (or has not been dispatched yet): the row+ // trails the reply so a still-running script stays visible after it.+ nextRows.push(setupRow);+ }+ }if (input.isWorking && (!hasActivityRow || latestToolFailed)) {nextRows.push({kind: "thinking",@@ -1300,6 +1335,11 @@ export function deriveMessagesTimelineRows(input: {export const WORKTREE_SETUP_ROW_ID = "worktree-setup-row";+/** True once the bootstrap handed off to the agent (async setup script may still run). */+function worktreeSetupAgentStarted(snapshot: WorktreeSetupSnapshot): boolean {+ return snapshot.stages.some((stage) => stage.id === "agent" && stage.status === "done");+}+type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];export interface MessagesTimelineRowsProjection {diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex bc3a66f4e28..b6383724e03 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -1464,8 +1464,11 @@ function WorktreeSetupTimelineRow({return (<WorktreeSetupCardsnapshot={row.snapshot}- onCancel={ctx.onCancelWorktreeSetup}- onWorkLocally={row.snapshot.phase === "running" ? ctx.onWorktreeSetupWorkLocally : null}+ embedded={row.embedded}+ onCancel={row.embedded ? null : ctx.onCancelWorktreeSetup}+ onWorkLocally={+ !row.embedded && row.snapshot.phase === "running" ? ctx.onWorktreeSetupWorkLocally : null+ }onOpenTerminal={onOpenTerminal}/>);diff --git a/apps/web/src/components/chat/WorktreeSetupCard.tsx b/apps/web/src/components/chat/WorktreeSetupCard.tsxindex 8b838fb81cc..6fe54269cd1 100644--- a/apps/web/src/components/chat/WorktreeSetupCard.tsx+++ b/apps/web/src/components/chat/WorktreeSetupCard.tsx@@ -10,16 +10,16 @@ import {ChevronRightIcon,CircleAlertIcon,CircleIcon,- GitBranchIcon,LaptopIcon,MinusIcon,TerminalIcon,XIcon,} from "lucide-react";-import { useEffect, useState } from "react";+import { useEffect, useState, type ReactNode } from "react";import { Button } from "~/components/ui/button";import { Spinner } from "~/components/ui/spinner";+import { observeVisibleAnimation } from "~/lib/visibleAnimation";import { cn } from "~/lib/utils";interface WorktreeSetupCardProps {@@ -74,20 +74,95 @@ function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) {function stageRowClassName(status: WorktreeSetupStage["status"]): string {switch (status) {- case "running":- return "text-foreground";case "failed":return "text-destructive-foreground";case "warning":return "text-warning-foreground";case "pending":+ return "text-secondary-label opacity-40";+ case "running":case "skipped":- return "text-secondary-label opacity-50";case "done":return "text-secondary-label";}}+/** Same shimmer treatment as the live tool rows in the timeline. */+function ShimmerOverlay({ children }: { children: ReactNode }) {+ return (+ <span+ aria-hidden+ className="live-activity-focus pointer-events-none absolute inset-y-0 select-none"+ >+ <span className="live-activity-focus-counter block">+ <span className="live-activity-focus-aligned block text-foreground">{children}</span>+ </span>+ </span>+ );+}++function headerLabel(snapshot: WorktreeSetupSnapshot): string {+ switch (snapshot.phase) {+ case "running":+ return "Setting up worktree…";+ case "done":+ return snapshot.stages.some((stage) => stage.status === "failed")+ ? "Worktree ready, setup script failed"+ : "Worktree ready";+ case "failed":+ return "Worktree setup failed";+ case "cancelled":+ return "Worktree setup cancelled";+ }+}++/**+ * Occupies the same slot, with the same metrics, as the "Working for" header+ * so the handoff to the agent's turn only swaps the text.+ */+function SetupHeaderRow({+ snapshot,+ totalElapsed,+}: {+ snapshot: WorktreeSetupSnapshot;+ totalElapsed: number | null;+}) {+ const running = snapshot.phase === "running";+ const failed = snapshot.phase === "failed";+ const finishedWithFailedStage =+ snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed");+ const text = headerLabel(snapshot);+ const tone = failed+ ? "text-destructive-foreground"+ : finishedWithFailedStage+ ? "text-warning-foreground"+ : "text-muted-foreground";+ return (+ <div className="border-b border-border/60 pb-2 pt-1">+ <div+ className={cn(+ "flex h-6 min-w-0 items-baseline gap-2 px-1 text-sm leading-relaxed tabular-nums",+ tone,+ )}+ >+ <span+ ref={running ? observeVisibleAnimation : undefined}+ className="relative min-w-0 shrink overflow-hidden whitespace-nowrap"+ >+ <span className="block truncate">{text}</span>+ {running ? <ShimmerOverlay>{text}</ShimmerOverlay> : null}+ </span>+ {totalElapsed !== null ? (+ <span className="ml-auto shrink-0 text-xs text-muted-foreground">+ {formatDuration(totalElapsed)}+ </span>+ ) : null}+ </div>+ </div>+ );+}++/** One stage, rendered like a live work entry row. */function StageRow({stage,nowMs,@@ -100,44 +175,49 @@ function StageRow({const elapsed = stageElapsedMs(stage, nowMs);const label =stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id);- const showBar = stage.id === "checkout" && stage.status === "running" && stage.percent !== null;+ const running = stage.status === "running";const trailing =stage.status === "pending"? null: stage.status === "skipped"? (stage.detail ?? "skipped")- : stage.detail;-+ : stage.id === "checkout" && running && stage.percent !== null+ ? `${stage.percent}%`+ : stage.detail;return (<div+ ref={running ? observeVisibleAnimation : undefined}className={cn(- "flex min-h-6 items-center gap-1.5 px-0.5 py-0.5 text-sm leading-relaxed",+ "relative flex min-h-6 min-w-0 items-center gap-1.5 overflow-hidden rounded-md px-0.5 py-0.5 text-sm leading-relaxed",stageRowClassName(stage.status),)}data-worktree-setup-stage={stage.id}data-worktree-setup-status={stage.status}>- <span className="flex size-6 shrink-0 items-center justify-center">+ <span className="flex size-6 shrink-0 items-center justify-center text-icon-muted"><StageIcon status={stage.status} /></span><span className="min-w-0 flex-1 truncate">{label}</span>- <span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">- {showBar ? (- <>- <span className="h-1 w-18 overflow-hidden rounded-full bg-input">- <span- className="block h-full rounded-full bg-primary"- style={{ width: `${stage.percent ?? 0}%` }}- />+ {trailing ? (+ <span className="min-w-0 truncate text-xs text-muted-foreground tabular-nums">+ {trailing}+ </span>+ ) : null}+ {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (+ <span className="shrink-0 text-xs text-muted-foreground tabular-nums">+ {formatDuration(elapsed)}+ </span>+ ) : null}+ {running ? (+ <ShimmerOverlay>+ <span className="flex min-h-6 items-center gap-1.5 px-0.5 py-0.5">+ <span className="flex size-6 shrink-0 items-center justify-center">+ <StageIcon status={stage.status} /></span>- <span className="text-foreground">{stage.percent}%</span>- </>- ) : null}- {!showBar && trailing ? <span className="truncate">{trailing}</span> : null}- {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (- <span>{formatDuration(elapsed)}</span>- ) : null}- </span>+ <span className="min-w-0 flex-1 truncate">{label}</span>+ </span>+ </ShimmerOverlay>+ ) : null}</div>);}@@ -158,19 +238,35 @@ function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: b);}-function headerLabel(snapshot: WorktreeSetupSnapshot): string {- switch (snapshot.phase) {- case "running":- return "Creating worktree";- case "done":- return snapshot.stages.some((stage) => stage.status === "failed")- ? "Worktree ready, setup script failed"- : "Worktree ready";- case "failed":- return "Worktree setup failed";- case "cancelled":- return "Worktree setup cancelled";- }+function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {+ return (+ <dl className="mt-1 mb-1.5 ml-8 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs text-muted-foreground">+ {snapshot.branch ? (+ <>+ <dt className="text-foreground/80">Branch</dt>+ <dd className="truncate font-mono">{snapshot.branch}</dd>+ </>+ ) : null}+ {snapshot.baseRef ? (+ <>+ <dt className="text-foreground/80">Base</dt>+ <dd className="truncate font-mono">{snapshot.baseRef}</dd>+ </>+ ) : null}+ {snapshot.worktreePath ? (+ <>+ <dt className="text-foreground/80">Path</dt>+ <dd className="truncate font-mono">{snapshot.worktreePath}</dd>+ </>+ ) : null}+ {snapshot.setupScript ? (+ <>+ <dt className="text-foreground/80">Setup</dt>+ <dd className="truncate font-mono">{snapshot.setupScript.command}</dd>+ </>+ ) : null}+ </dl>+ );}export function WorktreeSetupCard({@@ -178,7 +274,14 @@ export function WorktreeSetupCard({onCancel,onWorkLocally,onOpenTerminal,-}: WorktreeSetupCardProps) {+ embedded = false,+}: WorktreeSetupCardProps & {+ /**+ * The agent already started (async setup script), so the turn owns the+ * "Working for" header and only the script's row sits among the worklog.+ */+ embedded?: boolean;+}) {const running = snapshot.phase === "running";const nowMs = useNowWhile(running);const [detailsOpen, setDetailsOpen] = useState(false);@@ -188,79 +291,35 @@ export function WorktreeSetupCard({return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;})();const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");- const failed = snapshot.phase === "failed";- const finishedWithFailedStage =- snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed");- const headerClassName = failed- ? "text-destructive-foreground"- : finishedWithFailedStage- ? "text-warning-foreground"- : snapshot.phase === "cancelled"- ? "text-muted-foreground"- : "text-secondary-label";+ const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";+ const stages = embedded+ ? snapshot.stages.filter((stage) => stage.id === "setup-script")+ : snapshot.stages;return (- <section- aria-label="Worktree setup"- className="mt-3 rounded-lg border border-border bg-card/60 px-2.5 pt-1.5 pb-2"- data-worktree-setup-phase={snapshot.phase}- >- <div className={cn("flex min-h-6 items-center gap-1.5 px-0.5 text-sm", headerClassName)}>- <span className="flex size-6 shrink-0 items-center justify-center text-icon-muted">- <GitBranchIcon aria-hidden className="size-4 shrink-0 stroke-[1.8]" />- </span>- <span className="min-w-0 flex-1 truncate">{headerLabel(snapshot)}</span>- {totalElapsed !== null ? (- <span className="shrink-0 text-xs text-muted-foreground tabular-nums">- {formatDuration(totalElapsed)}- </span>- ) : null}+ <section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>+ {embedded ? null : <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} />}+ <div className={embedded ? undefined : "pt-1.5"}>+ {stages.map((stage) => (+ <div key={stage.id}>+ <StageRow stage={stage} nowMs={nowMs} scriptName={snapshot.setupScript?.name ?? null} />+ {stage.id === "setup-script" &&+ (stage.status === "running" || stage.status === "failed") ? (+ <OutputTail lines={stage.tail} failed={stage.status === "failed"} />+ ) : null}+ </div>+ ))}</div>- {snapshot.stages.map((stage) => (- <div key={stage.id}>- <StageRow stage={stage} nowMs={nowMs} scriptName={snapshot.setupScript?.name ?? null} />- {stage.id === "setup-script" &&- (stage.status === "running" || stage.status === "failed") ? (- <OutputTail lines={stage.tail} failed={stage.status === "failed"} />- ) : null}- </div>- ))}-- {failed && snapshot.error ? (- <p className="mt-1 px-0.5 text-xs text-muted-foreground">{snapshot.error}</p>+ {snapshot.phase === "failed" && snapshot.error ? (+ <p className="mt-1 ml-8 text-xs text-muted-foreground">{snapshot.error}</p>) : null}- {detailsOpen ? (- <dl className="mt-1 mb-1.5 ml-8 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs text-muted-foreground">- {snapshot.branch ? (- <>- <dt className="text-foreground/80">Branch</dt>- <dd className="truncate font-mono">{snapshot.branch}</dd>- </>- ) : null}- {snapshot.baseRef ? (- <>- <dt className="text-foreground/80">Base</dt>- <dd className="truncate font-mono">{snapshot.baseRef}</dd>- </>- ) : null}- {snapshot.worktreePath ? (- <>- <dt className="text-foreground/80">Path</dt>- <dd className="truncate font-mono">{snapshot.worktreePath}</dd>- </>- ) : null}- {snapshot.setupScript ? (- <>- <dt className="text-foreground/80">Setup</dt>- <dd className="truncate font-mono">{snapshot.setupScript.command}</dd>- </>- ) : null}- </dl>- ) : null}+ {detailsOpen ? <SetupDetails snapshot={snapshot} /> : null}- <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {/* Indented so the first label lines up with the stage labels: the icon+ column, minus the xs button's own horizontal padding. */}+ <div className="mt-0.5 ml-[calc(--spacing(6)+2px-(--spacing(2)-1px))] flex flex-wrap items-center gap-0.5"><Buttontype="button"size="xs"@@ -271,21 +330,20 @@ export function WorktreeSetupCard({{detailsOpen ? <ChevronDownIcon aria-hidden /> : <ChevronRightIcon aria-hidden />}Details</Button>- <span className="flex-1" />- {onOpenTerminal && setupStage && setupStage.status !== "pending" ? (- <Button type="button" size="xs" variant="outline" onClick={onOpenTerminal}>+ {showTerminal ? (+ <Button type="button" size="xs" variant="ghost-muted" onClick={onOpenTerminal}><TerminalIcon aria-hidden />Open terminal</Button>) : null}{onWorkLocally ? (- <Button type="button" size="xs" variant="outline" onClick={onWorkLocally}>+ <Button type="button" size="xs" variant="ghost-muted" onClick={onWorkLocally}><LaptopIcon aria-hidden />Work locally</Button>) : null}{onCancel && running ? (- <Button type="button" size="xs" variant="outline" onClick={onCancel}>+ <Button type="button" size="xs" variant="ghost-muted" onClick={onCancel}><XIcon aria-hidden />Cancel</Button>diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsxindex 74b189a02fc..774398feda0 100644--- a/apps/web/src/components/projectScriptEditor.tsx+++ b/apps/web/src/components/projectScriptEditor.tsx@@ -85,6 +85,8 @@ export interface NewProjectScriptInput {command: string;icon: ProjectScriptIcon;runOnWorktreeCreate: boolean;+ /** Setup scripts only: hold the agent until the script exits. */+ waitForSetup: boolean;keybinding: string | null;/** Optional URL to open in the in-app preview when this script runs. */previewUrl: string | null;@@ -99,6 +101,7 @@ export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {command: "",icon: "play",runOnWorktreeCreate: false,+ waitForSetup: false,keybinding: null,previewUrl: null,autoOpenPreview: false,@@ -123,6 +126,7 @@ export function editorRequestForScript(command: script.command,icon: script.icon,runOnWorktreeCreate: script.runOnWorktreeCreate,+ waitForSetup: script.runOnWorktreeCreate && script.async === false,keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),previewUrl: script.previewUrl ?? null,autoOpenPreview: script.autoOpenPreview ?? false,@@ -158,6 +162,7 @@ export function ProjectScriptEditorDialog({const [icon, setIcon] = useState<ProjectScriptIcon>("play");const [iconPickerOpen, setIconPickerOpen] = useState(false);const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);+ const [waitForSetup, setWaitForSetup] = useState(false);const [keybinding, setKeybinding] = useState("");const [previewUrl, setPreviewUrl] = useState("");const [autoOpenPreview, setAutoOpenPreview] = useState(false);@@ -188,6 +193,7 @@ export function ProjectScriptEditorDialog({setIcon(request.initial.icon);setIconPickerOpen(false);setRunOnWorktreeCreate(request.initial.runOnWorktreeCreate);+ setWaitForSetup(request.initial.waitForSetup);setKeybinding(request.initial.keybinding ?? "");setPreviewUrl(request.initial.previewUrl ?? "");setAutoOpenPreview(request.initial.autoOpenPreview);@@ -247,6 +253,7 @@ export function ProjectScriptEditorDialog({command: trimmedCommand,icon,runOnWorktreeCreate,+ waitForSetup: runOnWorktreeCreate && waitForSetup,keybinding: keybindingRule?.key ?? null,previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,@@ -396,6 +403,18 @@ export function ProjectScriptEditorDialog({onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}/></label>+ <label+ className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${+ runOnWorktreeCreate ? "" : "opacity-60"+ }`}+ >+ <span>Wait for it to finish before the agent starts</span>+ <Switch+ checked={waitForSetup}+ disabled={!runOnWorktreeCreate}+ onCheckedChange={(checked) => setWaitForSetup(Boolean(checked))}+ />+ </label><labelclassName={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${previewUrl.trim().length === 0 ? "opacity-60" : ""diff --git a/apps/web/src/components/settings/ProjectActionsSettings.tsx b/apps/web/src/components/settings/ProjectActionsSettings.tsxindex aa4d7077ff6..edbde5e7439 100644--- a/apps/web/src/components/settings/ProjectActionsSettings.tsx+++ b/apps/web/src/components/settings/ProjectActionsSettings.tsx@@ -111,6 +111,7 @@ export function ProjectActionsSettings() {command: fileScript.command,icon: fileScript.icon ?? "play",runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,+ waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,keybinding: null,previewUrl: fileScript.previewUrl ?? null,autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,diff --git a/apps/web/src/projectScripts.test.ts b/apps/web/src/projectScripts.test.tsindex a09a18d03b3..a1ed2afb989 100644--- a/apps/web/src/projectScripts.test.ts+++ b/apps/web/src/projectScripts.test.ts@@ -23,6 +23,7 @@ describe("projectScripts helpers", () => {command: "pnpm dev",icon: "debug",runOnWorktreeCreate: false,+ waitForSetup: false,previewUrl: "http://localhost:5733",autoOpenPreview: true,}),@@ -44,6 +45,7 @@ describe("projectScripts helpers", () => {command: "pnpm test",icon: "test",runOnWorktreeCreate: false,+ waitForSetup: false,previewUrl: null,autoOpenPreview: false,}),@@ -56,6 +58,25 @@ describe("projectScripts helpers", () => {});});+ it("only records async: false for setup scripts that should block the agent", () => {+ const input = {+ name: "Setup",+ command: "pnpm i",+ icon: "configure",+ previewUrl: null,+ autoOpenPreview: false,+ } as const;+ expect(+ buildProjectScript("setup", { ...input, runOnWorktreeCreate: true, waitForSetup: true }),+ ).toMatchObject({ runOnWorktreeCreate: true, async: false });+ expect(+ buildProjectScript("setup", { ...input, runOnWorktreeCreate: true, waitForSetup: false }),+ ).not.toHaveProperty("async");+ expect(+ buildProjectScript("setup", { ...input, runOnWorktreeCreate: false, waitForSetup: true }),+ ).not.toHaveProperty("async");+ });+it("builds and parses script run commands", () => {const command = commandForProjectScript("lint");expect(command).toBe("script.lint.run");diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.tsindex 20d06c9c572..f0bcb530141 100644--- a/apps/web/src/projectScripts.ts+++ b/apps/web/src/projectScripts.ts@@ -12,6 +12,7 @@ export interface ProjectScriptInput {readonly command: ProjectScript["command"];readonly icon: ProjectScript["icon"];readonly runOnWorktreeCreate: ProjectScript["runOnWorktreeCreate"];+ readonly waitForSetup: boolean;readonly previewUrl: Exclude<ProjectScript["previewUrl"], undefined> | null;readonly autoOpenPreview: boolean;}@@ -23,6 +24,7 @@ export function buildProjectScript(id: string, input: ProjectScriptInput): Projecommand: input.command,icon: input.icon,runOnWorktreeCreate: input.runOnWorktreeCreate,+ ...(input.runOnWorktreeCreate && input.waitForSetup ? { async: false } : {}),...(input.previewUrl === null? {}: {diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 7b1fd2f9659..1bb11ba0a67 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -404,6 +404,12 @@ export const ProjectScript = Schema.Struct({command: TrimmedNonEmptyString,icon: ProjectScriptIcon,runOnWorktreeCreate: Schema.Boolean,+ /**+ * For `runOnWorktreeCreate` scripts: when false, the agent's first turn waits+ * for the script to exit. Absent or true starts the agent right away and+ * lets the script finish in the background.+ */+ async: Schema.optional(Schema.Boolean),/*** URL to open in the in-app browser preview when this script runs (or* when the user explicitly requests a preview). Optional; only honored ondiff --git a/packages/contracts/src/t3ProjectFile.test.ts b/packages/contracts/src/t3ProjectFile.test.tsindex ed19c6d6988..4352449c7ad 100644--- a/packages/contracts/src/t3ProjectFile.test.ts+++ b/packages/contracts/src/t3ProjectFile.test.ts@@ -20,12 +20,14 @@ describe("T3ProjectFile", () => {autoOpenPreview: true,},{ name: "Test", command: "pnpm test" },+ { name: "Setup", command: "pnpm i", runOnWorktreeCreate: true, async: false },],});expect(decoded.iconPath).toBe("assets/logo.svg");- expect(decoded.scripts).toHaveLength(2);+ expect(decoded.scripts).toHaveLength(3);expect(decoded.scripts?.[1]).toEqual({ name: "Test", command: "pnpm test" });+ expect(decoded.scripts?.[2]?.async).toBe(false);});it("decodes an empty object and ignores unknown fields", () => {diff --git a/packages/contracts/src/t3ProjectFile.ts b/packages/contracts/src/t3ProjectFile.tsindex 5062a1a370b..6bd4168054d 100644--- a/packages/contracts/src/t3ProjectFile.ts+++ b/packages/contracts/src/t3ProjectFile.ts@@ -42,6 +42,12 @@ export const T3ProjectFileScript = Schema.Struct({"When true, the script runs automatically after a worktree is created for a new thread.",}),),+ async: Schema.optionalKey(+ Schema.Boolean.annotate({+ description:+ "Only for runOnWorktreeCreate scripts. When true (the default), the agent starts while the script is still running. Set false to hold the agent until the script exits.",+ }),+ ),previewUrl: Schema.optionalKey(trimmedNonEmpty({description:diff --git a/packages/shared/src/t3ProjectFile.test.ts b/packages/shared/src/t3ProjectFile.test.tsindex a1986ff35f9..924a01c4414 100644--- a/packages/shared/src/t3ProjectFile.test.ts+++ b/packages/shared/src/t3ProjectFile.test.ts@@ -44,6 +44,7 @@ describe("buildT3ProjectFileJsonSchema", () => {const script = schema.properties.scripts?.items;expect(script?.required).toEqual(["name", "command"]);expect(Object.keys(script?.properties ?? {}).sort()).toEqual([+ "async","autoOpenPreview","command","icon",