Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
test(rpc): house NDJSON framing tests in shared and lock LF readers
vastsa49d54db11e92
diff --git a/apps/desktop/electron/main/host-process.ts b/apps/desktop/electron/main/host-process.tsindex d9e1f8660..854125283 100644--- a/apps/desktop/electron/main/host-process.ts+++ b/apps/desktop/electron/main/host-process.ts@@ -6,8 +6,8 @@ import {ErrorCodes,MAX_HOST_STDIN_LINE_BYTES,PROTOCOL_VERSION,- rpcTimeoutMs,readNdjsonLines,+ rpcTimeoutMs,stripProxyEnv,} from "@pi-desktop/shared";import {diff --git a/apps/desktop/test/ndjson.test.mjs b/apps/desktop/test/ndjson.test.mjsdeleted file mode 100644index 06b7598d2..000000000--- a/apps/desktop/test/ndjson.test.mjs+++ /dev/null@@ -1,63 +0,0 @@-import assert from "node:assert/strict";-import { once } from "node:events";-import { PassThrough } from "node:stream";-import test from "node:test";-import { readNdjsonLines } from "../../../packages/shared/src/ndjson.ts";--const payload = { id: "rpc", result: { content: "A\u2028中文🙂\u2029B\r\nC" } };-const wire = Buffer.from(JSON.stringify(payload) + "\n");--test("NDJSON preserves Unicode separators at every possible byte split", async () => {- for (let split = 0; split <= wire.length; split++) {- const input = new PassThrough();- const lines = [];- readNdjsonLines(input, (line) => lines.push(JSON.parse(line)));- const ended = once(input, "end");- input.write(wire.subarray(0, split));- input.end(wire.subarray(split));- await ended;- assert.deepEqual(lines, [payload], `split at byte ${split}`);- }-});--test("NDJSON accepts consecutive LF/CRLF frames, blank lines, and EOF tail", async () => {- const input = new PassThrough();- const lines = [];- readNdjsonLines(input, (line) => lines.push(line));- const ended = once(input, "end");- input.write('\n{"id":1}\r');- assert.deepEqual(lines, [""], "CR alone does not terminate a frame");- input.write('\n{"id":2}\n{"id":');- input.end("3}");- await ended;- assert.deepEqual(lines, ["", '{"id":1}', '{"id":2}', '{"id":3}']);- for (const event of ["data", "end", "close"]) assert.equal(input.listenerCount(event), 0);-});--test("closing inside a callback stops buffered frames and removes only owned listeners", () => {- const input = new PassThrough();- const external = () => {};- input.on("data", external);- const lines = [];- const reader = readNdjsonLines(input, (line) => { lines.push(line); reader.close(); });- input.write("first\nsecond\npartial");- reader.close();- input.write("ignored\n");- assert.deepEqual(lines, ["first"]);- assert.deepEqual(input.listeners("data"), [external]);- assert.equal(input.listenerCount("end"), 0);- assert.equal(input.listenerCount("close"), 0);- input.destroy();-});--test("stream destruction discards a partial frame and detaches the reader", async () => {- const input = new PassThrough();- const lines = [];- readNdjsonLines(input, (line) => lines.push(line));- input.write('{"unfinished":');- const closed = once(input, "close");- input.destroy();- await closed;- assert.deepEqual(lines, []);- for (const event of ["data", "end", "close"]) assert.equal(input.listenerCount(event), 0);-});diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjsindex 65d556c0a..493a359fe 100644--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs@@ -27,11 +27,30 @@ const rpcTimeoutSource = await readFile(new URL("../../../packages/shared/src/rpc-timeouts.ts", import.meta.url),"utf8",);+const agentSidecarEntrySource = await readFile(+ new URL("../../../packages/agent-runtime/src/sidecar.ts", import.meta.url),+ "utf8",+);const apiSource = await readFile(new URL("../src/lib/api.ts", import.meta.url),"utf8",);+test("stdio RPC readers split frames on LF only", () => {+ for (const [name, source] of [+ ["host-process", hostSource],+ ["agent-sidecar", sidecarSource],+ ["runtime sidecar", agentSidecarEntrySource],+ ]) {+ assert.match(source, /readNdjsonLines/, `${name} must use LF NDJSON framing`);+ assert.doesNotMatch(+ source,+ /from ["']node:readline["']/,+ `${name} must not use readline on the RPC pipe`,+ );+ }+});+test("sidecar detaches host listeners and gates every child write", () => {assert.match(sidecarSource, /private closeTransport\(error: Error\)/);assert.match(sidecarSource, /unsubscribeHostExit/);diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 990d9add5..58ca9e363 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13072,8 +13072,8 @@ plugin-form fixtures in an isolated temporary directory at runtime.- **Expected:** Text survives unchanged across persistence and all stdiodirections. Requests settle without RPC timeouts; error replies and subsequentrequests remain usable. No migration of existing sessions is needed.-- **Automation:** `pnpm test:e2e:rpc-unicode`; `ndjson.test.mjs` additionally- checks every UTF-8 split boundary, consecutive frames, CRLF, EOF and disposal.+- **Automation:** `pnpm test:e2e:rpc-unicode`; `packages/shared/src/ndjson.test.ts`+ additionally checks every UTF-8 split boundary, consecutive frames, CRLF, EOF and disposal.- **Specs:** 03-runtime/06-host-rpc-protocol §2.- **Acceptance:** A (runtime), C (sessions).- **Milestone:** M6+.diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex 21aa0dbe7..d5323acc5 100644--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@ -19,14 +19,11 @@ MVP 传输决策 (**D001**):- 流程:Electron 主要生成 Rust host-core sidecar- 通道:子进程 stdin/stdout-- Framing: one JSON object per LF-delimited line (NDJSON); CRLF is accepted.- U+2028 and U+2029 inside JSON strings are payload, never frame delimiters.- All Node stdio readers preserve UTF-8 characters across input chunks and- release buffered fragments/listeners on transport close. A final unterminated- frame is accepted at EOF for compatibility.-- Invalid JSON frames produce a diagnostic containing only the byte length,- never payload text, before being discarded. Later complete frames remain- readable. Existing session text is not rewritten or migrated.+- 成帧:每行一个以 LF 分隔的 JSON 对象(NDJSON);接受 CRLF。+ JSON 字符串内的 U+2028 与 U+2029 属于载荷,不是帧分隔符。+ 所有 Node stdio 读取器会跨输入块保留 UTF-8 字符,并在传输关闭时释放缓冲片段和监听器。+ 为兼容起见,EOF 时接受最后一帧未以换行结束的情况。+- 非法 JSON 帧会先产出仅含字节长度、不含载荷文本的诊断,然后丢弃。后续完整帧仍可读。现有会话文本不会被改写或迁移。- 编码:UTF-8- Request/response:JSON-RPC 2.0 风格diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 1bd0e3173..209bc54ce 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5008,7 +5008,7 @@ IPC 请求无法关闭。| 验收 | 应用场景 ||---|---|-| A / C — Unicode stdio framing | E2E-RPC-unicode-separators |+| A / C — Unicode stdio 成帧 | E2E-RPC-unicode-separators || C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back || C / D / Quality — 侧边栏行状态 | E2E-LAYOUT-sidebar-row-states || A / C / Quality — 侧栏材质与设置返回 | E2E-LAYOUT-sidebar-settings |@@ -7802,19 +7802,11 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture### E2E-RPC-unicode-separators-- **Preconditions:** Built host-core, shared package and agent runtime; isolated- temporary data directory; loopback-only fixture provider. No live credentials.-- **Steps:** Append a user message containing U+2028/U+2029, CJK text, emoji and- escaped CR/LF; read it, restart the host, and read it again. Send a Unicode- prompt through AgentSidecar; restore history through the parent host proxy;- stream and persist a Unicode answer. Send an unknown method containing the- same characters, then a health request.-- **Expected:** Text survives unchanged across persistence and all stdio- directions. Requests settle without RPC timeouts; error replies and subsequent- requests remain usable. No migration of existing sessions is needed.-- **Automation:** `pnpm test:e2e:rpc-unicode`; `ndjson.test.mjs` additionally- checks every UTF-8 split boundary, consecutive frames, CRLF, EOF and disposal.-- **Specs:** 03-runtime/06-host-rpc-protocol §2.-- **Acceptance:** A (runtime), C (sessions).-- **Milestone:** M6+.-- **Status:** Automated; run against the task/PR integration candidate.+- **前置条件**:已构建 host-core、shared 与 agent-runtime;隔离的临时数据目录;仅回环的 fixture provider。不使用真实凭证。+- **步骤**:追加一条含 U+2028/U+2029、中文、emoji 以及转义 CR/LF 的用户消息;读取、重启 host 后再读。通过 AgentSidecar 发送 Unicode 提示;经 parent host proxy 恢复历史;流式返回并持久化 Unicode 回复。发送一条含相同字符的未知方法,再发健康检查。+- **预期**:文本在持久化与所有 stdio 方向上保持不变。请求在 RPC 超时前完成;错误回复之后的请求仍可用。无需迁移现有会话。+- **自动化**:`pnpm test:e2e:rpc-unicode`;`packages/shared/src/ndjson.test.ts` 额外覆盖每个 UTF-8 切分位置、连续帧、CRLF、EOF 与销毁。+- **规格**:03-runtime/06-host-rpc-protocol §2。+- **验收**:A(运行时),C(会话)。+- **里程碑**:M6+。+- **状态**:已自动化;针对 task/PR 集成候选运行。diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex a6348fbdc..a116af74b 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -32,9 +32,9 @@ import {isCommandShellOption,MAX_INLINE_IMAGE_BYTES,normalizeMode,- readNdjsonLines,normalizeNetworkProxy,OAUTH_AUTH_KIND,+ readNdjsonLines,} from "@pi-desktop/shared";import type {AgentEventEnvelope,diff --git a/packages/shared/src/ndjson.test.ts b/packages/shared/src/ndjson.test.tsnew file mode 100644index 000000000..e69812feb--- /dev/null+++ b/packages/shared/src/ndjson.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";+import { readNdjsonLines } from "./ndjson.js";++type DataListener = (chunk: string) => void;+type SignalListener = () => void;++class FakeNdjsonInput {+ private data: DataListener[] = [];+ private end: SignalListener[] = [];+ private close: SignalListener[] = [];++ setEncoding(_encoding: "utf8") {+ return this;+ }++ on(event: "data", listener: DataListener): this;+ on(event: "end" | "close", listener: SignalListener): this;+ on(event: string, listener: DataListener | SignalListener) {+ if (event === "data") this.data.push(listener as DataListener);+ else if (event === "end") this.end.push(listener as SignalListener);+ else if (event === "close") this.close.push(listener as SignalListener);+ return this;+ }++ off(event: "data", listener: DataListener): this;+ off(event: "end" | "close", listener: SignalListener): this;+ off(event: string, listener: DataListener | SignalListener) {+ if (event === "data") this.data = this.data.filter((item) => item !== listener);+ else if (event === "end") this.end = this.end.filter((item) => item !== listener);+ else if (event === "close") this.close = this.close.filter((item) => item !== listener);+ return this;+ }++ write(chunk: string) {+ for (const listener of this.data.slice()) listener(chunk);+ }++ finish(chunk?: string) {+ if (chunk) this.write(chunk);+ for (const listener of this.end.slice()) listener();+ }++ destroy() {+ for (const listener of this.close.slice()) listener();+ }++ listenerCount(event: "data" | "end" | "close") {+ return this[event].length;+ }++ listeners(event: "data" | "end" | "close") {+ return this[event].slice();+ }+}++const payload = { id: "rpc", result: { content: "A\u2028中文🙂\u2029B\r\nC" } };+const wire = new TextEncoder().encode(`${JSON.stringify(payload)}\n`);++describe("readNdjsonLines", () => {+ it("keeps U+2028/U+2029 inside JSON.stringify output as payload", () => {+ expect(JSON.stringify(payload)).toContain("\u2028");+ expect(JSON.stringify(payload)).toContain("\u2029");+ const input = new FakeNdjsonInput();+ const lines: unknown[] = [];+ readNdjsonLines(input, (line) => lines.push(JSON.parse(line)));+ input.finish(new TextDecoder().decode(wire));+ expect(lines).toEqual([payload]);+ });++ it("preserves Unicode separators at every possible byte split", () => {+ for (let split = 0; split <= wire.length; split++) {+ const input = new FakeNdjsonInput();+ const lines: unknown[] = [];+ readNdjsonLines(input, (line) => lines.push(JSON.parse(line)));+ const decoder = new TextDecoder();+ const head = decoder.decode(wire.subarray(0, split), { stream: true });+ if (head) input.write(head);+ input.finish(decoder.decode(wire.subarray(split)));+ expect(lines, `split at byte ${split}`).toEqual([payload]);+ }+ });++ it("accepts consecutive LF/CRLF frames, blank lines, and an EOF tail", () => {+ const input = new FakeNdjsonInput();+ const lines: string[] = [];+ readNdjsonLines(input, (line) => lines.push(line));+ input.write('\n{"id":1}\r');+ expect(lines, "CR alone does not terminate a frame").toEqual([""]);+ input.write('\n{"id":2}\n{"id":');+ input.finish("3}");+ expect(lines).toEqual(["", '{"id":1}', '{"id":2}', '{"id":3}']);+ for (const event of ["data", "end", "close"] as const) {+ expect(input.listenerCount(event)).toBe(0);+ }+ });++ it("stops buffered frames on close and removes only owned listeners", () => {+ const input = new FakeNdjsonInput();+ const external: DataListener = () => {};+ input.on("data", external);+ const lines: string[] = [];+ const reader = readNdjsonLines(input, (line) => {+ lines.push(line);+ reader.close();+ });+ input.write("first\nsecond\npartial");+ reader.close();+ input.write("ignored\n");+ expect(lines).toEqual(["first"]);+ expect(input.listeners("data")).toEqual([external]);+ expect(input.listenerCount("end")).toBe(0);+ expect(input.listenerCount("close")).toBe(0);+ });++ it("discards a partial frame and detaches when the stream is destroyed", () => {+ const input = new FakeNdjsonInput();+ const lines: string[] = [];+ readNdjsonLines(input, (line) => lines.push(line));+ input.write('{"unfinished":');+ input.destroy();+ expect(lines).toEqual([]);+ for (const event of ["data", "end", "close"] as const) {+ expect(input.listenerCount(event)).toBe(0);+ }+ });+});diff --git a/packages/shared/src/ndjson.ts b/packages/shared/src/ndjson.tsindex 8000ba567..254e36d3c 100644--- a/packages/shared/src/ndjson.ts+++ b/packages/shared/src/ndjson.ts@@ -12,7 +12,12 @@ interface NdjsonInput {* Unlike readline, Unicode line/paragraph separators are ordinary payload.* The input owns UTF-8 decoding, including characters split across byte chunks.*/-export function readNdjsonLines(input: NdjsonInput, onLine: (line: string) => void) {+export type NdjsonLineReader = { close: () => void };++export function readNdjsonLines(+ input: NdjsonInput,+ onLine: (line: string) => void,+): NdjsonLineReader {let closed = false;let fragments: string[] = [];const close = () => {