repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Verify ui phase 1 shell

efd1d5e34ede8bc1902344d6d82556124dbd5b77

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

unsigned

Browse filesCompare with HEAD

Changed files (7)

docs/super/plans/2026-07-01-ui-extension-phase-1-runtime-shell.md

Added
new file mode 100644
1 +# UI Extension Phase 1 Implementation Plan
3 +> **For agentic workers:** Use `/skill:executing-plans` to implement this plan task-by-task.
5 +**Goal:** Build `/ui` Phase 1: token-authenticated LAN web shell, QR/link terminal widget, and clean shutdown.
7 +**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`
9 +## Scope
11 +Included:
13 +- Create `extensions/ui` as a normal pi-ext workspace package.
14 +- Install UI deps through the root npm workspace lockfile so `mise run install` uses `npm ci`.
15 +- Register `/ui`, `/ui off`, `/ui status`, `/ui open`, and `/ui qr`.
16 +- Start HTTP server only from `/ui`, never during extension load.
17 +- Protect browser routes with random token auth, cookie auth, and bearer auth for API routes.
18 +- Render shell page, 401 page, and JSON status route.
19 +- Show terminal widget with OSC link, QR, state, session label, client count, ESC help, and `/ui off` help.
20 +- Stop server and clear widget on `/ui off`, ESC, and `session_shutdown`.
21 +- Add unit tests and harness tests.
23 +Excluded:
25 +- RPC subprocess.
26 +- Active-branch session seeding.
27 +- WebSocket event stream.
28 +- Browser composer.
29 +- Visual widgets.
30 +- Telemetry.
32 +## Tasks
34 +- [x] Scaffold `extensions/ui/package.json` and `README.md`.
35 +- [x] Add `qrcode` and `@types/qrcode` through `package-lock.json`.
36 +- [x] Verify `mise run install` installs UI deps via `npm ci`.
37 +- [x] Add network helpers and token redaction helpers.
38 +- [x] Add token-authenticated HTTP server.
39 +- [x] Add QR renderer and terminal widget renderer.
40 +- [x] Add cross-platform browser opener candidates.
41 +- [x] Add runtime state machine.
42 +- [x] Register `/ui` command and cleanup hooks.
43 +- [x] Add unit and harness tests.
44 +- [x] Run targeted UI tests.
45 +- [x] Run actual UI static check.
46 +- [x] Run `mise run check -- ui`.
47 +- [ ] Run real Pi + browser smoke test.
49 +## Done criteria
51 +- `extensions/ui` exists and passes static extension checks.
52 +- Runtime starts only from `/ui`.
53 +- LAN server requires token and serves shell, 401, and status routes.
54 +- Terminal widget shows link, QR, state, session label, ESC help, and `/ui off` help.
55 +- `/ui off`, ESC, and `session_shutdown` stop server and clear widget.
56 +- Dependencies are in `package-lock.json`; `mise run install` succeeds.
57 +- Targeted unit and harness tests pass.
58 +- Real Pi + browser smoke test passes.

extensions/ui/__tests__/runtime.test.ts

Modified
4 4 import { afterEach, describe, expect, it } from "vitest";
5 5 import { openerCandidates } from "../open";
6 6 import { createUiRuntime, type UiRuntime } from "../runtime";
8 8 describe("ui browser opener", () => {
9 9 it("uses platform openers", () => {
10 - expect(openerCandidates("http://x", { platform: "win32", env: {} })[0]).toEqual(
11 - {
12 - command: "cmd.exe",
13 - args: ["/c", "start", "", "http://x"],
14 - },
15 - );
10 + expect(
11 + openerCandidates("http://x", { platform: "win32", env: {} })[0],
12 + ).toEqual({
13 + command: "cmd.exe",
14 + args: ["/c", "start", "", "http://x"],
15 + });
16 16 expect(
17 17 openerCandidates("http://x", { platform: "darwin", env: {} })[0],
18 18 ).toEqual({
19 19 command: "open",
20 20 args: ["http://x"],
22 - expect(openerCandidates("http://x", { platform: "linux", env: {} })[0]).toEqual(
23 - {
24 - command: "xdg-open",
25 - args: ["http://x"],
26 - },
27 - );
22 + expect(
23 + openerCandidates("http://x", { platform: "linux", env: {} })[0],
24 + ).toEqual({
25 + command: "xdg-open",
26 + args: ["http://x"],
27 + });
30 30 it("uses termux opener when available", () => {
55 55 runtimes.push(runtime);
57 57 expect(runtime.status().active).toBe(true);
58 - expect(runtime.status().url).toContain("token=");
58 + expect(new URL(runtime.status().url ?? "").searchParams.has("token")).toBe(
59 + true,
60 + );
59 61 expect(runtime.widgetLines().join("\n")).toContain("ui: test");
61 63 await runtime.redrawQr();

extensions/ui/__tests__/server.test.ts

Modified
59 59 const authorized = await fetch(`${server.baseUrl}/?token=tok`);
60 60 expect(authorized.status).toBe(200);
61 61 expect(authorized.headers.get("set-cookie")).toContain("pi_ui_token=tok");
62 - expect(authorized.headers.get("set-cookie")).toContain(
63 - "SameSite=Strict",
64 - );
62 + expect(authorized.headers.get("set-cookie")).toContain("SameSite=Strict");
65 63 expect(await authorized.text()).toContain("Pi UI shell");
66 64 } finally {
67 65 await server.close("test");

extensions/ui/index.ts

Modified
5 5 ExtensionContext,
6 6 } from "@earendil-works/pi-coding-agent";
7 7 import { matchesKey } from "@earendil-works/pi-tui";
8 -import { humanError, redactToken, uiError, type UiError } from "./errors";
8 +import { humanError, redactToken, type UiError, uiError } from "./errors";
9 9 import { createUiRuntime, type UiRuntime } from "./runtime";
11 11 const COMMANDS = ["off", "status", "open", "qr"];
60 60 : undefined;
61 61 setWidget(ctx);
62 - ctx.ui.notify(`ui open: ${redactToken(runtime.status().url ?? "")}`, "info");
62 + ctx.ui.notify(
63 + `ui open: ${redactToken(runtime.status().url ?? "")}`,
64 + "info",
65 + );
65 68 pi.registerCommand("ui", {
67 70 "Start or control the browser UI runtime. Usage: /ui [off|status|open|qr]",
68 71 getArgumentCompletions(prefix) {
69 72 const trimmed = prefix.trimStart();
70 - return COMMANDS.filter((item) => item.startsWith(trimmed)).map((value) => ({
71 - value,
72 - label: value,
73 - }));
73 + return COMMANDS.filter((item) => item.startsWith(trimmed)).map(
74 + (value) => ({
75 + value,
76 + label: value,
77 + }),
78 + );
75 80 async handler(args, ctx) {
76 81 const command = args.trim();
102 107 function status(ctx: ExtensionCommandContext): void {
103 - if (!runtime) return ctx.ui.notify("ui inactive", "info");
108 + if (!runtime) {
109 + ctx.ui.notify("ui inactive", "info");
110 + return;
104 112 const current = runtime.status();
105 113 ctx.ui.notify(
106 114 `ui ${current.state}: ${redactToken(current.url ?? "")}`,

extensions/ui/network.ts

Modified
1 -import { networkInterfaces, type NetworkInterfaceInfo } from "node:os";
1 +import { type NetworkInterfaceInfo, networkInterfaces } from "node:os";
3 3 export type InterfaceMap = Record<string, NetworkInterfaceInfo[] | undefined>;

extensions/ui/server.ts

Modified
55 55 await listen(server, host, options.preferredPort ?? 0);
56 56 const address = server.address();
57 - if (!address || typeof address === "string") throw new Error("Failed to bind UI server");
57 + if (!address || typeof address === "string")
58 + throw new Error("Failed to bind UI server");
58 59 const baseUrl = `http://127.0.0.1:${address.port}`;
59 60 const publicUrl = uiUrl(options.address, address.port, token);
92 93 try {
93 94 const url = new URL(req.url ?? "/", "http://127.0.0.1");
94 95 setSecurityHeaders(res);
95 - if (hasOversizedBody(req)) return json(res, 413, { error: "body too large" });
96 + if (hasOversizedBody(req))
97 + return json(res, 413, { error: "body too large" });
96 98 if (req.method === "GET" && url.pathname === "/") {
97 99 return serveIndex(req, url, res, ctx);
114 116 res: ServerResponse,
115 117 ctx: RouteContext,
116 118 ): void {
117 - if (url.searchParams.get("token") !== ctx.token && !cookieAuthorized(req, ctx.token)) {
118 - return serveUnauthorized(res);
119 + if (
120 + url.searchParams.get("token") !== ctx.token &&
121 + !cookieAuthorized(req, ctx.token)
122 + ) {
123 + serveUnauthorized(res);
124 + return;
120 126 ctx.clientSeen();
121 127 ctx.setState("connected");
122 - res.setHeader("Set-Cookie", `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`);
128 + res.setHeader(
129 + "Set-Cookie",
130 + `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`,
131 + );
123 132 res.setHeader("Content-Type", "text/html; charset=utf-8");
124 133 res.end(renderShellPage());
160 169 function authorized(req: IncomingMessage, token: string): boolean {
161 - return req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token);
170 + return (
171 + req.headers.authorization === `Bearer ${token}` ||
172 + cookieAuthorized(req, token)
173 + );
164 176 function cookieAuthorized(req: IncomingMessage, token: string): boolean {

extensions/ui/terminal-widget.ts

Modified
24 24 if (state.lastError) lines.push(`┃ error: ${state.lastError}`);
25 25 lines.push("┣━ mobile qr ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
26 - for (const line of state.qr.split(/\r?\n/).filter(Boolean)) lines.push(`┃ ${line}`);
26 + for (const line of state.qr.split(/\r?\n/).filter(Boolean))
27 + lines.push(`┃ ${line}`);
27 28 lines.push("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
28 29 return lines;