Skip to content

Commit b4a5156

Browse files
fix(web): keep ChatView identity stable across thread navigation
Review follow-ups. Keying ChatView by thread ref remounted it on every thread-to-thread navigation; key by draft id instead (latched for the promoted thread's on-screen lifetime) so a draft keeps its own instance through promotion while plain threads reuse one. Make a failed setup script's row independent of whether a later turn is running, so it stops popping in and out at turn boundaries. Route every setup state through the same timeline tail so the working, thinking, and queued-message rows never go missing. Derive the collapsed summary from the setup's phase so failed and cancelled setups do not read as ready. Use the Button primitive for the chip. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent c66dfd0 commit b4a5156

10 files changed

Lines changed: 136 additions & 93 deletions

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,11 @@ export const make = Effect.gen(function* () {
259259
if (event.type === "output") {
260260
lineBuffer += event.data;
261261
// A bare carriage return is how installers redraw a progress line in
262-
// place. Treating it as a line break keeps each redraw a short line
263-
// of its own instead of gluing every update into one long one.
262+
// place; each redraw becomes a short line of its own instead of
263+
// being glued into one long one. The wrapper echo is filtered per
264+
// segment too, which is why `echoedWrapperLines` is split on the
265+
// same `\r`: a line editor repainting the typed command yields the
266+
// same segments.
264267
const lines = lineBuffer.split(/\r\n|\r|\n/);
265268
lineBuffer = lines.pop() ?? "";
266269
// A script that never prints a newline must not grow this forever.

‎apps/web/src/components/ChatView.logic.test.ts‎

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2535,43 +2535,33 @@ describe("worktree setup visibility", () => {
25352535
});
25362536

25372537
it("shows a running setup and drops a clean one once the turn started", () => {
2538-
const visible = (
2539-
snapshot: WorktreeSetupSnapshot | null,
2540-
turnStarted: boolean,
2541-
isWorking = true,
2542-
) => resolveVisibleWorktreeSetup({ live: null, recorded: snapshot, turnStarted, isWorking });
2543-
expect(
2544-
resolveVisibleWorktreeSetup({
2545-
live: base,
2546-
recorded: null,
2547-
turnStarted: false,
2548-
isWorking: true,
2549-
}),
2550-
).toEqual(base);
2538+
const visible = (snapshot: WorktreeSetupSnapshot | null, turnStarted: boolean) =>
2539+
resolveVisibleWorktreeSetup({ live: null, recorded: snapshot, turnStarted });
2540+
expect(resolveVisibleWorktreeSetup({ live: base, recorded: null, turnStarted: false })).toEqual(
2541+
base,
2542+
);
25512543
expect(visible(settledDone, false)).toEqual(settledDone);
25522544
expect(visible(settledDone, true)).toBeNull();
2553-
expect(visible(settledDone, true, false)).toBeNull();
25542545
expect(visible(null, true)).toBeNull();
25552546
});
25562547

2557-
it("keeps a failed script visible for the running turn and a failed setup always", () => {
2548+
it("keeps a failed script, a failed setup, and a cancelled setup visible", () => {
25582549
const scriptFailed = {
25592550
...settledDone,
25602551
stages: [stage("checkout", "done"), stage("setup-script", "failed"), stage("agent", "done")],
25612552
};
2562-
const visible = (snapshot: WorktreeSetupSnapshot, isWorking: boolean) =>
2563-
resolveVisibleWorktreeSetup({ live: null, recorded: snapshot, turnStarted: true, isWorking });
2564-
expect(visible(scriptFailed, true)).toEqual(scriptFailed);
2565-
expect(visible(scriptFailed, false)).toBeNull();
2553+
const visible = (snapshot: WorktreeSetupSnapshot) =>
2554+
resolveVisibleWorktreeSetup({ live: null, recorded: snapshot, turnStarted: true });
2555+
expect(visible(scriptFailed)).toEqual(scriptFailed);
25662556
const failed = { ...settledDone, phase: "failed" as const, error: "git exploded" };
2567-
expect(visible(failed, false)).toEqual(failed);
2557+
expect(visible(failed)).toEqual(failed);
25682558
const cancelled = { ...settledDone, phase: "cancelled" as const };
2569-
expect(visible(cancelled, false)).toEqual(cancelled);
2559+
expect(visible(cancelled)).toEqual(cancelled);
25702560
});
25712561

25722562
it("prefers whichever snapshot is newer by sequence", () => {
25732563
const pick = (live: WorktreeSetupSnapshot | null, recorded: WorktreeSetupSnapshot | null) =>
2574-
resolveVisibleWorktreeSetup({ live, recorded, turnStarted: false, isWorking: false });
2564+
resolveVisibleWorktreeSetup({ live, recorded, turnStarted: false });
25752565
expect(pick({ ...base, sequence: 3 }, { ...settledDone, sequence: 7 })).toEqual({
25762566
...settledDone,
25772567
sequence: 7,

‎apps/web/src/components/ChatView.logic.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -281,14 +281,14 @@ export function findRecordedWorktreeSetup(
281281
* running, failed, or cancelled setup always shows. A clean finish leaves no
282282
* trace once the turn is live: the setup is a means to the reply, not part of
283283
* the conversation. Before the turn is live it stays so nothing collapses in
284-
* the handoff gap. A failed script stays while the turn still runs so its
285-
* exit code and terminal remain reachable.
284+
* the handoff gap. A failed script stays for good, so its exit code and
285+
* terminal remain reachable; visibility never depends on whether some later
286+
* turn happens to be running, which would make the row come and go.
286287
*/
287288
export function resolveVisibleWorktreeSetup(input: {
288289
live: WorktreeSetupSnapshot | null;
289290
recorded: WorktreeSetupSnapshot | null;
290291
turnStarted: boolean;
291-
isWorking: boolean;
292292
}): WorktreeSetupSnapshot | null {
293293
const snapshot =
294294
input.live && (!input.recorded || input.live.sequence >= input.recorded.sequence)
@@ -297,8 +297,7 @@ export function resolveVisibleWorktreeSetup(input: {
297297
if (!snapshot) return null;
298298
if (snapshot.phase !== "done") return snapshot;
299299
if (!input.turnStarted) return snapshot;
300-
const stageFailed = snapshot.stages.some((stage) => stage.status === "failed");
301-
return stageFailed && input.isWorking ? snapshot : null;
300+
return snapshot.stages.some((stage) => stage.status === "failed") ? snapshot : null;
302301
}
303302

304303
export function resolveDraftHeroState(input: {

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3529,7 +3529,6 @@ export default function ChatView(props: ChatViewProps) {
35293529
live: liveWorktreeSetup,
35303530
recorded: recordedWorktreeSetup,
35313531
turnStarted: activeThread?.latestTurn?.startedAt != null,
3532-
isWorking,
35333532
});
35343533
// Sends wait for the agent handoff, not for the setup script: an async
35353534
// script keeps the snapshot running while the agent already works, and a

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

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
22
import type { ScopedThreadRef } from "@t3tools/contracts";
33
import { useNavigate } from "@tanstack/react-router";
4-
import { useEffect } from "react";
4+
import { useEffect, useState } from "react";
55

66
import ChatView from "./ChatView";
77
import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic";
@@ -33,13 +33,16 @@ import { resolveThreadSyncPhase } from "../threadSync";
3333

3434
/**
3535
* The single chat surface behind both `/draft/$draftId` and
36-
* `/$environmentId/$threadId`. A draft reserves its thread id up front, so
37-
* one ChatView element keyed by that id carries the draft through its
38-
* promotion to a server thread: the route swap only changes props, nothing
39-
* unmounts, and the timeline never paints an empty frame in between.
36+
* `/$environmentId/$threadId`. Each draft gets its own ChatView instance (so
37+
* a background send's state stays with the draft it came from), and that
38+
* instance carries the draft through its promotion to a server thread: the
39+
* thread route keeps keying by the draft id while the draft record exists,
40+
* so the route swap only changes props and the timeline never paints an
41+
* empty frame. Plain server threads are unkeyed, so navigating between them
42+
* reuses one instance as ChatView expects.
4043
*
4144
* Rendered by the `_chat` layout rather than by the two leaf routes, since
42-
* a keyed element only survives when the same parent renders it.
45+
* an element only survives a route swap when the same parent renders it.
4346
*/
4447
export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
4548
const navigate = useNavigate();
@@ -83,6 +86,25 @@ export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
8386
const draftThread = useComposerDraftStore((store) =>
8487
serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null,
8588
);
89+
const promotedDraftId = useComposerDraftStore((store) =>
90+
target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null,
91+
);
92+
// The draft record is removed once the promoted thread has started, which
93+
// is after the route swap. Latch the key so the element that carried the
94+
// draft keeps its identity for as long as this thread stays on screen.
95+
const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null);
96+
const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null;
97+
const nextChatViewKey =
98+
serverThreadKey === null
99+
? null
100+
: chatViewKey?.threadKey === serverThreadKey
101+
? chatViewKey
102+
: promotedDraftId
103+
? { threadKey: serverThreadKey, key: promotedDraftId }
104+
: null;
105+
if (nextChatViewKey !== chatViewKey) {
106+
setChatViewKey(nextChatViewKey);
107+
}
86108
const environmentHasDraftThreads = useComposerDraftStore((store) =>
87109
serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false,
88110
);
@@ -163,10 +185,7 @@ export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
163185
if (draftSession) {
164186
view = (
165187
<ChatView
166-
key={scopedThreadKey({
167-
environmentId: draftSession.environmentId,
168-
threadId: draftSession.threadId,
169-
})}
188+
key={target.draftId}
170189
draftId={target.draftId}
171190
environmentId={draftSession.environmentId}
172191
threadId={draftSession.threadId}
@@ -178,7 +197,7 @@ export function ThreadRouteView({ target }: { target: ThreadRouteTarget }) {
178197
} else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) {
179198
view = (
180199
<ChatView
181-
key={scopedThreadKey(target.threadRef)}
200+
{...(nextChatViewKey ? { key: nextChatViewKey.key } : {})}
182201
environmentId={target.threadRef.environmentId}
183202
threadId={target.threadRef.threadId}
184203
routeKind="server"

‎apps/web/src/components/chat/MessagesTimeline.logic.test.ts‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1092,19 +1092,20 @@ describe("resolveAssistantMessageCopyState", () => {
10921092
});
10931093

10941094
describe("deriveMessagesTimelineRows", () => {
1095+
const queuedMessage = (id: string, prompt: string) => ({
1096+
id,
1097+
prompt,
1098+
images: [],
1099+
files: [],
1100+
terminalContexts: [],
1101+
previewAnnotations: [],
1102+
reviewComments: [],
1103+
submissionIntent: "foreground" as const,
1104+
queuedAfterToolActivityId: null,
1105+
createdAt: "2026-01-01T00:00:01Z",
1106+
});
1107+
10951108
it("appends queued messages after the live rows, marking the oldest as next", () => {
1096-
const queuedMessage = (id: string, prompt: string) => ({
1097-
id,
1098-
prompt,
1099-
images: [],
1100-
files: [],
1101-
terminalContexts: [],
1102-
previewAnnotations: [],
1103-
reviewComments: [],
1104-
submissionIntent: "foreground" as const,
1105-
queuedAfterToolActivityId: null,
1106-
createdAt: "2026-01-01T00:00:01Z",
1107-
});
11081109
const rows = deriveMessagesTimelineRows({
11091110
timelineEntries: [],
11101111
isWorking: true,
@@ -1203,20 +1204,40 @@ describe("deriveMessagesTimelineRows", () => {
12031204
"worktree-setup",
12041205
]);
12051206

1206-
// A failed setup never handed off, so the card stays under the send.
1207+
// A failed setup never handed off, so the card stays under the send. The
1208+
// rest of the timeline is untouched: a running send still gets its
1209+
// working and thinking rows, and queued follow-ups still trail.
12071210
const withMessages = deriveMessagesTimelineRows({
12081211
timelineEntries: [userEntry, assistantEntry],
12091212
isWorking: true,
12101213
activeTurnStartedAt: "2026-01-01T00:00:00Z",
12111214
turnDiffSummaries: [],
12121215
supportsConversationRollback: false,
12131216
worktreeSetup: { ...snapshot, phase: "failed" },
1217+
queuedMessages: [queuedMessage("q1", "later")],
12141218
});
12151219
expect(withMessages.map((row) => row.kind)).toEqual([
12161220
"message",
12171221
"worktree-setup",
12181222
"working",
12191223
"message",
1224+
"thinking",
1225+
"queued-message",
1226+
]);
1227+
const runningWithQueue = deriveMessagesTimelineRows({
1228+
timelineEntries: [userEntry],
1229+
isWorking: true,
1230+
activeTurnStartedAt: "2026-01-01T00:00:00Z",
1231+
turnDiffSummaries: [],
1232+
supportsConversationRollback: false,
1233+
worktreeSetup: snapshot,
1234+
queuedMessages: [queuedMessage("q1", "later")],
1235+
});
1236+
expect(runningWithQueue.map((row) => row.kind)).toEqual([
1237+
"message",
1238+
"working",
1239+
"worktree-setup",
1240+
"queued-message",
12201241
]);
12211242

12221243
// Once the agent stage is done and the turn is live, a still-running

‎apps/web/src/components/chat/MessagesTimeline.logic.ts‎

Lines changed: 27 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1290,6 +1290,7 @@ export function deriveMessagesTimelineRows(input: {
12901290
input.worktreeSetup !== undefined &&
12911291
worktreeSetupAgentStarted(input.worktreeSetup) &&
12921292
input.latestTurn?.startedAt != null;
1293+
const setupRunning = !setupHandedOff && input.worktreeSetup?.phase === "running";
12931294
if (input.worktreeSetup && (!setupHandedOff || input.worktreeSetup.phase !== "running")) {
12941295
const setupRow = {
12951296
kind: "worktree-setup",
@@ -1301,42 +1302,38 @@ export function deriveMessagesTimelineRows(input: {
13011302
const firstUserRowIndex = nextRows.findIndex(
13021303
(row) => row.kind === "message" && row.message.role === "user",
13031304
);
1304-
if (!setupHandedOff && input.worktreeSetup.phase === "running") {
1305-
// The working header leads the card, in the same slot it keeps once the
1306-
// agent's own turn takes over. The main pass may already have placed
1307-
// that header (isWorking is true while a bootstrap runs); reuse it.
1308-
const workingRowIndex = nextRows.findIndex((row) => row.kind === "working");
1309-
if (workingRowIndex >= 0) {
1310-
nextRows.splice(workingRowIndex + 1, 0, setupRow);
1311-
} else {
1312-
const insertAt = firstUserRowIndex >= 0 ? firstUserRowIndex + 1 : nextRows.length;
1313-
nextRows.splice(
1314-
insertAt,
1315-
0,
1316-
{
1317-
kind: "working",
1318-
id: "working-indicator-row",
1319-
createdAt: input.worktreeSetup.startedAt,
1320-
},
1321-
setupRow,
1322-
);
1323-
}
1324-
return attachTrailingToolGroupsToAssistant(nextRows);
1325-
}
1326-
if (firstUserRowIndex >= 0) {
1327-
nextRows.splice(firstUserRowIndex + 1, 0, setupRow);
1305+
// While the setup runs, the working header leads the card in the same
1306+
// slot it keeps once the agent's own turn takes over. The main pass may
1307+
// already have placed that header (a bootstrap counts as working).
1308+
const workingRowIndex = setupRunning ? nextRows.findIndex((row) => row.kind === "working") : -1;
1309+
if (workingRowIndex >= 0) {
1310+
nextRows.splice(workingRowIndex + 1, 0, setupRow);
13281311
} else {
1329-
nextRows.push(setupRow);
1330-
}
1331-
if (!setupHandedOff) {
1332-
return attachTrailingToolGroupsToAssistant(nextRows);
1312+
const insertAt = firstUserRowIndex >= 0 ? firstUserRowIndex + 1 : nextRows.length;
1313+
nextRows.splice(
1314+
insertAt,
1315+
0,
1316+
...(setupRunning
1317+
? [
1318+
{
1319+
kind: "working",
1320+
id: "working-indicator-row",
1321+
createdAt: input.worktreeSetup.startedAt,
1322+
} as const,
1323+
setupRow,
1324+
]
1325+
: [setupRow]),
1326+
);
13331327
}
13341328
}
13351329

1336-
if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1330+
// A running setup owns the working slot above its card and shows no
1331+
// activity row of its own; every other state gets the usual tail.
1332+
const hasWorkingRow = nextRows.some((row) => row.kind === "working");
1333+
if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === input.timelineEntries.length) {
13371334
appendWorkingRow();
13381335
}
1339-
if (input.isWorking && (!hasActivityRow || latestToolFailed)) {
1336+
if (input.isWorking && !setupRunning && (!hasActivityRow || latestToolFailed)) {
13401337
nextRows.push({
13411338
kind: "thinking",
13421339
id: LIVE_ACTIVITY_ROW_ID,

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2286,8 +2286,8 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnap
22862286
<Popover>
22872287
<PopoverTrigger
22882288
render={
2289-
<button
2290-
type="button"
2289+
<Button
2290+
variant="chip"
22912291
className="ml-auto inline-flex h-5 min-w-0 shrink-0 items-center gap-1 rounded-full border border-border/70 px-2 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
22922292
aria-label={`${scriptName} is still running. Show setup progress.`}
22932293
/>

‎apps/web/src/components/chat/WorktreeSetupCard.tsx‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,8 @@ function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
287287

288288
/**
289289
* One-line summary of a settled setup under a live turn. A clean finish is
290-
* removed from the timeline altogether, so this only ever renders the
291-
* script-failed outcome while the turn still runs and the terminal matters.
290+
* removed from the timeline altogether, so this only renders the outcomes
291+
* worth keeping: a failed script, a failed setup, or a cancelled one.
292292
*/
293293
function CollapsedSummaryRow({
294294
snapshot,
@@ -297,11 +297,13 @@ function CollapsedSummaryRow({
297297
snapshot: WorktreeSetupSnapshot;
298298
totalElapsed: number | null;
299299
}) {
300-
const scriptFailed = snapshot.stages.some(
301-
(stage) => stage.id === "setup-script" && stage.status === "failed",
302-
);
303-
const status: WorktreeSetupStage["status"] = scriptFailed ? "failed" : "done";
304-
const label = scriptFailed ? "Worktree ready, setup script failed" : "Worktree ready";
300+
const status: WorktreeSetupStage["status"] =
301+
snapshot.phase === "failed" || snapshot.phase === "cancelled"
302+
? "failed"
303+
: snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed")
304+
? "failed"
305+
: "done";
306+
const label = headerLabel(snapshot);
305307
return (
306308
<div
307309
className={cn(

0 commit comments

Comments
 (0)