repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Wire ui rpc runtime

e6ecacefe3575f7cd9f43e6d864e401a16111761

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

unsigned

Browse filesCompare with HEAD

Changed files (12)

extensions/ui/__tests__/events.test.ts

Modified
6 6 const store = new EventStore({ maxEvents: 10, now: () => 1000 });
8 8 const first = store.append({ type: "state", state: "starting" });
9 - const second = store.append({ type: "log", level: "info", message: "ready" });
9 + const second = store.append({
10 + type: "log",
11 + level: "info",
12 + message: "ready",
13 + });
11 15 expect(first).toMatchObject({ id: 1, at: 1000, type: "state" });
12 16 expect(second).toMatchObject({ id: 2, at: 1000, type: "log" });

extensions/ui/__tests__/harness.test.ts

Modified
28 28 expect(t.events.uiCallsFor("setWidget")).toHaveLength(0);
31 - it("starts web shell, serves auth pages, and stops from /ui off", async () => {
31 + it("reports an actionable seed error in an empty session", async () => {
32 32 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
33 33 t = await createTestSession({ extensions: [extensionPath] });
34 34 const command = t.session.extensionRunner.extensions[0].commands.get("ui");
35 35 expect(command).toBeDefined();
36 - const ctx = t.session.extensionRunner.createCommandContext();
38 - await command?.handler("", ctx);
37 + await command?.handler(
38 + "",
39 + t.session.extensionRunner.createCommandContext(),
40 + );
40 - const widget = latestWidgetLines(t);
41 - expect(widget.join("\n")).toContain("pi ui");
42 - expect(widget.join("\n")).toContain("mobile qr");
43 - const url = extractUrl(widget);
44 - expect(url.searchParams.has("token")).toBe(true);
45 - expect(await fetchText(url)).toContain("Pi UI shell");
47 - const badUrl = new URL(url);
48 - badUrl.searchParams.set("token", "bad");
49 - const unauthorized = await fetch(badUrl);
50 - expect(unauthorized.status).toBe(401);
52 - await command?.handler("status", ctx);
53 - expect(latestNotify(t)).toContain("ui connected");
54 - expect(latestNotify(t)).toContain("<redacted>");
56 - await command?.handler("qr", ctx);
57 - expect(latestWidgetLines(t).join("\n")).toContain("mobile qr");
59 - await command?.handler("off", ctx);
42 + expect(latestNotify(t)).toContain("Cannot seed UI session");
43 + expect(latestNotify(t)).toContain("Action:");
60 44 expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
61 45 "ui",
62 46 undefined,
64 - await expect(fetch(url)).rejects.toThrow();
68 -function latestWidgetLines(t: TestSession): string[] {
69 - const call = t.events.uiCallsFor("setWidget").at(-1);
70 - expect(call).toBeDefined();
71 - return call?.args[1] as string[];
72 -}
74 51 function latestNotify(t: TestSession): string {
75 52 return String(t.events.uiCallsFor("notify").at(-1)?.args[0] ?? "");
78 -function extractUrl(lines: string[]): URL {
79 - const text = lines.join("\n");
80 - const match = /http:\/\/[^\u001b\s]+/.exec(text);
81 - expect(match).toBeTruthy();
82 - return new URL(match?.[0] ?? "http://127.0.0.1");
83 -}
85 -async function fetchText(url: URL): Promise<string> {
86 - const response = await fetch(url);
87 - expect(response.status).toBe(200);
88 - return await response.text();
89 -}

extensions/ui/__tests__/rpc.test.ts

Modified
75 75 try {
76 - await expect(rpc.send({ type: "get_state" })).rejects.toThrow(/timed out/);
76 + await expect(rpc.send({ type: "get_state" })).rejects.toThrow(
77 + /timed out/,
78 + );
77 79 } finally {
78 80 await rpc.close("test");

extensions/ui/__tests__/runtime.test.ts

Modified
1 +import { EventEmitter } from "node:events";
2 +import { Writable } from "node:stream";
1 3 import { afterEach, describe, expect, it } from "vitest";
2 4 import { openerCandidates } from "../open";
3 5 import { createUiRuntime, type UiRuntime } from "../runtime";
77 79 await runtime.stop("second");
78 80 expect(runtime.status().active).toBe(false);
83 + it("seeds an active branch and starts rpc when a session manager is provided", async () => {
84 + const sent: unknown[] = [];
85 + const runtime = await createUiRuntime({
86 + sessionLabel: "ui: test",
87 + address: "127.0.0.1",
88 + cwd: "C:/repo",
89 + openBrowser: false,
90 + sessionManager: fakeSessionManager(),
91 + startRpcBridge: ({ sessionPath, onState }) => {
92 + onState?.("connected");
93 + return fakeRpc(sent, sessionPath);
94 + },
95 + });
96 + runtimes.push(runtime);
98 + expect(runtime.status()).toMatchObject({
99 + active: true,
100 + rpcState: "connected",
101 + sessionPath: "C:/sessions/ui-branch.jsonl",
102 + });
103 + expect(runtime.widgetLines().join("\n")).toContain("rpc: connected");
104 + });
106 + it("forwards browser prompts to rpc and publishes stream events", async () => {
107 + const sent: unknown[] = [];
108 + const runtime = await createUiRuntime({
109 + sessionLabel: "ui: test",
110 + address: "127.0.0.1",
111 + cwd: "C:/repo",
112 + openBrowser: false,
113 + sessionManager: fakeSessionManager(),
114 + startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
115 + });
116 + runtimes.push(runtime);
117 + const url = new URL(runtime.status().url ?? "");
118 + const socketUrl = new URL("/ws", url);
119 + socketUrl.protocol = "ws:";
120 + socketUrl.searchParams.set("token", url.searchParams.get("token") ?? "");
121 + const socket = new WebSocket(socketUrl);
122 + await new Promise((resolve) =>
123 + socket.addEventListener("open", resolve, { once: true }),
124 + );
125 + socket.send(JSON.stringify({ type: "prompt", text: "hello" }));
126 + await new Promise((resolve) => setTimeout(resolve, 20));
127 + socket.close();
129 + expect(sent).toContainEqual(
130 + expect.objectContaining({ type: "prompt", message: "hello" }),
131 + );
132 + });
135 +function fakeSessionManager() {
136 + return {
137 + getLeafId: () => "leaf-1",
138 + getSessionFile: () => "C:/sessions/source.jsonl",
139 + createBranchedSession: () => "C:/sessions/ui-branch.jsonl",
140 + };
143 +function fakeRpc(sent: unknown[], sessionPath: string) {
144 + return {
145 + child: Object.assign(new EventEmitter(), {
146 + stdout: new EventEmitter(),
147 + stderr: new EventEmitter(),
148 + stdin: new Writable({
149 + write(_chunk, _encoding, callback) {
150 + callback();
151 + },
152 + }),
153 + kill() {},
154 + }),
155 + sessionPath,
156 + send(request: unknown) {
157 + sent.push(request);
158 + return Promise.resolve({ type: "response", success: true, data: {} });
159 + },
160 + stderr: () => "",
161 + close: () => Promise.resolve(),
162 + };

extensions/ui/__tests__/server.test.ts

Modified
1 1 import { once } from "node:events";
2 2 import { describe, expect, it } from "vitest";
3 3 import WebSocket from "ws";
4 -import { EventStore } from "../events";
5 4 import { humanError, redactToken, uiError } from "../errors";
5 +import { EventStore } from "../events";
6 6 import { chooseLanAddress, uiUrl } from "../network";
7 7 import { startUiServer } from "../server";
149 149 events,
150 150 snapshotStatus: "connected",
152 - const ws = new WebSocket(`${server.baseUrl.replace("http", "ws")}/ws?token=tok&after=1`);
152 + const ws = new WebSocket(
153 + `${server.baseUrl.replace("http", "ws")}/ws?token=tok&after=1`,
154 + );
154 156 const [firstRaw] = (await once(ws, "message")) as [Buffer];
155 157 expect(JSON.parse(String(firstRaw))).toEqual({
157 159 events: [live],
160 - const next = events.append({ type: "message", role: "user", text: "hello" });
162 + const next = events.append({
163 + type: "message",
164 + role: "user",
165 + text: "hello",
166 + });
161 167 server.publish(next);
162 168 const [secondRaw] = (await once(ws, "message")) as [Buffer];
163 169 expect(JSON.parse(String(secondRaw))).toEqual({

extensions/ui/__tests__/web-smoke.test.ts

Modified
16 16 expect(html).toContain('id="ui-stream"');
17 17 expect(html).toContain('id="ui-composer"');
18 18 expect(html).toContain('type="module"');
19 - expect(html).toContain('/assets/app.js');
19 + expect(html).toContain("/assets/app.js");
21 21 const js = await fetch(`${server.baseUrl}/assets/app.js`, {
22 22 headers: { authorization: "Bearer tok" },

extensions/ui/index.ts

Modified
7 7 import { matchesKey } from "@earendil-works/pi-tui";
8 8 import { humanError, redactToken, type UiError, uiError } from "./errors";
9 9 import { createUiRuntime, type UiRuntime } from "./runtime";
10 +import type { UiSeedSessionManager } from "./session-seed";
11 12 const COMMANDS = ["off", "status", "open", "qr"];
12 13 const WIDGET_KEY = "ui";
47 48 if (ctx.hasUI) ctx.ui.setWorkingVisible?.(false);
48 49 runtime = await createUiRuntime({
49 50 sessionLabel: sessionLabel(pi, ctx),
51 + cwd: ctx.cwd,
52 + sessionManager: ctx.sessionManager as unknown as UiSeedSessionManager,
50 53 onChange: () => setWidget(ctx),
52 55 terminalUnsubscribe = ctx.hasUI

extensions/ui/rpc.ts

Modified
1 -import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
1 +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2 2 import { randomUUID } from "node:crypto";
3 3 import { once } from "node:events";
63 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];
64 + const command =
65 + options.command ?? process.env.PI_UI_RPC_BIN ?? defaultPiBin();
66 + const args = options.args ?? [
67 + "--mode",
68 + "rpc",
69 + "--session",
70 + options.sessionPath,
71 + ];
66 72 const child = spawn(command, args, {
67 73 cwd: options.cwd,
68 74 env: { ...process.env, ...options.env },

extensions/ui/runtime.ts

Modified
1 +import path from "node:path";
2 +import { EventStore } from "./events";
1 3 import { chooseLanAddress } from "./network";
2 4 import { openBrowser } from "./open";
3 5 import { renderQr } from "./qr";
6 +import { type RpcClient, type StartRpcOptions, startRpc } from "./rpc";
4 7 import { startUiServer, type UiServer, type UiServerState } from "./server";
8 +import { seedUiSession, type UiSeedSessionManager } from "./session-seed";
5 9 import { renderUiWidget } from "./terminal-widget";
7 11 export type UiRuntimeStatus = {
9 13 url?: string;
10 14 state: UiServerState | "starting" | "stopped" | "error";
11 15 clients: number;
16 + rpcState?: string;
17 + sessionPath?: string;
12 18 lastError?: string;
23 29 export type CreateUiRuntimeOptions = {
24 30 sessionLabel: string;
31 + cwd?: string;
25 32 address?: string;
26 33 preferredPort?: number;
27 34 openBrowser?: boolean;
28 35 onChange?: () => void;
36 + sessionManager?: UiSeedSessionManager;
37 + startRpcBridge?: (options: StartRpcOptions) => RpcClient;
38 + events?: EventStore;
31 41 export async function createUiRuntime(
34 44 let state: UiRuntimeStatus = { active: false, state: "starting", clients: 0 };
35 45 let qr = "";
36 46 let server: UiServer | undefined;
47 + let rpc: RpcClient | undefined;
48 + let sessionPath: string | undefined;
49 + let rpcState: string | undefined;
50 + const events = options.events ?? new EventStore();
52 + const publish = (input: Parameters<EventStore["append"]>[0]) => {
53 + const event = events.append(input);
54 + server?.publish(event);
55 + return event;
56 + };
58 + if (options.sessionManager) {
59 + const seed = seedUiSession({
60 + cwd: options.cwd ?? process.cwd(),
61 + sessionManager: options.sessionManager,
62 + });
63 + sessionPath = seed.path;
64 + if (seed.warning)
65 + publish({ type: "log", level: "warning", message: seed.warning });
66 + publish({ type: "state", state: "rpc-starting" });
67 + rpcState = "starting";
68 + rpc = (options.startRpcBridge ?? startRpc)({
69 + sessionPath,
70 + cwd: options.cwd ?? process.cwd(),
71 + onState(next) {
72 + rpcState = next;
73 + publish({ type: "state", state: mapRpcState(next) });
74 + state = currentStatus();
75 + options.onChange?.();
76 + },
77 + onEvent(event) {
78 + publish(normalizeRpcEvent(event));
79 + },
80 + });
81 + }
38 83 const address = options.address ?? chooseLanAddress();
39 84 server = await startUiServer({
40 85 address,
41 86 preferredPort: options.preferredPort,
87 + events,
88 + snapshotStatus: rpcState ? mapRpcState(rpcState) : "waiting",
89 + onBrowserMessage: async (message) => {
90 + await handleBrowserMessage(message, rpc, publish);
91 + },
42 92 onClientState: () => {
43 93 state = currentStatus();
44 94 options.onChange?.();
55 105 url: server.publicUrl,
56 106 state: server.state(),
57 107 clients: server.clients(),
108 + rpcState,
109 + sessionPath,
68 120 state: state.state,
69 121 sessionLabel: options.sessionLabel,
70 122 clients: state.clients,
123 + rpcState: state.rpcState,
124 + sessionPath: state.sessionPath
125 + ? path.basename(state.sessionPath)
126 + : undefined,
71 127 lastError: state.lastError,
82 138 await openBrowser(server.publicUrl);
84 140 async stop(reason: string) {
85 - const current = server;
141 + const currentServer = server;
142 + const currentRpc = rpc;
86 143 server = undefined;
144 + rpc = undefined;
87 145 state = { active: false, state: "stopped", clients: 0 };
88 146 options.onChange?.();
89 - if (current) await current.close(reason);
147 + await currentRpc?.close(reason);
148 + if (currentServer) await currentServer.close(reason);
153 +async function handleBrowserMessage(
154 + message: unknown,
155 + rpc: RpcClient | undefined,
156 + publish: (input: Parameters<EventStore["append"]>[0]) => unknown,
157 +): Promise<void> {
158 + if (!isPromptMessage(message)) return;
159 + publish({ type: "message", role: "user", text: message.text });
160 + await rpc?.send({ type: "prompt", message: message.text });
163 +function isPromptMessage(
164 + value: unknown,
165 +): value is { type: "prompt"; text: string } {
166 + return (
167 + !!value &&
168 + typeof value === "object" &&
169 + (value as { type?: unknown }).type === "prompt" &&
170 + typeof (value as { text?: unknown }).text === "string"
171 + );
174 +function mapRpcState(state: string) {
175 + if (state === "connected") return "rpc-connected";
176 + if (state === "exit") return "rpc-dead";
177 + return "rpc-starting";
180 +function normalizeRpcEvent(
181 + event: unknown,
182 +): Parameters<EventStore["append"]>[0] {
183 + if (isRpcMessageUpdate(event)) {
184 + return {
185 + type: "message",
186 + role: "assistant",
187 + text: event.assistantMessageEvent.delta,
188 + };
190 + if (isRpcToolEvent(event)) {
191 + return {
192 + type: "tool",
193 + phase: event.type.endsWith("start")
194 + ? "start"
195 + : event.type.endsWith("end")
196 + ? "end"
197 + : "update",
198 + toolCallId: event.toolCallId,
199 + name: event.toolName,
200 + };
202 + return { type: "log", level: "info", message: JSON.stringify(event) };
205 +function isRpcMessageUpdate(
206 + event: unknown,
207 +): event is { assistantMessageEvent: { delta: string } } {
208 + return (
209 + !!event &&
210 + typeof event === "object" &&
211 + (event as { type?: unknown }).type === "message_update" &&
212 + typeof (event as { assistantMessageEvent?: { delta?: unknown } })
213 + .assistantMessageEvent?.delta === "string"
214 + );
217 +function isRpcToolEvent(
218 + event: unknown,
219 +): event is { type: string; toolCallId: string; toolName: string } {
220 + return (
221 + !!event &&
222 + typeof event === "object" &&
223 + typeof (event as { type?: unknown }).type === "string" &&
224 + (event as { type: string }).type.startsWith("tool_execution_") &&
225 + typeof (event as { toolCallId?: unknown }).toolCallId === "string" &&
226 + typeof (event as { toolName?: unknown }).toolName === "string"
227 + );

extensions/ui/server.ts

Modified
5 5 type Server,
6 6 type ServerResponse,
7 7 } from "node:http";
8 -import { WebSocketServer, type WebSocket } from "ws";
8 +import { type WebSocket, WebSocketServer } from "ws";
9 9 import type { EventStore } from "./events";
10 10 import { listenHostFor, uiUrl } from "./network";
11 11 import type { UiConnectionStatus, UiEvent } from "./protocol";
33 33 onClientState?: (state: UiServerState) => void;
34 34 events?: EventStore;
35 35 snapshotStatus?: UiConnectionStatus;
36 + onBrowserMessage?: (message: unknown) => void | Promise<void>;
38 39 const COOKIE = "pi_ui_token";
90 + ws.on("message", (data) => {
91 + try {
92 + void options.onBrowserMessage?.(JSON.parse(String(data)));
93 + } catch {
94 + ws.send(JSON.stringify({ type: "error", message: "invalid json" }));
95 + }
96 + });
89 97 ws.on("close", () => sockets.delete(ws));
216 224 function authorized(req: IncomingMessage, token: string): boolean {
217 - return req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token);
225 + return (
226 + req.headers.authorization === `Bearer ${token}` ||
227 + cookieAuthorized(req, token)
228 + );
220 231 function authorizedUrlOrRequest(

extensions/ui/session-seed.ts

Modified
27 27 export function seedUiSession(options: UiSeedOptions): UiSeedResult {
28 28 const leafId = options.sessionManager.getLeafId();
29 29 if (!leafId) {
30 - throw uiError("session_seed_failed", "Cannot seed UI session: no active leaf", {
31 - action: "Send at least one message in the terminal session, then run /ui again.",
32 - retryable: true,
33 - });
30 + throw uiError(
31 + "session_seed_failed",
32 + "Cannot seed UI session: no active leaf",
33 + {
34 + action:
35 + "Send at least one message in the terminal session, then run /ui again.",
36 + retryable: true,
37 + },
38 + );
36 41 const branched = options.sessionManager.createBranchedSession(leafId);
39 44 if (options.allowWholeTreeFallback) {
40 45 const source = options.sessionManager.getSessionFile();
41 - const forked = source ? options.forkWholeTree?.(source, options.cwd) : undefined;
46 + const forked = source
47 + ? options.forkWholeTree?.(source, options.cwd)
48 + : undefined;
42 49 if (forked) {
43 50 return {
44 51 path: forked,

extensions/ui/terminal-widget.ts

Modified
6 6 state: UiServerState | "starting" | "error";
7 7 sessionLabel: string;
8 8 clients: number;
9 + rpcState?: string;
10 + sessionPath?: string;
9 11 lastError?: string;
19 21 `┃ ${osc8Link(state.url, "open browser ui")}`,
20 22 `┃ session: ${state.sessionLabel}`,
21 23 `┃ state: ${state.state} · clients: ${state.clients}`,
24 + `┃ rpc: ${state.rpcState ?? "not-started"}${state.sessionPath ? ` · ${state.sessionPath}` : ""}`,
22 25 "┃ press ESC to cancel UI mode · run /ui off to restore terminal UI",
24 27 if (state.lastError) lines.push(`┃ error: ${state.lastError}`);