feat(web): show each worktree setup step and let users cancel it #11372
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 11 commits into
main fromrefs/pull/11372/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -2537,3 +2750,14 @@25372750 "rpc.aggregate": "vcs",25382751 },25392752 ),2753+ [WS_METHODS.subscribeWorktreeSetup]: (input) =>2754+ observeRpcStream(2755+ WS_METHODS.subscribeWorktreeSetup,2756+ worktreeSetupTracker.stream(input.threadId),2757+ { "rpc.aggregate": "vcs" },2758+ ),2759+ [WS_METHODS.worktreeSetupCancel]: (input) =>2760+ observeRpcEffect(2761+ WS_METHODS.worktreeSetupCancel,2762+ worktreeSetupTracker2763+ .cancel(input.threadId)apps/server/src/vcs/GitVcsDriverCore.ts line 3054Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3014,11 +3030,21 @@3030+ )(function* (input, options) {30143031 const targetBranch = input.newRefName ?? input.refName;30153032 const sanitizedBranch = targetBranch.replace(/\//g, "-");30163033 const repoName = path.basename(input.cwd);30173034 const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);30183035 const args = input.newRefName30193036 ? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]30203037 : ["worktree", "add", worktreePath, input.refName];3038+ const progress = options?.progress;3039+ const onCheckoutProgress = progress?.onCheckoutProgress;3021304030223041 yield* executeGit("GitVcsDriver.createWorktree", input.cwd, args, {30233042 fallbackErrorDetail: "git worktree add failed",30243043 timeoutMs: WORKTREE_ADD_TIMEOUT_MS,3044+ ...(onCheckoutProgress3045+ ? {3046+ // Git only prints checkout progress when stderr is a tty or the3047+ // delay elapsed. GIT_PROGRESS_DELAY=0 forces it through the pipe.3048+ env: { GIT_PROGRESS_DELAY: "0", LC_ALL: "C" },3049+ progress: {3050+ onStderrLine: (line) => {@@ -1078,13 +1086,19 @@1086+ // exit so the card can show the exit code and the agent stage never1087+ // starts on a half-installed tree. Untracked callers keep the old1088+ // fire-and-forget behavior.10781089 const runSetupProgram = () =>10791090 Effect.gen(function* () {10801091 if (!bootstrap?.runSetupScript || !targetWorktreePath) {1092+ yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "skipped"));10811093 return;10821094 }10831095 const worktreePath = targetWorktreePath;10841096 const requestedAt = yield* nowIso;1085- yield* projectSetupScriptRunner1097+ yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "running"));1098+ const setupResult = yield* projectSetupScriptRunner10861099 .runForThread({1087- threadId: command.threadId,1100+ threadId,10881101 ...(targetProjectId ? { projectId: targetProjectId } : {}),10891102 ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),10901103 worktreePath,1104+ ...(trackedapps/server/src/project/ProjectSetupScriptRunner.ts line 143OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -86,0 +123,21 @@123+ .replace(124+ // eslint-disable-next-line no-control-regex125+ /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,126+ "",127+ )128+ // eslint-disable-next-line no-control-regex129+ .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's135+ * command runs in a subshell so `&&` chains and `cd` cannot leak, then the136+ * exit status is echoed. PowerShell reports `$LASTEXITCODE` or falls back to137+ * 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' "$?"`;apps/server/src/project/ProjectSetupScriptRunner.ts line 310OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -173,3 +306,5 @@173306 }),174307 ),175308 );309+ // Subscribe before writing so the sentinel cannot race past the listener.310+ const completion = observeapps/web/src/components/ChatView.tsx line 3333OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3322,3 +3327,7 @@33223327 refresh: gitStatusQuery.refresh,33233328 resourceKey: `git-status:${activeThreadKey ?? ""}:${gitStatusCwd ?? ""}`,33243329 });3330+ // Live stages of a bootstrap worktree setup. Subscribed only while the3331+ // client is dispatching one, or for a short while after so the final card3332+ // state (done or failed) is still visible.3333+ const worktreeSetupSubscriptionActive =apps/server/src/project/ProjectSetupScriptRunner.ts line 141OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -86,0 +121,21 @@121+ return (122+ text123+ .replace(124+ // eslint-disable-next-line no-control-regex125+ /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][A-Za-z0-9]|\x1b[=>]/g,126+ "",127+ )128+ // eslint-disable-next-line no-control-regex129+ .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's135+ * command runs in a subshell so `&&` chains and `cd` cannot leak, then the136+ * exit status is echoed. PowerShell reports `$LASTEXITCODE` or falls back to137+ * 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"`;apps/server/src/project/WorktreeSetupTracker.ts lines 265 to 266OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +246,21 @@246+ const current = yield* Ref.get(setups);247+ const tracked = current.get(threadId);248+ if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {249+ return false;250+ }251+ yield* Fiber.interrupt(tracked.fiber).pipe(Effect.forkDetach);252+ return true;253+ });254+255+ const get: WorktreeSetupTracker["Service"]["get"] = (threadId) =>256+ Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null));257+258+ const stream: WorktreeSetupTracker["Service"]["stream"] = (threadId) =>259+ Stream.unwrap(260+ Effect.gen(function* () {261+ const subscription = yield* PubSub.subscribe(changes);262+ const initial = yield* get(threadId);263+ return Stream.concat(264+ Stream.make(initial),265+ Stream.fromSubscription(subscription).pipe(266+ Stream.filter((change) => change.threadId === threadId),apps/server/src/ws.ts line 1412OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1192,4 +1393,20 @@1393+ ),1394+ }),1395+ );1396+1397+ return yield* runBootstrap.pipe(11921398 Effect.catchCause((cause) => {11931399 const dispatchError = toBootstrapDispatchCommandCauseError(cause);11941400 if (Cause.hasInterruptsOnly(cause)) {1195- return Effect.fail(dispatchError);1401+ // A user cancel interrupts the forked bootstrap fiber. The1402+ // created thread is rolled back like any other failure so the1403+ // draft returns to the composer.1404+ const removeCreatedWorktree =1405+ tracked && targetWorktreePath && bootstrap?.prepareWorktree1406+ ? gitWorkflow1407+ .removeWorktree({1408+ cwd: bootstrap.prepareWorktree.projectCwd,1409+ path: targetWorktreePath,1410+ force: true,1411+ })1412+ .pipe(Effect.ignoreCause({ log: true }), Effect.uninterruptible)
- apps/server/src/project/ProjectSetupScriptRunner.ts lines 310 to 315OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -173,3 +306,10 @@173306 }),174307 ),175308 );309+ // Subscribe before writing so the sentinel cannot race past the listener.310+ const completion = observe311+ ? yield* observeTerminalCompletion({312+ threadId: input.threadId,313+ terminalId,314+ onOutputLine: observe.onOutputLine,315+ })apps/server/src/project/WorktreeSetupTracker.ts lines 121 to 124Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +81,21 @@81+ readonly fiber: Fiber.Fiber<unknown, unknown> | null;82+}83+84+function emptyStage(id: WorktreeSetupStageId): WorktreeSetupStage {85+ return {86+ id,87+ status: "pending",88+ startedAt: null,89+ endedAt: null,90+ percent: null,91+ detail: null,92+ tail: [],93+ };94+}95+96+export const make = Effect.gen(function* () {97+ const setups = yield* Ref.make(new Map<ThreadId, TrackedSetup>());98+ const changes = yield* PubSub.unbounded<{99+ readonly threadId: ThreadId;100+ readonly snapshot: WorktreeSetupSnapshot | null;101+ }>();@@ -1096,4 +1117,15 @@10961117 error,10971118 requestedAt,10981119 worktreePath,1099- }),1120+ }).pipe(1121+ Effect.andThen(1122+ track(1123+ worktreeSetupTracker.stageStatus(1124+ threadId,1125+ "setup-script",1126+ "failed",1127+ "failed to start",1128+ ),1129+ ),1130+ ),1131+ Effect.as(null),apps/server/src/ws.ts lines 1404 to 1412OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1192,4 +1393,20 @@1393+ ),1394+ }),1395+ );1396+1397+ return yield* runBootstrap.pipe(11921398 Effect.catchCause((cause) => {11931399 const dispatchError = toBootstrapDispatchCommandCauseError(cause);11941400 if (Cause.hasInterruptsOnly(cause)) {1195- return Effect.fail(dispatchError);1401+ // A user cancel interrupts the forked bootstrap fiber. The1402+ // created thread is rolled back like any other failure so the1403+ // draft returns to the composer.1404+ const removeCreatedWorktree =1405+ tracked && targetWorktreePath && bootstrap?.prepareWorktree1406+ ? gitWorkflow1407+ .removeWorktree({1408+ cwd: bootstrap.prepareWorktree.projectCwd,1409+ path: targetWorktreePath,1410+ force: true,1411+ })1412+ .pipe(Effect.ignoreCause({ log: true }), Effect.uninterruptible)apps/web/src/components/chat/MessagesTimeline.logic.ts lines 1245 to 1251OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1225,3 +1238,14 @@12251238 });12261239 }122712401241+ // The setup card takes the place of the working and thinking placeholders1242+ // while a worktree is being prepared. It stays after the setup settles so a1243+ // failure and its actions remain visible until the thread state moves on.1244+ if (input.worktreeSetup) {1245+ nextRows.push({1246+ kind: "worktree-setup",1247+ id: WORKTREE_SETUP_ROW_ID,1248+ createdAt: input.worktreeSetup.startedAt,1249+ snapshot: input.worktreeSetup,1250+ });1251+ return attachTrailingToolGroupsToAssistant(nextRows);apps/web/src/components/ChatView.tsx lines 8462 to 8474Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -8207,3 +8250,18 @@82078250 ],82088251 );820982528253+ // "Work locally" on the setup card: stop the bootstrap, flip the draft to8254+ // local mode, and resend the same message. The failed bootstrap rolls the8255+ // draft back into the composer, so the resend picks it up as-is.8256+ const onSendRef = useRef(onSend);8257+ onSendRef.current = onSend;8258+ const onWorktreeSetupWorkLocally = useCallback(() => {8259+ if (!activeThreadId || !isLocalDraftThread) return;8260+ void (async () => {8261+ await cancelWorktreeSetup({ environmentId, input: { threadId: activeThreadId } });8262+ // Wait for the failed dispatch to restore the draft before resending.8263+ await new Promise<void>((resolve) => setTimeout(resolve, 0));8264+ onEnvModeChange("local");8265+ await new Promise<void>((resolve) => setTimeout(resolve, 0));8266+ await onSendRef.current();8267+ })();
github-actions[bot](GitHub profile, opens in a new tab) added labels📱 Native Change
- apps/server/src/project/WorktreeSetupTracker.ts line 158OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +138,21 @@138+ next.delete(threadId);139+ return next;140+ }).pipe(Effect.andThen(publish(threadId, null)));141+142+ const begin: WorktreeSetupTracker["Service"]["begin"] = (input) =>143+ Effect.gen(function* () {144+ yield* clearRetention(input.threadId);145+ const startedAt = yield* nowIso;146+ const ordered = WORKTREE_SETUP_STAGE_ORDER.filter((id) => input.stages.includes(id));147+ const snapshot: WorktreeSetupSnapshot = {148+ threadId: input.threadId,149+ phase: "running",150+ startedAt,151+ endedAt: null,152+ branch: input.branch,153+ baseRef: input.baseRef,154+ worktreePath: null,155+ setupScript: null,156+ stages: ordered.map(emptyStage),157+ error: null,158+ sequence: 0,apps/web/src/components/ChatView.tsx line 3378OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3324,0 +3358,21 @@3358+ return;3359+ }3360+ // The server drops finished snapshots after a grace period and emits null.3361+ // Hold the last real snapshot so the failed card does not vanish.3362+ setHeldWorktreeSetup(latestWorktreeSetup);3363+ }, [latestWorktreeSetup]);3364+ const worktreeSetup =3365+ worktreeSetupActive && heldWorktreeSetup?.threadId === worktreeSetupRef.threadId3366+ ? heldWorktreeSetup3367+ : null;3368+ const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {3369+ reportFailure: false,3370+ });3371+ const onCancelWorktreeSetup = useCallback(() => {3372+ if (!worktreeSetup || worktreeSetup.phase !== "running") return;3373+ void cancelWorktreeSetup({ environmentId, input: { threadId: worktreeSetup.threadId } });3374+ }, [cancelWorktreeSetup, environmentId, worktreeSetup]);3375+ const onOpenWorktreeSetupTerminal = useCallback(3376+ (terminalId: string) => {3377+ if (!activeThreadRef) return;3378+ storeEnsureTerminal(activeThreadRef, terminalId, { open: true, active: true });apps/web/src/components/ChatView.tsx line 3356OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3324 +3336,21 @@33243336 });3337+ // Live stages of a bootstrap worktree setup. The subscription follows the3338+ // thread that was set up, not the route: a deleted bootstrap thread rotates3339+ // the draft's thread id, and the failed card must survive that.3340+ const worktreeSetupOwnerKey = draftId ?? routeThreadKey;3341+ const worktreeSetupActive =3342+ worktreeSetupRef !== null && worktreeSetupRef.ownerKey === worktreeSetupOwnerKey;3343+ const worktreeSetupQuery = useEnvironmentQuery(3344+ worktreeSetupActive3345+ ? vcsEnvironment.worktreeSetup({3346+ environmentId,3347+ input: { threadId: worktreeSetupRef.threadId },3348+ })3349+ : null,3350+ );3351+ const latestWorktreeSetup = worktreeSetupQuery.data;3352+ useEffect(() => {3353+ if (!latestWorktreeSetup) return;3354+ if (latestWorktreeSetup.phase === "done") {3355+ // The turn is running now; the timeline hands over to the agent.3356+ setWorktreeSetupRef(null);apps/server/src/project/WorktreeSetupTracker.ts lines 284 to 294Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +225,21 @@225+ phase,226+ endedAt,227+ error: error ?? null,228+ stages: tracked.snapshot.stages.map((entry) =>229+ entry.status === "running"230+ ? {231+ ...entry,232+ status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",233+ endedAt,234+ }235+ : entry,236+ ),237+ },238+ }));239+ if (!snapshot) return;240+ yield* clearRetention(threadId);241+ const fiber = yield* remove(threadId).pipe(242+ Effect.delay(FINISHED_RETENTION),243+ Effect.forkDetach,244+ );245+ retentionFibers.set(threadId, fiber);apps/web/src/components/ChatView.tsx lines 8737 to 8737OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -8650,3 +8732,6 @@86508732 isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree}86518733 isCompacting={!paintOnlyDisplayedTimeline && isCompacting}86528734 activeTurnStartedAt={paintOnlyDisplayedTimeline ? null : activeWorkStartedAt}8735+ worktreeSetup={paintOnlyDisplayedTimeline ? null : worktreeSetup}8736+ onCancelWorktreeSetup={onCancelWorktreeSetup}8737+ onWorktreeSetupWorkLocally={onWorktreeSetupWorkLocally}
- apps/server/src/project/ProjectSetupScriptRunner.ts line 245Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -90,0 +203,21 @@203+ settled = true;204+ return Clock.currentTimeMillis.pipe(205+ Effect.flatMap((nowMs) =>206+ Deferred.succeed(done, { exitCode, durationMs: nowMs - startedAtMs }),207+ ),208+ Effect.asVoid,209+ );210+ });211+212+ const handleLine = (rawLine: string) =>213+ Effect.suspend(() => {214+ const sentinel = COMPLETION_SENTINEL_PATTERN.exec(rawLine);215+ if (sentinel) {216+ const parsed = Number(sentinel[1]);217+ return settle(Number.isFinite(parsed) ? parsed : null);218+ }219+ const cleaned = stripTerminalControl(rawLine).trimEnd();220+ if (221+ cleaned.length === 0 ||222+ cleaned.includes(COMPLETION_SENTINEL_PREFIX) ||223+ input.echoedWrapperLines.some((echoed) => cleaned.endsWith(echoed)) ||apps/server/src/project/ProjectSetupScriptRunner.ts line 320OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -154,3 +315,6 @@154315 project: { cwd: project.workspaceRoot },155316 worktreePath: input.worktreePath,156317 });318+ const observe = input.observeCompletion;319+ const commandLine = observe320+ ? wrapCommandForCompletion(script.command, completionShell)
- apps/server/src/project/WorktreeSetupTracker.ts line 128Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +90,21 @@90+ return {91+ id,92+ status: "pending",93+ startedAt: null,94+ endedAt: null,95+ percent: null,96+ detail: null,97+ tail: [],98+ };99+}100+101+export const make = Effect.gen(function* () {102+ const setups = yield* Ref.make(new Map<ThreadId, TrackedSetup>());103+ const changes = yield* PubSub.unbounded<{104+ readonly threadId: ThreadId;105+ readonly snapshot: WorktreeSetupSnapshot | null;106+ }>();107+ const retentionFibers = new Map<ThreadId, Fiber.Fiber<void, never>>();108+ // Sequences keep increasing across setups of the same thread so a stream109+ // opened during a previous setup still accepts the next one's first snapshot.110+ const lastSequenceByThread = new Map<ThreadId, number>();apps/web/src/components/chat/WorktreeSetupCard.tsx lines 150 to 150OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +130,21 @@130+ style={{ width: `${stage.percent ?? 0}%` }}131+ />132+ </span>133+ <span className="text-foreground">{stage.percent}%</span>134+ </>135+ ) : null}136+ {!showBar && trailing ? <span className="truncate">{trailing}</span> : null}137+ {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (138+ <span>{formatDuration(elapsed)}</span>139+ ) : null}140+ </span>141+ </div>142+ );143+}144+145+function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: boolean }) {146+ if (lines.length === 0) return null;147+ return (148+ <pre149+ className={cn(150+ "mb-1 ml-8 max-h-20 overflow-hidden rounded-md border px-2.5 py-1.5 font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all select-text",apps/web/src/components/chat/WorktreeSetupCard.tsx lines 124 to 124OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ const trailing =105+ stage.status === "pending"106+ ? null107+ : stage.status === "skipped"108+ ? (stage.detail ?? "skipped")109+ : stage.detail;110+111+ return (112+ <div113+ className={cn(114+ "flex min-h-6 items-center gap-1.5 px-0.5 py-0.5 text-sm leading-relaxed",115+ stageRowClassName(stage.status),116+ )}117+ data-worktree-setup-stage={stage.id}118+ data-worktree-setup-status={stage.status}119+ >120+ <span className="flex size-6 shrink-0 items-center justify-center">121+ <StageIcon status={stage.status} />122+ </span>123+ <span className="min-w-0 flex-1 truncate">{label}</span>124+ <span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">apps/web/src/components/ChatView.tsx line 8295OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -8208,2 +8275,21 @@82088275 );820982768277+ // "Work locally" on the setup card: flip the draft to local mode and cancel8278+ // the bootstrap. The cancelled dispatch fails and puts the message back in8279+ // the composer; the effect below resends it once that has settled.8280+ const onWorktreeSetupWorkLocally = useCallback(() => {8281+ if (!worktreeSetup || worktreeSetup.phase !== "running" || !isLocalDraftThread) return;8282+ const threadId = worktreeSetup.threadId;8283+ void (async () => {8284+ const result = await cancelWorktreeSetup({ environmentId, input: { threadId } });8285+ if (result._tag !== "Success" || !result.value.cancelled) return;8286+ onEnvModeChange("local");8287+ setWorkLocallyResendPending(true);8288+ })();8289+ }, [cancelWorktreeSetup, environmentId, isLocalDraftThread, onEnvModeChange, worktreeSetup]);8290+ const onSendRef = useRef(onSend);8291+ onSendRef.current = onSend;8292+ useEffect(() => {8293+ if (!workLocallyResendPending || isSendBusy || sendInFlightRef.current) return;8294+ if (sendEnvMode !== "local") return;8295+ setWorkLocallyResendPending(false);apps/web/src/components/ChatView.tsx line 3346OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3322,3 +3334,13 @@33223334 refresh: gitStatusQuery.refresh,33233335 resourceKey: `git-status:${activeThreadKey ?? ""}:${gitStatusCwd ?? ""}`,33243336 });3337+ // Live stages of a bootstrap worktree setup. The subscription follows the3338+ // thread that was set up, not the route: a deleted bootstrap thread rotates3339+ // the draft's thread id, and the failed card must survive that.3340+ const worktreeSetupOwnerKey = draftId ?? routeThreadKey;3341+ const worktreeSetupActive =3342+ worktreeSetupRef !== null && worktreeSetupRef.ownerKey === worktreeSetupOwnerKey;3343+ const worktreeSetupQuery = useEnvironmentQuery(3344+ worktreeSetupActive3345+ ? vcsEnvironment.worktreeSetup({3346+ environmentId,
- apps/web/src/components/ChatView.tsx line 5513OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -5439,3 +5510,4 @@54395510 return [];54405511 });54415512 resetLocalDispatch();5513+ setWorkLocallyResendPending(false);
- apps/web/src/components/ChatView.tsx line 8323OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -8209,0 +8303,21 @@8303+ const result = await cancelWorktreeSetup(target);8304+ if (result._tag !== "Success" || !result.value.cancelled) return;8305+ onEnvModeChange("local");8306+ setWorkLocallyResendPending(true);8307+ })();8308+ }, [cancelWorktreeSetup, isLocalDraftThread, onEnvModeChange, worktreeSetup, worktreeSetupRef]);8309+ const onSendRef = useRef(onSend);8310+ onSendRef.current = onSend;8311+ // Resend once the cancelled dispatch has settled and the composer is free.8312+ // The flag stays set until `onSend` gets past its own guards, so a reconnect8313+ // or a loading thread in between does not lose the message.8314+ const workLocallyResendReady =8315+ workLocallyResendPending &&8316+ !isSendBusy &&8317+ !isConnecting &&8318+ !threadDetailLoading &&8319+ clientSettingsHydrated &&8320+ sendEnvMode === "local";8321+ useEffect(() => {8322+ if (!workLocallyResendReady || sendInFlightRef.current) return;8323+ setWorkLocallyResendPending(false);
- apps/web/src/components/ChatView.tsx lines 1660 to 1662Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1634,3 +1635,17 @@16341635 return () => revokeBlobPreviewUrl(src);16351636 }, [expandedImage]);16361637 const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);1638+ // The bootstrap worktree setup this composer last dispatched. Set when a1639+ // worktree send starts and cleared once the turn starts or the next send1640+ // begins, so a failed or cancelled card stays until the user acts.1641+ const [worktreeSetupRef, setWorktreeSetupRef] = useState<{1642+ environmentId: EnvironmentId;1643+ threadId: ThreadId;1644+ ownerKey: string;1645+ } | null>(null);1646+ const [heldWorktreeSetup, setHeldWorktreeSetup] = useState<WorktreeSetupSnapshot | null>(null);1647+ // Set by "Work locally": the draft whose restored message should be resent1648+ // once the cancelled dispatch has settled and the draft is in local mode.1649+ // Keyed by draft id so a bootstrap rotating the thread id keeps it, while1650+ // moving to another draft drops it without an effect.1651+ const [workLocallyResendDraftId, setWorkLocallyResendDraftId] = useState<DraftId | null>(null);
github-actions[bot](GitHub profile, opens in a new tab) removed labels📱 Native Change
- packages/contracts/src/worktreeSetup.ts line 37OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+export type WorktreeSetupStageId = typeof WorktreeSetupStageId.Type;18+19+export const WorktreeSetupStageStatus = Schema.Literals([20+ "pending",21+ "running",22+ "done",23+ "skipped",24+ "warning",25+ "failed",26+]);27+export type WorktreeSetupStageStatus = typeof WorktreeSetupStageStatus.Type;28+29+export const WorktreeSetupStage = Schema.Struct({30+ id: WorktreeSetupStageId,31+ status: WorktreeSetupStageStatus,32+ startedAt: Schema.NullOr(IsoDateTime),33+ endedAt: Schema.NullOr(IsoDateTime),34+ /** Only the checkout stage reports a real percentage, parsed from git's `Updating files` lines. */35+ percent: Schema.NullOr(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 100 }))),36+ /** Short trailing text for the row: a file count, an exit code, a submodule name. */37+ detail: Schema.NullOr(Schema.String.check(Schema.isMaxLength(200))),@@ -1188,10 +1300,6 @@11881300 }1189130111901302 if (prepareWorktree && shouldPrepareWorktree && worktreeBaseRef) {1191- const worktree = yield* gitWorkflow.createWorktree({1192- cwd: prepareWorktree.projectCwd,1193- refName: worktreeBaseRef,1194- newRefName: prepareWorktree.branch,1195- baseRefName: prepareWorktree.baseBranch,1196- path: null,1197- });1303+ yield* worktreeSetupTracker.stageStatus(threadId, "checkout", "running");1304+ let checkoutTotal: number | null = null;1305+ const worktree = yield* gitWorkflow.createWorktree(apps/server/src/project/WorktreeSetupTracker.ts line 310Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +249,21 @@249+ }));250+ if (!snapshot) return;251+ yield* clearRetention(threadId);252+ const fiber = yield* remove(threadId).pipe(253+ Effect.delay(FINISHED_RETENTION),254+ Effect.ensuring(255+ Effect.sync(() => {256+ // Only drop our own entry: a newer setup may have replaced it.257+ if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);258+ }),259+ ),260+ Effect.forkDetach,261+ );262+ retentionFibers.set(threadId, fiber);263+ });264+265+ const cancel: WorktreeSetupTracker["Service"]["cancel"] = (threadId) =>266+ Effect.gen(function* () {267+ const current = yield* Ref.get(setups);268+ const tracked = current.get(threadId);269+ if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {
- apps/server/src/ws.ts line 1464OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1215,4 +1445,20 @@1445+ bootstrapThreadDisposition: "deleted",1446+ })1447+ : dispatchError,1448+ ),1449+ }),1450+ );1451+1452+ return yield* runBootstrap.pipe(12151453 Effect.catchCause((cause) => {12161454 const dispatchError = toBootstrapDispatchCommandCauseError(cause);12171455 if (Cause.hasInterruptsOnly(cause)) {1218- return Effect.fail(dispatchError);1456+ // A user cancel interrupts the forked bootstrap fiber. The1457+ // created thread is rolled back like any other failure so the1458+ // draft returns to the composer. The setup terminal is closed1459+ // first so a still-running script cannot hold files open in1460+ // the worktree while git removes it. Closing kills the1461+ // process asynchronously, so the removal retries briefly.1462+ const removeCreatedWorktree =1463+ tracked && targetWorktreePath && bootstrap?.prepareWorktree1464+ ? terminalManager.close({ threadId, deleteHistory: true }).pipe(@@ -1086,13 +1097,19 @@1097+ // fire-and-forget behavior.10861098 const runSetupProgram = () =>10871099 Effect.gen(function* () {10881100 if (!bootstrap?.runSetupScript || !targetWorktreePath) {1101+ yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "skipped"));10891102 return;10901103 }10911104 const worktreePath = targetWorktreePath;10921105 const requestedAt = yield* nowIso;1093- yield* projectSetupScriptRunner1106+ yield* track(worktreeSetupTracker.stageStatus(threadId, "setup-script", "running"));1107+ const setupResult = yield* projectSetupScriptRunner10941108 .runForThread({1095- threadId: command.threadId,1109+ threadId,10961110 ...(targetProjectId ? { projectId: targetProjectId } : {}),10971111 ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),10981112 worktreePath,1113+ ...(tracked1114+ ? {1115+ observeCompletion: {apps/server/src/ws.ts lines 1317 to 1320OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1195,3 +1303,18 @@1195- baseRefName: prepareWorktree.baseBranch,1196- path: null,1197- });1303+ yield* worktreeSetupTracker.stageStatus(threadId, "checkout", "running");1304+ let checkoutTotal: number | null = null;1305+ const worktree = yield* gitWorkflow.createWorktree(1306+ {1307+ cwd: prepareWorktree.projectCwd,1308+ refName: worktreeBaseRef,1309+ newRefName: prepareWorktree.branch,1310+ baseRefName: prepareWorktree.baseBranch,1311+ path: null,1312+ },1313+ {1314+ progress: {1315+ // Known before git writes anything, so a cancel during the1316+ // checkout still removes the half-made directory.1317+ onWorktreePathResolved: (path) =>1318+ Effect.sync(() => {1319+ targetWorktreePath = path;1320+ }),
Sign in to join this conversation.







Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
1bbca0e· PR result:ff6e84a· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.