Skip to content

Commit 79fad28

Browse files
t3dotggclaude
andcommitted
fix(server): bound setup snapshot delivery and keep the finished card visible
Second review round: - The tracker stream now hands each subscriber a one-slot sliding mailbox, so a stalled WebSocket holds one snapshot instead of every output line. Sequences keep increasing across setups of the same thread, and finished retention fibers are removed from the map when they expire. - A setup script that fails no longer aborts the bootstrap, matching the untracked path. The card shows the failed stage and the terminal stays open. The header reads "Worktree ready, setup script failed". - Worktree removal on cancel retries briefly, since closing the terminal kills its process asynchronously. - The web card renders its done state until the agent's turn appears, sits directly under the first user message, only offers "Open terminal" while the setup thread is still active, and only offers "Work locally" on local drafts. - Empty echoed wrapper lines no longer suppress all setup output. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 7a39bff commit 79fad28

8 files changed

Lines changed: 229 additions & 72 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ export const make = Effect.gen(function* () {
343343
? yield* observeTerminalCompletion({
344344
threadId: input.threadId,
345345
terminalId,
346-
echoedWrapperLines: commandLine.split("\r"),
346+
echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
347347
onOutputLine: observe.onOutputLine,
348348
})
349349
: undefined;

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

Lines changed: 80 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { describe, expect, it } from "@effect/vitest";
22
import { ThreadId } from "@t3tools/contracts";
33
import * as Deferred from "effect/Deferred";
4+
import * as Duration from "effect/Duration";
45
import * as Effect from "effect/Effect";
56
import * as Exit from "effect/Exit";
67
import * as Fiber from "effect/Fiber";
78
import * as Stream from "effect/Stream";
9+
import * as TestClock from "effect/testing/TestClock";
810

911
import * as WorktreeSetupTracker from "./WorktreeSetupTracker.ts";
1012

@@ -47,7 +49,37 @@ describe("WorktreeSetupTracker", () => {
4749
}),
4850
);
4951

50-
it.effect("stream drops queued changes already folded into the initial snapshot", () =>
52+
it.effect("stream emits the current snapshot first and then only newer ones", () =>
53+
Effect.gen(function* () {
54+
const tracker = yield* WorktreeSetupTracker.make;
55+
yield* tracker.begin({
56+
threadId,
57+
branch: null,
58+
baseRef: null,
59+
stages: ["agent"],
60+
fiber: null,
61+
});
62+
63+
const collected = yield* tracker.stream(threadId).pipe(
64+
Stream.takeUntil((snapshot) => snapshot?.sequence === 2),
65+
Stream.runCollect,
66+
Effect.forkChild,
67+
);
68+
yield* Effect.yieldNow;
69+
yield* tracker.stageStatus(threadId, "agent", "running");
70+
yield* tracker.appendTail(threadId, "agent", "line 1");
71+
72+
const snapshots = yield* Fiber.join(collected);
73+
const sequences = snapshots.map((snapshot) => snapshot?.sequence ?? -1);
74+
expect(sequences.at(-1)).toBe(2);
75+
// Delivery is latest-value per subscriber, so intermediates may be
76+
// skipped but never delivered out of order.
77+
expect(sequences).toEqual([...sequences].toSorted((a, b) => a - b));
78+
expect(snapshots.at(-1)?.stages[0]?.tail).toEqual(["line 1"]);
79+
}),
80+
);
81+
82+
it.effect("stream never steps back behind the snapshot it started from", () =>
5183
Effect.gen(function* () {
5284
const tracker = yield* WorktreeSetupTracker.make;
5385
yield* tracker.begin({
@@ -60,40 +92,72 @@ describe("WorktreeSetupTracker", () => {
6092
yield* tracker.stageStatus(threadId, "agent", "running");
6193
yield* tracker.stageStatus(threadId, "agent", "done");
6294

63-
// A late subscriber sees sequence 2 first and must never see 0 or 1.
64-
const collected = yield* tracker
65-
.stream(threadId)
66-
.pipe(Stream.take(2), Stream.runCollect, Effect.forkChild);
95+
// A late subscriber starts at sequence 2 and must never see 0 or 1.
96+
const collected = yield* tracker.stream(threadId).pipe(
97+
Stream.takeUntil((snapshot) => snapshot?.phase === "done"),
98+
Stream.runCollect,
99+
Effect.forkChild,
100+
);
67101
yield* Effect.yieldNow;
68102
yield* tracker.finish(threadId, "done");
69103

70104
const snapshots = yield* Fiber.join(collected);
71-
expect(snapshots.map((snapshot) => snapshot?.sequence)).toEqual([2, 3]);
105+
expect(snapshots.length).toBeGreaterThan(0);
106+
expect(snapshots.every((snapshot) => (snapshot?.sequence ?? -1) >= 2)).toBe(true);
107+
expect(snapshots.at(-1)?.phase).toBe("done");
72108
}),
73109
);
74110

75-
it.effect("stream emits the current snapshot first and then every change", () =>
111+
it.effect("a new setup on the same thread keeps sequences increasing", () =>
76112
Effect.gen(function* () {
77113
const tracker = yield* WorktreeSetupTracker.make;
78114
yield* tracker.begin({
79115
threadId,
80-
branch: null,
116+
branch: "first",
81117
baseRef: null,
82118
stages: ["agent"],
83119
fiber: null,
84120
});
121+
yield* tracker.finish(threadId, "failed", "boom");
122+
const failedSequence = (yield* tracker.get(threadId))?.sequence ?? -1;
85123

86-
const collected = yield* tracker
87-
.stream(threadId)
88-
.pipe(Stream.take(3), Stream.runCollect, Effect.forkChild);
89-
// Give the subscription time to attach before publishing.
124+
// A stream opened on the failed setup must still receive the next one.
125+
const collected = yield* tracker.stream(threadId).pipe(
126+
Stream.takeUntil((snapshot) => snapshot?.branch === "second"),
127+
Stream.runCollect,
128+
Effect.forkChild,
129+
);
90130
yield* Effect.yieldNow;
91-
yield* tracker.stageStatus(threadId, "agent", "running");
92-
yield* tracker.appendTail(threadId, "agent", "line 1");
131+
yield* tracker.begin({
132+
threadId,
133+
branch: "second",
134+
baseRef: null,
135+
stages: ["agent"],
136+
fiber: null,
137+
});
93138

94139
const snapshots = yield* Fiber.join(collected);
95-
expect(snapshots.map((snapshot) => snapshot?.sequence)).toEqual([0, 1, 2]);
96-
expect(snapshots[2]?.stages[0]?.tail).toEqual(["line 1"]);
140+
const last = snapshots.at(-1);
141+
expect(last?.phase).toBe("running");
142+
expect(last?.sequence).toBeGreaterThan(failedSequence);
143+
}),
144+
);
145+
146+
it.effect("finished setups are dropped after the retention window", () =>
147+
Effect.gen(function* () {
148+
const tracker = yield* WorktreeSetupTracker.make;
149+
yield* tracker.begin({
150+
threadId,
151+
branch: null,
152+
baseRef: null,
153+
stages: ["agent"],
154+
fiber: null,
155+
});
156+
yield* tracker.finish(threadId, "done");
157+
expect((yield* tracker.get(threadId))?.phase).toBe("done");
158+
159+
yield* TestClock.adjust(Duration.seconds(31));
160+
expect(yield* tracker.get(threadId)).toBeNull();
97161
}),
98162
);
99163

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

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as Effect from "effect/Effect";
1212
import * as Fiber from "effect/Fiber";
1313
import * as Layer from "effect/Layer";
1414
import * as PubSub from "effect/PubSub";
15+
import * as Queue from "effect/Queue";
1516
import * as Ref from "effect/Ref";
1617
import * as Stream from "effect/Stream";
1718

@@ -104,6 +105,9 @@ export const make = Effect.gen(function* () {
104105
readonly snapshot: WorktreeSetupSnapshot | null;
105106
}>();
106107
const retentionFibers = new Map<ThreadId, Fiber.Fiber<void, never>>();
108+
// Sequences keep increasing across setups of the same thread so a stream
109+
// opened during a previous setup still accepts the next one's first snapshot.
110+
const lastSequenceByThread = new Map<ThreadId, number>();
107111

108112
const publish = (threadId: ThreadId, snapshot: WorktreeSetupSnapshot | null) =>
109113
PubSub.publish(changes, { threadId, snapshot }).pipe(Effect.asVoid);
@@ -120,6 +124,7 @@ export const make = Effect.gen(function* () {
120124
...nextTracked.snapshot,
121125
sequence: existing.snapshot.sequence + 1,
122126
};
127+
lastSequenceByThread.set(threadId, nextSnapshot.sequence);
123128
const next = new Map(current);
124129
next.set(threadId, { ...nextTracked, snapshot: nextSnapshot });
125130
return [nextSnapshot, next] as const;
@@ -155,8 +160,9 @@ export const make = Effect.gen(function* () {
155160
setupScript: null,
156161
stages: ordered.map(emptyStage),
157162
error: null,
158-
sequence: 0,
163+
sequence: (lastSequenceByThread.get(input.threadId) ?? -1) + 1,
159164
};
165+
lastSequenceByThread.set(input.threadId, snapshot.sequence);
160166
yield* Ref.update(setups, (current) => {
161167
const next = new Map(current);
162168
next.set(input.threadId, { snapshot, fiber: input.fiber });
@@ -240,6 +246,12 @@ export const make = Effect.gen(function* () {
240246
yield* clearRetention(threadId);
241247
const fiber = yield* remove(threadId).pipe(
242248
Effect.delay(FINISHED_RETENTION),
249+
Effect.ensuring(
250+
Effect.sync(() => {
251+
// Only drop our own entry: a newer setup may have replaced it.
252+
if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);
253+
}),
254+
),
243255
Effect.forkDetach,
244256
);
245257
retentionFibers.set(threadId, fiber);
@@ -259,26 +271,34 @@ export const make = Effect.gen(function* () {
259271
const get: WorktreeSetupTracker["Service"]["get"] = (threadId) =>
260272
Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null));
261273

274+
/**
275+
* Each subscriber gets a one-slot sliding mailbox: a slow WebSocket only
276+
* ever holds the newest snapshot, so a chatty setup script cannot grow the
277+
* server heap. Snapshots are whole states, so skipping intermediates is safe.
278+
*/
262279
const stream: WorktreeSetupTracker["Service"]["stream"] = (threadId) =>
263-
Stream.unwrap(
264-
Effect.gen(function* () {
265-
const subscription = yield* PubSub.subscribe(changes);
266-
const initial = yield* get(threadId);
267-
// Changes published between subscribing and reading `initial` are
268-
// already folded into it. Drop them so the client never steps back.
269-
const initialSequence = initial?.sequence ?? -1;
270-
return Stream.concat(
271-
Stream.make(initial),
272-
Stream.fromSubscription(subscription).pipe(
273-
Stream.filter(
274-
(change) =>
275-
change.threadId === threadId &&
276-
(change.snapshot === null || change.snapshot.sequence > initialSequence),
280+
Stream.callback<WorktreeSetupSnapshot | null>(
281+
(mailbox) =>
282+
Effect.gen(function* () {
283+
const subscription = yield* PubSub.subscribe(changes);
284+
const initial = yield* get(threadId);
285+
// Changes published between subscribing and reading `initial` are
286+
// already folded into it. Drop them so the client never steps back.
287+
let lastSequence = initial?.sequence ?? -1;
288+
Queue.offerUnsafe(mailbox, initial);
289+
yield* Stream.fromSubscription(subscription).pipe(
290+
Stream.runForEach((change) =>
291+
Effect.sync(() => {
292+
if (change.threadId !== threadId) return;
293+
if (change.snapshot !== null && change.snapshot.sequence <= lastSequence) return;
294+
lastSequence = change.snapshot?.sequence ?? lastSequence;
295+
Queue.offerUnsafe(mailbox, change.snapshot);
296+
}),
277297
),
278-
Stream.map((change) => change.snapshot),
279-
),
280-
);
281-
}),
298+
Effect.forkScoped,
299+
);
300+
}),
301+
{ bufferSize: 1, strategy: "sliding" },
282302
);
283303

284304
return WorktreeSetupTracker.of({

‎apps/server/src/ws.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import * as Option from "effect/Option";
1313
import * as Path from "effect/Path";
1414
import * as Queue from "effect/Queue";
1515
import * as Ref from "effect/Ref";
16+
import * as Schedule from "effect/Schedule";
1617
import * as Schema from "effect/Schema";
1718
import * as Stream from "effect/Stream";
1819
import {
@@ -1168,6 +1169,9 @@ const makeWsRpcLayer = (
11681169
if (!tracked || !setupResult?.completion) {
11691170
return;
11701171
}
1172+
// The setup script is best effort, like the untracked path: a
1173+
// failed install must not throw away the worktree the user just
1174+
// waited for. The card keeps the failed stage and its terminal.
11711175
const completion = yield* setupResult.completion;
11721176
if (completion.exitCode === 0) {
11731177
yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "done");
@@ -1178,9 +1182,6 @@ const makeWsRpcLayer = (
11781182
? "terminal closed before the script finished"
11791183
: `exit ${completion.exitCode}`;
11801184
yield* worktreeSetupTracker.stageStatus(threadId, "setup-script", "failed", detail);
1181-
return yield* new OrchestrationDispatchCommandError({
1182-
message: `Setup script failed (${detail}). Open the setup terminal for details.`,
1183-
});
11841185
});
11851186

11861187
const bootstrapProgram = Effect.gen(function* () {
@@ -1402,17 +1403,22 @@ const makeWsRpcLayer = (
14021403
// created thread is rolled back like any other failure so the
14031404
// draft returns to the composer. The setup terminal is closed
14041405
// first so a still-running script cannot hold files open in
1405-
// the worktree while git removes it.
1406+
// the worktree while git removes it. Closing kills the
1407+
// process asynchronously, so the removal retries briefly.
14061408
const removeCreatedWorktree =
14071409
tracked && targetWorktreePath && bootstrap?.prepareWorktree
14081410
? terminalManager.close({ threadId, deleteHistory: true }).pipe(
14091411
Effect.ignoreCause({ log: true }),
14101412
Effect.andThen(
1411-
gitWorkflow.removeWorktree({
1412-
cwd: bootstrap.prepareWorktree.projectCwd,
1413-
path: targetWorktreePath,
1414-
force: true,
1415-
}),
1413+
gitWorkflow
1414+
.removeWorktree({
1415+
cwd: bootstrap.prepareWorktree.projectCwd,
1416+
path: targetWorktreePath,
1417+
force: true,
1418+
})
1419+
.pipe(
1420+
Effect.retry({ times: 4, schedule: Schedule.spaced("500 millis") }),
1421+
),
14161422
),
14171423
Effect.ignoreCause({ log: true }),
14181424
Effect.uninterruptible,

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

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3350,35 +3350,42 @@ export default function ChatView(props: ChatViewProps) {
33503350
);
33513351
const latestWorktreeSetup = worktreeSetupQuery.data;
33523352
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);
3357-
setHeldWorktreeSetup(null);
3358-
return;
3359-
}
33603353
// 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);
3354+
// Hold the last real snapshot so a settled card does not vanish.
3355+
if (latestWorktreeSetup) setHeldWorktreeSetup(latestWorktreeSetup);
33633356
}, [latestWorktreeSetup]);
33643357
const worktreeSetup =
33653358
worktreeSetupActive && heldWorktreeSetup?.threadId === worktreeSetupRef.threadId
33663359
? heldWorktreeSetup
33673360
: null;
3361+
// A finished card is dropped once the agent's turn shows in the timeline:
3362+
// the card belongs to the send, and the agent takes over from there.
3363+
const worktreeSetupDoneAndTurnVisible =
3364+
worktreeSetup?.phase === "done" && activeThread?.latestTurn?.startedAt != null;
3365+
useEffect(() => {
3366+
if (!worktreeSetupDoneAndTurnVisible) return;
3367+
setWorktreeSetupRef(null);
3368+
setHeldWorktreeSetup(null);
3369+
}, [worktreeSetupDoneAndTurnVisible]);
33683370
const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
33693371
reportFailure: false,
33703372
});
33713373
const onCancelWorktreeSetup = useCallback(() => {
33723374
if (!worktreeSetup || worktreeSetup.phase !== "running") return;
33733375
void cancelWorktreeSetup({ environmentId, input: { threadId: worktreeSetup.threadId } });
33743376
}, [cancelWorktreeSetup, environmentId, worktreeSetup]);
3375-
const onOpenWorktreeSetupTerminal = useCallback(
3376-
(terminalId: string) => {
3377-
if (!activeThreadRef) return;
3378-
storeEnsureTerminal(activeThreadRef, terminalId, { open: true, active: true });
3379-
},
3380-
[activeThreadRef, storeEnsureTerminal],
3381-
);
3377+
// The setup terminal belongs to the thread that was set up. A failed
3378+
// bootstrap deletes that thread and closes its terminals, so only offer the
3379+
// terminal while the setup thread is still the active one.
3380+
const onOpenWorktreeSetupTerminal = useMemo(() => {
3381+
if (!worktreeSetup || !activeThreadRef || worktreeSetup.threadId !== activeThreadRef.threadId) {
3382+
return null;
3383+
}
3384+
const setupThreadRef = activeThreadRef;
3385+
return (terminalId: string) => {
3386+
storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });
3387+
};
3388+
}, [activeThreadRef, storeEnsureTerminal, worktreeSetup]);
33823389
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
33833390
const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);
33843391
const manualCompactionProviderAvailable = useMemo(
@@ -8734,8 +8741,8 @@ export default function ChatView(props: ChatViewProps) {
87348741
activeTurnStartedAt={paintOnlyDisplayedTimeline ? null : activeWorkStartedAt}
87358742
worktreeSetup={paintOnlyDisplayedTimeline ? null : worktreeSetup}
87368743
onCancelWorktreeSetup={onCancelWorktreeSetup}
8737-
onWorktreeSetupWorkLocally={onWorktreeSetupWorkLocally}
8738-
onOpenWorktreeSetupTerminal={onOpenWorktreeSetupTerminal}
8744+
{...(isLocalDraftThread ? { onWorktreeSetupWorkLocally } : {})}
8745+
{...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
87398746
listRef={legendListRef}
87408747
timelineEntries={displayedTimeline.entries}
87418748
latestTurn={paintOnlyDisplayedTimeline ? null : activeLatestTurn}

0 commit comments

Comments
 (0)