From 9fcd7c146872efcbeffb5d240a259be6eab3cba8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A1nos=20Kranczler?= Date: Thu, 3 Dec 2026 18:25:42 +0100 Subject: [PATCH] perf(agents): skip re-rendering conversation rows on unrelated task updates (#7815) Each conversation row got the full task object, and every task update (usage, queue, settings) made a new one, so all replies rendered again while the agent worked. Rows now get a memoized RowTask with only the fields they show (id, provider, cwd, status, error, isolation, branch, base, fork/rollback capabilities); the RowTask type keeps a row from reading another field until it is added there. One usage_update in a 3580-entry session went from 185 ms (532 reply renders) to 3.3 ms (0). Co-authored-by: janoskranczler <6105557+janoskranczler@users.noreply.github.com> --- src/features/agents/AgentReply.tsx | 6 +- src/features/agents/FormCard.tsx | 5 +- src/features/agents/model.ts | 8 +- src/features/agents/rowRenders.test.tsx | 110 +++++++++++++++++++ src/features/agents/session/ChangesTab.tsx | 2 +- src/features/agents/session/ProcessRows.tsx | 5 +- src/features/agents/session/QuestionForm.tsx | 20 +--- src/features/agents/session/Stream.tsx | 11 +- src/features/agents/session/messages.tsx | 12 +- src/features/agents/session/shared.ts | 25 ++++- src/features/agents/session/toolEntries.tsx | 10 +- 11 files changed, 168 insertions(+), 46 deletions(-) create mode 100644 src/features/agents/rowRenders.test.tsx diff --git a/src/features/agents/AgentReply.tsx b/src/features/agents/AgentReply.tsx index fe40edb790..0e6edca27b 100644 --- a/src/features/agents/AgentReply.tsx +++ b/src/features/agents/AgentReply.tsx @@ -1,5 +1,5 @@ import { useEffect, useState, type ReactNode } from "react"; -import type { AgentTask } from "@/bindings"; +import type { RowTask } from "./session/shared"; import { IconButton } from "@/ui"; import { Markdown } from "./Markdown"; import { copyReplyAction, type CopyReply } from "./replyActions"; @@ -17,7 +17,7 @@ export function AgentReply({ }: { text: string; cwd: string; - task?: AgentTask; + task?: RowTask; reply?: ReplyTurn; turnCount?: number; onDiagramDrawn?: () => void; @@ -52,7 +52,7 @@ export function ReplyActions({ turnCount = 0, }: { text: string; - task?: AgentTask; + task?: RowTask; reply?: ReplyTurn; turnCount?: number; }) { diff --git a/src/features/agents/FormCard.tsx b/src/features/agents/FormCard.tsx index cca15543b2..ed7466d628 100644 --- a/src/features/agents/FormCard.tsx +++ b/src/features/agents/FormCard.tsx @@ -1,8 +1,9 @@ import { useId, useState } from "react"; import clsx from "clsx"; -import type { AgentForm, AgentFormField, AgentTask } from "@/bindings"; +import type { AgentForm, AgentFormField } from "@/bindings"; import { Button, Checkbox, Input, Radio, T } from "@/ui"; import type { PermissionEntry } from "./permission"; +import type { RowTask } from "./session/shared"; import { respond } from "./store"; import styles from "./Session.module.css"; @@ -31,7 +32,7 @@ function isValid(field: AgentFormField, value: string[]) { } /** An agent's open form (ACP elicitation), answered above the composer like a question. */ -export function FormCard({ task, entry, form }: { task: AgentTask; entry: PermissionEntry; form: AgentForm }) { +export function FormCard({ task, entry, form }: { task: RowTask; entry: PermissionEntry; form: AgentForm }) { const [values, setValues] = useState(() => Object.fromEntries( form.fields.map((field) => [ diff --git a/src/features/agents/model.ts b/src/features/agents/model.ts index b977e0334c..d143303d0e 100644 --- a/src/features/agents/model.ts +++ b/src/features/agents/model.ts @@ -357,14 +357,16 @@ export function replyTurns(entries: AgentEntry[]): Map { return out; } +type ForkTask = Pick; + /** Whether the task can be copied now: while a turn runs, the copy drops it, which needs rollback. */ -export function canForkTask(task: AgentTask): boolean { +export function canForkTask(task: ForkTask): boolean { const { fork = false, rollback = false } = task.capabilities ?? {}; return task.status !== "archived" && fork && (!isBusy(task.status) || rollback); } /** Whether the task can be copied up to and including `turn` of its `turnCount` turns. */ -export function canForkAt(task: AgentTask, turn: number, turnCount: number): boolean { +export function canForkAt(task: ForkTask, turn: number, turnCount: number): boolean { if (!canForkTask(task)) return false; const latest = turn === turnCount - 1; // A running turn is the latest one: only the finished ones before it can be copied. @@ -372,7 +374,7 @@ export function canForkAt(task: AgentTask, turn: number, turnCount: number): boo return !!task.capabilities?.rollback || latest; } -export function replyOperations(task: AgentTask, reply: ReplyTurn | undefined, turnCount: number) { +export function replyOperations(task: ForkTask, reply: ReplyTurn | undefined, turnCount: number) { const idle = task.status !== "archived" && !isBusy(task.status) && !!reply; const latest = reply?.turn === turnCount - 1; const { rollback = false } = task.capabilities ?? {}; diff --git a/src/features/agents/rowRenders.test.tsx b/src/features/agents/rowRenders.test.tsx new file mode 100644 index 0000000000..0eb64148ee --- /dev/null +++ b/src/features/agents/rowRenders.test.tsx @@ -0,0 +1,110 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, render, screen } from "@testing-library/react"; +import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings"; +import { SessionEditor } from "./SessionEditor"; +import { SESSION_KIND, sessionKey } from "./model"; +import { connect, disconnect, useAgents } from "./store"; + +const backend = vi.hoisted(() => ({ + channel: null as { onmessage: (event: AgentEvent) => void } | null, + tasks: [] as AgentTask[], + entries: [] as AgentEntry[], + replies: 0, +})); + +vi.mock("@tauri-apps/api/core", async (original) => ({ + ...(await original()), + Channel: class { + onmessage = () => {}; + }, +})); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + isTauri: () => true, + commands: { + agentSubscribe: async (channel: typeof backend.channel) => { + backend.channel = channel; + return { status: "ok", data: backend.tasks }; + }, + agentProviders: async () => ({ status: "ok", data: [] }), + agentCommands: async () => ({ status: "ok", data: [] }), + agentChanges: async () => ({ status: "ok", data: [] }), + agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }), + agentEntries: async () => ({ status: "ok", data: backend.entries }), + vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }), + vcsRemotes: async () => ({ status: "ok", data: [] }), + }, +})); +vi.mock("@tauri-apps/api/webview", () => ({ + getCurrentWebview: () => ({ onDragDropEvent: () => Promise.resolve(() => {}) }), +})); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn(), openTabs: () => [] }), + toolWindowService: () => ({ show: vi.fn() }), +})); +vi.mock("./AgentReply", async (original) => { + const reply = await original(); + return { + ...reply, + AgentReply: (props: Parameters[0]) => { + backend.replies++; + return reply.AgentReply(props); + }, + }; +}); + +const TURNS = 10; +const task: AgentTask = { + id: "one", + title: "one", + provider: "claude", + 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: [], + capabilities: { fork: true, rollback: true, steer: true }, +}; +const update = (changes: Partial) => + act(() => + backend.channel!.onmessage({ type: "task", task: { ...useAgents.getState().tasks.get("one")!, ...changes } }), + ); + +beforeEach(async () => { + disconnect(); + backend.tasks = [task]; + backend.entries = Array.from({ length: TURNS }, (_, i): AgentEntry[] => [ + { type: "user", text: `Question ${i}`, attachments: [], sentMs: null }, + { type: "agent", text: `Answer ${i}` }, + ]).flat(); + useAgents.setState({ sessionLocation: "editor" }); + await connect(); + vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); + render(); + expect(await screen.findByText(`Answer ${TURNS - 1}`)).toBeInTheDocument(); + backend.replies = 0; +}); +afterEach(() => { + disconnect(); + vi.useRealTimers(); +}); + +it("renders no reply again for a task update that changes nothing the rows show", () => { + update({ usage: { used: 1200, size: 200_000, cost: null }, updatedMs: 1, capabilities: { ...task.capabilities } }); + expect(backend.replies).toBe(0); +}); + +it("renders the replies again when the task's status changes", () => { + update({ status: "ready" }); + expect(backend.replies).toBeGreaterThan(0); +}); diff --git a/src/features/agents/session/ChangesTab.tsx b/src/features/agents/session/ChangesTab.tsx index 14863faaa9..709e43986c 100644 --- a/src/features/agents/session/ChangesTab.tsx +++ b/src/features/agents/session/ChangesTab.tsx @@ -659,7 +659,7 @@ async function changeDiffData( } /** Opens the diff of `path` between the task's start (or its last turn's) and now. */ -export async function openChangeDiff(task: AgentTask, path: string, scope: ChangesScope = "task") { +export async function openChangeDiff(task: DiffTask, path: string, scope: ChangesScope = "task") { const { changes, turnChanges } = useAgents.getState(); const listed = (scope === "turn" ? turnChanges : changes).get(task.id) ?? []; const changed = listed.map((change) => change.path); diff --git a/src/features/agents/session/ProcessRows.tsx b/src/features/agents/session/ProcessRows.tsx index 07f7f4ce3b..b4a1ec849e 100644 --- a/src/features/agents/session/ProcessRows.tsx +++ b/src/features/agents/session/ProcessRows.tsx @@ -1,4 +1,3 @@ -import type { AgentTask } from "@/bindings"; import { useTx } from "@/platform/i18n"; import { Icon } from "@/ui"; import clsx from "clsx"; @@ -7,7 +6,7 @@ import styles from "../Session.module.css"; import { summarizeWork, workParts, type WorkSummary } from "../timeline"; import { liveTool, sameRow, type IndexedEntry, type ProcessRow, type ToolEntryData } from "./conversationRows"; import { Fold } from "./Folds"; -import { commandTitle, samePropsExcept, shortTitle } from "./shared"; +import { commandTitle, type RowTask, samePropsExcept, shortTitle } from "./shared"; import { ThoughtEntry, ToolEntry } from "./toolEntries"; /** "Edited 2 files · Ran 3 commands": what a run of work did; "Reasoning" when it only thought. */ @@ -20,7 +19,7 @@ function workSummaryText(work: WorkSummary, tx: ReturnType, toolCa interface ProcessRunProps { row: ProcessRow; - task: AgentTask; + task: RowTask; lastIndex: number; busy: boolean; /** How long each finished thought took, by entry index. */ diff --git a/src/features/agents/session/QuestionForm.tsx b/src/features/agents/session/QuestionForm.tsx index 6888e2e84a..734caffd04 100644 --- a/src/features/agents/session/QuestionForm.tsx +++ b/src/features/agents/session/QuestionForm.tsx @@ -1,4 +1,4 @@ -import type { AgentEntry, AgentQuestion, AgentTask } from "@/bindings"; +import type { AgentEntry, AgentQuestion } from "@/bindings"; import { useTx } from "@/platform/i18n"; import { Button, Checkbox, Icon, Input, Radio, T, Tabs } from "@/ui"; import clsx from "clsx"; @@ -14,21 +14,13 @@ import { type PermissionEntry, } from "../permission"; import { answerQuestion, respond } from "../store"; -import { providerName, shortTitle } from "./shared"; +import { providerName, type RowTask, shortTitle } from "./shared"; /** * The answers to an open permission request. A request without options (some agents send * none) can still be cancelled, so the agent doesn't wait for an answer it can't get. */ -function PermissionAnswers({ - task, - entry, - className, -}: { - task: AgentTask; - entry: PermissionEntry; - className?: string; -}) { +function PermissionAnswers({ task, entry, className }: { task: RowTask; entry: PermissionEntry; className?: string }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const pending = useRef(false); @@ -80,7 +72,7 @@ function PermissionAnswers({ } /** A single inline decision, reduced to a compact record after it is answered. */ -export function PermissionLine({ task, entry }: { task: AgentTask; entry: PermissionEntry }) { +export function PermissionLine({ task, entry }: { task: RowTask; entry: PermissionEntry }) { const tx = useTx(); const ref = useRef(null); const hadFocus = useRef(false); @@ -156,7 +148,7 @@ export function QuestionCard({ entries, drafts, }: { - task: AgentTask; + task: RowTask; entries: AgentEntry[] | null; drafts: RefObject>; }) { @@ -199,7 +191,7 @@ export function QuestionForm({ drafts, pinned = false, }: { - task: AgentTask; + task: RowTask; entry: PermissionEntry | AsyncQuestionEntry; questions: AgentQuestion[]; drafts: RefObject>; diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index f4d3723384..b0d323df75 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -49,7 +49,7 @@ import { KeepFoldHeader, OpenFolds } from "./Folds"; import { Entry } from "./messages"; import { ProcessRun } from "./ProcessRows"; import { type QuestionAnswer } from "./QuestionForm"; -import { providerName } from "./shared"; +import { providerName, useRowTask } from "./shared"; import { WorkingRow } from "./WorkingRow"; /** @@ -734,6 +734,7 @@ export function Stream({ const times = useMemo(() => (entries && !subagent ? replyTimes(entries) : null), [entries, subagent]); const thinking = useMemo(() => (entries ? thoughtDurations(entries) : null), [entries]); const busy = subagent ? subagentWorking(subagent.status) : isBusy(task.status); + const rowTask = useRowTask(task); const lastIndex = entries ? entries.length - 1 : -1; // Keep the row stable when earlier history is prepended; its author can move with the work. const rows = useMemo(() => { @@ -757,7 +758,7 @@ export function Stream({ (row: EntryRow) => ( ), - [task, turns, replies, times, thinking, lastIndex, busy, drafts, onOpenSubagent, followEnd], + [rowTask, turns, replies, times, thinking, lastIndex, busy, drafts, onOpenSubagent, followEnd], ); const renderConversationRow = useCallback( (row: ConversationRow): ReactNode => row.kind === "process" ? ( ; +/** The fields conversation rows read: usage, queue and settings updates must not render every row again. */ +export type RowTask = Pick< + AgentTask, + "id" | "provider" | "cwd" | "status" | "error" | "isolation" | "branch" | "base" +> & { + capabilities?: Pick; +}; + +export function useRowTask(task: AgentTask): RowTask { + const { id, provider, cwd, status, error, isolation, branch, base } = task; + const { fork, rollback } = task.capabilities ?? {}; + return useMemo( + () => ({ id, provider, cwd, status, error, isolation, branch, base, capabilities: { fork, rollback } }), + [id, provider, cwd, status, error, isolation, branch, base, fork, rollback], + ); +} + /** A Windows path (`C:\\…`, `\\\\server\\…`): separators and letter case don't tell paths apart. */ const windowsPath = (path: string) => /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\"); @@ -40,7 +57,7 @@ function sameFolder(a: string, b: string): boolean { } /** Agent-written titles with the task's own folder dropped from paths. */ -export function shortTitle(task: AgentTask, title: string): string { +export function shortTitle(task: Pick, title: string): string { const prefix = task.cwd ? folderPrefix(task.cwd) : null; return prefix ? title.replace(prefix, "") : title; } @@ -49,7 +66,7 @@ export function shortTitle(task: AgentTask, title: string): string { * A command's title without the `cd &&` agents put before every call, and the folder it * moved to when that is not the task's own: the command is what tells calls apart. */ -export function commandTitle(task: AgentTask, title: string): { title: string; dir: string | null } { +export function commandTitle(task: Pick, title: string): { title: string; dir: string | null } { const { command, dir } = splitLeadingCd(title); return { title: shortTitle(task, command), diff --git a/src/features/agents/session/toolEntries.tsx b/src/features/agents/session/toolEntries.tsx index 30c38732e1..1d1a0a7a53 100644 --- a/src/features/agents/session/toolEntries.tsx +++ b/src/features/agents/session/toolEntries.tsx @@ -1,4 +1,4 @@ -import type { AgentEntry, AgentTask } from "@/bindings"; +import type { AgentEntry } from "@/bindings"; import { useTx } from "@/platform/i18n"; import { basename } from "@/platform/project"; import { Icon, IconButton, Spinner, T } from "@/ui"; @@ -17,7 +17,7 @@ import { cancelTask } from "../store"; import { openChangeDiff } from "./ChangesTab"; import { Fold } from "./Folds"; import { liveTool } from "./conversationRows"; -import { commandTitle, shortTitle, useNow } from "./shared"; +import { commandTitle, type RowTask, shortTitle, useNow } from "./shared"; /** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */ const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\"); @@ -50,7 +50,7 @@ export function ThoughtEntry({ working, onDiagramDrawn, }: { - task: AgentTask; + task: RowTask; text: string; /** How long the finished thought took, when its times are known. */ took: number | null; @@ -123,7 +123,7 @@ export const ToolEntry = memo(function ToolEntry({ task, entry, }: { - task: AgentTask; + task: RowTask; entry: Extract; }) { const { expandToolOutput } = useAgentSettings(); @@ -289,7 +289,7 @@ export function SubagentCard({ onOpen, onDiagramDrawn, }: { - task: AgentTask; + task: RowTask; entry: SubagentEntry; onOpen: () => void; onDiagramDrawn: () => void;