repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Add ui rpc bridge

7886d6df2214e37330a41b93378c4edbe638cd99

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/ui/__tests__/rpc.test.ts

Added
new file mode 100644
1 +import { once } from "node:events";
2 +import { describe, expect, it } from "vitest";
3 +import { parseJsonLines, startRpc } from "../rpc";
5 +const node = process.execPath;
7 +describe("ui rpc bridge", () => {
8 + it("splits only on LF and keeps partial records", () => {
9 + const parsed = parseJsonLines(
10 + '{"type":"event","text":"a
b"}\r\n{"type":"partial"',
11 + );
13 + expect(parsed.messages).toEqual([{ type: "event", text: "a
b" }]);
14 + expect(parsed.rest).toBe('{"type":"partial"');
15 + });
17 + it("matches responses by id and forwards events", async () => {
18 + const events: unknown[] = [];
19 + const rpc = startRpc({
20 + command: node,
21 + args: [
22 + "-e",
23 + `process.stdin.on('data', chunk => {
24 + for (const line of String(chunk).trim().split('\\n')) {
25 + const msg = JSON.parse(line);
26 + console.log(JSON.stringify({ type: 'event', seen: msg.type }));
27 + console.log(JSON.stringify({ id: msg.id, type: 'response', command: msg.type, success: true, data: { ok: true } }));
28 + }
29 + });`,
30 + ],
31 + cwd: process.cwd(),
32 + sessionPath: "session.jsonl",
33 + onEvent: (event) => events.push(event),
34 + });
36 + try {
37 + const response = await rpc.send({ type: "get_state" });
38 + expect(response).toMatchObject({
39 + type: "response",
40 + command: "get_state",
41 + success: true,
42 + data: { ok: true },
43 + });
44 + expect(events).toEqual([{ type: "event", seen: "get_state" }]);
45 + } finally {
46 + await rpc.close("test");
47 + }
48 + });
50 + it("captures stderr", async () => {
51 + const rpc = startRpc({
52 + command: node,
53 + args: ["-e", "console.error('rpc stderr'); setTimeout(() => {}, 50);"],
54 + cwd: process.cwd(),
55 + sessionPath: "session.jsonl",
56 + });
58 + try {
59 + await once(rpc.child.stderr, "data");
60 + expect(rpc.stderr()).toContain("rpc stderr");
61 + } finally {
62 + await rpc.close("test");
63 + }
64 + });
66 + it("times out unanswered requests", async () => {
67 + const rpc = startRpc({
68 + command: node,
69 + args: ["-e", "process.stdin.resume()"],
70 + cwd: process.cwd(),
71 + sessionPath: "session.jsonl",
72 + requestTimeoutMs: 10,
73 + });
75 + try {
76 + await expect(rpc.send({ type: "get_state" })).rejects.toThrow(/timed out/);
77 + } finally {
78 + await rpc.close("test");
79 + }
80 + });
82 + it("emits slow-start and exit lifecycle states", async () => {
83 + const states: string[] = [];
84 + const rpc = startRpc({
85 + command: node,
86 + args: ["-e", "setTimeout(() => process.exit(7), 40)"],
87 + cwd: process.cwd(),
88 + sessionPath: "session.jsonl",
89 + slowStartMs: 5,
90 + onState: (state) => states.push(state),
91 + });
93 + await once(rpc.child, "exit");
94 + expect(states).toContain("slow-start");
95 + expect(states).toContain("exit");
96 + });
97 +});

extensions/ui/rpc.ts

Added
new file mode 100644
1 +import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2 +import { randomUUID } from "node:crypto";
3 +import { once } from "node:events";
5 +export type RpcState = "starting" | "connected" | "slow-start" | "exit";
7 +export type RpcResponse = {
8 + id?: string;
9 + type: "response";
10 + command?: string;
11 + success: boolean;
12 + data?: unknown;
13 + error?: string;
14 +};
16 +export type RpcRequest = Record<string, unknown> & {
17 + id?: string;
18 + type: string;
19 +};
21 +export type ParsedJsonLines = {
22 + messages: unknown[];
23 + rest: string;
24 +};
26 +export type StartRpcOptions = {
27 + sessionPath: string;
28 + cwd: string;
29 + command?: string;
30 + args?: string[];
31 + env?: NodeJS.ProcessEnv;
32 + requestTimeoutMs?: number;
33 + slowStartMs?: number;
34 + onEvent?: (event: unknown) => void;
35 + onState?: (state: RpcState, details?: unknown) => void;
36 +};
38 +export type RpcClient = {
39 + child: ChildProcessWithoutNullStreams;
40 + send(request: RpcRequest): Promise<RpcResponse>;
41 + stderr(): string;
42 + close(reason: string): Promise<void>;
43 +};
45 +type Pending = {
46 + resolve(response: RpcResponse): void;
47 + reject(error: Error): void;
48 + timer: NodeJS.Timeout;
49 +};
51 +export function parseJsonLines(input: string): ParsedJsonLines {
52 + const messages: unknown[] = [];
53 + const parts = input.split("\n");
54 + const rest = parts.pop() ?? "";
55 + for (const raw of parts) {
56 + const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
57 + if (!line) continue;
58 + messages.push(JSON.parse(line));
59 + }
60 + return { messages, rest };
63 +export function startRpc(options: StartRpcOptions): RpcClient {
64 + const command = options.command ?? process.env.PI_UI_RPC_BIN ?? defaultPiBin();
65 + const args = options.args ?? ["--mode", "rpc", "--session", options.sessionPath];
66 + const child = spawn(command, args, {
67 + cwd: options.cwd,
68 + env: { ...process.env, ...options.env },
69 + stdio: "pipe",
70 + });
71 + const pending = new Map<string, Pending>();
72 + const stderrChunks: string[] = [];
73 + let stdoutRest = "";
74 + let closed = false;
75 + let connected = false;
76 + const timeoutMs = options.requestTimeoutMs ?? 30_000;
77 + const slowTimer = setTimeout(() => {
78 + if (!connected && !closed) options.onState?.("slow-start");
79 + }, options.slowStartMs ?? 8_000);
81 + child.stdout.on("data", (chunk) => {
82 + const parsed = parseJsonLines(stdoutRest + String(chunk));
83 + stdoutRest = parsed.rest;
84 + for (const message of parsed.messages) handleMessage(message);
85 + });
87 + child.stderr.on("data", (chunk) => {
88 + stderrChunks.push(String(chunk));
89 + });
91 + child.once("spawn", () => options.onState?.("starting"));
92 + child.once("exit", (code, signal) => {
93 + closed = true;
94 + clearTimeout(slowTimer);
95 + const error = new Error(
96 + `RPC process exited: code=${code ?? "null"} signal=${signal ?? "null"}`,
97 + );
98 + for (const item of pending.values()) {
99 + clearTimeout(item.timer);
100 + item.reject(error);
102 + pending.clear();
103 + options.onState?.("exit", { code, signal });
104 + });
106 + function handleMessage(message: unknown): void {
107 + connected = true;
108 + options.onState?.("connected");
109 + if (isResponse(message) && message.id && pending.has(message.id)) {
110 + const item = pending.get(message.id);
111 + if (!item) return;
112 + pending.delete(message.id);
113 + clearTimeout(item.timer);
114 + item.resolve(message);
115 + return;
117 + options.onEvent?.(message);
120 + return {
121 + child,
122 + send(request) {
123 + if (closed) return Promise.reject(new Error("RPC process is closed"));
124 + const id = request.id ?? randomUUID();
125 + const payload = { ...request, id };
126 + return new Promise((resolve, reject) => {
127 + const timer = setTimeout(() => {
128 + pending.delete(id);
129 + reject(new Error(`RPC request timed out: ${request.type}`));
130 + }, timeoutMs);
131 + pending.set(id, { resolve, reject, timer });
132 + child.stdin.write(`${JSON.stringify(payload)}\n`, (error) => {
133 + if (!error) return;
134 + pending.delete(id);
135 + clearTimeout(timer);
136 + reject(error);
137 + });
138 + });
139 + },
140 + stderr: () => stderrChunks.join(""),
141 + async close(reason) {
142 + void reason;
143 + if (closed) return;
144 + closed = true;
145 + clearTimeout(slowTimer);
146 + for (const item of pending.values()) {
147 + clearTimeout(item.timer);
148 + item.reject(new Error("RPC process closed"));
150 + pending.clear();
151 + child.kill();
152 + await Promise.race([
153 + once(child, "exit"),
154 + new Promise((resolve) => setTimeout(resolve, 1000)),
155 + ]);
156 + },
157 + };
160 +function isResponse(value: unknown): value is RpcResponse {
161 + return (
162 + !!value &&
163 + typeof value === "object" &&
164 + (value as { type?: unknown }).type === "response"
165 + );
168 +function defaultPiBin(): string {
169 + return process.platform === "win32" ? "pi.cmd" : "pi";