diff --git a/apps/desktop/src/state/fold.test.ts b/apps/desktop/src/state/fold.test.ts index 721007b2f..70f8d5ea6 100644 --- a/apps/desktop/src/state/fold.test.ts +++ b/apps/desktop/src/state/fold.test.ts @@ -14,6 +14,7 @@ import { toolGroupLabel, turnChangeLine, turnFoldKey, + turnItemsByEnd, } from "./fold"; import type { TranscriptItem } from "./thread"; @@ -680,4 +681,23 @@ describe("woken continuation turns", () => { const rows = foldTurns(items, false, new Set()); expect(keys(rows)).toEqual(["u1", `[${turnFoldKey("e1")}]`, "r1", "e1", "[fold-cmd2]", "r2"]); }); + + test("turnItemsByEnd slices replayed turns without turnEnd and keeps them out of later live turns", () => { + const replayed: TranscriptItem[] = [ + user("u1"), + tool("c1"), + reply("r1"), + user("u2"), + reply("r2"), + user("u3"), + tool("c3"), + reply("r3"), + end("e3", 4_000), + ]; + const byEnd = turnItemsByEnd(replayed); + expect(Object.keys(byEnd)).toEqual(["u1", "u2", "e3"]); + expect(byEnd.u1?.map((item) => item.id)).toEqual(["u1", "c1", "r1"]); + expect(byEnd.u2?.map((item) => item.id)).toEqual(["u2", "r2"]); + expect(byEnd.e3?.map((item) => item.id)).toEqual(["u3", "c3", "r3", "e3"]); + }); }); diff --git a/apps/desktop/src/state/fold.ts b/apps/desktop/src/state/fold.ts index d36d57d24..b86006d37 100644 --- a/apps/desktop/src/state/fold.ts +++ b/apps/desktop/src/state/fold.ts @@ -598,26 +598,51 @@ export function keepUnchangedRows(previous: readonly } /** - * Each finished turn's own items, by its footer's id: everything since the - * turn before it, so a wake turn (which has no message of its own) comes out - * whole. A turn whose items are the ones `previous` held keeps that array, so - * its footer's Trace is not handed a new one on every streamed chunk. + * Each finished turn's own items, by its footer's id (or its opening row's id + * for a replayed turn without a footer): everything since the turn before it, + * so a wake turn (which has no message of its own) comes out whole. A turn + * whose items are the ones `previous` held keeps that array, so its footer's + * Trace is not handed a new one on every streamed chunk. */ export function turnItemsByEnd( items: readonly TranscriptItem[], previous: Readonly> = {}, + running = false, ): Record { const map: Record = {}; let from = 0; - items.forEach((item, i) => { - if (item.kind !== "turnEnd") return; - const old = previous[item.id]; - const length = i + 1 - from; + let userId: string | undefined; + let worked = false; + const record = (id: string, to: number) => { + const old = previous[id]; + const length = to - from; let kept = old?.length === length; for (let k = 0; kept && k < length; k++) kept = old![k] === items[from + k]; - map[item.id] = kept ? old! : items.slice(from, i + 1); - from = i + 1; - }); + map[id] = kept ? old! : items.slice(from, to); + from = to; + userId = undefined; + worked = false; + }; + for (let i = 0; i <= items.length; i++) { + const item = items[i]; + const ended = i > from && items[i - 1]!.kind === "turnEnd"; + const nextTurn = + i > from && + !ended && + worked && + ((item?.kind === "user" && !item.steered) || (i === items.length && !running)); + if (ended) { + record(items[i - 1]!.id, i); + } else if (nextTurn) { + record(userId ?? items[from]!.id, i); + } + if (!item) break; + if (item.kind === "user" && !item.steered) { + userId ??= item.id; + } else if (item.kind === "assistant" || item.kind === "tool" || item.kind === "thought") { + worked = true; + } + } return map; } diff --git a/apps/desktop/src/state/thread.test.ts b/apps/desktop/src/state/thread.test.ts index a441c586e..1d294df4a 100644 --- a/apps/desktop/src/state/thread.test.ts +++ b/apps/desktop/src/state/thread.test.ts @@ -195,6 +195,8 @@ describe("thread reducer", () => { { kind: "user", text: "1" }, { kind: "agent", text: "a", turn: { elapsedMs: 5000, outcome: "completed" } }, { kind: "user", text: "2" }, + { kind: "agent", text: "", turn: { elapsedMs: 3000, outcome: "cancelled" } }, + { kind: "user", text: "3" }, { kind: "agent", text: "b", turn: { elapsedMs: 7000, outcome: "completed" } }, ]), ); @@ -203,10 +205,13 @@ describe("thread reducer", () => { "assistant", "turnEnd", "user", + "turnEnd", + "user", "assistant", "turnEnd", ]); - expect(s.items[5]).toMatchObject({ elapsedMs: 7000 }); + expect(s.items[4]).toMatchObject({ elapsedMs: 3000, outcome: "cancelled" }); + expect(s.items[7]).toMatchObject({ elapsedMs: 7000 }); expect(isLoaded(s)).toBe(true); }); diff --git a/apps/desktop/src/state/thread.ts b/apps/desktop/src/state/thread.ts index 0c02ed280..ab52dec35 100644 --- a/apps/desktop/src/state/thread.ts +++ b/apps/desktop/src/state/thread.ts @@ -640,7 +640,6 @@ export function applyUpdate(state: ThreadState, update: SessionUpdate, now = Dat }; } case "agent": { - if (!update.text) return state; const pendingTurn = update.turn ? { id: update.turn.id, @@ -649,13 +648,18 @@ export function applyUpdate(state: ThreadState, update: SessionUpdate, now = Dat outcome: update.turn.outcome, } : state.pendingTurn; + if (!update.text) return pendingTurn === state.pendingTurn ? state : { ...state, pendingTurn }; const items = finishThoughts(state.items, now); const tail = items[items.length - 1]; if (tail?.kind === "assistant") { return { ...state, pendingTurn, - items: replaceLast(items, { ...tail, text: tail.text + update.text }), + items: replaceLast(items, { + ...tail, + text: tail.text + update.text, + ...(update.at !== undefined ? { at: update.at } : {}), + }), }; } return { diff --git a/apps/desktop/src/ui/OverviewLog.tsx b/apps/desktop/src/ui/OverviewLog.tsx index 8125581d0..65f0cead3 100644 --- a/apps/desktop/src/ui/OverviewLog.tsx +++ b/apps/desktop/src/ui/OverviewLog.tsx @@ -114,6 +114,7 @@ function TurnRow({ export function ExecutionLogSection({ items, + running, usage, harness, model, @@ -121,6 +122,7 @@ export function ExecutionLogSection({ onToggle, }: { items: readonly TranscriptItem[]; + running?: boolean; /** The thread's own totals, which are what the store says it spent. */ usage?: SessionUsage; harness?: string; @@ -129,7 +131,7 @@ export function ExecutionLogSection({ folded: boolean; onToggle: () => void; }) { - const turns = useMemo(() => turnEntries(items), [items]); + const turns = useMemo(() => turnEntries(items, running), [items, running]); const totals = useMemo(() => logTotals(turns, usage), [turns, usage]); const [all, setAll] = useState(false); // Newest first: the turn a reader is waiting on is the one at the top of the list. @@ -139,7 +141,10 @@ export function ExecutionLogSection({ }, [turns, all]); // Each finished turn with the rows it ran, for the waterfall its row can open: // read when the log is expanded and not on every chunk of the turn it watches. - const turnItems = useMemo(() => (all ? turnItemsByEnd(items) : NO_TURNS), [items, all]); + const turnItems = useMemo( + () => (all ? turnItemsByEnd(items, undefined, running) : NO_TURNS), + [items, all, running], + ); const ends = useMemo(() => { const map = new Map>(); for (const item of items) if (item.kind === "turnEnd") map.set(item.id, item); diff --git a/apps/desktop/src/ui/ThreadDetails.tsx b/apps/desktop/src/ui/ThreadDetails.tsx index f48f48d2b..850f5d11a 100644 --- a/apps/desktop/src/ui/ThreadDetails.tsx +++ b/apps/desktop/src/ui/ThreadDetails.tsx @@ -13,8 +13,9 @@ import { contextPercent } from "../state/details"; import { turnItemsByEnd } from "../state/fold"; import { formatCost } from "../state/pricing"; import { PULL_LIMIT, usePullList } from "../state/pullQueries"; +import { engineBusy } from "../state/runState"; import { showPanel, useApp, worktreeOf } from "../state/store"; -import { formatDuration, formatTokens, isRunning, type TranscriptItem } from "../state/thread"; +import { formatDuration, formatTokens, isLoading, isRunning, type TranscriptItem } from "../state/thread"; import { relativeAge } from "../state/threadFormat"; import { splitThreadKey } from "../state/threadKeys"; import { statusOf } from "../state/threadStatus"; @@ -92,6 +93,7 @@ export function ThreadDetails() { const status = useApp((s) => (s.selectedId ? statusOf(s, s.selectedId) : "idle")); const items = thread?.items; const counts = useMemo(() => threadCounts(items ?? []), [items]); + const running = isRunning(thread) || isLoading(thread) || !!thread?.enginePhase || engineBusy(status); const changes = useChanges(host ? undefined : thread?.cwd, isRunning(thread)); // Which sections are folded away: the reader's habit, kept for every thread. const [folded, setFolded] = useState(readFolded); @@ -244,7 +246,14 @@ export function ThreadDetails() { )} - + ); } @@ -315,17 +324,19 @@ const OUTCOME = { /** Finished turns, newest first. Open a row for its messages and calls. */ function TurnsSection({ items, + running, model, folded, onToggle, }: { items: readonly TranscriptItem[]; + running?: boolean; model?: string; folded: boolean; onToggle: (id: SectionId) => void; }) { - const turns = useMemo(() => [...turnEntries(items)].reverse(), [items]); - const byEnd = useMemo(() => turnItemsByEnd(items), [items]); + const turns = useMemo(() => [...turnEntries(items, running)].reverse(), [items, running]); + const byEnd = useMemo(() => turnItemsByEnd(items, undefined, running), [items, running]); const ends = useMemo(() => { const map = new Map>(); for (const item of items) if (item.kind === "turnEnd") map.set(item.id, item); diff --git a/apps/desktop/src/ui/Transcript.tsx b/apps/desktop/src/ui/Transcript.tsx index 6fbf4ea92..2261be815 100644 --- a/apps/desktop/src/ui/Transcript.tsx +++ b/apps/desktop/src/ui/Transcript.tsx @@ -760,9 +760,9 @@ export function Transcript({ // A finished turn keeps its array, so its memoised footer skips a streamed chunk. const drawnTurnItems = useRef>({}); const turnItems = useMemo(() => { - drawnTurnItems.current = turnItemsByEnd(thread.items, drawnTurnItems.current); + drawnTurnItems.current = turnItemsByEnd(thread.items, drawnTurnItems.current, running); return drawnTurnItems.current; - }, [thread.items]); + }, [thread.items, running]); // Turn footers that render nothing at all. Nothing measures a row that never mounts, so the // virtualizer has to estimate no height for it, or every row below drifts by a footer. diff --git a/apps/desktop/src/ui/overview.test.ts b/apps/desktop/src/ui/overview.test.ts index 4b3c95a39..7b119d34d 100644 --- a/apps/desktop/src/ui/overview.test.ts +++ b/apps/desktop/src/ui/overview.test.ts @@ -215,6 +215,32 @@ describe("the thread's turns", () => { expect(turnHasTrace({ id: "e1", prompt: "", outcome: "completed", startedAt: 5, at: 5 })).toBe(false); expect(turnHasTrace({ id: "e1", prompt: "", outcome: "completed", at: 5 })).toBe(false); }); + + test("replayed turns without turnEnd footers stay listed across restarts and while a new turn runs", () => { + const replayed: TranscriptItem[] = [ + { kind: "user", id: "u1", text: "Inspect the sidebar" }, + { kind: "tool", id: "c1", title: "Read", status: "completed", diffs: [] }, + { kind: "assistant", id: "a1", text: "Found the turns section." }, + { kind: "user", id: "u2", text: "Fix the replay" }, + { kind: "assistant", id: "a2", text: "Done." }, + ]; + expect(turnEntries(replayed)).toEqual([ + { id: "u1", prompt: "Inspect the sidebar", outcome: "completed" }, + { id: "u2", prompt: "Fix the replay", outcome: "completed" }, + ]); + const withLiveTail: TranscriptItem[] = [ + ...replayed, + { kind: "user", id: "u3", text: "Run the checks" }, + { kind: "thought", id: "t3", text: "Checking", summary: false, startedAt: 1, done: false }, + ]; + expect(turnEntries(withLiveTail, true).map((turn) => turn.id)).toEqual(["u1", "u2"]); + const afterLiveEnd: TranscriptItem[] = [...withLiveTail, turnEnd("e3", { elapsedMs: 3000 })]; + expect(turnEntries(afterLiveEnd, false).map((turn) => [turn.id, turn.prompt])).toEqual([ + ["u1", "Inspect the sidebar"], + ["u2", "Fix the replay"], + ["e3", "Run the checks"], + ]); + }); }); describe("the log's stats", () => { diff --git a/apps/desktop/src/ui/overview.ts b/apps/desktop/src/ui/overview.ts index 305f1a130..f0dfdb48b 100644 --- a/apps/desktop/src/ui/overview.ts +++ b/apps/desktop/src/ui/overview.ts @@ -315,28 +315,55 @@ function promptLine(text: string): string { /** * The thread's turns, oldest first, each with the message that opened it. A * turn the app woke the thread for has no message of its own, so its row says - * what woke it instead of borrowing the one above. + * what woke it instead of borrowing the one above. A replayed turn that carries + * no `turnEnd` footer of its own still closes before the next message, and at + * the end of the transcript once the thread is idle. */ -export function turnEntries(items: readonly TranscriptItem[]): TurnEntry[] { +export function turnEntries(items: readonly TranscriptItem[], running = false): TurnEntry[] { const entries: TurnEntry[] = []; + let from = 0; let prompt = ""; - let woke = false; - for (const item of items) { - if (item.kind === "user") { - woke = !!item.wake; - prompt = woke ? "Woken for a delegate" : promptLine(item.text); - continue; + let userId: string | undefined; + let worked = false; + for (let i = 0; i <= items.length; i++) { + const item = items[i]; + const ended = i > from && items[i - 1]!.kind === "turnEnd"; + const nextTurn = + i > from && + !ended && + worked && + ((item?.kind === "user" && !item.steered) || (i === items.length && !running)); + if (ended) { + const end = items[i - 1] as Extract; + entries.push({ + id: end.id, + prompt: prompt || "No message", + at: end.at, + startedAt: end.startedAt, + outcome: end.outcome, + elapsedMs: end.elapsedMs, + ...turnUsage(end.usage), + }); + from = i; + userId = undefined; + worked = false; + } else if (nextTurn) { + entries.push({ + id: userId ?? items[from]!.id, + prompt: prompt || "No message", + outcome: "completed", + }); + from = i; + userId = undefined; + worked = false; + } + if (!item) break; + if (item.kind === "user" && !item.steered) { + prompt = item.wake ? "Woken for a delegate" : promptLine(item.text); + userId ??= item.id; + } else if (item.kind === "assistant" || item.kind === "tool" || item.kind === "thought") { + worked = true; } - if (item.kind !== "turnEnd") continue; - entries.push({ - id: item.id, - prompt: prompt || "No message", - at: item.at, - startedAt: item.startedAt, - outcome: item.outcome, - elapsedMs: item.elapsedMs, - ...turnUsage(item.usage), - }); } return entries; }