Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions apps/desktop/src/state/fold.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
toolGroupLabel,
turnChangeLine,
turnFoldKey,
turnItemsByEnd,
} from "./fold";
import type { TranscriptItem } from "./thread";

Expand Down Expand Up @@ -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"]);
});
});
47 changes: 36 additions & 11 deletions apps/desktop/src/state/fold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -598,26 +598,51 @@ export function keepUnchangedRows<T extends { key: string }>(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<Record<string, TranscriptItem[]>> = {},
running = false,
): Record<string, TranscriptItem[]> {
const map: Record<string, TranscriptItem[]> = {};
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;
}

Expand Down
7 changes: 6 additions & 1 deletion apps/desktop/src/state/thread.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" } },
]),
);
Expand All @@ -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);
});

Expand Down
8 changes: 6 additions & 2 deletions apps/desktop/src/state/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down
9 changes: 7 additions & 2 deletions apps/desktop/src/ui/OverviewLog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,15 @@ function TurnRow({

export function ExecutionLogSection({
items,
running,
usage,
harness,
model,
folded,
onToggle,
}: {
items: readonly TranscriptItem[];
running?: boolean;
/** The thread's own totals, which are what the store says it spent. */
usage?: SessionUsage;
harness?: string;
Expand All @@ -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.
Expand All @@ -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<string, Extract<TranscriptItem, { kind: "turnEnd" }>>();
for (const item of items) if (item.kind === "turnEnd") map.set(item.id, item);
Expand Down
19 changes: 15 additions & 4 deletions apps/desktop/src/ui/ThreadDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<SectionId[]>(readFolded);
Expand Down Expand Up @@ -244,7 +246,14 @@ export function ThreadDetails() {
</div>
)}
</Section>
<TurnsSection key={id} items={items ?? []} model={model} folded={isFolded("log")} onToggle={toggle} />
<TurnsSection
key={id}
items={items ?? []}
running={running}
model={model}
folded={isFolded("log")}
onToggle={toggle}
/>
</div>
);
}
Expand Down Expand Up @@ -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<string, Extract<TranscriptItem, { kind: "turnEnd" }>>();
for (const item of items) if (item.kind === "turnEnd") map.set(item.id, item);
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/ui/Transcript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -760,9 +760,9 @@ export function Transcript({
// A finished turn keeps its array, so its memoised footer skips a streamed chunk.
const drawnTurnItems = useRef<Record<string, TranscriptItem[]>>({});
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.
Expand Down
26 changes: 26 additions & 0 deletions apps/desktop/src/ui/overview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
63 changes: 45 additions & 18 deletions apps/desktop/src/ui/overview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TranscriptItem, { kind: "turnEnd" }>;
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;
}
Expand Down
Loading