perf(agents): stop re-rendering and rescanning the whole conversation for every streamed chunk (#5467)

While an agent streams, the visible session did work proportional to the whole conversation for every chunk: every earlier turn's reply and fold re-rendered, and the Composer re-read every tool output to rebuild the session assets. In a 170-turn conversation (2212 entries) that cost 12 ms per chunk in the stream and 7 ms in the composer; now it is 3 ms and 1 ms. Visible output, folding, turn numbers and reply actions are unchanged.
Root cause: the stream rebuilds its derived data for each chunk, and the props that carry it are new objects each time, so `memo` never held.
- `Entry:agent` (`session/messages.tsx`): `reply` (a fresh `ReplyTurn` from `replyTurns`) and `time` (a fresh `ReplyTimes` from `replyTimes`) for every earlier agent message.
- `TurnFold` (`session/ProcessRows.tsx`, rendered from `session/Stream.tsx`): a fresh `row`, the whole `entries` array, and fresh `children` elements. It was not memoized at all.
- `ProcessRun`: fresh `row` and `thinking` map each chunk.
- `extractSessionAssets` (`sessionAssetsModel.ts`, called from `SessionAssets.tsx`): re-parsed every tool entry's output each time `entries` changed.

Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com>
This commit is contained in:
Mr0Bread
2026-11-24 01:38:09 +08:00
committed by GitHub
parent 92d94a7ac4
commit 080b7e80e7
9 changed files with 886 additions and 163 deletions
+86 -46
View File
@@ -1,14 +1,23 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import type { AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { Icon } from "@/ui";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, type ReactNode } from "react";
import { createContext, memo, useContext, useLayoutEffect, useRef, type ReactNode } from "react";
import { formatDuration } from "../conversation";
import styles from "../Session.module.css";
import { summarizeWork, workParts, type WorkSummary } from "../timeline";
import { liveTool, type ConversationRow, type IndexedEntry, type ToolEntryData } from "./conversationRows";
import {
liveTool,
rowEntries,
sameRow,
type ConversationRow,
type IndexedEntry,
type ProcessRow,
type ToolEntryData,
type TurnRow,
} from "./conversationRows";
import { Fold } from "./Folds";
import { shortTitle } from "./shared";
import { samePropsExcept, shortTitle } from "./shared";
import { ThoughtEntry, ToolEntry } from "./toolEntries";
/** "Edited 2 files · Read 4 files": what a run of work did; "Reasoning" when it only thought. */
@@ -19,42 +28,81 @@ function workSummaryText(work: WorkSummary, tx: ReturnType<typeof useTx>, toolCa
return parts;
}
/** A finished turn's work, folded under its message: one line saying what it did and for how long. */
export function TurnFold({
row,
entries,
children,
}: {
row: Extract<ConversationRow, { kind: "turn" }>;
entries: readonly AgentEntry[];
children: ReactNode;
}) {
const tx = useTx();
const { turn } = row;
const work = summarizeWork(entries.slice(turn.user + 1, turn.reply));
const parts = workSummaryText(work, tx, 0);
const messages = entries.slice(turn.user + 1, turn.reply).filter((e) => e.type === "agent").length;
if (messages) parts.push(tx(messages === 1 ? "1 message" : "{count} messages").replace("{count}", String(messages)));
const took = turn.sentMs != null && turn.doneMs != null ? formatDuration(turn.doneMs - turn.sentMs) : null;
/** Renders the rows inside an open turn; the stream owns what a row needs (`Stream`). */
export const RowRenderer = createContext<(row: ConversationRow) => ReactNode>(() => null);
/** A finished turn's work, opened: its rows, painted only while the turn is open. */
function TurnBody({ row }: { row: TurnRow }) {
const renderRow = useContext(RowRenderer);
return (
<Fold
id={`turn:${turn.user}`}
className={clsx(styles.turnFold, styles.process)}
summary={
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
<span className={styles.processParts}>{parts.join(" · ")}</span>
{work.added > 0 && <span className={styles.added}>+{work.added}</span>}
{work.removed > 0 && <span className={styles.removed}>−{work.removed}</span>}
{took && <span className={styles.muted}>{took}</span>}
</summary>
}
>
<div className={styles.turnBody}>{children}</div>
</Fold>
<div className={styles.turnBody}>
{row.rows.map((inner) => (
<div key={inner.index} className={styles.conversationRow}>
{renderRow(inner)}
</div>
))}
</div>
);
}
/** A finished turn's work, folded under its message: one line saying what it did and for how long. */
export const TurnFold = memo(
function TurnFold({ row }: { row: TurnRow }) {
const tx = useTx();
const { turn } = row;
const entries = row.rows.flatMap(rowEntries);
const work = summarizeWork(entries);
const parts = workSummaryText(work, tx, 0);
const messages = entries.filter((e) => e.type === "agent").length;
if (messages)
parts.push(tx(messages === 1 ? "1 message" : "{count} messages").replace("{count}", String(messages)));
const took = turn.sentMs != null && turn.doneMs != null ? formatDuration(turn.doneMs - turn.sentMs) : null;
return (
<Fold
id={`turn:${turn.user}`}
className={clsx(styles.turnFold, styles.process)}
summary={
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
<span className={styles.processParts}>{parts.join(" · ")}</span>
{work.added > 0 && <span className={styles.added}>+{work.added}</span>}
{work.removed > 0 && <span className={styles.removed}>−{work.removed}</span>}
{took && <span className={styles.muted}>{took}</span>}
</summary>
}
>
<TurnBody row={row} />
</Fold>
);
},
(a, b) => sameRow(a.row, b.row),
);
interface ProcessRunProps {
row: ProcessRow;
task: AgentTask;
lastIndex: number;
busy: boolean;
/** How long each finished thought took, by entry index. */
thinking: ReadonlyMap<number, number> | null;
onDiagramDrawn: () => void;
}
/** Whether the run holds what the agent is doing right now. */
const holdsLive = ({ row, busy, lastIndex }: ProcessRunProps) =>
busy && row.entries.some(({ index }) => index === lastIndex);
/** The rows, the thought durations and the last entry are rebuilt with every chunk: compare what the run paints. */
const sameRun = samePropsExcept<ProcessRunProps>({
row: (a, b) => sameRow(a.row, b.row),
busy: () => true,
lastIndex: (a, b) => holdsLive(a) === holdsLive(b),
thinking: (a, b) =>
a.row.entries.every(
({ index, entry }) => entry.type !== "thought" || a.thinking?.get(index) === b.thinking?.get(index),
),
});
/** Reasoning and tool calls between messages, folded into one row. */
export const ProcessRun = memo(function ProcessRun({
row,
@@ -63,15 +111,7 @@ export const ProcessRun = memo(function ProcessRun({
busy,
thinking,
onDiagramDrawn,
}: {
row: Extract<ConversationRow, { kind: "process" }>;
task: AgentTask;
lastIndex: number;
busy: boolean;
/** How long each finished thought took, by entry index. */
thinking: ReadonlyMap<number, number> | null;
onDiagramDrawn: () => void;
}) {
}: ProcessRunProps) {
const tx = useTx();
const tools = row.entries.filter(
(item): item is IndexedEntry & { entry: ToolEntryData } => item.entry.type === "tool",
@@ -134,4 +174,4 @@ export const ProcessRun = memo(function ProcessRun({
</div>
</Fold>
);
});
}, sameRun);
+32 -36
View File
@@ -52,7 +52,7 @@ import {
import { FindBar } from "./FindBar";
import { KeepFoldHeader, OpenFolds } from "./Folds";
import { Entry } from "./messages";
import { ProcessRun, TurnFold } from "./ProcessRows";
import { ProcessRun, RowRenderer, TurnFold } from "./ProcessRows";
import { type QuestionAnswer } from "./QuestionForm";
import { providerName } from "./shared";
import { WorkingRow } from "./WorkingRow";
@@ -514,13 +514,7 @@ export function Stream({
);
const renderConversationRow = (row: ConversationRow): ReactNode =>
row.kind === "turn" ? (
<TurnFold row={row} entries={entries ?? []}>
{row.rows.map((inner) => (
<div key={inner.index} className={styles.conversationRow}>
{renderConversationRow(inner)}
</div>
))}
</TurnFold>
<TurnFold row={row} />
) : row.kind === "process" ? (
<ProcessRun
row={row}
@@ -636,35 +630,37 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
<RowRenderer.Provider value={renderConversationRow}>
{rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
</div>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})}
</RowRenderer.Provider>
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import type { AgentEntry } from "@/bindings";
import { foldedTurns } from "../timeline";
import { conversationRows, foldTurnRows, rowEntries, sameRow } from "./conversationRows";
const user = (text: string): AgentEntry => ({
type: "user",
text,
attachments: [],
steered: false,
sentMs: 1000,
doneMs: 5000,
});
const agent = (text: string): AgentEntry => ({ type: "agent", text });
const tool = (id: string, added = 0): AgentEntry => ({
type: "tool",
id,
title: id,
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: added ? [{ path: `/${id}.ts`, added, removed: 0 }] : [],
});
const rowsOf = (entries: AgentEntry[], busy = false) => {
const rows = conversationRows(entries, 0);
return foldTurnRows(rows, foldedTurns(entries, 0, busy));
};
describe("sameRow", () => {
const entries = [user("a"), tool("t1"), tool("t2"), agent("done"), user("b"), agent("streaming")];
it("sees the rows of the same conversation as the same, whichever copy it was built from", () => {
const again = rowsOf(entries);
expect(again.map((row) => row.kind)).toEqual(["entry", "turn", "entry", "entry", "entry"]);
rowsOf(entries).forEach((row, i) => expect(sameRow(row, again[i]!)).toBe(true));
});
it("leaves the rows a streamed chunk did not touch the same and the grown one different", () => {
const before = rowsOf(entries, true);
const after = rowsOf([...entries.slice(0, -1), agent("streaming on")], true);
expect(after.map((row, i) => sameRow(before[i]!, row))).toEqual([true, true, true, true, false]);
});
it("tells a turn whose work changed from one whose work did not", () => {
const [, turn] = rowsOf(entries);
const [, edited] = rowsOf([entries[0]!, tool("t1"), tool("t2", 7), ...entries.slice(3)]);
expect(sameRow(turn!, edited!)).toBe(false);
});
it("tells a run that gained a call from the run before", () => {
const run = conversationRows([user("a"), tool("t1"), tool("t2")], 0)[1]!;
const longer = conversationRows([user("a"), tool("t1"), tool("t2"), tool("t3")], 0)[1]!;
expect(run.kind).toBe("process");
expect(sameRow(run, longer)).toBe(false);
});
it("tells rows of different places apart even when they hold the same entry", () => {
const shared = agent("same");
expect(sameRow(conversationRows([shared], 0)[0]!, conversationRows([user("x"), shared], 1)[0]!)).toBe(false);
});
it("tells a turn that finished at another time from the turn before", () => {
const later = [{ ...(entries[0] as Extract<AgentEntry, { type: "user" }>), doneMs: 9000 }, ...entries.slice(1)];
expect(sameRow(rowsOf(entries)[1]!, rowsOf(later)[1]!)).toBe(false);
});
});
describe("rowEntries", () => {
it("lists the entries a folded turn paints, work first", () => {
const entries = [user("a"), tool("t1"), tool("t2"), agent("done")];
const [, turn] = rowsOf(entries);
expect(rowEntries(turn!)).toEqual([entries[1], entries[2]]);
});
});
@@ -14,6 +14,8 @@ export type ConversationRow =
| { kind: "turn"; index: number; turn: FoldedTurn; rows: ConversationRow[] };
export type EntryRow = Extract<ConversationRow, { kind: "entry" }>;
export type ProcessRow = Extract<ConversationRow, { kind: "process" }>;
export type TurnRow = Extract<ConversationRow, { kind: "turn" }>;
export const liveTool = (entry: AgentEntry) =>
entry.type === "tool" && (entry.status === "running" || entry.status === "pending");
@@ -68,3 +70,38 @@ export function foldTurnRows(rows: ConversationRow[], turns: ReadonlyMap<number,
}
return out;
}
/** The entries a row paints, in order. */
export function rowEntries(row: ConversationRow): AgentEntry[] {
if (row.kind === "entry") return [row.entry];
return row.kind === "process" ? row.entries.map(({ entry }) => entry) : row.rows.flatMap(rowEntries);
}
/**
* Whether two rows paint the same entries. Rows are rebuilt for every streamed chunk: a row's
* identity says nothing, and only the one the chunk grew differs.
*/
export function sameRow(a: ConversationRow, b: ConversationRow): boolean {
if (a === b) return true;
if (a.index !== b.index) return false;
switch (a.kind) {
case "entry":
return b.kind === "entry" && a.entry === b.entry;
case "process":
return (
b.kind === "process" &&
a.entries.length === b.entries.length &&
a.entries.every(({ entry }, i) => entry === b.entries[i]!.entry)
);
case "turn":
return (
b.kind === "turn" &&
a.turn.user === b.turn.user &&
a.turn.reply === b.turn.reply &&
a.turn.sentMs === b.turn.sentMs &&
a.turn.doneMs === b.turn.doneMs &&
a.rows.length === b.rows.length &&
a.rows.every((row, i) => sameRow(row, b.rows[i]!))
);
}
}
+34 -16
View File
@@ -19,7 +19,7 @@ import { isBusy, type ReplyTimes, type ReplyTurn } from "../model";
import { useRevealedText } from "../reveal";
import { forkTask, rerunFrom, resendMessage } from "../store";
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
import { type UserEntry } from "./shared";
import { samePropsExcept, type UserEntry } from "./shared";
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
/** When a message was sent, or when the turn behind a reply finished, and how long it took. */
@@ -92,19 +92,7 @@ function AgentMessage({
);
}
export const Entry = memo(function Entry({
task,
entry,
turn,
turnCount,
reply,
time,
thoughtMs,
working,
drafts,
onOpenSubagent,
onDiagramDrawn,
}: {
interface EntryProps {
task: AgentTask;
entry: AgentEntry;
/** Number of the turn this message started (from 0), when it started one. */
@@ -120,7 +108,21 @@ export const Entry = memo(function Entry({
drafts: RefObject<Map<string, QuestionAnswer[]>>;
onOpenSubagent: (id: string) => void;
onDiagramDrawn: () => void;
}) {
}
function EntryView({
task,
entry,
turn,
turnCount,
reply,
time,
thoughtMs,
working,
drafts,
onOpenSubagent,
onDiagramDrawn,
}: EntryProps) {
switch (entry.type) {
case "user":
return <UserMessage task={task} entry={entry} turn={turn} turnCount={turnCount} />;
@@ -220,7 +222,23 @@ export const Entry = memo(function Entry({
</div>
);
}
});
}
/** The reply and its times are rebuilt from the conversation with every chunk: what they say is what counts. */
export const Entry = memo(
EntryView,
samePropsExcept<EntryProps>({
reply: (a, b) =>
a.reply === b.reply ||
(!!a.reply &&
!!b.reply &&
a.reply.turn === b.reply.turn &&
a.reply.steered === b.reply.steered &&
a.reply.prompt === b.reply.prompt),
time: (a, b) =>
a.time === b.time || (!!a.time && !!b.time && a.time.sentMs === b.time.sentMs && a.time.doneMs === b.time.doneMs),
}),
);
function AgentErrorText({ message }: { message: string }) {
return <span>{useAgentErrorText(message)}</span>;
+16
View File
@@ -20,3 +20,19 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Agent-written titles with the task's own folder dropped from paths. */
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
/**
* `memo`'s comparison for props rebuilt with every render without changing: a prop named in
* `by` is equal when its rule says so, any other prop when it is the same value.
*/
export function samePropsExcept<P extends object>(by: { [K in keyof P]?: (a: P, b: P) => boolean }) {
return (a: P, b: P) => {
const keys = Object.keys(a) as Array<keyof P>;
if (keys.length !== Object.keys(b).length) return false;
for (const key of keys) {
const rule = by[key];
if (!(rule ? rule(a, b) : Object.is(a[key], b[key]))) return false;
}
return true;
};
}
+155 -65
View File
@@ -828,6 +828,67 @@ function relativeIfUnder(bases: readonly string[], absPath: string): string | nu
return null;
}
type FileAsset = Extract<SessionArtifact, { kind: "file" }>;
/** The artifact a path names for the session, or `null` when it is no artifact. */
function fileAsset(
rawPath: string,
source: "edit" | "read" | "mention",
cwd: string,
bases: readonly string[],
): FileAsset | null {
const trimmed = rawPath.trim();
if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed)) return null;
const abs = trimmed.startsWith("/") ? resolveTyped("", trimmed) : resolveTyped(cwd, trimmed);
if (!isArtifactCandidate(abs, source)) return null;
return {
key: `file:${abs}`,
kind: "file",
name: basename(abs) || abs,
path: abs,
rel: relativeIfUnder(bases, abs),
externalBinary: EXTERNAL_BINARY_EXTENSIONS.has(extOf(abs)),
};
}
type ForgeItemFields<T> = Omit<T, "title" | "state" | "hasExplicitTitle" | "hasExplicitState">;
interface IssueTouch {
created?: boolean;
title?: string | null;
fallbackTitle?: string | null;
state?: IssueAssetState | null;
}
/** What one entry says about the session's assets, in the order it says it. */
type Finding =
| {
kind: "pr";
item: ForgeItemFields<SessionPullRequest>;
title?: string | null;
state?: PullRequestAssetState | null;
}
| { kind: "issue"; item: ForgeItemFields<SessionIssue>; opts: IssueTouch }
| {
kind: "reference";
refKind: "commit" | "discussion";
key: string;
idLabel: string;
repo: string;
url: string;
title?: string | null;
}
| { kind: "website"; key: string; url: string; fallbackTitle: string; label?: string | null }
| { kind: "file"; asset: FileAsset };
/**
* Findings of each entry, kept while the entry is the same object. A streamed chunk replaces
* the last entry and leaves the rest as they were, so only the replaced one is read again.
* Findings depend on where the task runs: the same entry read for another folder or default
* repository is read again.
*/
const findings = new WeakMap<AgentEntry, { scope: string; found: Finding[] }>();
export interface ExtractAssetsOptions {
task: Pick<AgentTask, "cwd" | "projectRoot">;
entries: readonly AgentEntry[] | null;
@@ -861,7 +922,7 @@ export function extractSessionAssets({
let seq = 0;
const touchPr = (
item: Omit<SessionPullRequest, "title" | "state" | "hasExplicitTitle" | "hasExplicitState">,
item: ForgeItemFields<SessionPullRequest>,
title?: string | null,
state?: PullRequestAssetState | null,
bumpOrder = true,
@@ -890,15 +951,7 @@ export function extractSessionAssets({
});
};
const touchIssue = (
item: Omit<SessionIssue, "title" | "state" | "hasExplicitTitle" | "hasExplicitState">,
opts: {
created?: boolean;
title?: string | null;
fallbackTitle?: string | null;
state?: IssueAssetState | null;
} = {},
) => {
const touchIssue = (item: ForgeItemFields<SessionIssue>, opts: IssueTouch = {}) => {
const cleanTitle = opts.title?.trim() || null;
if (opts.created || createdIssues.has(item.key)) {
// Promote from `references` if it was seen before `gh issue create` completed.
@@ -1008,27 +1061,20 @@ export function extractSessionAssets({
});
};
const touchFile = (rawPath: string, source: "edit" | "read" | "mention") => {
const trimmed = rawPath.trim();
if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed)) return;
const abs = trimmed.startsWith("/") ? resolveTyped("", trimmed) : resolveTyped(task.cwd, trimmed);
if (!isArtifactCandidate(abs, source)) return;
const key = `file:${abs}`;
const existing = files.get(key);
const touchFile = (asset: FileAsset) => {
const existing = files.get(asset.key);
if (existing) {
existing.seq = ++seq;
return;
}
const ext = extOf(abs);
files.set(key, {
key,
kind: "file",
name: basename(abs) || abs,
path: abs,
rel: relativeIfUnder(bases, abs),
externalBinary: EXTERNAL_BINARY_EXTENSIONS.has(ext),
seq: ++seq,
});
files.set(asset.key, { ...asset, seq: ++seq });
};
/** What the entry being read says about assets, in the order it says it. */
let found: Finding[] = [];
const foundFile = (rawPath: string, source: "edit" | "read" | "mention") => {
const asset = fileAsset(rawPath, source, task.cwd, bases);
if (asset) found.push({ kind: "file", asset });
};
const ingestUrl = (
@@ -1043,38 +1089,50 @@ export function extractSessionAssets({
if (!classified) return;
switch (classified.kind) {
case "pr":
touchPr(classified, meaningfulLabel(label, classified.idLabel));
found.push({ kind: "pr", item: classified, title: meaningfulLabel(label, classified.idLabel) });
break;
case "issue":
touchIssue(classified, {
created: opts.createdIssue,
title: meaningfulLabel(label, classified.idLabel),
fallbackTitle: classified.fallbackTitle ?? null,
found.push({
kind: "issue",
item: classified,
opts: {
created: opts.createdIssue,
title: meaningfulLabel(label, classified.idLabel),
fallbackTitle: classified.fallbackTitle ?? null,
},
});
break;
case "discussion":
touchOtherReference(
"discussion",
classified.key,
classified.idLabel,
classified.repo,
classified.url,
meaningfulLabel(label, classified.idLabel),
);
found.push({
kind: "reference",
refKind: "discussion",
key: classified.key,
idLabel: classified.idLabel,
repo: classified.repo,
url: classified.url,
title: meaningfulLabel(label, classified.idLabel),
});
break;
case "commit":
touchOtherReference(
"commit",
classified.key,
classified.idLabel,
classified.repo,
classified.url,
meaningfulLabel(label, classified.idLabel),
);
found.push({
kind: "reference",
refKind: "commit",
key: classified.key,
idLabel: classified.idLabel,
repo: classified.repo,
url: classified.url,
title: meaningfulLabel(label, classified.idLabel),
});
break;
case "website":
if (opts.allowWebsites) {
touchWebsite(classified.key, classified.url, classified.fallbackTitle, label);
found.push({
kind: "website",
key: classified.key,
url: classified.url,
fallbackTitle: classified.fallbackTitle,
label,
});
}
break;
}
@@ -1092,13 +1150,13 @@ export function extractSessionAssets({
for (const meta of extractJsonMetadata(output)) {
const classified = classifyUrl(meta.url);
if (classified?.kind === "pr") {
touchPr(classified, meta.title, meta.state);
found.push({ kind: "pr", item: classified, title: meta.title, state: meta.state });
} else if (classified?.kind === "issue") {
const state: IssueAssetState | null = meta.state === "closed" ? "closed" : meta.state ? "open" : null;
touchIssue(classified, {
created: created.createdIssue,
title: meta.title ?? created.issueTitle,
state,
found.push({
kind: "issue",
item: classified,
opts: { created: created.createdIssue, title: meta.title ?? created.issueTitle, state },
});
}
}
@@ -1119,18 +1177,18 @@ export function extractSessionAssets({
// Markdown relative/absolute file links (`[Report](docs/report.md)`).
for (const m of prose.matchAll(/\[([^\][\n]{1,200})\]\(\s*([^)\s]+)\s*\)/g)) {
const file = fileHref(m[2]!, task.cwd);
if (file) touchFile(file.path, "mention");
if (file) foundFile(file.path, "mention");
}
// `@file` mentions in messages.
for (const tok of messageTokens(prose)) {
if (tok.kind !== "file") continue;
const mention = parseMention(tok.value);
if (mention && !mention.dir) touchFile(mention.rel, "mention");
if (mention && !mention.dir) foundFile(mention.rel, "mention");
}
// Inline code spans naming an artifact file (`storage_session_spec.docx`, `/tmp/report.md`).
for (const m of prose.matchAll(/`([^`\n]{3,240})`/g)) {
const link = pathLink(m[1]!, task.cwd);
if (link) touchFile(link.path, "mention");
if (link) foundFile(link.path, "mention");
}
};
@@ -1142,28 +1200,28 @@ export function extractSessionAssets({
touchPr(classified, bpr.title, state);
}
for (const entry of entries ?? []) {
const readEntry = (entry: AgentEntry) => {
if (entry.type === "user") {
ingestProse(entry.text);
const imageCount = entry.images?.length ?? 0;
const attachedFiles = entry.attachments.slice(0, Math.max(0, entry.attachments.length - imageCount));
for (const a of attachedFiles) touchFile(a, "mention");
continue;
for (const a of attachedFiles) foundFile(a, "mention");
return;
}
if (entry.type === "agent" || entry.type === "message") {
ingestProse(entry.text);
continue;
return;
}
if (entry.type === "subagent") {
if (entry.prompt) ingestProse(entry.prompt);
if (entry.reply) ingestProse(entry.reply);
continue;
return;
}
if (entry.type === "tool") {
const edited = entry.kind === "edit" || entry.kind === "move" || entry.diffs.length > 0;
for (const diff of entry.diffs) touchFile(diff.path, "edit");
for (const diff of entry.diffs) foundFile(diff.path, "edit");
if (edited || entry.kind === "read") {
for (const loc of entry.locations) touchFile(loc, edited ? "edit" : "read");
for (const loc of entry.locations) foundFile(loc, edited ? "edit" : "read");
}
if (entry.kind === "fetch") {
for (const link of extractLinks(entry.title)) {
@@ -1199,7 +1257,7 @@ export function extractSessionAssets({
linkLabel: createsPr?.titleFlag || createsIssue?.titleFlag || null,
});
}
continue;
return;
}
// Other tools (e.g. GitHub / Linear / Datadog MCP calls): inspect structured JSON and explicit links.
for (const link of extractLinks(entry.title)) {
@@ -1207,6 +1265,38 @@ export function extractSessionAssets({
}
if (entry.output) ingestToolOutput(entry.output);
}
};
const touch = (finding: Finding) => {
switch (finding.kind) {
case "pr":
touchPr(finding.item, finding.title, finding.state);
break;
case "issue":
touchIssue(finding.item, finding.opts);
break;
case "reference":
touchOtherReference(finding.refKind, finding.key, finding.idLabel, finding.repo, finding.url, finding.title);
break;
case "website":
touchWebsite(finding.key, finding.url, finding.fallbackTitle, finding.label);
break;
case "file":
touchFile(finding.asset);
break;
}
};
const scope = `${task.cwd}\0${task.projectRoot ?? ""}\0${defaultGithubRepo ?? ""}`;
for (const entry of entries ?? []) {
let known = findings.get(entry);
if (known?.scope !== scope) {
found = [];
readEntry(entry);
known = { scope, found };
findings.set(entry, known);
}
known.found.forEach(touch);
}
// Apply live `gh api` metadata enrichment (`title` and `state`).
@@ -0,0 +1,132 @@
/**
* Assets are read from the conversation after every streamed chunk: the entries a chunk
* leaves alone must not be scanned again, however long the conversation is.
*/
import { describe, expect, it } from "vitest";
import type { AgentEntry, AgentTask } from "@/bindings";
import { extractSessionAssets } from "./sessionAssetsModel";
const task = { cwd: "/repo", projectRoot: "/repo" } satisfies Pick<AgentTask, "cwd" | "projectRoot">;
/** A finished `gh` call whose output names a pull request; `reads.count` counts how often the output is read. */
function ghCall(i: number, reads: { count: number }): AgentEntry {
const entry: AgentEntry = {
type: "tool",
id: `gh-${i}`,
title: `gh pr view ${1000 + i}`,
kind: "execute",
status: "completed",
locations: [],
output: null,
diffs: [],
};
Object.defineProperty(entry, "output", {
get() {
reads.count++;
return `https://github.com/acme/app/pull/${1000 + i}`;
},
});
return entry;
}
const agent = (text: string): AgentEntry => ({ type: "agent", text });
const pullRequests = (entries: AgentEntry[]) =>
extractSessionAssets({ task, entries }).pullRequests.map((pr) => pr.idLabel);
describe("assets while a reply streams", () => {
it("does not read the output of earlier tool calls again for each chunk", () => {
const reads = { count: 0 };
const earlier = Array.from({ length: 200 }, (_, i) => ghCall(i, reads));
pullRequests([...earlier, agent("")]);
expect(reads.count).toBeGreaterThan(0);
reads.count = 0;
for (let chunk = 1; chunk <= 20; chunk++) pullRequests([...earlier, agent("word ".repeat(chunk))]);
expect(reads.count).toBe(0);
});
it("shows a reference the streamed message names as soon as its text has it", () => {
const reads = { count: 0 };
const earlier = [ghCall(0, reads), ghCall(1, reads)];
expect(pullRequests([...earlier, agent("Opened it: https://github.com/acme/app/pu")])).toEqual(["#1001", "#1000"]);
expect(pullRequests([...earlier, agent("Opened it: https://github.com/acme/app/pull/77 for review")])).toEqual([
"#77",
"#1001",
"#1000",
]);
});
it("ranks a conversation the same when it reads it from what it kept", () => {
const tool = (extra: Partial<Extract<AgentEntry, { type: "tool" }>>): AgentEntry => ({
type: "tool",
id: "t",
title: "tool",
kind: "other",
status: "completed",
locations: [],
output: null,
diffs: [],
...extra,
});
const entries: AgentEntry[] = [
{
type: "user",
text: "See [the spec](https://github.com/acme/app/issues/5) and @docs/spec.md",
attachments: ["/repo/notes.md"],
steered: false,
},
tool({ kind: "edit", diffs: [{ path: "/repo/docs/report.md", added: 3, removed: 0 }] }),
tool({
kind: "execute",
title: 'gh pr create --title "Add the thing"',
output: "https://github.com/acme/app/pull/40\n",
}),
tool({
kind: "execute",
title: "gh issue create",
output:
'https://github.com/acme/app/issues/41 {"url":"https://github.com/acme/app/issues/41","title":"Bug","state":"OPEN"}',
}),
tool({ kind: "fetch", title: "Fetch https://docs.example.com/guide" }),
agent(
"Done: https://github.com/acme/app/pull/40 and `/tmp/summary.md`, again [spec](https://github.com/acme/app/issues/5)",
),
];
const read = () => extractSessionAssets({ task, entries, remoteUrl: "git@github.com:acme/app.git" });
const first = read();
expect(first.pullRequests.length + first.createdIssues.length + first.references.length).toBeGreaterThan(2);
expect(first.artifacts.length).toBeGreaterThan(1);
expect(read()).toEqual(first);
expect(
extractSessionAssets({ task, entries: structuredClone(entries), remoteUrl: "git@github.com:acme/app.git" }),
).toEqual(first);
});
it("reads an entry again where the task runs elsewhere", () => {
const entries: AgentEntry[] = [{ ...agent("Wrote `docs/out.md`") }];
const rel = (cwd: string) =>
extractSessionAssets({ task: { cwd, projectRoot: cwd }, entries }).artifacts.map((a) =>
a.kind === "file" ? a.path : a.url,
);
expect(rel("/one")).toEqual(["/one/docs/out.md"]);
expect(rel("/two")).toEqual(["/two/docs/out.md"]);
});
it("shows what a replaced entry says now", () => {
const running: AgentEntry = {
type: "tool",
id: "gh",
title: "gh pr create",
kind: "execute",
status: "running",
locations: [],
output: null,
diffs: [],
};
expect(pullRequests([running])).toEqual([]);
expect(pullRequests([{ ...running, status: "completed", output: "https://github.com/acme/app/pull/9" }])).toEqual([
"#9",
]);
});
});
+318
View File
@@ -0,0 +1,318 @@
/**
* A streamed chunk changes the last message only: the rows of the history above it must
* not render again, however long the conversation is.
*/
import { act, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
import { SessionEditor } from "./SessionEditor";
import { SESSION_KIND, sessionKey } from "./model";
import { connect, disconnect, useAgents } from "./store";
const harness = vi.hoisted(() => ({
tasks: [] as unknown[],
/** The agents store only subscribes in the desktop app; nothing else here may take the desktop paths. */
tauri: false,
channel: null as null | { onmessage: (event: unknown) => void },
/** Renders of each agent message by its text, and of each fold by its id. */
replies: new Map<string, number>(),
folds: new Map<string, number>(),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: (event: unknown) => void = () => {};
constructor() {
harness.channel = this;
}
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => harness.tauri,
commands: {
agentSubscribe: async () => ({ status: "ok", data: harness.tasks }),
agentProviders: async () => ({ status: "ok", data: [] }),
agentEntries: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
agentGroupedChanges: async () => ({
status: "ok",
data: { uncommitted: [], commits: [] },
}),
agentContextUsage: async () => ({
status: "error",
error: { kind: "unavailable", message: "none" },
}),
vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }),
vcsBranches: async () => ({ status: "ok", data: [] }),
fsProbe: async () => ({
status: "ok",
data: { size: 1, binary: false, tooLarge: false },
}),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn() }),
maybeEditorService: () => ({ activePath: () => null }),
toolWindowService: () => ({ show: vi.fn() }),
}));
// Counts renders of what the rows paint. The factories run before the imports bind, hence the dynamic import.
vi.mock("./AgentReply", async (original) => {
const { createElement } = await import("react");
const actual = await original<typeof import("./AgentReply")>();
return {
...actual,
AgentReply: (props: Parameters<typeof actual.AgentReply>[0]) => {
harness.replies.set(props.text, (harness.replies.get(props.text) ?? 0) + 1);
return createElement(actual.AgentReply, props);
},
};
});
vi.mock("./session/Folds", async (original) => {
const { createElement } = await import("react");
const actual = await original<typeof import("./session/Folds")>();
return {
...actual,
Fold: (props: Parameters<typeof actual.Fold>[0]) => {
if (props.id) harness.folds.set(props.id, (harness.folds.get(props.id) ?? 0) + 1);
return createElement(actual.Fold, props);
},
};
});
const task: AgentTask = {
id: "T",
title: "T",
provider: "codex",
status: "running",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const input = {
kind: SESSION_KIND,
key: sessionKey(task.id),
data: { task: task.id },
};
const user = (text: string): AgentEntry => ({
type: "user",
text,
attachments: [],
steered: false,
sentMs: 1000,
doneMs: 5000,
});
/** Finished turns as agents write them: a question, reasoning, tool calls, a reply. */
function history(turns: number): AgentEntry[] {
return Array.from({ length: turns }, (_, i): AgentEntry[] => [
user(`Question ${i}`),
{ type: "thought", text: `Thinking ${i}`, startedMs: 1000 },
{
type: "tool",
id: `read-${i}`,
title: `Read src/file${i}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
startedMs: 1100,
endedMs: 1200,
},
{
type: "tool",
id: `edit-${i}`,
title: `Edit src/file${i}.ts`,
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: [{ path: `/project/src/file${i}.ts`, added: 2, removed: 1 }],
startedMs: 1300,
endedMs: 1400,
},
{ type: "agent", text: `Reply ${i}` },
]).flat();
}
const send = (event: AgentEvent) => act(() => harness.channel!.onmessage(event));
/** Opens a conversation of `turns` finished turns and a new one whose reply starts streaming. */
async function openStreaming(turns: number): Promise<{ stream: (chunks: number) => string; at: number }> {
const entries = [...history(turns), user("Now?")];
harness.tasks = [task];
harness.tauri = true;
await connect();
harness.tauri = false;
useAgents.setState({ entries: new Map([[task.id, entries]]) });
render(<SessionEditor input={input} />);
await screen.findByText(`Reply ${turns - 1}`);
send({
type: "entry",
task: task.id,
subagent: null,
index: entries.length,
entry: { type: "agent", text: "" },
});
let text = "";
return {
/** Index of the streaming reply: what comes next in the conversation follows it. */
at: entries.length,
stream(chunks) {
for (let i = 0; i < chunks; i++) {
const chunk = `word${i} `;
send({
type: "append",
task: task.id,
subagent: null,
index: entries.length,
from: text.length,
text: chunk,
});
text += chunk;
}
return text;
},
};
}
beforeEach(() => {
harness.replies.clear();
harness.folds.clear();
harness.channel = null;
disconnect();
useProject.setState({ settings: { agents: { smoothText: false } } as never });
});
afterEach(() => {
disconnect();
useProject.setState({ settings: null });
});
describe("streaming into a long conversation", () => {
it.each([
{ turns: 5, foldTurns: true },
{ turns: 40, foldTurns: true },
{ turns: 5, foldTurns: false },
{ turns: 40, foldTurns: false },
])(
"renders none of the $turns earlier turns again for a chunk (fold turns: $foldTurns)",
async ({ turns, foldTurns }) => {
useProject.setState({
settings: { agents: { smoothText: false, foldTurns } } as never,
});
const { stream } = await openStreaming(turns);
// The first chunk opens the streaming message; what follows is the steady state.
stream(1);
harness.replies.clear();
harness.folds.clear();
const text = stream(20);
await screen.findByText(/word19$/);
const renders = (counts: Map<string, number>, keep: (key: string) => boolean) =>
[...counts].filter(([key]) => keep(key)).map(([key, count]) => `${key}: ${count}`);
expect({
earlierReplies: renders(harness.replies, (reply) => reply.startsWith("Reply ")),
folds: renders(harness.folds, () => true),
}).toEqual({ earlierReplies: [], folds: [] });
// The message that grows does render for every chunk: the counters see renders at all.
expect(harness.replies.get(text)).toBeGreaterThan(0);
},
);
it("still shows what a new turn changes in the turns above it", async () => {
useProject.setState({ settings: { agents: { smoothText: false, foldTurns: true } } as never });
const { stream, at } = await openStreaming(3);
stream(3);
send({
type: "entry",
task: task.id,
subagent: null,
index: at + 1,
entry: {
type: "tool",
id: "late",
title: "Read late.ts",
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
},
});
send({
type: "entry",
task: task.id,
subagent: null,
index: at + 2,
entry: { type: "agent", text: "Final answer" },
});
const copies = () => screen.getAllByRole("button", { name: "Copy Markdown" }).length;
// The turn in progress has no actions yet; the three before it do, and its work is open.
expect(copies()).toBe(3);
expect(harness.folds.has(`turn:${at - 1}`)).toBe(false);
send({ type: "entry", task: task.id, subagent: null, index: at + 3, entry: user("Next?") });
// The turn that began mid-stream has ended: its reply has actions and its work is folded.
expect(copies()).toBe(4);
expect(harness.folds.has(`turn:${at - 1}`)).toBe(true);
expect(screen.getByText("Final answer")).toBeInTheDocument();
expect(screen.getByText("Next?")).toBeInTheDocument();
});
it.each([{ foldTurns: true }, { foldTurns: false }])(
"still shows an earlier edit that arrives while a reply streams (fold turns: $foldTurns)",
async ({ foldTurns }) => {
useProject.setState({ settings: { agents: { smoothText: false, foldTurns } } as never });
const { stream } = await openStreaming(3);
stream(3);
const added = () => within(document.body).queryAllByText("+7").length;
expect(added()).toBe(0);
// Turn 1's edit (index 8) is rewritten, and so is the reply of turn 2 (index 14).
send({
type: "entry",
task: task.id,
subagent: null,
index: 8,
entry: {
type: "tool",
id: "edit-1",
title: "Edit src/file1.ts",
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: [{ path: "/project/src/file1.ts", added: 7, removed: 1 }],
},
});
send({
type: "entry",
task: task.id,
subagent: null,
index: 14,
entry: { type: "agent", text: "Reply 2, revised" },
});
expect(await screen.findByText("Reply 2, revised")).toBeInTheDocument();
expect(added()).toBe(1);
expect(screen.getByText("Reply 1")).toBeInTheDocument();
},
);
});