perf(agents): send a running tool's output as the text it grew by (#5476)

A running tool's output was resent whole on every flush, so long outputs sent megabytes to the UI. The backend now sends a toolOutput event with only the appended text when the new output starts with everything already sent (checked by the sent length and a hash of the sent text); any replacement or other change goes out as a whole Entry. Agent and thought messages use the same check. PROTOCOL_VERSION is bumped to 4 so an older app refuses a newer server instead of showing stale output.

Co-authored-by: Mr0Bread <[email protected]>
Цей коміт міститься в:
Mr0Bread authored and GitHub committed 2026-11-24 21:30:53 +08:00
1 джерело c5f7b3ae98
коміт 40c616e46d
8 files changed
+556 -65

No files matched your search

+12
Переглянути файл
@@ -2664,6 +2664,12 @@ export type AgentEvent_Deserialize =
* `from` UTF-16 units of its text when the previous event for it was sent.
*/
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
/**
* Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
* units of its output when the previous event for it was sent. Any other change of the
* tool (status, title, diffs…) arrives as an `Entry`.
*/
({ type: "toolOutput"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** A model lookup started or completed, including unsuccessful lookups. */
@@ -2686,6 +2692,12 @@ export type AgentEvent_Serialize =
* `from` UTF-16 units of its text when the previous event for it was sent.
*/
({ type: "append"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
/**
* Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
* units of its output when the previous event for it was sent. Any other change of the
* tool (status, title, diffs…) arrives as an `Entry`.
*/
({ type: "toolOutput"; task: string; subagent: string | null; index: number; from: number; text: string }) & { catalog?: never; entry?: never; eventId?: never; id?: never; length?: never; limits?: never; provider?: never; reason?: never } |
/** An agent reported the usage limits of its account (shared by every task of `provider`). */
({ type: "limits"; provider: string; limits: AgentLimit[] }) & { catalog?: never; entry?: never; eventId?: never; from?: never; id?: never; index?: never; length?: never; reason?: never; subagent?: never; task?: never; text?: never } |
/** A model lookup started or completed, including unsuccessful lookups. */
+27 -11
Переглянути файл
@@ -136,21 +136,37 @@ export function upsertEntry(entries: AgentEntry[], index: number, entry: AgentEn
return next;
}
/** `shown` with `text`, which follows its first `from` units, added; `null` when `shown` is too short to take it. */
function grown(shown: string, from: number, text: string): string | null {
if (shown.length < from) return null;
return shown.length >= from + text.length ? shown : shown + text.slice(shown.length - from);
}
/**
* `entries` with `text` appended to the message at `index`, which read its first `from`
* UTF-16 units when the backend last sent it; `null` when the copy here can't take it (a
* gap, or another kind of entry), so the conversation is loaded again. A copy loaded while
* the text streamed may already hold some of it.
* `entries` with `text` appended to the message at `index` (or to the output of the tool call
* there), which read its first `from` UTF-16 units when the backend last sent it; `null` when
* the copy here can't take it (a gap, or another kind of entry), so the conversation is
* loaded again. A copy loaded while the text streamed may already hold some of it.
*/
export function appendEntry(entries: AgentEntry[], index: number, from: number, text: string): AgentEntry[] | null {
const entry = entries[index];
if (!entry || (entry.type !== "agent" && entry.type !== "thought")) return null;
const have = entry.text.length;
if (have < from) return null;
if (have >= from + text.length) return entries;
const next = entries.slice();
next[index] = { ...entry, text: entry.text + text.slice(have - from) };
return next;
let next: AgentEntry;
if (entry?.type === "tool") {
const output = grown(entry.output ?? "", from, text);
if (output === null) return null;
if (output === entry.output) return entries;
next = { ...entry, output };
} else if (entry?.type === "agent" || entry?.type === "thought") {
const added = grown(entry.text, from, text);
if (added === null) return null;
if (added === entry.text) return entries;
next = { ...entry, text: added };
} else {
return null;
}
const copy = entries.slice();
copy[index] = next;
return copy;
}
/** "agent/fix-lexer" → "fix-lexer". */
+6 -2
Переглянути файл
@@ -584,7 +584,7 @@ export async function connect(): Promise<void> {
}
}
type EntryEvent = Extract<AgentEvent, { type: "entry" | "append" }>;
type EntryEvent = Extract<AgentEvent, { type: "entry" | "append" | "toolOutput" }>;
/** Entry events that arrived while their conversation loaded, applied on top of the copy it loads. */
const arrivedWhileLoading = new Map<string, EntryEvent[]>();
@@ -593,7 +593,7 @@ const streamingReply = new Map<string, { index: number; reply: boolean }>();
/** `entries` with the event applied; `null` when the copy can't take it. */
function applyEntryEvent(entries: AgentEntry[], e: EntryEvent): AgentEntry[] | null {
if (e.type === "append") return appendEntry(entries, e.index, e.from, e.text);
if (e.type === "append" || e.type === "toolOutput") return appendEntry(entries, e.index, e.from, e.text);
const have = entries[e.index];
// Sent before the loaded copy was read: that copy already holds more of the message.
if (
@@ -851,6 +851,10 @@ function onEvent(e: AgentEvent) {
onEntryEvent(s, e);
break;
}
case "toolOutput": {
onEntryEvent(s, e);
break;
}
}
}
+133
Переглянути файл
@@ -0,0 +1,133 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { deferred } from "@/test/deferred";
import { entriesKey } from "./model";
import { connect, disconnect, loadEntries, useAgents } from "./store";
const backend = vi.hoisted(() => ({
channel: null as { onmessage: (event: AgentEvent) => void } | null,
entries: vi.fn(),
}));
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: [task] };
},
agentProviders: async () => ({ status: "ok", data: [] }),
agentEntries: async () => ({ status: "ok", data: await backend.entries() }),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openTabs: () => [] }),
}));
const task: AgentTask = {
id: "one",
title: "one",
status: "running",
provider: "codex",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const call = (output: string | null, status: "running" | "completed" = "running"): AgentEntry => ({
type: "tool",
id: "build",
title: "cargo build",
kind: "execute",
status,
locations: [],
output,
diffs: [],
startedMs: 1,
endedMs: null,
});
const emit = (event: AgentEvent) => backend.channel!.onmessage(event);
const entry = (index: number, e: AgentEntry): AgentEvent => ({
type: "entry",
task: "one",
subagent: null,
index,
entry: e,
});
const more = (index: number, from: number, text: string): AgentEvent => ({
type: "toolOutput",
task: "one",
subagent: null,
index,
from,
text,
});
const shown = () => useAgents.getState().entries.get(entriesKey("one", null));
const output = () => {
const tool = shown()?.[1];
return tool?.type === "tool" ? tool.output : undefined;
};
beforeEach(async () => {
disconnect();
backend.entries.mockReset();
backend.entries.mockResolvedValue([{ type: "user", text: "build it", attachments: [] }]);
await connect();
await loadEntries("one");
});
describe("a running tool's output", () => {
it("grows by what each event adds, and the last entry settles it", () => {
emit(entry(1, call("$ cargo build")));
emit(more(1, 13, "\nCompiling é"));
emit(more(1, 25, " 👋\nDone"));
expect(shown()![1]).toEqual(call("$ cargo build\nCompiling é 👋\nDone"));
emit(entry(1, call("$ cargo build\nCompiling é 👋\nDone\n", "completed")));
expect(shown()![1]).toEqual(call("$ cargo build\nCompiling é 👋\nDone\n", "completed"));
});
it("starts from nothing when the call had no output yet", () => {
emit(entry(1, call(null)));
emit(more(1, 0, "first"));
expect(output()).toBe("first");
});
it("takes text it already holds once, and loads the conversation again when it misses some", async () => {
emit(entry(1, call("abc")));
emit(more(1, 0, "abc"));
expect(output()).toBe("abc");
backend.entries.mockResolvedValue([{ type: "user", text: "build it", attachments: [] }, call("abcdef")]);
emit(more(1, 5, "g"));
await vi.waitFor(() => expect(output()).toBe("abcdef"));
expect(backend.entries).toHaveBeenCalledTimes(2);
});
it("lands on a copy that loads while the output streams", async () => {
const read = deferred<AgentEntry[]>();
backend.entries.mockReturnValue(read.promise);
useAgents.setState({ entries: new Map(), entryLoads: new Map() });
const loading = loadEntries("one");
emit(more(1, 3, "def"));
emit(more(1, 6, "ghi"));
read.resolve([{ type: "user", text: "build it", attachments: [] }, call("abcdef")]);
await loading;
expect(output()).toBe("abcdefghi");
});
});