Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): bound Bash progress by UTF-16 length without splitting surrogate pairs (#1939)
xpeng5278-webeb740b1677d8
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 114af7964..f5d35a72a 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2256,6 +2256,114 @@ describe("DesktopAgentRuntime configuration matching", () => {}});+ // Same 64Ki UTF-16 budget and 60/40 marker split as appendToolProgress.+ // Kept here so the tools.output path can lock the cap without exporting it.+ const TOOL_PROGRESS_CAP_CHARS = 64 * 1024;+ const TOOL_PROGRESS_CAP_MARKER = "\n\n[tool output progress truncated]\n\n";+ const LONE_SURROGATE =+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;++ async function flushedBashProgress(chunks: readonly string[]): Promise<string[]> {+ vi.useFakeTimers();+ try {+ const listeners = new Set<(method: string, params: unknown) => void>();+ let finishExecution!: (value: unknown) => void;+ const execution = new Promise((resolve) => {+ finishExecution = resolve;+ });+ const host = {+ call: vi.fn((method: string) =>+ method === "tools.execute"+ ? execution+ : Promise.resolve({ ok: true, content: "done" }),+ ),+ onNotification: vi.fn((handler: (method: string, params: unknown) => void) => {+ listeners.add(handler);+ return () => listeners.delete(handler);+ }),+ };+ const updates: unknown[] = [];+ const runtime = createRuntime({ host });+ const bash = runtimeTool(runtime, "Bash");+ const pending = bash.execute(+ "bash-progress-cap",+ { command: "printf progress" },+ undefined,+ (update: unknown) => updates.push(update),+ );+ await vi.advanceTimersByTimeAsync(0);+ for (const chunk of chunks) {+ for (const listener of listeners) {+ listener("tools.output", {+ sessionId: "session-1",+ toolCallId: "bash-progress-cap",+ commandShellId: "bash",+ stream: "stdout",+ chunk,+ });+ }+ await vi.advanceTimersByTimeAsync(100);+ }+ finishExecution({ ok: true, content: "done" });+ await pending;+ await runtime.dispose();+ return updates.map((update) => (update as { content: Array<{ text: string }> }).content[0]!.text);+ } finally {+ vi.useRealTimers();+ }+ }++ it("bounds supplementary-plane Bash progress to the UTF-16 cap without splitting pairs", async () => {+ const chunk = "π".repeat(40_000);+ expect(chunk.length).toBe(80_000);+ const texts = await flushedBashProgress([chunk, "z"]);+ expect(texts).toHaveLength(2);+ for (const text of texts) {+ expect(text.length).toBeLessThanOrEqual(TOOL_PROGRESS_CAP_CHARS);+ expect(text).not.toMatch(LONE_SURROGATE);+ }+ expect(texts[0]).toContain(TOOL_PROGRESS_CAP_MARKER);+ expect(texts[1]?.endsWith("z")).toBe(true);+ });++ it("keeps a surrogate pair whole when Bash progress truncation lands on it", async () => {+ const marker = TOOL_PROGRESS_CAP_MARKER;+ const remaining = TOOL_PROGRESS_CAP_CHARS - marker.length;+ const head = Math.ceil(remaining * 0.6);+ const tail = remaining - head;+ // One emoji starts on the last code unit of the head budget, and another+ // starts on the code unit just before the tail budget. A code-unit slice+ // would keep a lone surrogate; a code-point budget leaves both out.+ const chunk = `${"a".repeat(head - 1)}π${"b".repeat(100)}π${"c".repeat(tail - 1)}`;+ const [text] = await flushedBashProgress([chunk]);+ expect(text).toBeDefined();+ expect(text!.length).toBeLessThanOrEqual(TOOL_PROGRESS_CAP_CHARS);+ expect(text).not.toMatch(LONE_SURROGATE);+ expect(text!.indexOf(marker)).toBe(head - 1);+ expect(text!.endsWith("c".repeat(tail - 1))).toBe(true);+ expect(text).not.toContain("π");+ });++ it("preserves ASCII truncation and in-cap concatenation for Bash progress", async () => {+ const marker = TOOL_PROGRESS_CAP_MARKER;+ const remaining = TOOL_PROGRESS_CAP_CHARS - marker.length;+ const head = Math.ceil(remaining * 0.6);+ const tail = remaining - head;+ const oversized = `${"H".repeat(head)}${"M".repeat(1_000)}${"T".repeat(tail)}`;+ const [truncated] = await flushedBashProgress([oversized]);+ const expected = `${"H".repeat(head)}${marker}${"T".repeat(tail)}`;+ expect(truncated).toBe(expected);+ expect(truncated?.length).toBe(TOOL_PROGRESS_CAP_CHARS);+ expect(truncated?.indexOf(marker)).toBe(head);++ const within = await flushedBashProgress(["hello ", "πδΈη"]);+ expect(within).toEqual(["hello ", "hello πδΈη"]);++ const exact = "e".repeat(TOOL_PROGRESS_CAP_CHARS);+ const [atCap] = await flushedBashProgress([exact]);+ expect(atCap).toBe(exact);+ });+it("removes streamed-output resources when the host dies or runtime is disposed", async () => {vi.useFakeTimers();try {diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 8ce6954fc..de76a8001 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1471,17 +1471,53 @@ function commandTimeoutMs(params: unknown): number {return timeoutMs;}+/**+ * A supplementary-plane character is one code point and two UTF-16 code units.+ * The progress cap counts code units, so a point that does not fit is left out+ * whole instead of being sliced through the middle of its surrogate pair.+ */+function takePrefixCodeUnits(text: string, budget: number): string {+ let used = 0;+ let end = 0;+ for (const point of text) {+ if (used + point.length > budget) break;+ used += point.length;+ end += point.length;+ }+ return text.slice(0, end);+}++function takeSuffixCodeUnits(text: string, budget: number): string {+ let used = 0;+ let start = text.length;+ while (start > 0 && used < budget) {+ const low = text.charCodeAt(start - 1);+ const high = start >= 2 ? text.charCodeAt(start - 2) : 0;+ const pair =+ low >= 0xdc00 &&+ low <= 0xdfff &&+ high >= 0xd800 &&+ high <= 0xdbff;+ const size = pair ? 2 : 1;+ if (used + size > budget) break;+ used += size;+ start -= size;+ }+ return text.slice(start);+}+function appendToolProgress(current: string, chunk: string): string {const combined = `${current}${chunk}`;if (combined.length <= MAX_TOOL_PROGRESS_CHARS) return combined;- const codePoints = Array.from(combined);- const marker = Array.from(TOOL_PROGRESS_TRUNCATION_MARKER);- const remaining = Math.max(0, MAX_TOOL_PROGRESS_CHARS - marker.length);- const head = Math.ceil(remaining * 0.6);- const tail = remaining - head;- return `${codePoints.slice(0, head).join("")}${TOOL_PROGRESS_TRUNCATION_MARKER}${- tail > 0 ? codePoints.slice(-tail).join("") : ""- }`;+ const remaining = Math.max(+ 0,+ MAX_TOOL_PROGRESS_CHARS - TOOL_PROGRESS_TRUNCATION_MARKER.length,+ );+ const headBudget = Math.ceil(remaining * 0.6);+ const tailBudget = remaining - headBudget;+ const head = takePrefixCodeUnits(combined, headBudget);+ const tail = tailBudget > 0 ? takeSuffixCodeUnits(combined, tailBudget) : "";+ return `${head}${TOOL_PROGRESS_TRUNCATION_MARKER}${tail}`;}/** Bound a checkpoint message's text, naming the cut the way pi's tail does. */