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 <[email protected]>
Цей коміт міститься в:
János Kranczlerтаjanoskranczler authored and GitHub committed 2026-12-04 01:25:42 +08:00
1 джерело a6aa26ea2a
коміт 9fcd7c1468
11 files changed
+168 -46

No files matched your search

+3 -3
Переглянути файл
@@ -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;
}) {
+3 -2
Переглянути файл
@@ -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<Values>(() =>
Object.fromEntries(
form.fields.map((field) => [
+5 -3
Переглянути файл
@@ -357,14 +357,16 @@ export function replyTurns(entries: AgentEntry[]): Map<number, ReplyTurn> {
return out;
}
type ForkTask = Pick<AgentTask, "status" | "capabilities">;
/** 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 ?? {};
+110
Переглянути файл
@@ -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<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
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<typeof import("@/workbench/contributions")>()),
editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn(), openTabs: () => [] }),
toolWindowService: () => ({ show: vi.fn() }),
}));
vi.mock("./AgentReply", async (original) => {
const reply = await original<typeof import("./AgentReply")>();
return {
...reply,
AgentReply: (props: Parameters<typeof reply.AgentReply>[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<AgentTask>) =>
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(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("one"), data: { task: "one" } }} />);
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);
});
+1 -1
Переглянути файл
@@ -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);
+2 -3
Переглянути файл
@@ -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<typeof useTx>, toolCa
interface ProcessRunProps {
row: ProcessRow;
task: AgentTask;
task: RowTask;
lastIndex: number;
busy: boolean;
/** How long each finished thought took, by entry index. */
+6 -14
Переглянути файл
@@ -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<string | null>(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<HTMLDivElement>(null);
const hadFocus = useRef(false);
@@ -156,7 +148,7 @@ export function QuestionCard({
entries,
drafts,
}: {
task: AgentTask;
task: RowTask;
entries: AgentEntry[] | null;
drafts: RefObject<Map<string, QuestionAnswer[]>>;
}) {
@@ -199,7 +191,7 @@ export function QuestionForm({
drafts,
pinned = false,
}: {
task: AgentTask;
task: RowTask;
entry: PermissionEntry | AsyncQuestionEntry;
questions: AgentQuestion[];
drafts: RefObject<Map<string, QuestionAnswer[]>>;
+6 -5
Переглянути файл
@@ -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) => (
<Entry
key={row.index}
task={task}
task={rowTask}
entry={row.entry}
turn={turns?.get(row.index) ?? null}
turnCount={turns?.size ?? 0}
@@ -770,14 +771,14 @@ export function Stream({
onDiagramDrawn={followEnd}
/>
),
[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" ? (
<ProcessRun
row={row}
task={task}
task={rowTask}
lastIndex={lastIndex}
busy={busy}
thinking={thinking}
@@ -786,7 +787,7 @@ export function Stream({
) : (
renderRow(row)
),
[task, lastIndex, busy, thinking, followEnd, renderRow],
[rowTask, lastIndex, busy, thinking, followEnd, renderRow],
);
const agentName = providerName(task.provider);
// Switching tabs changes visibility without changing the conversation rows.
+6 -6
Переглянути файл
@@ -1,4 +1,4 @@
import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import type { AgentEntry, AgentImage } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { call, commands, isTauri } from "@/platform/ipc";
@@ -33,7 +33,7 @@ import {
useAgents,
} from "../store";
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
import { providerName, samePropsExcept, type UserEntry } from "./shared";
import { providerName, type RowTask, 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. */
@@ -67,7 +67,7 @@ function AgentMessage({
working,
onDiagramDrawn,
}: {
task: AgentTask;
task: RowTask;
text: string;
turnCount: number;
reply?: ReplyTurn;
@@ -107,7 +107,7 @@ function AgentMessage({
}
interface EntryProps {
task: AgentTask;
task: RowTask;
entry: AgentEntry;
/** Number of the turn this message started (from 0), when it started one. */
turn: number | null;
@@ -254,7 +254,7 @@ export const Entry = memo(
);
/** Offers recovery for the current writer conflict without replacing the saved conversation. */
function AgentErrorEntry({ task, message }: { task: AgentTask; message: string }) {
function AgentErrorEntry({ task, message }: { task: RowTask; message: string }) {
const [signingIn, setSigningIn] = useState(false);
const [recovering, setRecovering] = useState(false);
const text = useAgentErrorText(message);
@@ -342,7 +342,7 @@ function UserMessage({
turn,
turnCount,
}: {
task: AgentTask;
task: RowTask;
entry: UserEntry;
turn: number | null;
turnCount: number;
+21 -4
Переглянути файл
@@ -1,5 +1,5 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import { useEffect, useState } from "react";
import type { AgentCapabilities, AgentEntry, AgentTask } from "@/bindings";
import { useEffect, useMemo, useState } from "react";
import { splitLeadingCd } from "../shellCommand";
import { useAgents } from "../store";
@@ -19,6 +19,23 @@ export function useNow(interval: number): number {
export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** 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<AgentCapabilities, "fork" | "rollback">;
};
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<AgentTask, "cwd">, 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 <dir> &&` 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<AgentTask, "cwd">, title: string): { title: string; dir: string | null } {
const { command, dir } = splitLeadingCd(title);
return {
title: shortTitle(task, command),
+5 -5
Переглянути файл
@@ -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<AgentEntry, { type: "tool" }>;
}) {
const { expandToolOutput } = useAgentSettings();
@@ -289,7 +289,7 @@ export function SubagentCard({
onOpen,
onDiagramDrawn,
}: {
task: AgentTask;
task: RowTask;
entry: SubagentEntry;
onOpen: () => void;
onDiagramDrawn: () => void;