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
Addednew 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"',
13 + expect(parsed.messages).
toEqual([{ type:
"event", text:
"a
b" }]);
14 + expect(parsed.rest).
toBe(
'{"type":"partial"');
17 + it(
"matches responses by id and forwards events",
async ()
=> {
18 + const events
: unknown[]
= [];
19 + const rpc
= startRpc({
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 } })); 32 + sessionPath:
"session.jsonl",
33 + onEvent: (event)
=> events.
push(
event),
37 + const response
= await rpc.
send({ type:
"get_state" });
38 + expect(response).
toMatchObject({
40 + command:
"get_state",
44 + expect(events).
toEqual([{ type:
"event", seen:
"get_state" }]);
46 + await rpc.
close(
"test");
50 + it(
"captures stderr",
async ()
=> {
51 + const rpc
= startRpc({
53 + args: [
"-e",
"console.error('rpc stderr'); setTimeout(() => {}, 50);"],
55 + sessionPath:
"session.jsonl",
59 + await once(rpc.child.stderr,
"data");
60 + expect(rpc.
stderr()).
toContain(
"rpc stderr");
62 + await rpc.
close(
"test");
66 + it(
"times out unanswered requests",
async ()
=> {
67 + const rpc
= startRpc({
69 + args: [
"-e",
"process.stdin.resume()"],
71 + sessionPath:
"session.jsonl",
72 + requestTimeoutMs:
10,
76 + await expect(rpc.
send({ type:
"get_state" })).rejects.
toThrow(
/timed out/);
78 + await rpc.
close(
"test");
82 + it(
"emits slow-start and exit lifecycle states",
async ()
=> {
83 + const states
: string[]
= [];
84 + const rpc
= startRpc({
86 + args: [
"-e",
"setTimeout(() => process.exit(7), 40)"],
88 + sessionPath:
"session.jsonl",
90 + onState: (state)
=> states.
push(state),
93 + await once(rpc.child,
"exit");
94 + expect(states).
toContain(
"slow-start");
95 + expect(states).
toContain(
"exit");
extensions/ui/rpc.ts
Addednew 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 = {
16 +export type RpcRequest = Record<
string,
unknown>
& {
21 +export type ParsedJsonLines = {
22 + messages
: unknown[];
26 +export type StartRpcOptions = {
27 + sessionPath
: string;
31 + env
?: NodeJS.
ProcessEnv;
32 + requestTimeoutMs
?: number;
33 + slowStartMs
?: number;
34 + onEvent?: (event
: unknown)
=> void;
35 + onState?: (state
: RpcState, details
?: unknown)
=> void;
38 +export type RpcClient = {
39 + child
: ChildProcessWithoutNullStreams;
40 + send(request
: RpcRequest)
: Promise<
RpcResponse>;
42 + close(reason
: string)
: Promise<
void>;
46 + resolve(response
: RpcResponse)
: void;
47 + reject(error
: Error)
: void;
48 + timer
: NodeJS.
Timeout;
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));
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, {
68 + env: {
...process.
env,
...options.env },
71 + const pending
= new Map<
string,
Pending>();
72 + const stderrChunks
: string[]
= [];
73 + let stdoutRest
= "";
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);
87 + child.stderr.
on(
"data", (chunk)
=> {
88 + stderrChunks.
push(
String(chunk));
91 + child.
once(
"spawn", ()
=> options.
onState?.(
"starting"));
92 + child.
once(
"exit", (code, signal)
=> {
94 + clearTimeout(slowTimer);
95 + const error
= new Error(
96 + `RPC process exited: code=${code ?? "null"} signal=${signal ?? "null"}`,
98 + for (
const item
of pending.
values()) {
99 + clearTimeout(item.timer);
100 + item.
reject(error);
103 + options.
onState?.(
"exit", { code, signal });
106 + function handleMessage(message
: unknown)
: void {
108 + options.
onState?.(
"connected");
109 + if (
isResponse(message)
&& message.
id && pending.
has(message.
id)) {
110 + const item
= pending.
get(message.
id);
112 + pending.
delete(message.
id);
113 + clearTimeout(item.timer);
114 + item.
resolve(message);
117 + options.
onEvent?.(message);
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}`));
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);
140 + stderr: ()
=> stderrChunks.
join(
""),
141 + async close(reason) {
143 + if (closed)
return;
145 + clearTimeout(slowTimer);
146 + for (
const item
of pending.
values()) {
147 + clearTimeout(item.timer);
148 + item.
reject(
new Error(
"RPC process closed"));
152 + await Promise.
race([
153 + once(child,
"exit"),
154 + new Promise((resolve)
=> setTimeout(resolve,
1000)),
160 +function isResponse(value
: unknown)
: value
is RpcResponse {
163 + typeof value
=== "object" && 164 + (value
as { type
?: unknown }).
type === "response" 168 +function defaultPiBin()
: string {
169 + return process.
platform === "win32" ? "pi.cmd" : "pi";