deletes ui extension
1122ba0a16ae4b3eeefeb06603ec6e2818148c84
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 31526e9c2dca
bugabingas pi extensions
1122ba0a16ae4b3eeefeb06603ec6e2818148c84
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+30 / −10827 text lines · all files grouped into 32 bars
deleted file mode 100644+0 / −63 text lines
# UI Extension Phase 1 Implementation Plan> **For agentic workers:** Use `/skill:executing-plans` to implement this plan task-by-task.**Goal:** Build `/ui` Phase 1: token-authenticated LAN web shell, QR/link terminal widget, and clean shutdown.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`## ScopeIncluded:- Create `extensions/ui` as a normal pi-ext workspace package.- Install UI deps through the root npm workspace lockfile so `mise run install` uses `npm ci`.- Register `/ui`, `/ui off`, `/ui status`, `/ui open`, and `/ui qr`.- Start HTTP server only from `/ui`, never during extension load.- Protect browser routes with random token auth, cookie auth, and bearer auth for API routes.- Render shell page, 401 page, and JSON status route.- Show terminal widget with OSC link, QR, state, session label, client count, ESC help, and `/ui off` help.- Stop server and clear widget on `/ui off`, ESC, and `session_shutdown`.- Add unit tests and harness tests.Excluded:- RPC subprocess.- Active-branch session seeding.- WebSocket event stream.- Browser composer.- Visual widgets.- Telemetry.## Tasks- [x] Scaffold `extensions/ui/package.json` and `README.md`.- [x] Add `qrcode` and `@types/qrcode` through `package-lock.json`.- [x] Verify `mise run install` installs UI deps via `npm ci`.- [x] Add network helpers and token redaction helpers.- [x] Add token-authenticated HTTP server.- [x] Add QR renderer and terminal widget renderer.- [x] Add cross-platform browser opener candidates.- [x] Add runtime state machine.- [x] Register `/ui` command and cleanup hooks.- [x] Add unit and harness tests.- [x] Run targeted UI tests.- [x] Run actual UI static check.- [x] Run `mise run check -- ui`.- [x] Run real Pi + browser smoke test.## Execution noteWin32 zellij smoke passed with fallback disabled using `extensions/ui/scripts/zellij-smoke.mjs --no-fallback`.The run launched Pi in a zellij session, sent `/ui`, captured the exact token URL through the smoke-only local handoff file, verified tokenless `/api/status` returned `401`, verified the browser shell with Playwright, sent `/ui off`, and wrote a redacted summary.## Done criteria- `extensions/ui` exists and passes static extension checks.- Runtime starts only from `/ui`.- LAN server requires token and serves shell, 401, and status routes.- Terminal widget shows link, QR, state, session label, ESC help, and `/ui off` help.- `/ui off`, ESC, and `session_shutdown` stop server and clear widget.- Dependencies are in `package-lock.json`; `mise run install` succeeds.- Targeted unit and harness tests pass.- Real Pi + browser smoke test passes.deleted file mode 100644+0 / −127 text lines
# UI Extension Phase 2 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Make `/ui` a minimal browser Pi frontend backed by a seeded active-branch RPC subprocess.**Architecture:** Keep Phase 1 server/runtime as owner. Add active-branch session seeding, a Pi RPC child-process bridge, a small event protocol, WebSocket fanout, and a no-framework browser shell that renders snapshots plus ordered events.**Tech Stack:** Node `child_process`, `fs`, `readline`, `crypto`; Pi `SessionManager`; browser WebSocket, Web Components, CSS; Vitest harness tests.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`**Phase:** Phase 2: Active-Branch RPC Session and Basic Web Stream---## ScopeIncluded:- Seed a persistent web session from `ctx.sessionManager.createBranchedSession(ctx.sessionManager.getLeafId())`.- Spawn `pi --mode rpc --session <seeded-session>` with normal extensions/skills/settings.- Parse LF-delimited JSONL from RPC stdout and keep stderr diagnostics separate.- Add RPC request queue with ids, timeout, startup, death, and slow-start states.- Add `/api/snapshot`, `/ws`, event replay buffer, monotonic event ids, and JSON protocol types.- Replace Phase 1 shell page with a basic stream-first browser app and composer.- Send browser prompts through RPC and render user/assistant/tool/error stream items.Excluded:- Full slash-command parity.- Rich syntax/autocomplete.- Visual widgets.- Telemetry.- Nugu polish beyond readable brutal defaults.## FilesCreate:- `extensions/ui/session-seed.ts` — active-branch seed path and warnings.- `extensions/ui/rpc.ts` — child process, JSONL parser, request queue, lifecycle.- `extensions/ui/protocol.ts` — event/snapshot/request types.- `extensions/ui/events.ts` — monotonic event store and replay.- `extensions/ui/web/app.html.ts` — HTML shell.- `extensions/ui/web/app.css.ts` — minimal stream-first CSS.- `extensions/ui/web/app.js.ts` — browser app source emitted by server.- `extensions/ui/__tests__/session-seed.test.ts`.- `extensions/ui/__tests__/rpc.test.ts`.- `extensions/ui/__tests__/events.test.ts`.- `extensions/ui/__tests__/web-smoke.test.ts`.Modify:- `extensions/ui/runtime.ts` — own seed, RPC, event store.- `extensions/ui/server.ts` — add snapshot, app assets, WebSocket upgrade.- `extensions/ui/index.ts` — pass command context into runtime start.- `extensions/ui/terminal-widget.ts` — show RPC startup/connected/dead states.- `extensions/ui/package.json` — add `ws` and `@types/ws` if native upgrade handling is not enough.## Tasks### Task 1: Event protocol and store- [x] Write `events.test.ts` for monotonic ids, bounded replay, and snapshot shape.- [x] Implement `protocol.ts` and `events.ts` with `UiEvent`, `UiSnapshot`, `EventStore.append`, `EventStore.snapshot`, and `EventStore.replayAfter`.- [x] Run `npx vitest run extensions/ui/__tests__/events.test.ts`; expect PASS.- [x] Commit `Add ui event protocol`.### Task 2: Active-branch session seed- [x] Write `session-seed.test.ts` using a fake session manager with `getLeafId()` and `createBranchedSession()`.- [x] Implement `session-seed.ts` so the default path calls `createBranchedSession(getLeafId())` and returns `{ path, warning: undefined }`.- [x] Add fallback warning only when whole-tree `forkFrom` is explicitly used by option.- [x] Run `npx vitest run extensions/ui/__tests__/session-seed.test.ts`; expect PASS.- [x] Commit `Add ui active branch session seed`.### Task 3: RPC bridge- [x] Write `rpc.test.ts` for JSONL parsing, request id matching, stderr capture, timeout, process exit event, and slow-start event.- [x] Implement `rpc.ts` with `startRpc`, `sendRpc`, `closeRpc`, `parseJsonLines`, and typed lifecycle callbacks.- [x] Make subprocess command resolve to `pi.cmd` on win32 and `pi` elsewhere unless `PI_UI_RPC_BIN` overrides it for tests.- [x] Run `npx vitest run extensions/ui/__tests__/rpc.test.ts`; expect PASS.- [x] Commit `Add ui rpc bridge`.### Task 4: Server snapshot and WebSocket stream- [x] Write server tests for authenticated `/api/snapshot`, authenticated WebSocket connect, replay after event id, and 401 on missing token.- [x] Implement `server.ts` upgrade handling and snapshot route.- [x] Add heartbeat ping/pong and disconnect cleanup.- [x] Run `npx vitest run extensions/ui/__tests__/server.test.ts`; expect PASS.- [x] Commit `Add ui browser event transport`.### Task 5: Browser shell and composer- [x] Add `web-smoke.test.ts` that fetches the shell and verifies it contains module script, stream root, composer, and status strip.- [x] Implement `web/app.html.ts`, `web/app.css.ts`, and `web/app.js.ts`.- [x] Browser JS must fetch snapshot first, then connect WebSocket, then render replayed stream items in id order.- [x] Composer submit sends `{ type: "prompt", text }` to server, disables during in-flight RPC, and appends visible pending state.- [x] Run `npx vitest run extensions/ui/__tests__/web-smoke.test.ts`; expect PASS.- [x] Commit `Add ui basic browser shell`.### Task 6: Runtime integration- [x] Extend runtime tests to start with fake seed and fake RPC bridge.- [x] Modify `runtime.ts` to create event store, seed session, start RPC, publish startup state, and expose snapshot/transport dependencies to server.- [x] Modify `index.ts` so `/ui` passes `ctx` into runtime start.- [x] Modify terminal widget to show web URL, RPC state, seeded session path basename, and last lifecycle error.- [x] Run all UI tests: `npx vitest run extensions/ui/__tests__/*.test.ts`; expect PASS.- [x] Commit `Wire ui rpc runtime`.### Task 7: Verification- [x] Run actual static check: `node --input-type=module -e "import {checkStatic, extDirs} from './scripts/extensions.mjs'; process.exit(checkStatic(extDirs(['ui'])));"`.- [x] Run `mise run install` and `mise run check -- ui`.- [x] On win32, run the manual smoke with zellij instead of tmux: create a zellij background session, launch `pi -e extensions/ui/index.ts`, send `/ui`, open the browser URL, send one browser prompt, then `/ui off`.- [x] On non-win32, tmux remains acceptable for manual smoke.- [x] Commit any verification fixes as `Verify ui phase 2 rpc stream`.## Done criteria- Browser page renders seeded session snapshot and live ordered RPC events.- Browser prompt submission reaches the RPC Pi session.- RPC slow startup/death are visible in browser and terminal widget.- Token auth protects snapshot and WebSocket.- UI tests, static check, `mise run install`, and `mise run check -- ui` pass.- Win32 manual terminal smoke uses zellij, not tmux.deleted file mode 100644+0 / −111 text lines
# UI Extension Phase 3 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Bring browser composer behavior close to normal Pi interaction: slash commands, references, keybindings, model/thinking controls, and extension UI requests.**Architecture:** Build on the Phase 2 RPC transport. Add browser-side parsing for Pi syntax, RPC command adapters, and a small UI-request protocol for select/confirm/input/editor/notify/status/title/widget/editor-text interactions.**Tech Stack:** Browser Web Components, WebSocket RPC events, Pi RPC commands, Vitest browser/parser tests.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`**Phase:** Phase 3: Pi Syntax, Commands, Keybindings, and Extension UI---## ScopeIncluded:- Slash command autocomplete and execution.- `/skill:*` and prompt-template entries from RPC command state.- `@` reference parsing and visible unsupported attachment errors when Phase 3 cannot attach yet.- `!` and `!!` mapping to RPC `bash` with correct `excludeFromContext`.- Enter, Shift+Enter, Esc, Ctrl+O, Ctrl+P controls.- Model/thinking controls through RPC where available.- Extension UI request/response rendering for select, confirm, input, editor, notify, status, title, widget, editor text.Excluded:- Trusted full-JS visual widgets.- Telemetry digest.- Pierre/Shiki polish.## FilesCreate:- `extensions/ui/composer.ts` — shared parser for slash/ref/bash forms.- `extensions/ui/command-adapter.ts` — server-side RPC command helpers.- `extensions/ui/extension-ui.ts` — request/response event model.- `extensions/ui/web/components/composer.js.ts`.- `extensions/ui/web/components/dialogs.js.ts`.- `extensions/ui/__tests__/composer.test.ts`.- `extensions/ui/__tests__/command-adapter.test.ts`.- `extensions/ui/__tests__/extension-ui.test.ts`.Modify:- `extensions/ui/protocol.ts`.- `extensions/ui/rpc.ts`.- `extensions/ui/server.ts`.- `extensions/ui/web/app.js.ts`.- `extensions/ui/web/app.css.ts`.## Tasks### Task 1: Composer parser- [x] Write parser tests for plain prompts, `/command args`, `/skill:name`, `@path`, `!cmd`, and `!!cmd`.- [x] Implement `composer.ts` with `parseComposerInput(text)` returning `{ kind, command, args, refs, excludeFromContext }`.- [x] Run `npx vitest run extensions/ui/__tests__/composer.test.ts`; expect PASS.- [x] Commit `Add ui composer parser`.### Task 2: RPC command adapters- [x] Write adapter tests using fake RPC send calls for slash commands, model cycle, thinking cycle, compact, and bash.- [x] Implement `command-adapter.ts` with explicit functions: `sendPrompt`, `runSlashCommand`, `runBash`, `cycleModel`, `cycleThinking`, `abortCurrent`.- [x] Ensure `!!` calls RPC `bash` with `excludeFromContext: true`.- [x] Run adapter tests; expect PASS.- [x] Commit `Add ui rpc command adapters`.### Task 3: Browser autocomplete- [x] Add web tests for slash menu filtering and keyboard selection.- [x] Implement composer component with slash menu from snapshot commands and skills.- [x] Keep desktop minimal; show mobile tap targets only under phone-width CSS.- [x] Run web smoke tests; expect PASS.- [x] Commit `Add ui slash autocomplete`.### Task 4: Keybindings- [x] Add tests for Enter submit, Shift+Enter newline, Esc abort, Ctrl+O expand toggle, Ctrl+P model cycle.- [x] Implement keybinding dispatch in `composer.js.ts` and server RPC routes.- [x] Render immediate local state for abort/model/thinking actions before RPC response when safe.- [x] Run UI tests; expect PASS.- [x] Commit `Add ui browser keybindings`.### Task 5: Extension UI protocol- [x] Write tests for select/confirm/input/editor requests and responses.- [x] Implement `extension-ui.ts` and protocol events `ui_request`, `ui_response`, `ui_notify`, `ui_status`, `ui_title`, `ui_widget`, `ui_editor_text`.- [x] Wire RPC stderr/stdout UI request messages into event store.- [x] Render dialogs in browser and send response ids back through RPC.- [x] Run extension UI tests; expect PASS.- [x] Commit `Add ui extension request protocol`.### Task 6: Integration verification- [x] Run `npx vitest run extensions/ui/__tests__/*.test.ts`.- [x] Run actual static check for `ui`.- [x] Run `mise run install` and `mise run check -- ui`.- [x] On win32, run zellij manual smoke for `/`, `/skill:`, `!`, `!!`, Esc, Ctrl+O, Ctrl+P.- [x] Commit fixes as `Verify ui phase 3 syntax controls`.## Done criteria- Browser composer supports core Pi text syntax and keybindings.- Extension UI requests render and respond through the browser.- Unsupported terminal-only semantics show explicit stream errors, not silent failure.- Tests and mise checks pass.deleted file mode 100644+0 / −110 text lines
# UI Extension Phase 4 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Let agents render trusted full-JS visual widgets in the browser stream with `window.pi` action bridges and visible attribution.**Architecture:** Register UI visual tools in the web RPC session. Store widget lifecycle events in the existing event stream. Mount widget documents in bounded `iframe srcdoc` containers, expose `window.pi` in the parent bridge, and audit every widget-originated action.**Tech Stack:** Pi extension tools, browser iframe `srcdoc`, postMessage, Web Components, Vitest, Playwright Chrome/Firefox probes.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`**Phase:** Phase 4: Trusted Visual Widgets and `window.pi`---## ScopeIncluded:- Visual tools: card, table, diagram, form, mockup/prototype, raw HTML/CSS/JS, update/patch, wait-for-action.- Stable widget ids and lifecycle events.- Bounded iframe layout with height negotiation and overflow containment.- Parent-provided `window.pi` methods for action/result, prompt/steer/follow-up, state, events, update, local notify, and attachment request.- Visible attribution before widget-originated prompts/actions reach the agent/session.- Audit details in expanded stream metadata.Excluded:- Telemetry digest beyond widget action events.- Rendering polish and virtualization.- Any sandbox or permission wall.## FilesCreate:- `extensions/ui/visual-tools.ts`.- `extensions/ui/widget-state.ts`.- `extensions/ui/web/components/visual-block.js.ts`.- `extensions/ui/web/components/widget-bridge.js.ts`.- `extensions/ui/__tests__/visual-tools.test.ts`.- `extensions/ui/__tests__/widget-state.test.ts`.- `extensions/ui/__tests__/widget-layout.test.ts`.- `extensions/ui/__tests__/widget-bridge.test.ts`.Modify:- `extensions/ui/index.ts`.- `extensions/ui/protocol.ts`.- `extensions/ui/server.ts`.- `extensions/ui/web/app.js.ts`.- `extensions/ui/web/app.css.ts`.- `extensions/ui/errors.ts`.## Tasks### Task 1: Widget protocol and state- [x] Write tests for stable ids, mount/update/action/error lifecycle, and audit records.- [x] Implement `widget-state.ts` and protocol event types.- [x] Ensure every widget action has `widgetId`, `toolCallId`, `actionId`, visible label, and timestamp.- [x] Run widget state tests; expect PASS.- [x] Commit `Add ui widget lifecycle state`.### Task 2: Visual tools- [x] Write tests for each visual tool returning fallback text and appending widget events.- [x] Implement `visual-tools.ts` with no sibling extension imports.- [x] Register tools from `index.ts` only for the UI RPC session where tool registration is safe.- [x] Run visual tool tests; expect PASS.- [x] Commit `Add ui visual tools`.### Task 3: Iframe bridge- [x] Write bridge tests for `window.pi.action`, `window.pi.prompt`, `window.pi.notify`, and error reporting.- [x] Implement bounded `iframe srcdoc` bridge with parent postMessage routing.- [x] Reject silent prompts: widget-originated prompt must first append attribution event.- [x] Run bridge tests; expect PASS.- [x] Commit `Add ui widget bridge`.### Task 4: Layout probes- [x] Add Playwright tests for Chrome and Firefox iframe bridge access.- [x] Add mobile-width bounded-layout test with intentionally over-wide/tall content.- [x] Use installed Playwright Firefox; do not skip Firefox silently.- [x] Run layout tests; expect PASS.- [x] Commit `Add ui widget browser layout tests`.### Task 5: Stream rendering- [x] Render visual blocks in main stream with title, fallback, lifecycle state, expand/collapse, ids, and audit details.- [x] Show widget JS errors as stream errors with human action and agent fix hint.- [x] Add tests for fallback and error rendering.- [x] Run UI tests; expect PASS.- [x] Commit `Render ui visual widgets`.### Task 6: Verification- [x] Run all UI tests plus Chrome/Firefox widget probes.- [x] Run static check and `mise run check -- ui`.- [x] On win32, run zellij smoke asking the agent for card/form/raw widget and click a widget action.- [x] Commit fixes as `Verify ui phase 4 widgets`.## Done criteria- Agents can create trusted full-JS widgets in stream.- `window.pi` actions work and are visibly attributed.- Layout is bounded in Chrome and Firefox on desktop and phone widths.- Tests and mise checks pass.deleted file mode 100644+0 / −99 text lines
# UI Extension Phase 5 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Summarize browser behavior for the next prompt and show actionable browser lifecycle errors.**Architecture:** Track raw browser interactions locally, aggregate them in a worker into a capped digest, and attach the digest exactly once to the next user prompt. Treat lifecycle changes as stream events so both human and agent can see disconnects, stale clients, and telemetry failures.**Tech Stack:** Browser Worker, WebSocket heartbeat, Page Visibility API, `pagehide`, local redaction helpers, Vitest browser tests.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`**Phase:** Phase 5: Telemetry Digest and Browser Lifecycle Errors---## ScopeIncluded:- Track scroll dwell, clicks/taps, focus/blur, inactive time, viewport/device class, selected text, widget actions, form abandon/submit, and visible errors.- Redact selected/input text before digest generation.- Show inspectable “digest will be sent” indicator when non-empty.- Attach digest once to the next accepted prompt, then clear.- Detect visibility changes, pagehide, heartbeat loss, WebSocket close, stale clients, and likely browser crash/disconnect.- Render lifecycle errors with human action, agent hint, retryability, and related ids.Excluded:- Raw analytics persistence.- Multi-tab SharedWorker optimization.- Rendering polish.## FilesCreate:- `extensions/ui/telemetry.ts`.- `extensions/ui/lifecycle.ts`.- `extensions/ui/web/worker.js.ts`.- `extensions/ui/web/components/digest-indicator.js.ts`.- `extensions/ui/__tests__/telemetry.test.ts`.- `extensions/ui/__tests__/lifecycle.test.ts`.Modify:- `extensions/ui/protocol.ts`.- `extensions/ui/server.ts`.- `extensions/ui/command-adapter.ts`.- `extensions/ui/web/app.js.ts`.- `extensions/ui/web/app.css.ts`.## Tasks### Task 1: Telemetry aggregation- [x] Write tests for scroll/click/focus/pagehide/widget/form events, caps, and digest text.- [x] Implement `telemetry.ts` with `TelemetryAggregator.add`, `digest`, `clear`, and redaction helpers.- [x] Ensure raw values never cross into prompt context.- [x] Run telemetry tests; expect PASS.- [x] Commit `Add ui telemetry aggregator`.### Task 2: Browser worker tracking- [x] Write worker tests for batching and redaction messages.- [x] Implement `web/worker.js.ts` to batch raw events off the hot path.- [x] Wire `app.js.ts` event listeners for scroll, click, selection, focus, blur, pagehide, and widget actions.- [x] Run worker/web tests; expect PASS.- [x] Commit `Add ui browser telemetry worker`.### Task 3: Digest prompt attachment- [x] Write adapter tests proving digest attaches once to next prompt and then clears.- [x] Modify prompt send path to prepend or attach the digest in a deterministic bounded block.- [x] Render digest indicator near composer with inspectable details.- [x] Run prompt/digest tests; expect PASS.- [x] Commit `Attach ui telemetry digest once`.### Task 4: Lifecycle detection- [x] Write lifecycle tests for heartbeat timeout, WebSocket close, pagehide, stale client, and browser reconnect.- [x] Implement `lifecycle.ts` and server heartbeat state.- [x] Emit lifecycle stream events with action, agent hint, retryability, client id, and timestamps.- [x] Run lifecycle tests; expect PASS.- [x] Commit `Add ui browser lifecycle events`.### Task 5: Verification- [x] Run all UI tests.- [x] Run static check and `mise run check -- ui`.- [x] On win32, use zellij smoke to scroll/click/select/background/return/send next prompt and verify digest appears once.- [x] Commit fixes as `Verify ui phase 5 telemetry lifecycle`.## Done criteria- Digest is capped, inspectable, redacted, prompt-gated, and sent once.- Browser lifecycle errors are visible and actionable.- Telemetry failure does not break prompt submission.- Tests and mise checks pass.deleted file mode 100644+0 / −100 text lines
# UI Extension Phase 6 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Apply the accepted Nugu brutal/minimal visual direction and make long streams, diffs, code, and widgets stay fast.**Architecture:** Keep behavior unchanged. Add semantic CSS variables, lazy rendering upgrades, diff/highlight modules loaded on demand, stream batching, and virtualization thresholds behind the existing event protocol.**Tech Stack:** Nugu CSS variables, `prefers-color-scheme`, Pierre diffs, Shiki lazy import, Web Components, `content-visibility`, `requestAnimationFrame`, `MessageChannel`.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`**Phase:** Phase 6: Nugu Polish, Diffs, Highlighting, and Performance---## ScopeIncluded:- Nugu semantic dark/light variables.- Stream-first layout: no sidebar by default, dominant `YOU` anchors, tiny top/status strips, brutal styling.- Pierre diff rendering with summary, expanded file view, anchors, copied hunks, and annotations.- Shiki lazy/cached highlighting with immediate plaintext fallback.- Long output truncation/expansion.- Virtualization threshold, content visibility, rAF batching, and worker parsing.- Responsive stream/widget containment on desktop and phone.Excluded:- New semantics or transport features.- SharedWorker multi-tab optimization unless measured pain proves it necessary.## FilesCreate:- `extensions/ui/web/theme.css.ts`.- `extensions/ui/web/components/code-block.js.ts`.- `extensions/ui/web/components/diff-view.js.ts`.- `extensions/ui/web/components/long-output.js.ts`.- `extensions/ui/web/components/virtual-stream.js.ts`.- `extensions/ui/__tests__/theme.test.ts`.- `extensions/ui/__tests__/rendering.test.ts`.- `extensions/ui/__tests__/performance.test.ts`.Modify:- `extensions/ui/package.json` and `package-lock.json` — add Pierre/Shiki deps.- `extensions/ui/web/app.css.ts`.- `extensions/ui/web/app.js.ts`.- `extensions/ui/web/worker.js.ts`.- `extensions/ui/README.md`.## Tasks### Task 1: Dependencies through mise/npm workspace- [x] Add Pierre and Shiki dependencies to `extensions/ui/package.json`.- [x] Run `npm install` to update `package-lock.json`.- [x] Run `mise run install` to verify `npm ci` installs them.- [x] Commit `Add ui rendering dependencies`.### Task 2: Nugu theme and layout- [x] Write theme tests for emitted semantic variables and dark/light media query.- [x] Implement `theme.css.ts` and update `app.css.ts`.- [x] Verify stream layout has no default sidebar and keeps top/status strips tiny.- [x] Run theme tests; expect PASS.- [x] Commit `Apply ui Nugu theme`.### Task 3: Code and diff rendering- [x] Write rendering tests for plaintext-first code, lazy Shiki upgrade, and Pierre diff summary/expanded view.- [x] Implement `code-block.js.ts` and `diff-view.js.ts`.- [x] Lazy-load Shiki only after initial plaintext is visible.- [x] Run rendering tests; expect PASS.- [x] Commit `Add ui code and diff rendering`.### Task 4: Long output and virtualization- [x] Write tests for truncation, expansion persistence, selected item preservation, and virtualized stream order.- [x] Implement `long-output.js.ts` and `virtual-stream.js.ts`.- [x] Use `content-visibility` and rAF/MessageChannel batching.- [x] Run performance tests; expect PASS.- [x] Commit `Add ui stream performance guards`.### Task 5: Visual verification- [x] Run all UI tests.- [x] Run static check and `mise run check -- ui`.- [x] On win32, run zellij smoke for dark/light desktop, phone width, long output, code, diff, and widgets.- [x] Commit fixes as `Verify ui phase 6 polish performance`.## Done criteria- Accepted Nugu direction is visible in dark and light mode.- Long streams remain responsive.- Code and diffs show plaintext immediately and upgrade lazily.- Tests and mise checks pass.deleted file mode 100644+0 / −112 text lines
# UI Extension Phase 7 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Harden `/ui` for release with packaging, docs, E2E coverage, and a reproducible manual playbook.**Architecture:** Freeze feature scope, strengthen tests around complete flows, document limitations, and make manual/browser verification explicit. Use zellij instead of tmux on win32; use tmux only on non-win32 systems where available.**Tech Stack:** Pi extension static checks, Vitest, Playwright Chrome/Firefox, zellij on win32, tmux on non-win32, mise tasks.**Roadmap:** `docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md`**Phase:** Phase 7: Package Hardening, E2E, Manual Playbook---## ScopeIncluded:- Finalize package metadata, README, dependencies, and no sibling-extension imports.- Complete unit, harness, browser component, fake-RPC E2E, and real-RPC smoke tiers.- Harden cleanup for subprocess, server, sockets, timers, widgets, terminal restore, and browser clients.- Add manual playbook with zellij on win32 and tmux on non-win32.- Document trusted full JS, LAN HTTP token model, terminal minimization limits, RPC unsupported semantics, and troubleshooting.Excluded:- New UI features.- Automatic RPC restart.- Old-browser support.## FilesCreate:- `extensions/ui/playwright.config.ts`.- `extensions/ui/__e2e__/fake-rpc.spec.ts`.- `extensions/ui/__e2e__/real-rpc-smoke.spec.ts`.- `extensions/ui/docs/manual-playbook.md`.- `extensions/ui/scripts/zellij-smoke.mjs`.- `extensions/ui/scripts/tmux-smoke.mjs`.- `extensions/ui/__tests__/cleanup.test.ts`.Modify:- `extensions/ui/package.json`.- `extensions/ui/README.md`.- `mise.toml` — only if a repo task is needed for UI E2E; otherwise keep using existing root tasks.- `docs/super/specs/2026-07-01-ui-extension-design.md` only for discovered corrections.## Tasks### Task 1: Cleanup hardening- [x] Write cleanup tests for `/ui off`, Esc, session shutdown, RPC death, socket close, and repeated stop.- [x] Fix runtime cleanup until all resources are idempotently closed.- [x] Run cleanup and all UI tests; expect PASS.- [x] Commit `Harden ui cleanup`.### Task 2: E2E fake-RPC tier- [x] Add Playwright config and fake-RPC E2E fixture.- [x] Test auth shell, snapshot, stream render, composer submit, tool lifecycle, widget render, telemetry digest, and shutdown.- [x] Add package script `test:e2e` for UI workspace.- [x] Run `npm --workspace extensions/ui run test:e2e`; expect PASS.- [x] Commit `Add ui fake rpc e2e`.### Task 3: Real-RPC smoke tier- [x] Add real-RPC smoke with long startup budget and explicit skip only when `pi` is unavailable.- [x] Verify active-branch seeded history, one browser prompt, command state, and shutdown.- [x] Keep the test small and non-flaky; fake-RPC remains the broad E2E tier.- [x] Run real smoke locally; expect PASS or documented environment skip.- [x] Commit `Add ui real rpc smoke`.### Task 4: Manual playbook scripts- [x] Implement `scripts/zellij-smoke.mjs` for win32: create zellij background session, launch Pi, send `/ui`, dump screen, extract URL, open browser, test 401, run `/ui off`, and leave attach/kill commands.- [x] Implement `scripts/tmux-smoke.mjs` for non-win32 with the same checkpoints.- [x] Ensure win32 path never invokes tmux.- [x] Add `docs/manual-playbook.md` with exact zellij/tmux commands and evidence checkpoints.- [x] Commit `Add ui manual smoke playbook`.### Task 5: Documentation and package review- [x] Update `extensions/ui/README.md` with commands, security/trust model, LAN token, zellij-on-win32 playbook, troubleshooting, and known limitations.- [x] Verify package metadata has no version, `private:true`, `main:index.ts`, MIT, peer deps, and required harness dev dep.- [x] Run `mise run readme -- ui` only if the generated style preserves required manual details; otherwise update manually.- [x] Commit `Document ui extension`.### Task 6: Release gate verification- [x] Run `npx vitest run extensions/ui/__tests__/*.test.ts`.- [x] Run UI E2E.- [x] Run actual static check for `ui`.- [x] Run `mise run install`, `mise run check -- ui`, and then `mise run ci` if unrelated dirty work does not make CI meaningless.- [x] Run win32 zellij manual smoke on this host.- [x] Commit fixes as `Verify ui release hardening`.## Done criteria- Full UI feature set is tested at unit/harness/browser/E2E levels.- Manual playbook is executable and uses zellij on win32.- README documents commands, trust, LAN HTTP, limitations, and troubleshooting.- Static check, mise install/check, and relevant test suites pass.## Execution noteAutomated verification passed for Vitest, fake-RPC E2E, static check, install, `mise run check -- ui`, and `mise run ci`.The win32 zellij smoke path now uses `scripts/zellij-smoke.mjs` and never invokes tmux.On this host, zellij background `run` panes exited immediately for `pi.cmd`, `cmd.exe /K`, and PowerShell `-NoExit`, and `dump-screen` returned blank output, so the script records evidence and leaves attach/kill commands for manual continuation.deleted file mode 100644+0 / −556 text lines
# Mise Task Architecture Phase 2 Implementation Plan> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.**Goal:** Move existing diff-review and UI browser suites into extension-local mise tasks, run both in Chromium and Firefox, and replace extension-specific root commands with one aggregate `e2e` task.**Architecture:** A root Playwright base owns the shared Chromium/Firefox headless policy, while each browser-owning extension overlays suite-specific paths and timeouts and controls its local `e2e` command. Root mise installs both browser engines once, then dispatches extension-local suites sequentially through monorepo task syntax.**Tech Stack:** mise monorepo tasks, Playwright 1.61, Chromium, Firefox, npm workspaces, TypeScript.**Roadmap:** [`docs/super/roadmaps/2026-07-12-mise-task-architecture-roadmap.md`](../roadmaps/2026-07-12-mise-task-architecture-roadmap.md)**Phase:** Phase 2: Existing E2E Suites And Aggregate Command---## File Structure**Create:**- `test/playwright.base.ts`: shared Chromium, Firefox, and headless policy.- `extensions/diff-review/mise.toml`: diff-review E2E ownership.- `extensions/ui/mise.toml`: UI E2E ownership.**Modify:**- `extensions/diff-review/playwright.config.ts`: diff-review overlay on the shared browser base.- `extensions/ui/playwright.config.ts`: UI overlay on the shared browser base without a Windows-only executable override.- `extensions/diff-review/package.json`: remove duplicate `test:e2e` script ownership.- `extensions/ui/package.json`: remove duplicate `test:e2e` script ownership.- `scripts/extensions.mjs`: allow Playwright configs to import root test infrastructure without weakening production extension isolation.- `scripts/test_extensions_static_check.mjs`: regress the narrow Playwright-config allowance.- `mise.toml`: replace public browser-install and diff-review-specific tasks with aggregate `e2e`.- `AGENTS.md`: document the aggregate root task and qualified local tasks.- `extensions/diff-review/README.md`: document local and root-qualified E2E usage.- `extensions/ui/README.md`: document local and root-qualified E2E usage.**Unchanged:**- Existing Playwright specs remain behaviorally unchanged.- Root `test` remains Vitest-only.- Root `ci` remains lint, test, and check until Phase 4.- The-system and tune E2E coverage remain deferred to Phases 3 and 4.### Task 1: Normalize Existing Playwright Browser Matrices**Files:**- Create: `test/playwright.base.ts`- Modify: `extensions/diff-review/playwright.config.ts`- Modify: `extensions/ui/playwright.config.ts`- Modify: `scripts/extensions.mjs`- Test: `scripts/test_extensions_static_check.mjs`- [ ] **Step 1: Record unrelated work before editing**Run:```bashgit status --shortgit diff -- extensions/diff-review/playwright.config.ts extensions/ui/playwright.config.ts```Expected: neither Playwright config has pre-existing worktree changes.Preserve every unrelated dirty path shown by status.- [ ] **Step 2: Verify the current single-browser behavior**Run:```bashnpm exec --workspace extensions/diff-review -- playwright test --config playwright.config.ts --listnpm --workspace extensions/ui exec -- node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts --list```Expected: diff-review lists Firefox tests only, and UI lists Chromium tests only.This is the failing baseline for the required two-browser matrix.- [ ] **Step 3: Create the shared browser base**Create `test/playwright.base.ts`:```tsimport { defineConfig } from "@playwright/test";export default defineConfig({ projects: [ { name: "chromium", use: { browserName: "chromium" } }, { name: "firefox", use: { browserName: "firefox" } }, ], use: { headless: true, },});```The root base owns only policy common to every extension suite.- [ ] **Step 4: Configure diff-review as a local overlay**Replace `extensions/diff-review/playwright.config.ts` with:```tsimport { defineConfig } from "@playwright/test";import base from "../../test/playwright.base.ts";export default defineConfig(base, { testDir: "__e2e__", testMatch: "*.spec.ts", timeout: 30_000, retries: 1,});```Keep existing timeout and retry policy unchanged.- [ ] **Step 5: Configure UI as a local overlay**Replace `extensions/ui/playwright.config.ts` with:```tsimport { defineConfig } from "@playwright/test";import base from "../../test/playwright.base.ts";export default defineConfig(base, { testDir: "./__e2e__", timeout: 30_000, expect: { timeout: 5_000 }, use: { viewport: { width: 900, height: 700 }, },});```Delete the `node:fs` import and hard-coded Windows Chrome path.Playwright’s installed Chromium must be used consistently on every platform.- [ ] **Step 6: Add a failing static-check regression for shared test infrastructure**Add a temporary extension with `playwright.config.ts` importing `../test/playwright.base.ts` to `scripts/test_extensions_static_check.mjs`, then assert `staticCheck()` returns no errors.Run `node scripts/test_extensions_static_check.mjs`.Expected: FAIL with `cross-extension relative import ../test/playwright.base.ts in playwright.config.ts`.- [ ] **Step 7: Allow only Playwright configs to import root test infrastructure**Extend `isAllowedTestImport()` in `scripts/extensions.mjs` so resolved paths must remain under root `test/`, and importers must be either inside `__tests__` or named `playwright.config.ts`.Run `node scripts/test_extensions_static_check.mjs`.Expected: PASS.- [ ] **Step 8: Verify both projects are discovered**Run:```bashnpm exec --workspace extensions/diff-review -- playwright test --config playwright.config.ts --listnpm --workspace extensions/ui exec -- node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts --list```Expected:- Every diff-review spec appears once under `[chromium]` and once under `[firefox]`.- Both UI specs appear once under `[chromium]` and once under `[firefox]`.- `real-rpc-smoke.spec.ts` remains listed but runtime-skipped unless explicitly enabled.- [ ] **Step 9: Install the two browser engines for verification**Run:```bashnpm exec -- playwright install chromium firefox```Expected: exit 0.Existing cached engines may be reused.Do not use `--with-deps`; system-package mutation belongs to CI environment setup, not this cross-platform task.- [ ] **Step 10: Run both suites directly**Run:```bashnpm exec --workspace extensions/diff-review -- playwright test --config playwright.config.tsnpm --workspace extensions/ui exec -- node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts```Expected:- Diff-review passes in Chromium and Firefox.- UI’s fake-RPC suite passes in Chromium and Firefox.- UI’s real-RPC smoke is skipped by default in both projects.- No OS-specific browser executable is required.- [ ] **Step 11: Commit browser matrix normalization**Run:```bashgit add test/playwright.base.ts extensions/diff-review/playwright.config.ts extensions/ui/playwright.config.ts scripts/extensions.mjs scripts/test_extensions_static_check.mjsgit diff --cached --checkgit commit -m "test(e2e): cover chromium and firefox"```Expected: the shared base and two extension overlays are committed.### Task 2: Move E2E Command Ownership Into Extensions**Files:**- Create: `extensions/diff-review/mise.toml`- Create: `extensions/ui/mise.toml`- Modify: `extensions/diff-review/package.json`- Modify: `extensions/ui/package.json`- [ ] **Step 1: Verify qualified E2E tasks are absent**Run:```bashmise tasks --all --name-only```Expected: neither `//extensions/diff-review:e2e` nor `//extensions/ui:e2e` exists.- [ ] **Step 2: Add diff-review’s local E2E task**Create `extensions/diff-review/mise.toml`:```toml[tasks.e2e]description = "Run diff-review browser E2E tests"depends = ["//:install"]run = "npm exec -- playwright test --config playwright.config.ts"```- [ ] **Step 3: Add UI’s local E2E task**Create `extensions/ui/mise.toml`:```toml[tasks.e2e]description = "Run UI browser E2E tests"depends = ["//:install"]run = "node --import tsx ../../node_modules/@playwright/test/cli.js test --config playwright.config.ts"```- [ ] **Step 4: Remove duplicate package-script ownership**Remove only `test:e2e` from both extension `scripts` objects.`extensions/diff-review/package.json` keeps:```json"scripts": { "dev:smoke": "tsx scripts/dev-server.ts"},````extensions/ui/package.json` keeps:```json"scripts": { "test": "vitest run ./__tests__/*.test.ts"},```Do not change dependencies in this phase.Playwright remains a declared development dependency of the root and each E2E-owning workspace.- [ ] **Step 5: Regenerate npm lock metadata**Run:```bashmise run lock```Expected: exit 0.Package scripts normally do not alter `package-lock.json`; if the lockfile changes, inspect and include only metadata caused by these package edits.- [ ] **Step 6: Verify local task discovery and execution**Run:```bashmise tasks --all --name-onlymise run //extensions/diff-review:e2emise run //extensions/ui:e2e```Expected: both qualified tasks exist and both browser matrices pass.- [ ] **Step 7: Commit local E2E ownership**Run:```bashgit add extensions/diff-review/mise.toml extensions/ui/mise.toml extensions/diff-review/package.json extensions/ui/package.json package-lock.jsongit diff --cached --checkgit commit -m "build(e2e): localize browser suites"```Expected: two local mise files and removal of duplicate package scripts are committed.Omit `package-lock.json` if unchanged.### Task 3: Replace Root E2E Tasks With One Aggregate**Files:**- Modify: `mise.toml:59-72`- [ ] **Step 1: Confirm the obsolete root commands**Run:```bashmise tasks --name-only```Expected: `//:install-e2e-browsers` and `//:e2e-diff-review` exist, while `//:e2e` does not.- [ ] **Step 2: Replace both obsolete task blocks**Delete the complete `[tasks.install-e2e-browsers]` and `[tasks.e2e-diff-review]` blocks.Insert this task in their place:```toml[tasks.e2e]description = "Run all extension browser E2E tests"depends = ["install"]run = [ "npm exec -- playwright install chromium firefox", "mise run --jobs 1 //extensions/...:e2e",]```Browser installation occurs once at root.Extension execution is sequential to avoid browser/process contention and interleaved reports.Local qualified tasks assume browsers were installed through root `e2e` or an explicit Playwright install.- [ ] **Step 3: Verify root and all-task surfaces**Run:```bashmise tasks validatemise tasks --name-onlymise tasks --all --name-onlymise run --dry-run e2e```Expected:- Task validation exits 0.- Root contains `//:e2e`.- Root no longer contains `//:install-e2e-browsers` or `//:e2e-diff-review`.- All-task output contains both qualified extension E2E tasks.- The dry run shows one browser install followed by sequential monorepo dispatch.- [ ] **Step 4: Run the aggregate E2E task**Run:```bashmise run e2e```Expected: browser installation succeeds once, then diff-review and UI suites both pass in Chromium and Firefox.The two extension task headers do not overlap.- [ ] **Step 5: Confirm Vitest and CI remain unchanged**Run:```bashmise run testmise run --dry-run ci```Expected:- Vitest does not discover files under `__e2e__`.- CI resolves lint, test, and check only.- E2E remains outside CI until Phase 4.- [ ] **Step 6: Commit root aggregation**Run:```bashgit add mise.tomlgit diff --cached --checkgit commit -m "build(e2e): aggregate browser suites"```Expected: the commit contains only replacement of the two legacy E2E tasks with root `e2e`.### Task 4: Document The Phase 2 Task Surface**Files:**- Modify: `AGENTS.md:10-35`- Modify: `extensions/diff-review/README.md`- Modify: `extensions/ui/README.md`- [ ] **Step 1: Replace legacy E2E rows in AGENTS.md**Remove:```markdown| E2E browsers | `mise run install-e2e-browsers` | Install Playwright E2E browsers || E2E review | `mise run e2e-diff-review` | Run diff-review headless browser E2E |```Add after `Bench`:```markdown| E2E | `mise run e2e` | Run extension E2E in Chromium and Firefox |```Keep the Phase 2 CI description as `Release gate (lint + test + check)`.- [ ] **Step 2: Document diff-review E2E usage**Add this section near diff-review’s development/testing documentation:```markdown## E2ERun root `mise run e2e` first to install browsers and execute every extension suite.After that bootstrap, run `mise run e2e` here, or `mise //extensions/diff-review:e2e` from the repository root, to test only the browser review flow in Chromium and Firefox.```- [ ] **Step 3: Document UI E2E usage**Add this section near UI’s development/testing documentation:```markdown## E2ERun root `mise run e2e` first to install browsers and execute every extension suite.After that bootstrap, run `mise run e2e` here, or `mise //extensions/ui:e2e` from the repository root, to test only the browser UI in Chromium and Firefox.The real Pi RPC smoke remains opt-in through `UI_REAL_RPC_SMOKE=1`.```- [ ] **Step 4: Verify obsolete command references are gone from live docs**Run:```bashnode -e "const fs=require('node:fs'); for(const p of ['AGENTS.md','extensions/diff-review/README.md','extensions/ui/README.md']) { const s=fs.readFileSync(p,'utf8'); for(const old of ['install-e2e-browsers','e2e-diff-review']) if(s.includes(old)) throw new Error(p+': '+old); }"```Expected: exit 0 with no output.- [ ] **Step 5: Verify changed documentation formatting**Run:```bashgit diff --check -- AGENTS.md extensions/diff-review/README.md extensions/ui/README.md```Expected: exit 0 with no output.Do not run repository-wide formatting while unrelated dirty files remain.The final CI lint check validates Markdown formatting without mutating those files.- [ ] **Step 6: Commit documentation**Run:```bashgit add AGENTS.md extensions/diff-review/README.md extensions/ui/README.mdgit diff --cached --checkgit commit -m "docs: explain aggregate browser E2E"```Expected: only E2E command documentation is committed.### Task 5: Verify The Phase 2 Boundary**Files:**- Verify: `mise.toml`- Verify: `extensions/diff-review/mise.toml`- Verify: `extensions/ui/mise.toml`- Verify: both Playwright configurations and suites- [ ] **Step 1: Validate final task discovery**Run:```bashmise tasks validatemise tasks --name-onlymise tasks --all --name-only```Expected:- Exactly one public root E2E task exists: `//:e2e`.- Qualified diff-review and UI E2E tasks exist.- Legacy root E2E task names are absent.- Phase 1 benchmark tasks remain unchanged.- [ ] **Step 2: Run the complete browser aggregate**Run:```bashmise run e2e```Expected:- Both browser engines are available.- Diff-review passes in Chromium and Firefox.- UI fake-RPC passes in Chromium and Firefox.- UI real-RPC smoke is skipped by default.- [ ] **Step 3: Run the unchanged release gate**Run:```bashmise run ci```Expected: lint, all Vitest tests, typecheck, and static checks pass.E2E remains a separate manual gate in Phase 2.- [ ] **Step 4: Inspect final scope**Run:```bashgit status --shortgit diff --statgit log -5 --oneline```Expected: unrelated pre-existing work remains untouched.No the-system or tune E2E files were added.No CI workflow was changed.No TypeScript import standardization from Phase 5 was started.- [ ] **Step 5: Report completion evidence**Report:- Task validation and root/all task lists.- Chromium and Firefox results for diff-review and UI.- `mise run ci` result.- Commits created.- Confirmation that E2E is not yet part of CI.- Confirmation that Phases 3 through 5 remain unimplemented.+0 / −1 text lines
+0 / −1 text lines
deleted file mode 100644+0 / −358 text lines
# UI Extension Roadmap> **For agentic workers:** Use /skill:writing-plans to create one detailed implementation plan per phase. Start with Phase 1 and proceed sequentially unless the user explicitly changes the order.**Goal:** Build `/ui`, a persistent browser Pi frontend backed by an active-branch RPC session while terminal Pi remains independent.**Design Spec:** [`docs/super/specs/2026-07-01-ui-extension-design.md`](../specs/2026-07-01-ui-extension-design.md)**Planning Strategy:** The design spans terminal extension behavior, LAN auth, RPC/session bridging, a browser frontend, trusted full-JS widgets, telemetry, rendering performance, and test hardening. Each phase leaves a usable, visually verifiable slice before adding the next subsystem.---## Phase 1: `/ui` Runtime Shell, LAN Server, Terminal Widget**Outcome:** `/ui` starts and stops a runtime with a token-authenticated LAN web server and minimal terminal widget.**Why now:** This creates the visible entry point, mobile link/QR path, and lifecycle shell every later phase uses.**Scope:**- Register `/ui`, `/ui off`, `/ui status`, `/ui open`, and `/ui qr`.- Start/stop one runtime per terminal session.- Bind LAN HTTP server with random token auth, same-origin CORS, and 401 handling.- Render terminal widget with OSC link, QR, host/port, session label, ESC help, `/ui off`, and connection state.- Restore terminal UI on `/ui off`, ESC, or session shutdown.**Out of scope:**- RPC subprocess.- Seeded active-branch session history.- Full Pi web composer.- Visual widgets and telemetry.**Key files/areas likely affected:**- `extensions/ui/index.ts`: extension registration and commands.- `extensions/ui/server.ts`: HTTP server and token auth.- `extensions/ui/terminal-widget.ts`: terminal minimized widget.- `extensions/ui/qr.ts`: QR generation.- `extensions/ui/errors.ts`: typed startup/shutdown errors.- `extensions/ui/__tests__/`: harness and server tests.**Dependencies:**- Pi extension command/widget APIs.- QR generation dependency decision.**Verification:**- Automated: extension loads without side effects; commands register; token auth accepts good token and rejects bad/missing token; duplicate `/ui` is idempotent; `/ui off` cleans server/timers/widget.- Visual: run real Pi, execute `/ui`, and visually confirm terminal collapses to one widget showing OSC link, QR, host/port, state, ESC, and `/ui off` help.- Visual: open browser link and bad-token URL; confirm authenticated page and precise 401 page are visibly distinct and understandable.- Visual: scan QR from phone on same LAN and see the same authenticated startup page.**Phase boundary health:** Terminal Pi still works independently; the browser page is only a shell, but start/stop/auth/restore are complete and testable.**Risks:**- Terminal APIs may not fully hide existing UI; mitigate by minimizing as far as APIs allow and documenting limitations.- LAN address detection may fail; mitigate with actionable stream/terminal error and `/ui status` diagnostics.**Context notes:** Keep startup work inside `/ui`; extension load must stay cheap and side-effect-free.## Phase 2: Active-Branch RPC Session and Basic Web Stream**Outcome:** Browser UI talks to a persistent Pi RPC session seeded from the terminal active branch and renders a basic ordered stream plus composer.**Why now:** This proves `/ui` is a real Pi frontend, not a companion page.**Scope:**- Extract the active terminal session branch into a persistent web session with `createBranchedSession(getLeafId())` where possible.- Spawn `pi --mode rpc --session <seeded-session>` with normal extensions/skills/settings.- Parse RPC stdout as LF-delimited JSONL and capture stderr separately.- Implement server event bus, snapshot, replay buffer, WebSocket stream, and RPC stdin queue.- Render basic browser shell: top state strip, central stream, tiny status strip, composer.- Send normal prompts from browser and show user/assistant/tool/error stream items.**Out of scope:**- Complete slash-command parity.- Rich diffs/highlighting.- Visual widget tools.- Telemetry digest.**Key files/areas likely affected:**- `extensions/ui/session-seed.ts`: fork/fallback session seeding.- `extensions/ui/rpc.ts`: subprocess bridge and command queue.- `extensions/ui/protocol.ts`: event types, snapshots, replay.- `extensions/ui/web/`: initial browser shell, stream, composer, worker.- `extensions/ui/__tests__/rpc.test.ts`: parser, queue, death, stderr.**Dependencies:**- Phase 1.- Verified Pi active-branch session extraction and RPC flags.**Verification:**- Automated: `createBranchedSession(getLeafId())` path selected; parent recorded; exact active branch preserved; whole-tree `forkFrom` fallback warns; JSONL parser splits LF only; event sequence monotonic; reconnect replays or snapshots; slow RPC startup and RPC death produce actionable events.- Visual: open `/ui` and see seeded terminal history in the central stream with dominant `YOU` blocks.- Visual: send a browser prompt and watch user message, assistant stream, and tool lifecycle appear in order.- Visual: kill RPC process and confirm browser shows a clear, actionable stream error while terminal widget updates state.**Phase boundary health:** `/ui` becomes minimally useful as a browser Pi session; missing advanced syntax is visible but not broken.**Risks:**- Exact active-branch extraction APIs may differ; mitigate by failing with actionable error rather than ad-hoc corrupt JSON rewriting.- RPC event shapes may need normalization; mitigate with typed protocol tests before UI assumptions spread.**Context notes:** Keep the stream deterministic and boring; defer polish until behavior is correct.## Phase 3: Pi Syntax, Commands, Keybindings, and Extension UI**Outcome:** Browser composer and controls match normal Pi interaction expectations.**Why now:** After the RPC path works, parity features can be layered without confusing transport failures with UI behavior.**Scope:**- Slash command autocomplete and execution.- `/skill:*`, prompt templates, model/thinking controls, compact/session commands where RPC supports them.- `@` file/image references and attachment flow.- `!`/`!!` bash behavior or explicit equivalent web mapping.- Enter, Shift+Enter, Esc abort, Ctrl+O expand/collapse, Ctrl+P model cycle.- Render RPC extension UI requests: select, confirm, input, editor, notify, status/title/widget/editor text.- Keep desktop chrome minimal; add tap targets only where mobile needs them.**Out of scope:**- Full-JS visual widgets.- Telemetry.- Pierre/Shiki polish.**Key files/areas likely affected:**- `extensions/ui/web/components/`: composer, autocomplete, dialogs, stream selection.- `extensions/ui/rpc.ts`: command adapters.- `extensions/ui/protocol.ts`: extension UI request/response events.- `extensions/ui/web/worker.js.ts`: batched input/event dispatch.**Dependencies:**- Phase 2.- RPC command availability check.**Verification:**- Automated: composer parsing for `/`, `/skill:*`, `@`, `!`, `!!`; keybindings dispatch expected RPC commands; dialogs return selected values.- Visual: type `/` and visually verify command autocomplete, skill entries, and prompt templates look and behave like Pi.- Visual: invoke select/confirm/input/editor flows and confirm dialogs appear in stream or modal form with clear action targets.- Visual: use Ctrl+P, Ctrl+O, Esc, Enter, Shift+Enter and see immediate visible state changes.- Visual: on phone width, confirm essential controls remain visible without desktop button clutter.**Phase boundary health:** Web UI now behaves like a normal Pi frontend for text, commands, tools, and extension UI; richer widgets remain additive.**Risks:**- Some terminal-only semantics may lack RPC equivalents; mitigate with explicit web mappings or visible unsupported errors.- Mobile controls can bloat desktop; mitigate by CSS/media-gated tap targets.**Context notes:** Preserve Pi syntax over inventing web-only controls.## Phase 4: Trusted Visual Widgets and `window.pi`**Outcome:** Agents can create, update, and receive actions from trusted full-JS visual widgets embedded in the stream.**Why now:** Widget actions require stable stream, composer, RPC, and extension UI foundations.**Scope:**- Register visual tool families for web RPC session: card, table, diagram, form/control, mockup/prototype, raw HTML/CSS/JS, update/patch, wait-for-action.- Render bounded visual blocks with stable widget ids, title, fallback text, lifecycle state, expand/collapse, and response expectation.- Expose `window.pi` methods for widget action/result, prompt/steer/follow-up, state, widget events, payload update, local notify, and attachment request.- Attribute every widget-originated action/prompt visibly in the stream.- Audit `window.pi` calls in details available to the agent.- Deliberately no sandbox or separate permission wall; full-JS widgets are trusted agent output, constrained by layout/lifecycle boundaries and visible attribution.**Out of scope:**- Telemetry digest beyond widget action events needed for actions.- Pierre/Shiki rendering polish.- Heavy virtualization.**Key files/areas likely affected:**- `extensions/ui/visual-tools.ts`: tool registration and fallback text.- `extensions/ui/web/components/`: visual block, widget bridge, errors.- `extensions/ui/protocol.ts`: widget lifecycle/action events.- `extensions/ui/errors.ts`: widget runtime/action errors.**Dependencies:**- Phase 3.- User decision: no sandbox; trust boundary is visual attribution/audit, not containment.**Verification:**- Automated: stable widget ids; fallback text returned; mount/update/action/error events; `window.pi` method routing; Chrome/Firefox iframe bridge and bounded-layout probes pass; widget errors become human+agent actionable stream errors.- Visual: ask agent for a visual card, form, diagram/prototype, and full HTML/CSS/JS widget; confirm all appear in the main stream, bounded and responsive.- Visual: click widget controls and confirm resulting action is visibly attributed to that widget before reaching agent/session.- Visual: trigger a widget JS error and confirm the block shows widget id/tool call id plus human action and agent fix hint.- Visual: inspect expanded metadata and see `full JS / trusted`, lifecycle, fallback, ids, and audit details.**Phase boundary health:** Visual widgets are useful and honest about trust; later telemetry/perf can improve observability and scale without changing the bridge contract.**Risks:**- Trusted full JS can leak data or impersonate actions; accepted by design, mitigated only through visible attribution, audit, and no silent widget-originated prompts.- CSS/layout interference can damage page usability; mitigate with document/layout boundary, containment, overflow, explicit height negotiation, and Chrome/Firefox mobile-width layout tests.**Context notes:** Do not reintroduce sandbox planning unless user changes the threat model.## Phase 5: Telemetry Digest and Browser Lifecycle Errors**Outcome:** Browser behavior is summarized for the agent on the next prompt, and inactive/closed/disconnected clients produce actionable state.**Why now:** Telemetry needs stable stream item/widget ids and working prompt submission.**Scope:**- Track scroll dwell, clicks/taps, pointer summaries, focus/blur, inactive time, viewport/device class, selected text, widget actions, form abandon/submit, and error visibility.- Aggregate locally into capped digest; redact obvious secrets from selected text/input fields.- Show inspectable “telemetry digest will be sent” when non-empty.- Attach digest once to next accepted user prompt, then clear.- Detect visibility changes, pagehide, heartbeat loss, WebSocket close, stale clients, and browser crash/disconnect symptoms.- Render human-facing and agent-facing lifecycle errors with retry safety.**Out of scope:**- Multi-tab single-socket optimization.- Advanced analytics UI.- Rendering polish.**Key files/areas likely affected:**- `extensions/ui/telemetry.ts`: digest aggregation and redaction.- `extensions/ui/web/worker.js.ts`: off-hot-path tracking.- `extensions/ui/server.ts`: heartbeat/client state.- `extensions/ui/web/components/`: digest indicator and lifecycle stream errors.**Dependencies:**- Phase 4.**Verification:**- Automated: scroll/click/focus/pagehide aggregate; digest cap/redaction; digest attaches once; heartbeat timeout states; disconnect errors include action/fix/retryability.- Visual: scroll, click, select text, background tab, return, and see an inspectable digest indicator near the composer/status.- Visual: send next prompt and confirm digest appears in/with the prompt context once, then disappears.- Visual: close tab, disable phone Wi-Fi, and kill browser; confirm top strip/stream errors say exactly what happened and what to do.**Phase boundary health:** The UI remains functional if telemetry fails; errors are visible and actionable rather than silent.**Risks:**- Telemetry can feel creepy/noisy; mitigate with digest-only, inspectable, capped, prompt-gated behavior.- Browser close detection is best-effort; mitigate with heartbeat timeout as source of truth.**Context notes:** Keep raw telemetry out of agent context; only digest crosses on user prompt.## Phase 6: Nugu Polish, Diffs, Highlighting, and Performance**Outcome:** The UI reaches accepted visual direction and handles long streams/code/diffs without blocking.**Why now:** Polish and scale are safest after core behavior and event contracts stabilize.**Scope:**- Apply Nugu semantic theme with `prefers-color-scheme` dark/light.- Strengthen terminal-like web layout: no sidebars by default, dominant user anchors, tiny top/status strips, brutal minimal styling.- Integrate Pierre for diffs with collapsed summary, expanded file views, anchors, copied hunks, and annotations where needed.- Integrate Shiki lazy/cached highlighting with plain text immediate fallback.- Add truncation, lazy expansion, virtualization threshold, `content-visibility`, `requestAnimationFrame` batching, `MessageChannel` chunks, and worker parsing for high-volume streams.- Ensure responsive widget/container behavior on desktop and phone.**Out of scope:**- New feature semantics.- Multi-tab SharedWorker optimization unless required by measured pain.**Key files/areas likely affected:**- `extensions/ui/web/app.css.ts`: Nugu theme and layout.- `extensions/ui/web/components/`: diff, code, long output, stream virtualization.- `extensions/ui/web/worker.js.ts`: batching and parsing.- `extensions/ui/package.json`: Pierre/Shiki deps.**Dependencies:**- Phase 5.**Verification:**- Automated: dark/light variables emitted; stream roles render expected classes; long outputs truncate/expand; Shiki lazy upgrade does not block startup; virtualization preserves selection/expand state.- Visual: compare dark and light system themes and confirm Nugu semantics, dominant `YOU` messages, tiny status, and no useless side chrome.- Visual: render real edit diffs and code blocks; confirm plain text appears immediately, then upgrades to Pierre/Shiki without layout jump.- Visual: load a long tool-output stream and confirm scrolling, expansion, and selection remain smooth.- Visual: verify the same stream and widgets on phone width remain bounded and readable.**Phase boundary health:** Behavior should not change, only visual quality and scale; tests remain green against existing contracts.**Risks:**- Highlight/diff deps can slow startup; mitigate with lazy loading and immediate plaintext fallback.- Virtualization can break anchors/selection; mitigate with tests around selected item and replayed stream state.**Context notes:** Measure before adding more complexity; keep no-framework default.## Phase 7: Package Hardening, E2E, Manual Playbook**Outcome:** The extension is packaged, documented, and verified through automated and manual real-Pi/browser flows.**Why now:** Final hardening should validate the whole assembled system, not unstable intermediate APIs.**Scope:**- Finalize standalone package metadata, peer/dev deps, README, and no cross-extension imports.- Complete unit, harness, browser component, and E2E coverage around critical flows.- Harden shutdown cleanup: subprocess, server, sockets, timers, widgets, terminal restore.- Run and maintain manual testing playbook with real terminal, tmux, desktop browser, and phone.- Document known limitations: terminal minimization API limits, trusted full JS, LAN HTTP not encrypted, RPC unsupported semantics.**Out of scope:**- New UI features beyond spec.- Automatic RPC restart.- Old-browser support.**Key files/areas likely affected:**- `extensions/ui/package.json`: package and scripts.- `extensions/ui/README.md`: usage, security/trust, troubleshooting.- `extensions/ui/__tests__/`: full test suite.- Playwright/E2E test area chosen during detailed planning.- `docs/super/specs/2026-07-01-ui-extension-design.md`: only if implementation discovers spec corrections.**Dependencies:**- Phase 6.**Verification:**- Automated: full unit/harness/web/E2E suite passes; extension load has no side effects; session shutdown cleans all resources; critical flows pass with fake or real RPC tiers.- Visual: run manual playbook end-to-end and visually confirm startup, seeded history, Pi syntax, tool rendering, widgets, telemetry, lifecycle errors, mobile QR, shutdown/restore.- Visual: capture or record final dark/light desktop and phone checkpoints for future regression comparison.- Visual: intentionally trigger failure cases and confirm each visible error has human action, agent hint, retryability, and related ids/session/log path.**Phase boundary health:** This is the release boundary; project should be green, documented, and manually reproducible.**Risks:**- E2E flakiness from real subprocess/browser timing; mitigate with fake-RPC tier plus smaller real-RPC smoke tests.- Manual playbook drift; mitigate by keeping it tied to visible checkpoints from this roadmap.**Context notes:** Do not expand scope during hardening; file discovered enhancements as later specs.+8 / −11 text lines
**Outcome:** Diff-review and UI own consistent local E2E tasks, both suites run in Chromium and Firefox, and one root `e2e` command installs browsers once and dispatches discovered suites.**Outcome:** Diff-review owns a local E2E task, its suite runs in Chromium and Firefox, and one root `e2e` command installs browsers once and dispatches discovered suites.**Why now:** These are the existing Playwright suites and establish the minimal reusable task shape before adding coverage to untested browser servers.**Why now:** The existing Playwright suite establishes the minimal reusable task shape before adding coverage to untested browser servers.- Add local mise ownership for UI’s existing E2E suite.- Normalize both Playwright configurations to Chromium and Firefox projects.- Normalize its Playwright configuration to Chromium and Firefox projects.- Replace the public root `e2e-diff-review` and extension-specific browser installer with one aggregate root `e2e` workflow.- `extensions/ui/mise.toml`: local E2E task.- `extensions/ui/playwright.config.ts`: two-browser matrix.- Existing package scripts and Playwright dependencies: remove duplicate command ownership where safe.**Phase boundary health:** All existing browser suites gain one consistent manual aggregate while the release gate remains unchanged until complete coverage exists.**Phase boundary health:** The existing browser suite gains one consistent manual aggregate while the release gate remains unchanged until complete coverage exists.- Firefox may expose assumptions hidden by Chromium-only UI tests.- Firefox may expose assumptions hidden by Chromium-only tests.- Browser installation and executable selection differ across Windows, macOS, Linux, and CI, so Playwright defaults should replace OS-specific executable logic unless explicitly required.**Context notes:** Exercise the real extension and browser path; avoid mocks that reduce E2E to another unit test.deleted file mode 100644+0 / −958 text lines
# UI Extension DesignDate: 2026-07-01Status: Approved## GoalCreate a Pi extension named `ui`, activated with `/ui`, that opens a full web UI backed by a normal Pi RPC session. The terminal Pi session remains independent and usable. The web UI is a separate, persistent, fully fledged Pi session seeded from the terminal session branch.The web UI lets the agent communicate through rich visual surfaces: text, tools, forms, controls, prototypes, diagrams, images, annotations, and full HTML/CSS/JS widgets. It keeps normal Pi syntax and behavior: slash commands, skills, `@` file/image references, `!` bash, model/thinking controls, abort, expand/collapse, notifications, errors, status, and keybindings.## Non-goals- Do not replace Pi core.- Do not make the terminal and web sessions mirror each other live.- Do not make the web UI ephemeral by default.- Do not prevent parallel terminal/web use, even if both edit the same cwd.- Do not limit scope to a companion view; web UI must be a normal Pi frontend.## User decisions- Use RPC, not SDK in-process.- `/ui` minimizes the terminal Pi UI as much as extension APIs allow; `/ui off` restores it.- Web Pi session is independent and can run in parallel with terminal Pi.- Web session is persistent and normal.- Seed web session with full terminal active branch.- Seed via exact active-branch extraction where possible; whole-tree fork is allowed only if explicitly chosen.- Allow parallel edit races.- Mobile support uses LAN HTTP + random token.- Show QR code in terminal widget.- Agent-injected snippets may use full JS.- Full JS gets `window.pi` access by default.- Do not sandbox full-JS widgets; use visible attribution/audit and layout boundaries instead.- Include accepted mockup direction in this spec.- Theme must use Nugu semantics and respect system dark/light preference.- Prefer modern Chrome/Firefox APIs; no old-browser support.## Architecture```textterminal pi session └─ /ui command ├─ extract active terminal branch into new persistent session ├─ spawn `pi --mode rpc --session <seeded-session>` subprocess ├─ start LAN HTTP/WebSocket server with random token ├─ show terminal widget: OSC link, QR, ESC cancel, /ui off help └─ keep terminal session independentbrowser ├─ GET snapshot ├─ WebSocket event stream ├─ Pi-capable composer ├─ central stream renderer ├─ full-JS visual widgets └─ telemetry digest sent on next user message```### Runtime model`/ui` starts one web runtime per terminal Pi session unless an existing runtime is already active. The runtime contains:- local HTTP server bound for LAN access,- token-authenticated browser app,- WebSocket event channel,- spawned Pi RPC subprocess,- active-branch persistent session file,- in-memory event store and replay buffer,- telemetry aggregator,- terminal TUI minimizer state.`/ui off` stops the server, closes WebSocket clients, terminates the RPC subprocess, clears the terminal widget, restores footer/header/editor/working visibility where changed, and reports the saved web session path.### Terminal UI while activeThe terminal Pi UI is reduced to one custom widget as much as extension APIs permit. The widget shows:- clickable OSC 8 link,- QR code for mobile,- host/port,- session id/name,- “press ESC to cancel UI mode”,- “run `/ui off` to restore terminal UI”,- connection state: waiting, connected, inactive, disconnected, RPC dead.ESC in terminal while UI mode is active calls the same shutdown path as `/ui off`.## Session seedingUse Pi `SessionManager` APIs rather than ad-hoc JSON rewriting.Preferred exact active-branch path:```textsource = terminal ctx.sessionManager.getSessionFile()leaf = terminal ctx.sessionManager.getLeafId()seededPath = terminal ctx.sessionManager.createBranchedSession(leaf)spawn pi --mode rpc --session seededPath```Prototype result: `SessionManager.forkFrom(source, cwd)` copies the whole session tree into the new file. That keeps LLM context clean because the active branch path is clean, but it also brings abandoned branches into `/tree`, increases history size, and may expose old branch history. Therefore use `createBranchedSession(leaf)` for the default exact active-branch seed. Whole-tree `forkFrom` is acceptable only behind an explicit option or fallback with visible warning.The seeded session must preserve the full active branch: user messages, assistant messages, thinking blocks, tool calls, tool results, bash execution messages, custom messages, compaction summaries, model changes, thinking-level changes, and relevant branch summaries.The web session header records the terminal session as parent. The web session gets a clear display name such as `ui: <terminal session name or cwd>`.If the terminal session is ephemeral or has no session file, create a normal persistent web session and seed by appending the active branch messages through `SessionManager` APIs. If exact branch copy is impossible, fail with an actionable terminal error.## RPC subprocessThe web runtime spawns Pi in RPC mode with normal extension/skill/settings discovery enabled.Requirements:- do not pass `--no-extension`, `--no-skills`, or `--no-session`,- pass the seeded active-branch session via `--session`,- inherit cwd,- inherit normal environment,- parse stdout strictly as JSONL split on LF only,- capture stderr separately for diagnostics,- restart only by explicit user action, not automatically,- expose RPC startup, slow startup, and death as stream/terminal states with fix instructions.Prototype result: a normal RPC subprocess with full extensions can take longer than 8 seconds to answer first state requests. The browser and terminal widget must show an explicit “starting RPC” state instead of appearing frozen.RPC commands used by the web UI:- `prompt`, `steer`, `follow_up`, `abort`,- `get_state`, `get_messages`, `get_commands`, `get_session_stats`,- `set_model`, `cycle_model`, `set_thinking_level`, `cycle_thinking_level`,- `compact`, `new_session`, `switch_session`, `fork`, `clone`,- `bash`, `abort_bash`,- `export_html`, `set_session_name`.RPC extension UI requests are rendered as normal stream items or dialogs:- `select`, `confirm`, `input`, `editor`,- `notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`.## Web transport### Binding and authUse LAN HTTP with random token.- Bind to `0.0.0.0` or selected LAN interface.- Prefer a stable port if configured; otherwise port `0`.- Generate a 32-byte base64url token.- URL format: `http://<lan-ip>:<port>/?token=<token>`.- First HTML load requires query token and sets a `SameSite=Strict` cookie.- API and WebSocket require `Authorization: Bearer <token>` or auth cookie.- Never log the token except inside the terminal widget link/QR.- Restrict CORS to same origin.This follows the diff-review token pattern, but changes binding from `127.0.0.1` to LAN for mobile.### Browser lifecycle awarenessThe extension must quickly learn:- page close,- tab inactive,- browser crash,- network disconnect,- WebSocket close,- stale client heartbeat.Mechanisms:- browser sends heartbeat every few seconds while visible,- server marks client inactive on missed heartbeats,- browser sends `visibilitychange` events,- browser uses `pagehide` and `navigator.sendBeacon()` or `fetch(..., { keepalive: true })` for best-effort close notice,- server times out missing clients,- RPC continues unless `/ui off` or explicit stop occurs.Human-facing connection errors must say exactly what happened and what to do. Agent-facing errors must include fix instructions, likely cause, and whether retry is safe.## Event and data flow```textRPC stdout JSONL -> server parser -> typed event bus -> ordered event store -> replay ring buffer -> browser WebSocket -> worker parse/batch -> main-thread render store -> stream componentsbrowser input -> command builder -> server auth -> RPC stdin queue -> RPC prompt/steer/follow_up/etc.```### Event modelEvery server-side event sent to browsers has:- `seq`: monotonically increasing number,- `time`: server timestamp,- `source`: `rpc | ui | telemetry | server`,- `type`: stable string,- `payload`: JSON payload,- optional `rpcId`, `messageId`, `toolCallId`, `entryId`, `widgetId`.Browsers request a snapshot first, then subscribe from the latest `seq`. Reconnect uses `?since=<seq>`. If replay buffer no longer contains `since`, server sends a fresh snapshot.### QueuesServer queues:- one RPC stdin command queue to serialize writes and correlate responses,- one RPC stdout event queue from JSONL parser,- one browser replay ring buffer,- one telemetry digest queue per browser/client,- one visual-widget event queue per widget id.Browser queues:- Worker receives WebSocket messages,- Worker parses and batches events,- main thread applies batches on `requestAnimationFrame`,- high-volume token/tool updates coalesce by message/tool id,- telemetry events aggregate off the hot render path.Do not depend on `scheduler.postTask`; support is limited. Use `requestAnimationFrame`, `MessageChannel`, and normal microtasks.## Web UI shellThe shell is deterministic, stream-first, brutal, minimal, and Nugu-themed.Layout:- tiny top strip: Pi mark, running/disconnected state, `/ui off`,- central stream: all important things appear here,- bottom status strip: model, thinking, context,- bottom composer: normal Pi input syntax.No permanent sidebars by default. Contextual inspectors may appear only when a message/tool/widget is selected.### Stream item typesThe central stream renders:- user messages,- assistant text/thinking,- tool call/update/result,- visual widgets,- extension UI dialogs,- notifications,- warnings/errors,- permission prompts,- compaction/retry/status events,- telemetry digest when it will affect the next user prompt.User messages must visually dominate as primary anchors: strong border, high contrast, distinct spacing, and clear “YOU” label.Tool and visual blocks support selected-item expand/collapse. Keyboard shortcut behavior should match terminal Pi where possible, especially Esc abort, Ctrl+O expand/collapse selected, Ctrl+P model cycling, and slash command flow.### ComposerThe composer must preserve Pi syntax and expectations:- `/` commands and command autocomplete,- `/skill:*` skill invocation,- prompt templates,- `@` file/image references,- `!` and `!!` bash behavior where RPC supports it or equivalent web command flow,- Enter to submit,- Shift+Enter newline,- Esc abort when running,- paste handling,- image/file attachment.The composer should not have redundant buttons for actions that are better done by keybind or command. Buttons may exist only where mobile needs tap targets, and they must not clutter desktop.### StatusPersistent status is intentionally tiny:- selected model,- thinking level,- context usage.Everything else appears where it matters:- notifications/warnings/errors in stream,- permission prompts in stream/dialog,- queued prompts near composer only when non-empty and understandable,- widget expand/collapse on the widget itself,- connection state in top strip and stream error when broken.## Accepted mockupThe accepted direction is “terminal-like web”: pure stream plus Pi-capable composer, with Nugu/system-theme refinements.Key review notes incorporated:- messages, tools, and visuals all live in the main middle stream,- user messages must stand out strongly,- avoid useless side chrome and implementation detail labels,- status belongs near the composer and must be meaningful,- normal Pi syntax must work exactly as expected,- redundant buttons should be removed on desktop,- use Nugu and system theme,- use modern CSS so agent HTML still flows inside deterministic layout,- use Pierre/Shiki for beautiful diffs/highlighting,- browser close/inactive/crash errors must be detected and actionable.Representative mockup fragment:```html<style>.nugu-ui { --bg: #070706; --panel: #11100d; --text: #f3efe5; --muted: #9d9486; --accent: #ff6a2a; --minor: #2a2722; --warn: #ffd35a; --focus: #fff; font: 14px ui-monospace, SFMono-Regular, Menlo, monospace; background: var(--bg); color: var(--text); border: 4px solid var(--focus); min-height: 580px; display: grid; grid-template-rows: 34px minmax(0, 1fr) 128px;}@media (prefers-color-scheme: light) { .nugu-ui { --bg: #f8f5ee; --panel: #eee7d8; --text: #17140f; --muted: #70695f; --accent: #b84722; --minor: #d8cfc0; --warn: #9c6a00; --focus: #111; }}.nugu-ui .top { display: flex; align-items: center; justify-content: space-between; border-bottom: 3px solid var(--minor); padding: 0 12px; background: var(--panel); color: var(--muted);}.nugu-ui .stream { max-width: 960px; margin: auto;}.nugu-ui .row { display: grid; grid-template-columns: 92px minmax(0, 1fr); gap: 14px; margin: 0 0 14px;}.nugu-ui .who { color: var(--muted); text-align: right; padding-top: 12px; font-weight: 1000;}.nugu-ui .bubble { border: 3px solid var(--minor); background: var(--panel); padding: 13px; min-width: 0;}.nugu-ui .user { border: 5px solid var(--focus); background: var(--focus); color: var(--bg); box-shadow: 8px 8px 0 var(--accent); font-size: 17px; font-weight: 900;}.nugu-ui .visual { border: 4px solid var(--accent); background: var(--panel); color: var(--text); box-shadow: 8px 8px 0 var(--focus); padding: 18px; container-type: inline-size; overflow: auto; contain: layout paint;}.nugu-ui .bottom { border-top: 4px solid var(--focus); background: var(--panel);}.nugu-ui .status { display: flex; align-items: center; justify-content: space-between; padding: 7px 12px; border-bottom: 2px solid var(--minor); color: var(--muted);}.nugu-ui .editor { border: 4px solid var(--focus); background: var(--bg); min-height: 58px; padding: 10px; color: var(--text); box-shadow: 6px 6px 0 var(--minor);}</style><div class="nugu-ui"> <div class="top"> <div class="brand">π</div> <div>running</div> <div>/ui off</div> </div> <main class="mid"> <div class="stream"> <div class="row"> <div class="who">YOU</div> <div class="bubble user">I want Nugu, modern web, all Pi syntax.</div> </div> <div class="row"> <div class="who">TOOL</div> <div class="bubble">Pierre diff / Shiki code block</div> </div> <div class="row"> <div class="who">VISUAL</div> <div class="visual">Constrained full-JS widget</div> </div> </div> </main> <div class="bottom"> <div class="status"> <div><strong>sonnet</strong> · medium · ctx 31%</div> <div>Esc abort · Ctrl+O expand · Ctrl+P model · / · @ · !</div> </div> <div class="composer"><div class="editor">Message Pi…</div></div> </div></div>```## Visual widget systemAgents get UI tools injected into the web RPC session. Tool names are implementation detail, but tool families are:- visual message/card,- structured data/table,- diagram,- form/control,- mockup/prototype,- raw HTML/CSS/JS widget,- update/patch existing widget,- wait for widget user action.Every visual has:- stable `widgetId`,- title/label,- fallback text for agent context and terminal export,- expand/collapse state,- lifecycle: mounted, updated, action, closed, errored,- whether it expects user response,- telemetry summary scope.### Full JS policyFull JS widgets are allowed by default. They receive `window.pi` inside their execution context.`window.pi` exposes controlled methods:- send a widget action/result,- request agent prompt/steer/follow-up,- read current widget state,- subscribe to widget-scoped events,- update the widget payload,- show a local notification,- request file/image attachment through host UI.Full-JS widgets are trusted agent output, not untrusted third-party apps. They may impersonate user-like actions through `window.pi` and may use browser/network capabilities available to the page. The UI must make this trust boundary visible:- visual blocks show “full JS / trusted” in expanded metadata,- widget errors identify widget id and tool call id,- all widget-originated prompts/actions are visibly attributed in stream,- `window.pi` calls are audited in details available to the agent.### Layout constraints for agent HTMLAgent HTML must flow inside deterministic stream layout.- Mount each widget in a bounded visual block.- Do not use iframe sandboxing or a separate permission wall for full JS.- Use `iframe srcdoc`, Shadow DOM, or equivalent document/layout boundary only to keep CSS, layout, and lifecycle contained.- Prototype result: unsandboxed `iframe srcdoc` can call parent `window.pi` in system Chrome and Playwright Firefox.- Prototype result: a host-bounded iframe with intentionally over-wide/tall content can fit the stream on a 390px mobile viewport in system Chrome and Playwright Firefox when the host applies `width: 100%`, overflow containment, and capped height negotiation.- Container gets fixed stream width, `max-width: 100%`, overflow boundary, and resize observer.- Host applies a minimal reset and Nugu CSS variables.- Widget document receives theme variables and container dimensions.- Use CSS containment: `contain: layout paint`, `content-visibility` where safe.- Use container queries for responsive widget internals.- Widget cannot resize the whole page except through explicit host height negotiation.## Diffs and code highlightingUse modern high-quality rendering:- Pierre for file diffs, preferably SSR/preload where possible.- Shiki for code highlighting, lazy and cached.- Show plain text immediately for long code, then upgrade async.- Never block startup on Shiki cold init.- Large tool/code outputs use truncation, lazy expansion, and virtualized rendering.- Diffs must support collapsed summary, expanded file-level view, line anchors, copied hunks, and annotations where needed.## TelemetryThe browser tracks user behavior transparently and summarizes it for the agent on the next user message.Tracked classes:- scroll position and scroll dwell by stream item,- click/tap positions and target ids,- pointer movement summaries,- focused/blurred tab time,- inactive time,- viewport size and device class,- selected text,- widget action events,- form dwell/abandon/submit,- error visibility and whether user saw it.Rules:- collect locally in browser/worker,- aggregate into digest, not raw spam,- show “telemetry digest will be sent” when non-empty,- attach digest to next user prompt as hidden or visible context according to implementation choice, but it must be inspectable by user,- cap digest size,- redact obvious secrets from selected text and input fields,- do not send telemetry while no user prompt is sent,- clear sent digest after successful prompt acceptance.Example digest:```textUI telemetry since last message:- Viewed visual widget visual-42 for 18s.- Clicked Approve in visual-42.- Scrolled bash tool result tool-17 to bottom.- Tab inactive for 4m12s.- Form requirements-form abandoned after editing field “scope”.```## Error modelErrors are first-class stream items and must be actionable.Every error has:- `code`,- severity,- human title,- precise human description,- human action,- agent hint,- source component,- retryability,- related ids/session path/log path.Human error example:```textBrowser disconnectedNo heartbeat from Chrome for 12s. The RPC session is still running.Action: reload the QR/link page, or run /ui off to stop it.```Agent error example:```textui_widget_render_failedWidget visual-42 threw ReferenceError: foo is not defined.Fix: call ui_update_widget with corrected JS, or replace widget with fallback HTML.```Error categories:- server bind failure,- no LAN address,- QR generation failure,- RPC spawn failure,- RPC JSON parse failure,- RPC process exit,- WebSocket disconnect,- browser inactive/closed/crashed,- auth failure,- widget render/runtime failure,- telemetry send failure,- session fork failure,- unsupported terminal OSC.## Performance architectureBrowser target: current Chrome and Firefox only.Use:- normal WebSocket, not `WebSocketStream` because it is experimental/nonstandard,- HTTP snapshot + WebSocket events,- Dedicated Worker for WS parsing and telemetry aggregation,- optional SharedWorker later for multi-tab single-socket behavior,- native `EventTarget` as in-page event bus,- `BroadcastChannel` for same-browser tab coordination,- Web Locks only if multi-tab write coordination becomes necessary,- Web Components for message/tool/visual cards,- no framework by default,- CSS Grid/Flex, container queries, CSS containment,- `content-visibility: auto` for long stream items,- virtualization after a configurable item threshold,- `requestAnimationFrame` batching for DOM updates,- `MessageChannel` for cooperative chunks,- `OffscreenCanvas` only for heavy canvas widgets/diagrams.Avoid:- React/Vue/Angular,- old-browser polyfills,- `scheduler.postTask` as required dependency,- WebSocketStream,- main-thread JSON parsing for high-volume streams,- unbounded DOM growth,- layout measurement loops.## Package structure```textextensions/ui/ package.json index.ts server.ts rpc.ts session-seed.ts terminal-widget.ts qr.ts protocol.ts errors.ts telemetry.ts visual-tools.ts web/ index.html.ts app.css.ts app.js.ts worker.js.ts components/*.ts __tests__/ harness.test.ts server.test.ts rpc.test.ts telemetry.test.ts e2e.test.ts README.md```Extension package requirements:- standalone package,- peer-depend on `@earendil-works/pi-coding-agent`,- dev-depend on `@marcfargas/pi-test-harness`,- include harness test,- no imports from other `@bugabinga/pi-ext-*` extensions,- startup fast: no blocking network, subprocess, or FS scans during `session_start`.Runtime startup work happens in `/ui` command, not extension load.## Commands### `/ui`Start UI mode. If already active, show current link/QR/status.Optional future args:- `--host <ip|0.0.0.0>`- `--port <port>`- `--local`- `--no-open`- `--no-qr`- `--session <path>`Argument autocomplete is required if subcommands/options are implemented.### `/ui off`Stop UI mode and restore terminal UI.### `/ui status`Show server URL, browser count, RPC status, web session path, last error.### `/ui open`Open browser again using desktop opener.### `/ui qr`Re-render QR/link widget.## Testing strategy### Unit testsServer/auth:- token required for `/`, APIs, and WebSocket,- query token sets cookie,- Bearer auth works,- bad token gets 401,- LAN URL generation chooses expected address,- body size limits,- CORS same-origin only.RPC bridge:- JSONL parser splits LF only,- parse errors become actionable events,- command ids correlate with responses,- stdin command queue serializes writes,- stdout events keep order,- subprocess exit generates typed error,- stderr is captured without leaking token.Session seed:- `createBranchedSession(getLeafId())` selected when source session file exists,- exact active branch preserved,- whole-tree `forkFrom` fallback warns that abandoned branches are included,- parent session recorded,- display name set,- ephemeral source fallback behaves as specified,- failure gives actionable error.Event store:- monotonic sequence,- snapshot includes current state,- replay after reconnect,- replay miss triggers snapshot,- high-volume updates coalesce correctly.Telemetry:- scroll/click/focus/pagehide events aggregate,- digest size cap,- digest redaction,- digest attaches once to next prompt,- inactive/browser closed states detected.Visual tools:- widget ids stable,- fallback text returned to agent,- full-JS widget mount event emitted,- widget action flows to agent/web stream,- widget runtime error creates human+agent actionable error.Theme/rendering:- Nugu dark/light variables emitted,- `prefers-color-scheme` works,- stream item classes render expected roles,- user message has dominant styling.### Pi extension harness testsUse the real Pi extension runtime.- extension loads without side effects,- `/ui` command registers,- `/ui off/status/open/qr` commands register,- `/ui` starts runtime from command, not `session_start`,- terminal widget appears,- `/ui off` clears widget and restores UI state,- duplicate `/ui` is idempotent,- session_shutdown cleans subprocess/server/timers,- ESC terminal input cancels UI mode,- visual tools register only for the web RPC session as designed.### Web unit/component testsUse browser-capable tests where possible.- WebSocket worker batches events,- components render message/tool/visual/error/notice rows,- selected item expand/collapse,- keyboard shortcuts dispatch expected commands,- composer handles Enter/Shift+Enter/Esc,- command autocomplete renders slash commands and skills,- `@` references and `!` bash parsing match Pi expectations,- mobile layout hides nothing essential,- iframe widget bridge exposes `window.pi`,- iframe widget layout does not create page-level horizontal overflow in Chrome or Firefox,- widget height negotiation stays bounded.### E2E testsUse Playwright with real server and fake or real RPC subprocess depending on test tier.Critical flows:- run `/ui`, obtain URL/token, open browser,- QR URL and link route to same authenticated page,- initial snapshot shows exact active-branch seeded session history,- send prompt from web, observe RPC events stream,- invoke slash command,- invoke `/skill:*`,- test command autocomplete,- attach `@` file/image reference,- run `!` bash equivalent,- model cycle via Ctrl+P,- expand/collapse via Ctrl+O,- abort via Esc,- tool call start/update/end renders,- visual full-JS widget mounts and sends action,- telemetry digest appears and is attached to next prompt,- tab inactive/active changes state,- close tab triggers heartbeat lost,- kill RPC subprocess shows actionable error,- kill/restart browser reconnects through snapshot/replay,- `/ui off` disconnects browser and restores terminal UI.## Manual testing playbookRun this in a real terminal with tmux and a real browser, not only automated tests.### Setup1. Open tmux session.2. Start real `pi` in `C:/Users/okr/Workspace/dotfiles/pi-ext`.3. Confirm repo has visible session history.4. Run `/ui`.5. Verify terminal becomes minimal widget with OSC link, QR, ESC help, `/ui off` help, connection state.6. Open desktop browser link.7. Scan QR from phone on same LAN.### Startup/session- Verify web loads with token.- Verify bad/missing token gets precise 401 page.- Verify web session is a persistent normal Pi session.- Verify web session history is seeded from the terminal active branch.- Verify terminal and web sessions can both receive prompts independently.- Verify web session appears in Pi session list with clear name and parent link.### Pi syntax/composer- Type normal prompt, verify response.- Use `/` autocomplete.- Invoke a prompt template command.- Invoke `/skill:<name>`.- Use `@` file reference.- Attach image/file if available.- Run `!pwd` or equivalent user bash.- Verify `!!` exclude-from-context behavior if supported.- Paste multi-line text.- Use Shift+Enter newline and Enter send.### Keybindings/status- Esc aborts running agent.- Ctrl+P cycles model.- Change thinking level if key/command is available.- Ctrl+O expands/collapses selected tool/visual block.- Verify status shows model, thinking, context usage.- Verify warnings/errors/notifications appear as stream items.- Verify permission/confirm/select/input/editor extension UI requests are usable.### Tools and stream- Ask agent to run `bash`, `read`, `grep`, `find`, `ls`, `edit` on safe files.- Verify tool start/update/end render live.- Verify long tool output is collapsed and expandable.- Verify edit diffs render beautifully with Pierre.- Verify code blocks highlight with Shiki after lazy upgrade.- Verify compaction/retry events display clearly.### Visual widgets- Ask agent to create a visual card.- Ask for a form with controls.- Ask for a diagram/prototype/mockup.- Ask for full HTML/CSS/JS interactive widget.- Click widget buttons and verify actions reach agent/stream.- Verify widget can update itself through `window.pi`.- Intentionally create widget JS error and verify human+agent error guidance.- Verify widget remains bounded and responsive on desktop and phone.### Telemetry- Scroll stream and tool output.- Click visual widget.- Select text.- Leave tab inactive for at least 30 seconds.- Return and send next prompt.- Verify telemetry digest is shown/inspectable and attached once.- Verify digest does not include obvious secret-like input.### Browser/mobile lifecycle- Close browser tab; terminal/web status should detect close/heartbeat loss.- Reopen link; snapshot/replay restores state.- Put phone browser in background; inactive state detected.- Disable phone Wi-Fi briefly; disconnect is clear and recoverable.- Kill browser process; server detects stale heartbeat.### Failure handling- Start `/ui` when preferred port is busy.- Start `/ui` with no LAN address if possible.- Kill RPC subprocess.- Break WebSocket auth token.- Force malformed RPC line in fake/dev mode if available.- Verify every failure gives exact action for human and fix hint for agent.### Shutdown/restore- Run `/ui status`.- Run `/ui qr`.- Run `/ui open`.- Press ESC in terminal widget.- Start again, then run `/ui off`.- Verify server stops, browser disconnects, RPC exits, terminal UI restores, and web session persists.## Open implementation risks- Extension APIs cannot truly replace the whole terminal UI; design intentionally minimizes terminal UI instead.- Exact active-branch seeding should use `createBranchedSession(getLeafId())`; `forkFrom` copies the whole tree and should not be the default.- RPC mode does not support some interactive-only UI methods; web must emulate or degrade.- `!`/`!!` exact terminal semantics may need explicit web-side mapping to RPC `bash`.- Full JS widgets are powerful and risky; attribution/audit is mandatory.- Mobile LAN HTTP is token-protected but not encrypted.## Planning recommendationThis is large enough for a phased roadmap, not a single implementation plan.Suggested phases:1. Extension command + terminal widget + LAN auth server + QR.2. Active-branch RPC subprocess + event bridge + basic web stream/composer.3. Pi syntax, commands, skills, keybindings, status, extension UI protocol.4. Visual tools and full-JS widget bridge.5. Telemetry digest and lifecycle detection.6. Nugu polish, Pierre/Shiki rendering, virtualization/perf.7. Complete tests and manual playbook hardening.deleted file mode 100644+0 / −77 text lines
# uiBrowser UI runtime shell for Pi.## Install / loadLoaded through the root [pi-ext](../../README.md) package.## Commands- `/ui` — start LAN web shell, token URL, QR, terminal widget, seeded RPC session.- `/ui off` — stop server/RPC and restore terminal widget state.- `/ui status` — show runtime URL, clients, state, and last error.- `/ui open` — open current URL in desktop browser.- `/ui qr` — redraw QR/link widget.## Behavior`/ui` starts a token-authenticated LAN browser UI backed by a seeded Pi RPC session.The browser stream supports normal prompts, slash commands, bash shorthands, extension UI requests, trusted visual widgets, telemetry digest attachment, lifecycle errors, lazy code/diff rendering, and Nugu brutal/minimal styling.## Security and trust modelTransport is HTTP on LAN with a random bearer token in the URL/cookie.There is no HTTPS.Treat the URL as secret.The browser UI is for trusted local/LAN use only.Agent-created visual widgets are trusted full HTML/CSS/JS.They are not sandboxed.Widget actions are audited and visibly attributed before widget-originated prompts reach the Pi session.## E2ERun root `mise run e2e` first to install browsers and execute every extension suite.After that bootstrap, run `mise run e2e` here, or `mise //extensions/ui:e2e` from the repository root, to test only the browser UI in Chromium and Firefox.The real Pi RPC smoke remains opt-in through `UI_REAL_RPC_SMOKE=1`.## Manual smokeOn win32, use zellij, never tmux:```shnode extensions/ui/scripts/zellij-smoke.mjs```On non-win32, use tmux where available:```shnode extensions/ui/scripts/tmux-smoke.mjs```Full checkpoints live in [docs/manual-playbook.md](docs/manual-playbook.md).## Mockup parity auditThe accepted mockup was treated as visual direction, not a finished parity checklist.That was wrong for user expectations.Implemented now: stream-first shell, Nugu theme, sticky bottom composer, token auth, RPC stream, command input, dialogs, trusted widgets, code/diff rendering, telemetry digest, and no sidebars.Still incomplete versus the representative mockup/spec: richer top strip with Pi mark and `/ui off`, meaningful bottom status strip for model/thinking/context, stronger `YOU` labels, selected-item inspector, clearer tool lifecycle cards, and polished mobile status/actions.Track these as UI polish/parity work, not transport/runtime work.## Troubleshooting- `401` means the token is missing or stale; reopen `/ui` or rescan QR.- Browser says disconnected: run `/ui status`, then `/ui open` or restart with `/ui off` and `/ui`.- RPC unavailable: verify `pi` is on `PATH` and the seeded session can start in the current repo.- Browser features target modern Chrome/Firefox only.- Parallel terminal/browser edits are allowed and can race.## Package invariants- Private package.- `main` is `index.ts`.- MIT license.- Pi packages are peer dependencies.- Tests use Vitest, Pi harness, and Playwright E2E.deleted file mode 100644+0 / −100 text lines
import { expect, test } from "@playwright/test";import { EventStore } from "../events";import { startUiServer, type UiServer } from "../server";let server: UiServer | undefined;test.afterEach(async () => { await server?.close("e2e cleanup"); server = undefined;});test("auth shell, stream, composer, widget, telemetry, and shutdown", async ({ page, request,}) => { const pageErrors: string[] = []; page.on("pageerror", (error) => pageErrors.push(error.message)); const events = new EventStore(); events.append({ type: "message", role: "assistant", text: "ready" }); for (let index = 0; index < 80; index += 1) { events.append({ type: "message", role: "assistant", text: `history line ${index}`, }); } events.append({ type: "widget_mount", widgetId: "widget-e2e", toolCallId: "call-e2e", title: "Widget", fallback: "Widget fallback", html: "<button onclick=\"window.pi.action('clicked')\">click</button>", status: "mounted", }); server = await startUiServer({ address: "127.0.0.1", events, commands: [{ name: "ui", description: "Browser UI" }], onBrowserMessage(message) { if (isPrompt(message)) { const event = events.append({ type: "message", role: "assistant", text: `echo ${message.text}`, }); server?.publish(event); } if (isTelemetry(message)) { const event = events.append({ type: "log", level: "info", message: "browser digest will be sent", }); server?.publish(event); } }, }); const unauthorized = await request.get(server.baseUrl + "/api/status"); expect(unauthorized.status()).toBe(401); await page.goto(server.publicUrl); await expect(page.locator("#ui-progress")).toHaveText( /starting|connected|waiting|rpc/, ); if (pageErrors.length) throw new Error(pageErrors.join("\n")); await expect(page.locator("#ui-stream")).toContainText("ready"); await expect(page.locator("#ui-stream")).toContainText("history line 79"); await expect(page.locator("#ui-stream")).toContainText("Widget fallback"); await expect(page.locator("#ui-composer")).toBeInViewport(); expect( await page.evaluate( () => document.documentElement.scrollHeight <= window.innerHeight, ), ).toBe(true); await page.locator("#ui-input").fill("hello e2e"); await page.locator("#ui-send").click(); await expect(page.locator("#ui-stream")).toContainText("echo hello e2e"); await page.evaluate(() => scrollTo(0, 50)); await page.waitForTimeout(1_100); await expect(page.locator("#ui-digest")).toContainText(/digest/);});function isPrompt(value: unknown): value is { type: "prompt"; text: string } { return ( !!value && typeof value === "object" && (value as { type?: unknown }).type === "prompt" );}function isTelemetry(value: unknown): value is { type: "telemetry_batch" } { return ( !!value && typeof value === "object" && (value as { type?: unknown }).type === "telemetry_batch" );}deleted file mode 100644+0 / −14 text lines
import { spawnSync } from "node:child_process";import { expect, test } from "@playwright/test";test("real Pi RPC smoke prerequisites", async () => { test.skip( process.env.UI_REAL_RPC_SMOKE !== "1", "Set UI_REAL_RPC_SMOKE=1 to run the real Pi RPC/browser smoke tier.", ); const pi = process.platform === "win32" ? "pi.cmd" : "pi"; const probe = spawnSync(pi, ["--version"], { encoding: "utf8" }); const error = probe.error as NodeJS.ErrnoException | undefined; test.skip(error?.code === "ENOENT", "pi CLI is unavailable on PATH."); expect(probe.status).toBe(0);});deleted file mode 100644+0 / −87 text lines
import path from "node:path";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";import { createTestSession, type TestSession } from "../../../test/harness";import { createUiRuntime, type UiRuntime } from "../runtime";const runtimes: Array<{ stop(reason: string): Promise<void> }> = [];let t: TestSession | undefined;describe("ui cleanup", () => { afterEach(async () => { while (runtimes.length) await runtimes.pop()?.stop("test cleanup"); t?.dispose(); t = undefined; }); it("stops runtime idempotently after socket close", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: cleanup", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath), }); runtimes.push(runtime); const socket = await connectRuntimeSocket(runtime); socket.close(); await new Promise((resolve) => setTimeout(resolve, 20)); await runtime.stop("first"); await runtime.stop("second"); expect(runtime.status().active).toBe(false); expect(sent).toContainEqual({ type: "close", reason: "first" }); }); it("/ui off removes terminal widget even when inactive", async () => { const extensionPath = path.resolve(import.meta.dirname, "../index.ts"); t = await createTestSession({ extensions: [extensionPath] }); const command = t.session.extensionRunner.extensions[0].commands.get("ui"); expect(command).toBeDefined(); await command?.handler( "off", t.session.extensionRunner.createCommandContext(), ); expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([ "ui", undefined, ]); });});async function connectRuntimeSocket(runtime: UiRuntime): Promise<WebSocket> { const url = new URL(runtime.status().url ?? ""); const response = await fetch(url); const cookie = response.headers.get("set-cookie") ?? ""; const socketUrl = new URL("/ws", url); socketUrl.protocol = "ws:"; const socket = new WebSocket(socketUrl, { headers: { cookie } }); await new Promise((resolve) => socket.once("open", resolve)); return socket;}function fakeSessionManager() { return { getLeafId: () => "leaf", createBranchedSession: () => ({ path: "C:/repo/.pi/sessions/ui.json" }), };}function fakeRpc(sent: unknown[], sessionPath: string) { return { state: () => "connected", sessionPath, send(request: unknown) { sent.push(request); return Promise.resolve({ type: "response", success: true }); }, close(reason: string) { sent.push({ type: "close", reason }); return Promise.resolve(); }, };}deleted file mode 100644+0 / −84 text lines
import { describe, expect, it } from "vitest";import { abortCurrent, compactSession, cycleModel, cycleThinking, runBash, runSlashCommand, sendPrompt,} from "../command-adapter";describe("ui rpc command adapters", () => { it("sends normal prompts", async () => { const rpc = fakeRpc(); await sendPrompt(rpc, "hello"); expect(rpc.sent).toEqual([{ type: "prompt", message: "hello" }]); }); it("attaches digest once to the next prompt", async () => { const rpc = fakeRpc(); let digest = "Browser digest:\n- click SEND"; await sendPrompt(rpc, "hello", { digest: () => digest, clearDigest: () => { digest = ""; }, }); await sendPrompt(rpc, "again", { digest: () => digest, clearDigest: () => { digest = ""; }, }); expect(rpc.sent).toEqual([ { type: "prompt", message: "Browser digest:\n- click SEND\n\nUser prompt:\nhello", }, { type: "prompt", message: "again" }, ]); }); it("runs slash commands through prompt expansion", async () => { const rpc = fakeRpc(); await runSlashCommand(rpc, "mode", "terse"); expect(rpc.sent).toEqual([{ type: "prompt", message: "/mode terse" }]); }); it("runs bash and preserves context exclusion", async () => { const rpc = fakeRpc(); await runBash(rpc, "git status", true); expect(rpc.sent).toEqual([ { type: "bash", command: "git status", excludeFromContext: true }, ]); }); it("cycles model and thinking", async () => { const rpc = fakeRpc(); await cycleModel(rpc); await cycleThinking(rpc); expect(rpc.sent).toEqual([ { type: "cycle_model" }, { type: "cycle_thinking_level" }, ]); }); it("compacts and aborts", async () => { const rpc = fakeRpc(); await compactSession(rpc); await abortCurrent(rpc); expect(rpc.sent).toEqual([{ type: "compact" }, { type: "abort" }]); });});function fakeRpc() { const sent: unknown[] = []; return { sent, send(request: unknown) { sent.push(request); return Promise.resolve({ type: "response", success: true }); }, };}deleted file mode 100644+0 / −60 text lines
import { describe, expect, it } from "vitest";import { parseComposerInput } from "../composer";describe("ui composer parser", () => { it("parses plain prompts", () => { expect(parseComposerInput("hello pi")).toEqual({ kind: "prompt", text: "hello pi", refs: [], }); }); it("parses slash commands and arguments", () => { expect(parseComposerInput("/mode terse now")).toEqual({ kind: "slash", command: "mode", args: "terse now", text: "/mode terse now", refs: [], }); }); it("parses skill commands", () => { expect(parseComposerInput("/skill:brutal make it short")).toEqual({ kind: "slash", command: "skill:brutal", args: "make it short", text: "/skill:brutal make it short", refs: [], }); }); it("extracts at-references from prompts", () => { expect( parseComposerInput("read @README.md and @docs/spec.md please"), ).toEqual({ kind: "prompt", text: "read @README.md and @docs/spec.md please", refs: ["README.md", "docs/spec.md"], }); }); it("parses single-bang bash", () => { expect(parseComposerInput("!git status --short")).toEqual({ kind: "bash", command: "git status --short", excludeFromContext: false, refs: [], }); }); it("parses double-bang bash as excluded from context", () => { expect(parseComposerInput("!!node --version")).toEqual({ kind: "bash", command: "node --version", excludeFromContext: true, refs: [], }); });});deleted file mode 100644+0 / −9 text lines
import { describe, expect, it } from "vitest";import { digestIndicatorText } from "../web/components/digest-indicator.js";describe("ui digest indicator", () => { it("describes pending digest state as a compact chip", () => { expect(digestIndicatorText(0)).toBe("digest 0"); expect(digestIndicatorText(3)).toBe("digest 3"); });});deleted file mode 100644+0 / −53 text lines
import { describe, expect, it } from "vitest";import { EventStore } from "../events";describe("ui event store", () => { it("assigns monotonic ids and timestamps", () => { const store = new EventStore({ maxEvents: 10, now: () => 1000 }); const first = store.append({ type: "state", state: "starting" }); const second = store.append({ type: "log", level: "info", message: "ready", }); expect(first).toMatchObject({ id: 1, at: 1000, type: "state" }); expect(second).toMatchObject({ id: 2, at: 1000, type: "log" }); }); it("keeps a bounded replay buffer", () => { const store = new EventStore({ maxEvents: 3, now: () => 1 }); for (let i = 0; i < 5; i++) { store.append({ type: "log", level: "info", message: `event ${i}` }); } expect(store.replayAfter(0).map((event) => event.id)).toEqual([3, 4, 5]); expect(store.replayAfter(3).map((event) => event.id)).toEqual([4, 5]); }); it("builds deterministic snapshots", () => { const store = new EventStore({ maxEvents: 10, now: () => 7 }); store.append({ type: "state", state: "starting" }); store.append({ type: "message", role: "user", text: "hello" }); expect( store.snapshot({ status: "connected", sessionPath: "C:/tmp/ui.jsonl", commands: [{ name: "ui", description: "browser ui" }], }), ).toEqual({ version: 1, lastEventId: 2, status: "connected", sessionPath: "C:/tmp/ui.jsonl", commands: [{ name: "ui", description: "browser ui" }], events: [ { id: 1, at: 7, type: "state", state: "starting" }, { id: 2, at: 7, type: "message", role: "user", text: "hello" }, ], }); });});deleted file mode 100644+0 / −110 text lines
import { describe, expect, it } from "vitest";import { extensionUiEventFromRequest, extensionUiResponseCommand, isExtensionUiRequest,} from "../extension-ui";describe("ui extension UI protocol", () => { it("recognizes dialog requests", () => { expect( isExtensionUiRequest({ type: "extension_ui_request", id: "u1", method: "select", title: "Pick", options: ["a", "b"], }), ).toBe(true); }); it("normalizes select requests into stream events", () => { expect( extensionUiEventFromRequest({ type: "extension_ui_request", id: "u1", method: "select", title: "Pick one", options: ["a", "b"], }), ).toEqual({ type: "ui_request", requestId: "u1", method: "select", title: "Pick one", message: "select: Pick one", options: ["a", "b"], expectsResponse: true, }); }); it("normalizes fire-and-forget notify requests", () => { expect( extensionUiEventFromRequest({ type: "extension_ui_request", id: "u2", method: "notify", message: "Blocked", notifyType: "warning", }), ).toMatchObject({ type: "ui_notify", requestId: "u2", message: "Blocked", notifyType: "warning", }); }); it("preserves status request keys for the browser status strip", () => { expect( extensionUiEventFromRequest({ type: "extension_ui_request", id: "s1", method: "setStatus", statusKey: "model-info", statusText: "gpt-5 high", }), ).toMatchObject({ type: "ui_status", requestId: "s1", message: "gpt-5 high", statusKey: "model-info", statusText: "gpt-5 high", }); }); it("keeps status clears empty instead of rendering setStatus", () => { expect( extensionUiEventFromRequest({ type: "extension_ui_request", id: "s2", method: "setStatus", statusKey: "vcs", statusText: undefined, }), ).toMatchObject({ type: "ui_status", requestId: "s2", message: "", statusKey: "vcs", }); }); it("creates response commands for values, confirmations, and cancellations", () => { expect(extensionUiResponseCommand("u1", { value: "a" })).toEqual({ type: "extension_ui_response", id: "u1", value: "a", }); expect(extensionUiResponseCommand("u2", { confirmed: true })).toEqual({ type: "extension_ui_response", id: "u2", confirmed: true, }); expect(extensionUiResponseCommand("u3", { cancelled: true })).toEqual({ type: "extension_ui_response", id: "u3", cancelled: true, }); });});deleted file mode 100644+0 / −71 text lines
import path from "node:path";import { afterEach, describe, expect, it } from "vitest";import { createTestSession, type TestSession } from "../../../test/harness";import { notifyUrl } from "../index";describe("ui notifications", () => { it("omits token params from notification URLs", () => { expect(notifyUrl("http://127.0.0.1:123/?token=abc")).toBe( "http://127.0.0.1:123/", ); });});describe("ui pi-test-harness", () => { let t: TestSession | undefined; afterEach(() => { t?.dispose(); t = undefined; }); it("loads in real Pi extension runtime", async () => { const extensionPath = path.resolve(import.meta.dirname, "../index.ts"); t = await createTestSession({ extensions: [extensionPath] }); expect(t.session.extensionRunner.extensions).toHaveLength(1); expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath); }); it("registers the /ui command without starting a runtime", async () => { const extensionPath = path.resolve(import.meta.dirname, "../index.ts"); t = await createTestSession({ extensions: [extensionPath] }); const extension = t.session.extensionRunner.extensions[0]; expect([...extension.commands.keys()]).toEqual(["ui"]); expect([...extension.tools.keys()]).toEqual([ "ui_card", "ui_table", "ui_diagram", "ui_form", "ui_mockup", "ui_html", "ui_update", "ui_wait_action", ]); expect(t.events.uiCallsFor("setWidget")).toHaveLength(0); }); it("reports an actionable seed error in an empty session", async () => { const extensionPath = path.resolve(import.meta.dirname, "../index.ts"); t = await createTestSession({ extensions: [extensionPath] }); const command = t.session.extensionRunner.extensions[0].commands.get("ui"); expect(command).toBeDefined(); await command?.handler( "", t.session.extensionRunner.createCommandContext(), ); expect(latestNotify(t)).toContain("Cannot seed UI session"); expect(latestNotify(t)).toContain("Action:"); expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([ "ui", undefined, ]); });});function latestNotify(t: TestSession): string { return String(t.events.uiCallsFor("notify").at(-1)?.args[0] ?? "");}deleted file mode 100644+0 / −40 text lines
import { describe, expect, it } from "vitest";import { LifecycleTracker } from "../lifecycle";describe("ui browser lifecycle", () => { it("emits heartbeat timeout errors", () => { const tracker = new LifecycleTracker({ now: () => 10_000, heartbeatMs: 5_000, }); tracker.heartbeat("client-1", 1_000); expect(tracker.check()).toEqual([ expect.objectContaining({ type: "error", clientId: "client-1", message: "browser heartbeat lost", retryable: true, }), ]); }); it("emits close pagehide stale and reconnect lifecycle events", () => { const tracker = new LifecycleTracker({ now: () => 20 }); expect(tracker.close("client-1")).toMatchObject({ type: "error", message: "browser websocket closed", }); expect(tracker.pagehide("client-1")).toMatchObject({ type: "error", message: "browser page hidden/unloaded", }); expect(tracker.stale("client-1")).toMatchObject({ type: "error", message: "browser client stale", }); expect(tracker.reconnect("client-1")).toMatchObject({ type: "log", message: "browser reconnected: client-1", }); });});deleted file mode 100644+0 / −36 text lines
import { describe, expect, it } from "vitest";import { longOutputModel, toggleLongOutput,} from "../web/components/long-output.js";import { virtualWindow } from "../web/components/virtual-stream.js";describe("ui stream performance guards", () => { it("truncates long output and preserves expansion state", () => { const text = "x".repeat(2_000); expect(longOutputModel("e1", text, new Set(), 120)).toMatchObject({ id: "e1", truncated: true, text: "x".repeat(120), }); const expanded = toggleLongOutput("e1", new Set()); expect(longOutputModel("e1", text, expanded, 120)).toMatchObject({ truncated: false, text, }); }); it("returns ordered virtual windows around selected item", () => { const events = Array.from({ length: 100 }, (_, index) => ({ id: index + 1, })); expect( virtualWindow(events, { selectedId: 50, threshold: 20, radius: 3 }).map( (e) => e.id, ), ).toEqual([47, 48, 49, 50, 51, 52, 53]); expect( virtualWindow(events, { selectedId: 2, threshold: 200, radius: 3 }), ).toEqual(events); });});deleted file mode 100644+0 / −62 text lines
import { describe, expect, it } from "vitest";import { renderAppJs } from "../web/app.js";import { renderCodeBlockComponentJs, renderPlainCodeBlock,} from "../web/components/code-block.js";import { diffSummary, renderDiffViewJs } from "../web/components/diff-view.js";describe("ui code and diff rendering", () => { it("renders plaintext code immediately", () => { expect(renderPlainCodeBlock("ts", "const x = 1;")).toContain( "const x = 1;", ); expect(renderPlainCodeBlock("ts", "const x = 1;")).toContain( 'data-language="ts"', ); }); it("keeps Shiki lazy and optional", () => { expect(renderCodeBlockComponentJs()).toContain("import('shiki')"); expect(renderCodeBlockComponentJs()).toContain("textContent"); }); it("summarizes diffs and emits Pierre lazy loader", () => { expect(diffSummary("--- a/a.ts\n+++ b/a.ts\n+add\n-del\n context")).toEqual( { files: 1, additions: 1, deletions: 1, }, ); expect(renderDiffViewJs()).toContain("import('pierre')"); }); it("coalesces streaming message updates by stream id", () => { const js = renderAppJs(); expect(js).toContain("event.streamId"); expect(js).toContain("replaceWith(row)"); expect(js).toContain("finalizeStreamingRows()"); }); it("clears empty extension status instead of showing method names", () => { const js = renderAppJs(); expect(js).toContain("statusItems.delete(String(key))"); expect(js).not.toContain("key + ': ' + 'setStatus'"); }); it("does not locally echo submitted prompts", () => { const js = renderAppJs(); expect(js).not.toContain( "Number.MAX_SAFE_INTEGER, at: Date.now(), type: 'message', role: 'user'", ); }); it("keeps internal runtime chatter out of the main stream", () => { const js = renderAppJs(); expect(js).toContain("isStreamEvent(event)"); expect(js).toContain("event.type === 'message'"); expect(js).toContain("event.type === 'ui_request'"); expect(js).not.toContain("JSON.stringify(event)"); });});deleted file mode 100644+0 / −112 text lines
import { once } from "node:events";import { describe, expect, it } from "vitest";import { parseJsonLines, rpcSpawnPlan, startRpc } from "../rpc";const node = process.execPath;describe("ui rpc bridge", () => { it("splits only on LF and keeps partial records", () => { const parsed = parseJsonLines( '{"type":"event","text":"a
b"}\r\n{"type":"partial"', ); expect(parsed.messages).toEqual([{ type: "event", text: "a
b" }]); expect(parsed.rest).toBe('{"type":"partial"'); }); it("wraps win32 cmd shims through cmd.exe", () => { expect(rpcSpawnPlan("pi.cmd", ["--mode", "rpc"], "win32")).toEqual({ command: "cmd.exe", args: ["/d", "/s", "/c", "pi.cmd", "--mode", "rpc"], windowsHide: true, }); expect(rpcSpawnPlan("pi", ["--mode", "rpc"], "linux")).toEqual({ command: "pi", args: ["--mode", "rpc"], windowsHide: false, }); }); it("matches responses by id and forwards events", async () => { const events: unknown[] = []; const rpc = startRpc({ command: node, args: [ "-e", `process.stdin.on('data', chunk => { for (const line of String(chunk).trim().split('\\n')) { const msg = JSON.parse(line); console.log(JSON.stringify({ type: 'event', seen: msg.type })); console.log(JSON.stringify({ id: msg.id, type: 'response', command: msg.type, success: true, data: { ok: true } })); } });`, ], cwd: process.cwd(), sessionPath: "session.jsonl", onEvent: (event) => events.push(event), }); try { const response = await rpc.send({ type: "get_state" }); expect(response).toMatchObject({ type: "response", command: "get_state", success: true, data: { ok: true }, }); expect(events).toEqual([{ type: "event", seen: "get_state" }]); } finally { await rpc.close("test"); } }); it("captures stderr", async () => { const rpc = startRpc({ command: node, args: ["-e", "console.error('rpc stderr'); setTimeout(() => {}, 50);"], cwd: process.cwd(), sessionPath: "session.jsonl", }); try { await once(rpc.child.stderr, "data"); expect(rpc.stderr()).toContain("rpc stderr"); } finally { await rpc.close("test"); } }); it("times out unanswered requests", async () => { const rpc = startRpc({ command: node, args: ["-e", "process.stdin.resume()"], cwd: process.cwd(), sessionPath: "session.jsonl", requestTimeoutMs: 10, }); try { await expect(rpc.send({ type: "get_state" })).rejects.toThrow( /timed out/, ); } finally { await rpc.close("test"); } }); it("emits slow-start and exit lifecycle states", async () => { const states: string[] = []; const rpc = startRpc({ command: node, args: ["-e", "setTimeout(() => process.exit(7), 40)"], cwd: process.cwd(), sessionPath: "session.jsonl", slowStartMs: 5, onState: (state) => states.push(state), }); await once(rpc.child, "exit"); expect(states).toContain("slow-start"); expect(states).toContain("exit"); });});deleted file mode 100644+0 / −318 text lines
import { EventEmitter } from "node:events";import { mkdtemp, readFile, rm } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { Writable } from "node:stream";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";import { openBrowser, openerCandidates } from "../open";import { createUiRuntime, normalizeRpcEvent, type UiRuntime } from "../runtime";describe("ui browser opener", () => { it("uses platform openers", () => { expect( openerCandidates("http://x", { platform: "win32", env: {} })[0], ).toEqual({ command: "explorer.exe", args: ["http://x"], windowsHide: true, }); expect( openerCandidates("http://x", { platform: "darwin", env: {} })[0], ).toEqual({ command: "open", args: ["http://x"], }); expect( openerCandidates("http://x", { platform: "linux", env: {} })[0], ).toEqual({ command: "xdg-open", args: ["http://x"], }); }); it("uses termux opener when available", () => { expect( openerCandidates("http://x", { platform: "linux", env: { TERMUX_VERSION: "1" }, })[0], ).toEqual({ command: "termux-open-url", args: ["http://x"], }); }); it("can suppress auto-open for smoke harnesses", async () => { const previous = process.env.PI_UI_NO_AUTO_OPEN; process.env.PI_UI_NO_AUTO_OPEN = "1"; try { await expect(openBrowser("http://127.0.0.1:9")).resolves.toBeUndefined(); } finally { if (previous === undefined) delete process.env.PI_UI_NO_AUTO_OPEN; else process.env.PI_UI_NO_AUTO_OPEN = previous; } });});const runtimes: UiRuntime[] = [];afterEach(async () => { await Promise.all( runtimes.splice(0).map((runtime) => runtime.stop("test cleanup")), );});describe("ui rpc event normalization", () => { it("drops unknown rpc startup chatter", () => { expect( normalizeRpcEvent({ type: "startup_log", message: "builtin-tools" }), ).toBeUndefined(); }); it("uses accumulated assistant text for streaming updates", () => { expect( normalizeRpcEvent({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "Ready. What" }], }, assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: " What", }, }), ).toEqual({ type: "message", role: "assistant", text: "Ready. What", streamId: "assistant-stream", }); });});describe("ui runtime", () => { it("starts, reports status, redraws QR, and stops", async () => { const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", openBrowser: false, }); runtimes.push(runtime); expect(runtime.status().active).toBe(true); expect(runtime.status().url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/?$/); expect(runtime.widgetLines().join("\n")).toContain("ui: test"); await runtime.redrawQr(); expect(runtime.widgetLines().join("\n")).toContain("mobile QR: /ui qr"); await runtime.stop("test"); expect(runtime.status().active).toBe(false); }); it("writes smoke URL handoff only when requested", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pi-ui-smoke-")); const file = path.join(dir, "url.txt"); const previous = process.env.PI_UI_SMOKE_URL_FILE; process.env.PI_UI_SMOKE_URL_FILE = file; try { const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", openBrowser: false, }); runtimes.push(runtime); const value = await readFile(file, "utf8"); expect(new URL(value.trim()).searchParams.has("token")).toBe(true); expect(value.trim()).not.toBe(runtime.status().url); } finally { if (previous === undefined) delete process.env.PI_UI_SMOKE_URL_FILE; else process.env.PI_UI_SMOKE_URL_FILE = previous; await rm(dir, { recursive: true, force: true }); } }); it("is safe to stop twice", async () => { const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", openBrowser: false, }); await runtime.stop("first"); await runtime.stop("second"); expect(runtime.status().active).toBe(false); }); it("seeds an active branch and starts rpc when a session manager is provided", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath, onState }) => { onState?.("connected"); return fakeRpc(sent, sessionPath); }, }); runtimes.push(runtime); expect(runtime.status()).toMatchObject({ active: true, rpcState: "connected", sessionPath: "C:/sessions/ui-branch.jsonl", }); expect(runtime.widgetLines().join("\n")).toContain("rpc: connected"); }); it("forwards browser prompts to rpc and publishes stream events", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath), }); runtimes.push(runtime); const socket = await connectRuntimeSocket(runtime); socket.send(JSON.stringify({ type: "prompt", text: "hello" })); await new Promise((resolve) => setTimeout(resolve, 20)); socket.close(); expect(sent).toContainEqual( expect.objectContaining({ type: "prompt", message: "hello" }), ); }); it("routes bash and browser control actions to rpc", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath), }); runtimes.push(runtime); const socket = await connectRuntimeSocket(runtime); socket.send(JSON.stringify({ type: "prompt", text: "!!git status" })); socket.send(JSON.stringify({ type: "cycle_model" })); socket.send(JSON.stringify({ type: "abort" })); await new Promise((resolve) => setTimeout(resolve, 20)); socket.close(); expect(sent).toContainEqual({ type: "bash", command: "git status", excludeFromContext: true, }); expect(sent).toContainEqual({ type: "cycle_model" }); expect(sent).toContainEqual({ type: "abort" }); }); it("attaches telemetry digest once to browser prompt", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath), }); runtimes.push(runtime); const socket = await connectRuntimeSocket(runtime); socket.send( JSON.stringify({ type: "telemetry_batch", events: [{ type: "click", target: "SEND" }], }), ); socket.send(JSON.stringify({ type: "prompt", text: "hello" })); socket.send(JSON.stringify({ type: "prompt", text: "again" })); await new Promise((resolve) => setTimeout(resolve, 20)); socket.close(); expect(sent).toContainEqual({ type: "prompt", message: "Browser digest:\n- click SEND\n\nUser prompt:\nhello", }); expect(sent).toContainEqual({ type: "prompt", message: "again" }); }); it("routes extension UI responses to rpc", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: test", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath), }); runtimes.push(runtime); const socket = await connectRuntimeSocket(runtime); socket.send( JSON.stringify({ type: "ui_response", id: "u1", value: "Allow" }), ); await new Promise((resolve) => setTimeout(resolve, 20)); socket.close(); expect(sent).toContainEqual({ type: "extension_ui_response", id: "u1", value: "Allow", }); });});async function connectRuntimeSocket(runtime: UiRuntime): Promise<WebSocket> { const url = new URL(runtime.status().url ?? ""); const response = await fetch(url); const cookie = response.headers.get("set-cookie") ?? ""; const socketUrl = new URL("/ws", url); socketUrl.protocol = "ws:"; const socket = new WebSocket(socketUrl, { headers: { cookie } }); await new Promise((resolve) => socket.once("open", resolve)); return socket;}function fakeSessionManager() { return { getLeafId: () => "leaf-1", getSessionFile: () => "C:/sessions/source.jsonl", createBranchedSession: () => "C:/sessions/ui-branch.jsonl", };}function fakeRpc(sent: unknown[], sessionPath: string) { return { child: Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter(), stdin: new Writable({ write(_chunk, _encoding, callback) { callback(); }, }), kill() {}, }), sessionPath, send(request: unknown) { sent.push(request); return Promise.resolve({ type: "response", success: true, data: {} }); }, stderr: () => "", close: () => Promise.resolve(), };}deleted file mode 100644+0 / −208 text lines
import { once } from "node:events";import { describe, expect, it } from "vitest";import WebSocket from "ws";import { humanError, redactToken, uiError } from "../errors";import { EventStore } from "../events";import { chooseLanAddress, uiUrl } from "../network";import { startUiServer } from "../server";describe("ui network helpers", () => { it("prefers non-internal IPv4 LAN addresses", () => { const address = chooseLanAddress({ lo: [{ address: "127.0.0.1", family: "IPv4", internal: true } as never], wifi: [ { address: "192.168.1.44", family: "IPv4", internal: false } as never, ], }); expect(address).toBe("192.168.1.44"); }); it("falls back to 127.0.0.1 when no LAN address exists", () => { const address = chooseLanAddress({ lo: [{ address: "127.0.0.1", family: "IPv4", internal: true } as never], }); expect(address).toBe("127.0.0.1"); }); it("builds token URLs and redacts tokens in diagnostics", () => { const url = uiUrl("10.0.0.9", 54321, "abc"); expect(url).toBe("http://10.0.0.9:54321/?token=abc"); expect(redactToken(url)).toBe("http://10.0.0.9:54321/?token=<redacted>"); });});async function waitFor(predicate: () => boolean): Promise<void> { for (let attempt = 0; attempt < 20; attempt += 1) { if (predicate()) return; await new Promise((resolve) => setTimeout(resolve, 10)); }}describe("ui errors", () => { it("formats human-actionable errors", () => { const err = uiError("server_bind_failed", "Could not bind LAN server", { action: "Pick another port with /ui --port <port>.", retryable: true, }); expect(humanError(err)).toContain("Could not bind LAN server"); expect(humanError(err)).toContain("Pick another port"); expect(humanError(err)).toContain("Retryable: yes"); });});describe("ui server", () => { it("serves shell at bare root and sets strict cookie", async () => { const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, }); try { const authorized = await fetch(server.baseUrl); expect(authorized.status).toBe(200); expect(authorized.headers.get("set-cookie")).toContain("pi_ui_token=tok"); expect(authorized.headers.get("set-cookie")).toContain("SameSite=Strict"); const body = await authorized.text(); expect(body).toContain("<title>Pi UI</title>"); expect(body).toContain('id="ui-composer"'); } finally { await server.close("test"); } }); it("accepts cookie and bearer auth for status", async () => { const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, }); try { const cookie = await fetch(`${server.baseUrl}/api/status`, { headers: { cookie: "pi_ui_token=tok" }, }); expect(cookie.status).toBe(200); expect(await cookie.json()).toMatchObject({ state: "waiting", clients: 0, }); const bearer = await fetch(`${server.baseUrl}/api/status`, { headers: { authorization: "Bearer tok" }, }); expect(bearer.status).toBe(200); } finally { await server.close("test"); } }); it("rejects wrong tokens", async () => { const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, }); try { const response = await fetch(`${server.baseUrl}/api/status`, { headers: { authorization: "Bearer wrong" }, }); expect(response.status).toBe(401); } finally { await server.close("test"); } }); it("serves authenticated snapshots", async () => { const events = new EventStore({ now: () => 1 }); events.append({ type: "state", state: "rpc-starting" }); const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, events, snapshotStatus: "rpc-starting", }); try { const unauthorized = await fetch(`${server.baseUrl}/api/snapshot`); expect(unauthorized.status).toBe(401); const response = await fetch(`${server.baseUrl}/api/snapshot`, { headers: { authorization: "Bearer tok" }, }); expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ version: 1, lastEventId: 1, status: "rpc-starting", }); } finally { await server.close("test"); } }); it("counts active websocket tabs, not html loads", async () => { const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, }); try { const page = await fetch(`${server.baseUrl}/?token=tok`); expect(page.status).toBe(200); expect(server.clients()).toBe(0); const ws = new WebSocket( `${server.baseUrl.replace("http", "ws")}/ws?token=tok`, ); await once(ws, "open"); expect(server.clients()).toBe(1); ws.close(); await once(ws, "close"); await waitFor(() => server.clients() === 0); expect(server.clients()).toBe(0); } finally { await server.close("test"); } }); it("authenticates websocket replay and broadcasts events", async () => { const events = new EventStore({ now: () => 2 }); events.append({ type: "log", level: "info", message: "old" }); const live = events.append({ type: "log", level: "info", message: "live" }); const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, events, snapshotStatus: "connected", }); const ws = new WebSocket( `${server.baseUrl.replace("http", "ws")}/ws?token=tok&after=1`, ); try { const [firstRaw] = (await once(ws, "message")) as [Buffer]; expect(JSON.parse(String(firstRaw))).toEqual({ type: "events", events: [live], }); const next = events.append({ type: "message", role: "user", text: "hello", }); server.publish(next); const [secondRaw] = (await once(ws, "message")) as [Buffer]; expect(JSON.parse(String(secondRaw))).toEqual({ type: "events", events: [next], }); } finally { ws.close(); await server.close("test"); } });});deleted file mode 100644+0 / −59 text lines
import { describe, expect, it } from "vitest";import { seedUiSession } from "../session-seed";describe("ui session seed", () => { it("creates an exact active-branch session from the current leaf", () => { const calls: string[] = []; const result = seedUiSession({ cwd: "C:/repo", sessionManager: { getLeafId: () => "leaf-1", getSessionFile: () => "C:/sessions/source.jsonl", createBranchedSession: (leafId: string) => { calls.push(leafId); return "C:/sessions/ui-branch.jsonl"; }, }, }); expect(calls).toEqual(["leaf-1"]); expect(result).toEqual({ path: "C:/sessions/ui-branch.jsonl", method: "active-branch", warning: undefined, }); }); it("fails actionably when no active leaf exists", () => { expect(() => seedUiSession({ cwd: "C:/repo", sessionManager: { getLeafId: () => null, getSessionFile: () => "C:/sessions/source.jsonl", createBranchedSession: () => "unused", }, }), ).toThrow(/active leaf/); }); it("uses whole-tree fallback only when explicitly requested", () => { const result = seedUiSession({ cwd: "C:/repo", allowWholeTreeFallback: true, sessionManager: { getLeafId: () => "leaf-1", getSessionFile: () => "C:/sessions/source.jsonl", createBranchedSession: () => undefined, }, forkWholeTree: (source, cwd) => `fork:${source}:${cwd}`, }); expect(result).toEqual({ path: "fork:C:/sessions/source.jsonl:C:/repo", method: "whole-tree", warning: "Whole-tree session fork includes abandoned branches; active LLM context remains branch-clean.", }); });});deleted file mode 100644+0 / −55 text lines
import { describe, expect, it } from "vitest";import { redactText, TelemetryAggregator } from "../telemetry";describe("ui telemetry aggregator", () => { it("redacts selected and input text", () => { expect(redactText("secret text")).toBe("[redacted 11 chars]"); expect(redactText("")).toBe(""); }); it("summarizes scroll click focus pagehide widget and form events", () => { const telemetry = new TelemetryAggregator({ maxEvents: 8 }); telemetry.add({ type: "viewport", device: "phone", width: 390, height: 760, }); telemetry.add({ type: "scroll", y: 320, dwellMs: 1200 }); telemetry.add({ type: "click", target: "SEND" }); telemetry.add({ type: "focus", target: "composer" }); telemetry.add({ type: "selection", text: "private selection" }); telemetry.add({ type: "widget_action", widgetId: "widget-1", label: "Approve", }); telemetry.add({ type: "form", formId: "f1", state: "abandon" }); telemetry.add({ type: "pagehide" }); expect(telemetry.digest()).toBe( [ "Browser digest:", "- viewport phone 390x760", "- scroll y=320 dwell=1200ms", "- click SEND", "- focus composer", "- selection [redacted 17 chars]", "- widget widget-1 action Approve", "- form f1 abandon", "- pagehide", ].join("\n"), ); }); it("caps events and clears digest", () => { const telemetry = new TelemetryAggregator({ maxEvents: 2 }); telemetry.add({ type: "click", target: "one" }); telemetry.add({ type: "click", target: "two" }); telemetry.add({ type: "click", target: "three" }); expect(telemetry.digest()).toContain("three"); expect(telemetry.digest()).not.toContain("one"); telemetry.clear(); expect(telemetry.digest()).toBe(""); });});deleted file mode 100644+0 / −61 text lines
import { describe, expect, it } from "vitest";import { osc8Link, renderUiWidget } from "../terminal-widget";const OSC8_RE = /\u001b]8;;.*?\u001b\\|\u001b]8;;\u001b\\/g;function visibleLength(line: string): number { return line.replace(OSC8_RE, "").length;}describe("ui terminal widget", () => { it("renders OSC 8 links", () => { expect(osc8Link("http://127.0.0.1:123/open", "open ui")).toBe( "\u001b]8;;http://127.0.0.1:123/open\u001b\\open ui\u001b]8;;\u001b\\", ); }); it("renders a closed bounded widget box", () => { const lines = renderUiWidget({ url: "http://127.0.0.1:123/?token=abc", qr: Array.from({ length: 30 }, (_, index) => `QR ${index}`).join("\n"), state: "connected", sessionLabel: "ui: pi-ext", clients: 1, }); const text = lines.join("\n"); const visibleText = text.replace(OSC8_RE, ""); expect(lines).toHaveLength(9); expect(lines[0]).toMatch(/^┏━+┓$/); expect(lines.at(-1)).toMatch(/^┗━+┛$/); expect(lines.slice(1, -1).every((line) => /^┃.*┃$/.test(line))).toBe(true); expect(new Set(lines.map((line) => visibleLength(line))).size).toBe(1); expect(text).toContain("pi ui"); expect(visibleText).toContain("url: http://127.0.0.1:123/"); expect(visibleText).not.toContain("token=abc"); expect(text).toContain("connected"); expect(text).toContain("ui: pi-ext"); expect(text).toContain("press ESC to stop"); expect(text).toContain("/ui off"); expect(text).toContain("/ui qr"); expect(text).not.toContain("widget truncated"); expect(text).not.toContain("QR 29"); }); it("wraps long content inside the box without truncating", () => { const longLabel = "ui: " + "x".repeat(90); const lines = renderUiWidget({ url: "http://127.0.0.1:123/?token=abc", qr: "QR", state: "connected", sessionLabel: longLabel, clients: 1, }); const text = lines.join("\n"); expect(text).toContain("session: ui: "); expect(text.match(/x/g)).toHaveLength(90); expect(text).not.toContain("…"); expect(new Set(lines.map((line) => visibleLength(line))).size).toBe(1); });});deleted file mode 100644+0 / −46 text lines
import { describe, expect, it } from "vitest";import { renderAppCss } from "../web/app.css";import { renderAppHtml } from "../web/app.html";import { renderThemeCss } from "../web/theme.css";describe("ui Nugu theme", () => { it("emits semantic brutal variables and dark/light media query", () => { const css = renderThemeCss(); expect(css).toContain("--nugu-bg"); expect(css).toContain("--nugu-fg"); expect(css).toContain("--nugu-accent"); expect(css).toContain("prefers-color-scheme: light"); }); it("keeps stream-first layout without sidebar", () => { const css = renderThemeCss(); expect(css).toContain("grid-template-rows: auto minmax(0, 1fr) auto"); expect(css).not.toContain("sidebar"); }); it("keeps the composer visible while only the stream scrolls", () => { const css = renderAppCss(); expect(css).toContain( "body { margin: 0; min-height: 100vh; height: 100vh; overflow: hidden;", ); expect(css).toContain( "#ui-shell { min-height: 100vh; height: 100vh; display: grid; grid-template-rows: auto minmax(0, 1fr) auto;", ); expect(css).toContain("#ui-stream { min-height: 0;"); expect(css).toContain("#ui-bottom { position: sticky; bottom: 0;"); expect(css).toContain("#ui-input { width: 100%; max-height: 30vh;"); }); it("renders explicit progress and status regions", () => { const html = renderAppHtml(); const css = renderAppCss(); expect(html).toContain('id="ui-top"'); expect(html).toContain('id="ui-progress"'); expect(html).toContain('id="ui-meta"'); expect(html).toContain('id="ui-digest"'); expect(html).not.toContain("<details"); expect(css).toContain("#ui-progress"); expect(css).toContain("#ui-meta"); expect(css).toContain("#ui-digest"); });});deleted file mode 100644+0 / −43 text lines
import { describe, expect, it } from "vitest";import { renderVisualBlockShell, visualBlockSummary,} from "../web/components/visual-block.js";describe("ui visual block rendering", () => { it("renders widget fallback and ids", () => { expect( visualBlockSummary({ type: "widget_mount", widgetId: "widget-1", title: "Demo", fallback: "Fallback text", status: "mounted", }), ).toBe("Demo · widget-1 · mounted · Fallback text"); }); it("renders widget errors with a fix hint", () => { expect( visualBlockSummary({ type: "widget_error", widgetId: "widget-1", message: "boom", status: "error", }), ).toBe("widget-1 · error · boom · agent: fix widget HTML/JS"); }); it("renders bounded iframe shell", () => { const html = renderVisualBlockShell({ widgetId: "widget-1", title: "Demo", fallback: "Fallback", srcdoc: "<p>Hi</p>", }); expect(html).toContain("ui-visual-block"); expect(html).toContain("widget-1"); expect(html).toContain("iframe"); expect(html).toContain("Fallback"); });});deleted file mode 100644+0 / −71 text lines
import { describe, expect, it } from "vitest";import { createVisualTools } from "../visual-tools";import { WidgetStore } from "../widget-state";describe("ui visual tools", () => { it("creates the expected visual tool family", () => { const tools = createVisualTools({ store: new WidgetStore({ now: () => 1 }), }); expect(tools.map((tool) => tool.name)).toEqual([ "ui_card", "ui_table", "ui_diagram", "ui_form", "ui_mockup", "ui_html", "ui_update", "ui_wait_action", ]); }); it("mounts raw HTML widgets with fallback text", async () => { const events: unknown[] = []; const [, , , , , htmlTool] = createVisualTools({ store: new WidgetStore({ now: () => 2 }), publish: (event) => events.push(event), }); const result = await htmlTool.execute( "call-1", { title: "Demo", fallback: "fallback", html: "<button>go</button>" }, undefined, undefined, {} as never, ); expect(result.content).toEqual([{ type: "text", text: "fallback" }]); expect(result.details).toMatchObject({ widgetId: "widget-call-1", type: "widget_mount", title: "Demo", }); expect(events).toHaveLength(1); }); it("updates existing widgets", async () => { const store = new WidgetStore({ now: () => 3 }); store.mount({ toolCallId: "call-2", title: "Demo", fallback: "fallback", html: "<p>old</p>", }); const tools = createVisualTools({ store }); const updateTool = tools.find((tool) => tool.name === "ui_update"); expect(updateTool).toBeDefined(); const result = await updateTool?.execute( "call-update", { widgetId: "widget-call-2", html: "<p>new</p>" }, undefined, undefined, {} as never, ); expect(result?.content).toEqual([ { type: "text", text: "Updated widget-call-2" }, ]); expect(store.get("widget-call-2")?.html).toBe("<p>new</p>"); });});deleted file mode 100644+0 / −50 text lines
import { describe, expect, it } from "vitest";import { composerKeyAction, filterCommandItems, moveMenuIndex,} from "../web/components/composer.js";describe("ui web composer autocomplete", () => { const commands = [ { name: "mode", description: "Switch mode" }, { name: "skill:brutal", description: "Brutal style" }, { name: "skill:wiki", description: "Wiki research" }, { name: "ui", description: "Browser UI" }, ]; it("filters slash command items", () => { expect(filterCommandItems(commands, "/skill:b")).toEqual([ { name: "skill:brutal", description: "Brutal style" }, ]); }); it("returns extension, skill, and prompt command items for empty slash prefix", () => { expect(filterCommandItems(commands, "/").map((item) => item.name)).toEqual([ "mode", "skill:brutal", "skill:wiki", "ui", ]); }); it("wraps keyboard menu selection", () => { expect(moveMenuIndex(0, 1, 3)).toBe(1); expect(moveMenuIndex(2, 1, 3)).toBe(0); expect(moveMenuIndex(0, -1, 3)).toBe(2); expect(moveMenuIndex(0, 1, 0)).toBe(0); }); it("maps composer keybindings", () => { expect(composerKeyAction({ key: "Enter" })).toBe("submit"); expect(composerKeyAction({ key: "Enter", shiftKey: true })).toBe("newline"); expect(composerKeyAction({ key: "Escape" })).toBe("abort"); expect(composerKeyAction({ key: "o", ctrlKey: true })).toBe( "toggle-expand", ); expect(composerKeyAction({ key: "p", ctrlKey: true })).toBe("cycle-model"); expect( composerKeyAction({ key: "Arrow" + "Down", menuVisible: true }), ).toBe("menu-next"); });});deleted file mode 100644+0 / −22 text lines
import { describe, expect, it } from "vitest";import { dialogResponse } from "../web/components/dialogs.js";describe("ui web dialogs", () => { it("builds extension UI responses", () => { expect(dialogResponse("u1", "select", "Allow")).toEqual({ type: "ui_response", id: "u1", value: "Allow", }); expect(dialogResponse("u2", "confirm", true)).toEqual({ type: "ui_response", id: "u2", confirmed: true, }); expect(dialogResponse("u3", "input", undefined)).toEqual({ type: "ui_response", id: "u3", cancelled: true, }); });});deleted file mode 100644+0 / −37 text lines
import { describe, expect, it } from "vitest";import { startUiServer } from "../server";describe("ui web shell", () => { it("serves a stream-first shell and static browser assets", async () => { const server = await startUiServer({ address: "127.0.0.1", token: "tok", preferredPort: 0, }); try { const shell = await fetch(`${server.baseUrl}/?token=tok`); expect(shell.status).toBe(200); const html = await shell.text(); expect(html).toContain('id="ui-progress"'); expect(html).toContain('id="ui-meta"'); expect(html).toContain('id="ui-stream"'); expect(html).toContain('id="ui-composer"'); expect(html).toContain('type="module"'); expect(html).toContain("/assets/app.js"); const js = await fetch(`${server.baseUrl}/assets/app.js`, { headers: { authorization: "Bearer tok" }, }); expect(js.status).toBe(200); expect(await js.text()).toContain("fetchSnapshot"); const css = await fetch(`${server.baseUrl}/assets/app.css`, { headers: { authorization: "Bearer tok" }, }); expect(css.status).toBe(200); expect(await css.text()).toContain("#ui-stream"); } finally { await server.close("test"); } });});deleted file mode 100644+0 / −40 text lines
import { describe, expect, it } from "vitest";import { attributionEventFromWidgetMessage, renderWidgetBridgeScript, widgetActionMessage,} from "../web/components/widget-bridge.js";describe("ui widget bridge", () => { it("creates window.pi bridge source", () => { const source = renderWidgetBridgeScript("widget-1"); expect(source).toContain("window.pi"); expect(source).toContain("action"); expect(source).toContain("prompt"); expect(source).toContain("notify"); }); it("builds widget action messages", () => { expect(widgetActionMessage("widget-1", "Approve", { ok: true })).toEqual({ type: "widget_action", widgetId: "widget-1", label: "Approve", payload: { ok: true }, }); }); it("turns widget prompts into visible attribution events", () => { expect( attributionEventFromWidgetMessage( { type: "widget_prompt", widgetId: "widget-1", text: "continue" }, () => 50, ), ).toEqual({ type: "widget_action", widgetId: "widget-1", label: "prompt", payload: { text: "continue" }, at: 50, }); });});deleted file mode 100644+0 / −106 text lines
import { existsSync } from "node:fs";import { type BrowserType, chromium, firefox, type Page,} from "@playwright/test";import { describe, expect, it } from "vitest";const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe";describe("ui widget browser layout", () => { it("lets unsandboxed srcdoc widgets call parent window.pi in Chrome and Firefox", async () => { for (const browser of browsers()) { const result = await withBrowser(browser, async (page) => { await page.setContent(bridgeProbeHtml()); await page.waitForFunction(() => window.calls?.length === 1); return await page.evaluate(() => window.calls[0]); }); expect(result).toEqual({ from: "srcdoc", sameOrigin: true }); } }, 120_000); it("keeps over-wide iframe content bounded at phone width in Chrome and Firefox", async () => { for (const browser of browsers()) { const result = await withBrowser(browser, async (page) => { await page.setViewportSize({ width: 390, height: 760 }); await page.setContent(layoutProbeHtml()); await page.waitForFunction( () => document.querySelector("iframe")?.clientHeight === 600, ); return await page.evaluate(() => ({ viewport: document.documentElement.clientWidth, scrollWidth: document.documentElement.scrollWidth, iframeHeight: document .querySelector("iframe") ?.getBoundingClientRect().height, })); }); expect(result).toEqual({ viewport: 390, scrollWidth: 390, iframeHeight: 600, }); } }, 120_000);});function browsers(): Array<{ name: string; type: BrowserType; executablePath?: string;}> { return [ ...(existsSync(chromePath) ? [{ name: "chrome", type: chromium, executablePath: chromePath }] : []), { name: "firefox", type: firefox }, ];}async function withBrowser<T>( browser: { name: string; type: BrowserType; executablePath?: string }, fn: (page: Page) => Promise<T>,): Promise<T> { const instance = await browser.type.launch({ headless: true, executablePath: browser.executablePath, }); try { const page = await instance.newPage(); return await fn(page); } finally { await instance.close(); }}function bridgeProbeHtml(): string { const srcdoc = "<script>parent.pi.action({from:'srcdoc',sameOrigin:!!parent.document});</" + "script>"; const attr = srcdoc.replaceAll(String.fromCharCode(34), """); return [ "<!doctype html>", "<script>window.calls=[];window.pi={action(x){window.calls.push(x)}};</script>", `<iframe srcdoc="${attr}"></iframe>`, ].join("");}function layoutProbeHtml(): string { const srcdoc = [ "<style>body{margin:0}.wide{width:2200px;height:80px}.tall{height:900px}</style>", "<div class=wide>x</div><div class=tall>y</div>", "<script>parent.postMessage({height:document.documentElement.scrollHeight},'*')</" + "script>", ].join(""); const attr = srcdoc .replaceAll("&", "&") .replaceAll(String.fromCharCode(34), """); return [ "<!doctype html>", "<style>*{box-sizing:border-box}body{margin:0}.wrap{width:min(960px,100vw);overflow:auto}.visual{min-width:0;overflow:auto;contain:layout paint;padding:12px}.visual iframe{display:block;width:100%;height:120px;max-height:600px;border:0}</style>", `<div class=wrap><div class=visual><iframe srcdoc="${attr}"></iframe></div></div>`, "<script>addEventListener('message',e=>{document.querySelector('iframe').style.height=Math.min(e.data.height,600)+'px'})</script>", ].join("");}deleted file mode 100644+0 / −62 text lines
import { describe, expect, it } from "vitest";import { WidgetStore } from "../widget-state";describe("ui widget state", () => { it("creates stable widget ids from tool call ids", () => { const store = new WidgetStore({ now: () => 100 }); const first = store.mount({ toolCallId: "call-1", title: "Card", fallback: "fallback", html: "<p>hi</p>", }); const second = store.mount({ toolCallId: "call-1", title: "Card", fallback: "fallback", html: "<p>hi</p>", }); expect(first.widgetId).toBe("widget-call-1"); expect(second.widgetId).toBe(first.widgetId); expect(store.get(first.widgetId)?.status).toBe("mounted"); }); it("records mount update action and error lifecycle", () => { const store = new WidgetStore({ now: () => 200 }); const mount = store.mount({ toolCallId: "call-2", title: "Form", fallback: "fallback", html: "<button>go</button>", }); const update = store.update(mount.widgetId, { html: "<button>stop</button>", }); const action = store.action(mount.widgetId, { toolCallId: "call-2", label: "Approve", payload: { ok: true }, }); const error = store.error(mount.widgetId, "boom"); expect(update).toMatchObject({ type: "widget_update", widgetId: mount.widgetId, }); expect(action).toMatchObject({ type: "widget_action", widgetId: mount.widgetId, toolCallId: "call-2", label: "Approve", actionId: "action-1", at: 200, }); expect(error).toMatchObject({ type: "widget_error", widgetId: mount.widgetId, message: "boom", }); expect(store.get(mount.widgetId)?.audit).toHaveLength(4); });});deleted file mode 100644+0 / −30 text lines
import { describe, expect, it } from "vitest";import { createTelemetryBatcher, renderTelemetryWorkerJs,} from "../web/worker.js";describe("ui telemetry worker", () => { it("batches raw events", () => { const batcher = createTelemetryBatcher({ maxBatch: 2 }); expect(batcher.add({ type: "click", target: "SEND" })).toEqual([]); expect(batcher.add({ type: "scroll", y: 20, dwellMs: 100 })).toEqual([ { type: "click", target: "SEND" }, { type: "scroll", y: 20, dwellMs: 100 }, ]); }); it("redacts selection and input text before flush", () => { const batcher = createTelemetryBatcher({ maxBatch: 10 }); batcher.add({ type: "selection", text: "private" }); expect(batcher.flush()).toEqual([ { type: "selection", text: "[redacted 7 chars]" }, ]); }); it("renders browser worker source", () => { const source = renderTelemetryWorkerJs(); expect(source).toContain("postMessage"); expect(source).toContain("telemetry_batch"); });});deleted file mode 100644+0 / −55 text lines
import type { RpcClient, RpcResponse } from "./rpc";export type RpcSender = Pick<RpcClient, "send">;export type PromptOptions = { digest?: () => string; clearDigest?: () => void;};export function sendPrompt( rpc: RpcSender, text: string, options: PromptOptions = {},): Promise<RpcResponse> { const digest = options.digest?.() ?? ""; if (!digest) return rpc.send({ type: "prompt", message: text }); options.clearDigest?.(); return rpc.send({ type: "prompt", message: `${digest}\n\nUser prompt:\n${text}`, });}export function runSlashCommand( rpc: RpcSender, command: string, args = "",): Promise<RpcResponse> { const suffix = args.trim() ? ` ${args.trim()}` : ""; return sendPrompt(rpc, `/${command}${suffix}`);}export function runBash( rpc: RpcSender, command: string, excludeFromContext: boolean,): Promise<RpcResponse> { return rpc.send({ type: "bash", command, excludeFromContext });}export function cycleModel(rpc: RpcSender): Promise<RpcResponse> { return rpc.send({ type: "cycle_model" });}export function cycleThinking(rpc: RpcSender): Promise<RpcResponse> { return rpc.send({ type: "cycle_thinking_level" });}export function compactSession(rpc: RpcSender): Promise<RpcResponse> { return rpc.send({ type: "compact" });}export function abortCurrent(rpc: RpcSender): Promise<RpcResponse> { return rpc.send({ type: "abort" });}deleted file mode 100644+0 / −59 text lines
export type ComposerParseResult = | { kind: "prompt"; text: string; refs: string[]; } | { kind: "slash"; command: string; args: string; text: string; refs: string[]; } | { kind: "bash"; command: string; excludeFromContext: boolean; refs: string[]; };const REF_RE = /(^|\s)@([^\s]+)/g;export function parseComposerInput(input: string): ComposerParseResult { const text = input.trim(); if (text.startsWith("!!")) { return { kind: "bash", command: text.slice(2).trimStart(), excludeFromContext: true, refs: [], }; } if (text.startsWith("!")) { return { kind: "bash", command: text.slice(1).trimStart(), excludeFromContext: false, refs: [], }; } if (text.startsWith("/") && text.length > 1) { const body = text.slice(1); const space = body.search(/\s/); const command = space === -1 ? body : body.slice(0, space); const args = space === -1 ? "" : body.slice(space).trimStart(); return { kind: "slash", command, args, text, refs: refs(text), }; } return { kind: "prompt", text, refs: refs(text) };}function refs(text: string): string[] { return [...text.matchAll(REF_RE)].map((match) => match[2]);}deleted file mode 100644+0 / −57 text lines
# UI manual smoke playbook## Host ruleUse zellij on win32.Do not invoke tmux on win32.Use tmux only on non-win32 hosts where it is installed.## win32 zellij```shnode extensions/ui/scripts/zellij-smoke.mjszellij attach <printed-session>```The script creates a zellij session through a real Windows console process, launches Pi in the default zellij terminal pane, sends `/ui`, captures the exact URL through a smoke-only local handoff file, dumps the terminal screen, probes tokenless `401`, verifies the authenticated browser shell with Playwright, sends `/ui off`, and writes `.pi/tmp/ui-zellij-smoke/*.summary.json`.It sets `MSYS_NO_PATHCONV=1` for zellij actions so `/ui` is not rewritten to a Git-for-Windows path.If URL extraction still fails, the script can run `scripts/phase1-smoke.mjs` as a fallback unless `--no-fallback` is passed.Do not switch to tmux on win32.Checkpoints:1. Run `pi -e extensions/ui/index.ts` inside the zellij pane if the script did not keep Pi running.2. Send `/ui`.3. Verify the terminal widget shows a token URL and QR.4. Open the exact URL in Chrome or Firefox.5. Verify `/api/status` without the token returns `401`.6. Try `/`, `/skill:`, `!`, `!!`, Esc, Ctrl+O, and Ctrl+P from the browser composer.7. Ask for card, form, and raw HTML widgets.8. Click one widget action and verify a visible attribution row appears before any widget-originated prompt reaches the agent.9. Scroll, click, select text, background the tab, return, and send one prompt.10. Verify the digest indicator appears and the digest is attached once only.11. Send `/ui off` in Pi.12. Verify browser disconnect and terminal UI restores as far as Pi exposes.Cleanup:```shzellij kill-session <printed-session>```## non-win32 tmux```shnode extensions/ui/scripts/tmux-smoke.mjstmux attach -t <printed-session>```Use the same checkpoints.## Evidence to capture- zellij/tmux session name.- `/ui` URL redacted to origin plus `token=[redacted]`.- 401 result for tokenless request.- Browser stream screenshot for widget + attribution + digest.- `/ui off` terminal state.deleted file mode 100644+0 / −46 text lines
export type UiErrorCode = | "server_bind_failed" | "no_lan_address" | "auth_failed" | "runtime_not_active" | "runtime_already_active" | "session_seed_failed" | "open_failed" | "qr_failed";export type UiError = Error & { code: UiErrorCode; action: string; retryable: boolean; cause?: unknown;};export function uiError( code: UiErrorCode, message: string, options: { action: string; retryable?: boolean; cause?: unknown },): UiError { const error = new Error(message) as UiError; error.name = "UiError"; error.code = code; error.action = options.action; error.retryable = options.retryable ?? false; error.cause = options.cause; return error;}export function humanError(error: UiError): string { return [ `${error.code}: ${error.message}`, `Action: ${error.action}`, `Retryable: ${error.retryable ? "yes" : "no"}`, ].join("\n");}export function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error);}export function redactToken(value: string): string { return value.replace(/([?&]token=)[^&#\s]+/g, "$1<redacted>");}deleted file mode 100644+0 / −58 text lines
import type { UiCommandInfo, UiConnectionStatus, UiEvent, UiEventInput, UiSnapshot,} from "./protocol";export type EventStoreOptions = { maxEvents?: number; now?: () => number;};export type SnapshotOptions = { status: UiConnectionStatus; sessionPath?: string; commands?: UiCommandInfo[];};export class EventStore { readonly #maxEvents: number; readonly #now: () => number; #nextId = 1; #events: UiEvent[] = []; constructor(options: EventStoreOptions = {}) { this.#maxEvents = Math.max(1, options.maxEvents ?? 500); this.#now = options.now ?? Date.now; } append(input: UiEventInput): UiEvent { const event = { id: this.#nextId++, at: this.#now(), ...input } as UiEvent; this.#events.push(event); if (this.#events.length > this.#maxEvents) { this.#events.splice(0, this.#events.length - this.#maxEvents); } return event; } replayAfter(lastEventId: number): UiEvent[] { return this.#events.filter((event) => event.id > lastEventId); } snapshot(options: SnapshotOptions): UiSnapshot { return { version: 1, lastEventId: this.lastEventId(), status: options.status, sessionPath: options.sessionPath, commands: options.commands ?? [], events: [...this.#events], }; } lastEventId(): number { return this.#nextId - 1; }}deleted file mode 100644+0 / −135 text lines
import type { UiEventInput } from "./protocol";export type ExtensionUiRequest = { type: "extension_ui_request"; id: string; method: string; [key: string]: unknown;};export type ExtensionUiResponseInput = | { value: string } | { confirmed: boolean } | { cancelled: true };export function isExtensionUiRequest( value: unknown,): value is ExtensionUiRequest { return ( !!value && typeof value === "object" && (value as { type?: unknown }).type === "extension_ui_request" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { method?: unknown }).method === "string" );}export function extensionUiEventFromRequest( request: ExtensionUiRequest,): UiEventInput { if (request.method === "select") { return { type: "ui_request", requestId: request.id, method: "select", title: stringField(request.title), message: `select: ${stringField(request.title)}`, options: arrayField(request.options), expectsResponse: true, }; } if (request.method === "confirm") { return { type: "ui_request", requestId: request.id, method: "confirm", title: stringField(request.title), message: stringField(request.message) || `confirm: ${stringField(request.title)}`, expectsResponse: true, }; } if (request.method === "input") { return { type: "ui_request", requestId: request.id, method: "input", title: stringField(request.title), message: `input: ${stringField(request.title)}`, placeholder: stringField(request.placeholder), expectsResponse: true, }; } if (request.method === "editor") { return { type: "ui_request", requestId: request.id, method: "editor", title: stringField(request.title), message: `editor: ${stringField(request.title)}`, prefill: stringField(request.prefill), expectsResponse: true, }; } if (request.method === "notify") { return { type: "ui_notify", requestId: request.id, message: stringField(request.message), notifyType: notifyType(request.notifyType), }; } const fields: Record<string, unknown> = { ...request }; delete fields.type; delete fields.id; delete fields.method; return { type: extensionUiEventType(request.method), requestId: request.id, message: statusMessage(request.method, fields), ...fields, };}export function extensionUiResponseCommand( id: string, input: ExtensionUiResponseInput,): { type: "extension_ui_response"; id: string } & ExtensionUiResponseInput { return { type: "extension_ui_response", id, ...input };}function stringField(value: unknown): string { return typeof value === "string" ? value : "";}function arrayField(value: unknown): string[] | undefined { return Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;}function notifyType(value: unknown): "info" | "warning" | "error" | undefined { return value === "info" || value === "warning" || value === "error" ? value : undefined;}function extensionUiEventType( method: string,): "ui_status" | "ui_title" | "ui_widget" | "ui_editor_text" { if (method === "setTitle") return "ui_title"; if (method === "setWidget") return "ui_widget"; if (method === "set_editor_text") return "ui_editor_text"; return "ui_status";}function statusMessage( method: string, fields: Record<string, unknown>,): string { if (typeof fields.statusText === "string") return fields.statusText; if (method === "setStatus") return ""; if (typeof fields.title === "string") return fields.title; return method;}deleted file mode 100644+0 / −167 text lines
import path from "node:path";import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext,} from "@earendil-works/pi-coding-agent";import { matchesKey } from "@earendil-works/pi-tui";import { humanError, type UiError, uiError } from "./errors";import { createUiRuntime, type UiRuntime } from "./runtime";import type { UiSeedSessionManager } from "./session-seed";import { createVisualTools } from "./visual-tools";const COMMANDS = ["off", "status", "open", "qr"];const WIDGET_KEY = "ui";export default function uiExtension(pi: ExtensionAPI): void { for (const tool of createVisualTools()) pi.registerTool(tool); let runtime: UiRuntime | undefined; let terminalUnsubscribe: (() => void) | undefined; function setWidget(ctx: ExtensionContext): void { if (!ctx.hasUI) return; ctx.ui.setWidget(WIDGET_KEY, runtime?.widgetLines(), { placement: "aboveEditor", }); } async function stop(ctx: ExtensionContext, reason: string): Promise<void> { terminalUnsubscribe?.(); terminalUnsubscribe = undefined; const current = runtime; runtime = undefined; if (ctx.hasUI) { ctx.ui.setWidget(WIDGET_KEY, undefined); ctx.ui.setWorkingVisible?.(true); } if (current) await current.stop(reason); } async function start(ctx: ExtensionCommandContext): Promise<void> { if (runtime) { setWidget(ctx); ctx.ui.notify( `ui already active: ${notifyUrl(runtime.status().url ?? "")}`, "info", ); return; } if (ctx.hasUI) ctx.ui.setWorkingVisible?.(false); runtime = await createUiRuntime({ sessionLabel: sessionLabel(pi, ctx), cwd: ctx.cwd, sessionManager: ctx.sessionManager as unknown as UiSeedSessionManager, onChange: () => setWidget(ctx), }); terminalUnsubscribe = ctx.hasUI ? ctx.ui.onTerminalInput((data) => { if (!matchesKey(data, "escape")) return undefined; void stop(ctx, "escape").then(() => ctx.ui.notify("ui stopped", "info"), ); return { consume: true }; }) : undefined; setWidget(ctx); ctx.ui.notify(`ui open: ${notifyUrl(runtime.status().url ?? "")}`, "info"); } pi.registerCommand("ui", { description: "Start or control the browser UI runtime. Usage: /ui [off|status|open|qr]", getArgumentCompletions(prefix) { const trimmed = prefix.trimStart(); return COMMANDS.filter((item) => item.startsWith(trimmed)).map( (value) => ({ value, label: value, }), ); }, async handler(args, ctx) { const command = args.trim(); try { if (!command) return await start(ctx); if (command === "off") return await stop(ctx, "command"); if (command === "status") return status(ctx); if (command === "open") return await open(ctx); if (command === "qr") return await redrawQr(ctx); throw uiError( "runtime_not_active", `Unknown /ui subcommand: ${command}`, { action: "Use /ui, /ui off, /ui status, /ui open, or /ui qr.", retryable: true, }, ); } catch (error) { ctx.ui.notify(formatError(error), "error"); setWidget(ctx); } }, }); pi.on("session_shutdown", async (_event, ctx) => { await stop(ctx, "session shutdown"); }); function status(ctx: ExtensionCommandContext): void { if (!runtime) { ctx.ui.notify("ui inactive", "info"); return; } const current = runtime.status(); ctx.ui.notify( `ui ${current.state}: ${notifyUrl(current.url ?? "")}`, "info", ); setWidget(ctx); } async function open(ctx: ExtensionCommandContext): Promise<void> { if (!runtime) throw inactiveError(); await runtime.open(); ctx.ui.notify("ui open requested", "info"); } async function redrawQr(ctx: ExtensionCommandContext): Promise<void> { if (!runtime) throw inactiveError(); await runtime.redrawQr(); setWidget(ctx); }}function sessionLabel(pi: ExtensionAPI, ctx: ExtensionContext): string { const name = pi.getSessionName() ?? path.basename(ctx.cwd); return `ui: ${name || "session"}`;}export function notifyUrl(value: string): string { if (!value) return ""; const url = new URL(value); url.search = ""; url.hash = ""; return url.toString();}function inactiveError(): UiError { return uiError("runtime_not_active", "UI runtime is not active", { action: "Run /ui first.", retryable: true, });}function formatError(error: unknown): string { if (isUiError(error)) return humanError(error); return error instanceof Error ? error.message : String(error);}function isUiError(error: unknown): error is UiError { return ( error instanceof Error && "code" in error && "action" in error && "retryable" in error );}deleted file mode 100644+0 / −69 text lines
import type { UiEventInput } from "./protocol";export type LifecycleTrackerOptions = { now?: () => number; heartbeatMs?: number;};export class LifecycleTracker { readonly #now: () => number; readonly #heartbeatMs: number; #clients = new Map<string, number>(); #reported = new Set<string>(); constructor(options: LifecycleTrackerOptions = {}) { this.#now = options.now ?? Date.now; this.#heartbeatMs = options.heartbeatMs ?? 15_000; } heartbeat(clientId: string, at = this.#now()): void { this.#clients.set(clientId, at); this.#reported.delete(clientId); } check(): UiEventInput[] { const now = this.#now(); const events: UiEventInput[] = []; for (const [clientId, at] of this.#clients) { if (now - at <= this.#heartbeatMs || this.#reported.has(clientId)) continue; events.push(lifecycleError(clientId, "browser heartbeat lost")); this.#reported.add(clientId); } return events; } close(clientId: string): UiEventInput { this.#clients.delete(clientId); return lifecycleError(clientId, "browser websocket closed"); } pagehide(clientId: string): UiEventInput { return lifecycleError(clientId, "browser page hidden/unloaded"); } stale(clientId: string): UiEventInput { return lifecycleError(clientId, "browser client stale"); } reconnect(clientId: string): UiEventInput { this.heartbeat(clientId); return { type: "log", level: "info", message: `browser reconnected: ${clientId}`, }; }}function lifecycleError(clientId: string, message: string): UiEventInput { return { type: "error", message, action: "reload /ui browser tab or run /ui open", retryable: true, clientId, agentHint: "wait for browser reconnect before relying on widget interaction", };}deleted file mode 100644+0 / −4 text lines
deleted file mode 100644+0 / −30 text lines
import { type NetworkInterfaceInfo, networkInterfaces } from "node:os";export type InterfaceMap = Record<string, NetworkInterfaceInfo[] | undefined>;export function chooseLanAddress( interfaces: InterfaceMap = networkInterfaces(),): string { const candidates = Object.values(interfaces) .flatMap((items) => items ?? []) .filter((item) => item.family === "IPv4" && !item.internal) .map((item) => item.address) .sort((a, b) => scoreAddress(b) - scoreAddress(a)); return candidates[0] ?? "127.0.0.1";}export function listenHostFor(address: string): string { return address === "127.0.0.1" ? "127.0.0.1" : "0.0.0.0";}export function uiUrl(address: string, port: number, token: string): string { return `http://${address}:${port}/?token=${encodeURIComponent(token)}`;}function scoreAddress(address: string): number { if (address.startsWith("192.168.")) return 30; if (address.startsWith("10.")) return 20; if (/^172\.(1[6-9]|2\d|3[01])\./.test(address)) return 10; return 1;}deleted file mode 100644+0 / −65 text lines
import { spawn } from "node:child_process";import { uiError } from "./errors";export type OpenerCandidate = { command: string; args: string[]; windowsHide?: boolean;};export function openerCandidates( url: string, options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},): OpenerCandidate[] { const platform = options.platform ?? process.platform; const env = options.env ?? process.env; if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }]; if (platform === "darwin") return [{ command: "open", args: [url] }]; if (platform === "win32") { return [{ command: "explorer.exe", args: [url], windowsHide: true }]; } return [ { command: "xdg-open", args: [url] }, { command: "wslview", args: [url] }, { command: "gio", args: ["open", url] }, ];}export async function openBrowser(url: string): Promise<void> { if ( process.env.NODE_ENV === "test" || process.env.VITEST || process.env.PI_UI_NO_AUTO_OPEN === "1" ) return; for (const candidate of openerCandidates(url)) { if (await trySpawn(candidate.command, candidate.args)) return; } throw uiError("open_failed", "Could not open browser", { action: "Open the /ui link manually from the terminal widget or scan the QR code.", retryable: true, });}function trySpawn(command: string, args: string[]): Promise<boolean> { return new Promise((resolve) => { const child = spawn(command, args, { detached: true, stdio: "ignore", windowsHide: true, }); let settled = false; const done = (ok: boolean) => { if (settled) return; settled = true; resolve(ok); }; child.once("error", () => done(false)); child.once("spawn", () => { child.unref(); done(true); }); setTimeout(() => done(false), 1500).unref(); });}deleted file mode 100644+0 / −35 text lines
{ "name": "@bugabinga/pi-ext-ui", "type": "module", "main": "index.ts", "scripts": { "test": "vitest run ./__tests__/*.test.ts" }, "dependencies": { "@types/ws": "^8.18.1", "pierre": "^2.1.16", "qrcode": "^1.5.4", "shiki": "^4.3.0", "ws": "^8.21.0" }, "peerDependencies": { "@earendil-works/pi-coding-agent": "*", "@earendil-works/pi-tui": "*", "typebox": "*" }, "license": "MIT", "description": "Browser UI runtime shell for Pi.", "keywords": [ "pi", "pi-extension", "ui" ], "devDependencies": { "@marcfargas/pi-test-harness": "^0.6.1", "@playwright/test": "^1.61.0", "@types/qrcode": "^1.5.5", "tsx": "^4.20.6", "vitest": "^4.1.9" }, "private": true}deleted file mode 100644+0 / −12 text lines
deleted file mode 100644+0 / −124 text lines
export type UiConnectionStatus = | "starting" | "waiting" | "connected" | "inactive" | "rpc-starting" | "rpc-connected" | "rpc-dead" | "error" | "stopped";export type UiEventBase = { id: number; at: number;};export type UiStateEvent = UiEventBase & { type: "state"; state: UiConnectionStatus; message?: string;};export type UiLogEvent = UiEventBase & { type: "log"; level: "info" | "warning" | "error"; message: string;};export type UiMessageEvent = UiEventBase & { type: "message"; role: "user" | "assistant" | "tool" | "system"; text: string; streamId?: string;};export type UiToolEvent = UiEventBase & { type: "tool"; phase: "start" | "update" | "end"; toolCallId: string; name: string; text?: string; isError?: boolean;};export type UiErrorEvent = UiEventBase & { type: "error"; message: string; action: string; retryable: boolean; clientId?: string; agentHint?: string; relatedId?: string;};export type UiRequestEvent = UiEventBase & { type: "ui_request"; requestId: string; method: "select" | "confirm" | "input" | "editor"; title: string; message: string; options?: string[]; placeholder?: string; prefill?: string; expectsResponse: true;};export type UiNotifyEvent = UiEventBase & { type: "ui_notify"; requestId: string; message: string; notifyType?: "info" | "warning" | "error";};export type UiStatusEvent = UiEventBase & { type: "ui_status" | "ui_title" | "ui_widget" | "ui_editor_text"; requestId: string; message: string; [key: string]: unknown;};export type UiWidgetEvent = UiEventBase & { type: "widget_mount" | "widget_update" | "widget_action" | "widget_error"; widgetId: string; toolCallId?: string; title?: string; fallback?: string; html?: string; status?: "mounted" | "updated" | "action" | "error"; actionId?: string; label?: string; payload?: unknown; message?: string;};export type UiEvent = | UiStateEvent | UiLogEvent | UiMessageEvent | UiToolEvent | UiErrorEvent | UiRequestEvent | UiNotifyEvent | UiStatusEvent | UiWidgetEvent;export type UiEventInput = UiEvent extends infer Event ? Event extends UiEventBase ? Omit<Event, keyof UiEventBase> : never : never;export type UiCommandInfo = { name: string; description?: string;};export type UiSnapshot = { version: 1; lastEventId: number; status: UiConnectionStatus; sessionPath?: string; commands: UiCommandInfo[]; events: UiEvent[];};deleted file mode 100644+0 / −18 text lines
import QRCode from "qrcode";import { uiError } from "./errors";export async function renderQr(url: string): Promise<string> { try { return await QRCode.toString(url, { type: "terminal", small: true, margin: 1, }); } catch (cause) { throw uiError("qr_failed", "Could not render terminal QR code", { action: "Use the OSC link in the /ui widget instead.", retryable: true, cause, }); }}deleted file mode 100644+0 / −199 text lines
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";import { randomUUID } from "node:crypto";import { once } from "node:events";export type RpcState = "starting" | "connected" | "slow-start" | "exit";export type RpcResponse = { id?: string; type: "response"; command?: string; success: boolean; data?: unknown; error?: string;};export type RpcRequest = Record<string, unknown> & { id?: string; type: string;};export type ParsedJsonLines = { messages: unknown[]; rest: string;};export type StartRpcOptions = { sessionPath: string; cwd: string; command?: string; args?: string[]; env?: NodeJS.ProcessEnv; requestTimeoutMs?: number; slowStartMs?: number; onEvent?: (event: unknown) => void; onState?: (state: RpcState, details?: unknown) => void;};export type RpcClient = { child: ChildProcessWithoutNullStreams; send(request: RpcRequest): Promise<RpcResponse>; stderr(): string; close(reason: string): Promise<void>;};export type RpcSpawnPlan = { command: string; args: string[]; windowsHide?: boolean;};type Pending = { resolve(response: RpcResponse): void; reject(error: Error): void; timer: NodeJS.Timeout;};export function parseJsonLines(input: string): ParsedJsonLines { const messages: unknown[] = []; const parts = input.split("\n"); const rest = parts.pop() ?? ""; for (const raw of parts) { const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw; if (!line) continue; messages.push(JSON.parse(line)); } return { messages, rest };}export function startRpc(options: StartRpcOptions): RpcClient { const command = options.command ?? process.env.PI_UI_RPC_BIN ?? defaultPiBin(); const args = options.args ?? [ "--mode", "rpc", "--session", options.sessionPath, ]; const spawnPlan = rpcSpawnPlan(command, args); const child = spawn(spawnPlan.command, spawnPlan.args, { cwd: options.cwd, env: { ...process.env, ...options.env }, stdio: "pipe", windowsHide: spawnPlan.windowsHide, }); const pending = new Map<string, Pending>(); const stderrChunks: string[] = []; let stdoutRest = ""; let closed = false; let connected = false; const timeoutMs = options.requestTimeoutMs ?? 30_000; const slowTimer = setTimeout(() => { if (!connected && !closed) options.onState?.("slow-start"); }, options.slowStartMs ?? 8_000); child.stdout.on("data", (chunk) => { const parsed = parseJsonLines(stdoutRest + String(chunk)); stdoutRest = parsed.rest; for (const message of parsed.messages) handleMessage(message); }); child.stderr.on("data", (chunk) => { stderrChunks.push(String(chunk)); }); child.once("spawn", () => options.onState?.("starting")); child.once("exit", (code, signal) => { closed = true; clearTimeout(slowTimer); const error = new Error( `RPC process exited: code=${code ?? "null"} signal=${signal ?? "null"}`, ); for (const item of pending.values()) { clearTimeout(item.timer); item.reject(error); } pending.clear(); options.onState?.("exit", { code, signal }); }); function handleMessage(message: unknown): void { connected = true; options.onState?.("connected"); if (isResponse(message) && message.id && pending.has(message.id)) { const item = pending.get(message.id); if (!item) return; pending.delete(message.id); clearTimeout(item.timer); item.resolve(message); return; } options.onEvent?.(message); } return { child, send(request) { if (closed) return Promise.reject(new Error("RPC process is closed")); const id = request.id ?? randomUUID(); const payload = { ...request, id }; return new Promise((resolve, reject) => { const timer = setTimeout(() => { pending.delete(id); reject(new Error(`RPC request timed out: ${request.type}`)); }, timeoutMs); pending.set(id, { resolve, reject, timer }); child.stdin.write(`${JSON.stringify(payload)}\n`, (error) => { if (!error) return; pending.delete(id); clearTimeout(timer); reject(error); }); }); }, stderr: () => stderrChunks.join(""), async close(reason) { void reason; if (closed) return; closed = true; clearTimeout(slowTimer); for (const item of pending.values()) { clearTimeout(item.timer); item.reject(new Error("RPC process closed")); } pending.clear(); child.kill(); await Promise.race([ once(child, "exit"), new Promise((resolve) => setTimeout(resolve, 1000)), ]); }, };}function isResponse(value: unknown): value is RpcResponse { return ( !!value && typeof value === "object" && (value as { type?: unknown }).type === "response" );}export function rpcSpawnPlan( command: string, args: string[], platform: NodeJS.Platform = process.platform,): RpcSpawnPlan { if (platform === "win32" && command.toLowerCase().endsWith(".cmd")) { return { command: "cmd.exe", args: ["/d", "/s", "/c", command, ...args], windowsHide: true, }; } return { command, args, windowsHide: platform === "win32" };}function defaultPiBin(): string { return process.platform === "win32" ? "pi.cmd" : "pi";}deleted file mode 100644+0 / −444 text lines
import { mkdirSync, writeFileSync } from "node:fs";import path from "node:path";import { abortCurrent, cycleModel, runBash, runSlashCommand, sendPrompt,} from "./command-adapter";import { parseComposerInput } from "./composer";import { EventStore } from "./events";import { extensionUiEventFromRequest, extensionUiResponseCommand, isExtensionUiRequest,} from "./extension-ui";import { LifecycleTracker } from "./lifecycle";import { chooseLanAddress } from "./network";import { openBrowser } from "./open";import { renderQr } from "./qr";import { type RpcClient, type StartRpcOptions, startRpc } from "./rpc";import { startUiServer, type UiServer, type UiServerState } from "./server";import { seedUiSession, type UiSeedSessionManager } from "./session-seed";import { TelemetryAggregator, type TelemetryEvent } from "./telemetry";import { renderUiWidget } from "./terminal-widget";export type UiRuntimeStatus = { active: boolean; url?: string; state: UiServerState | "starting" | "stopped" | "error"; clients: number; rpcState?: string; sessionPath?: string; lastError?: string;};export type UiRuntime = { status(): UiRuntimeStatus; widgetLines(): string[]; redrawQr(): Promise<void>; open(): Promise<void>; stop(reason: string): Promise<void>;};export type CreateUiRuntimeOptions = { sessionLabel: string; cwd?: string; address?: string; preferredPort?: number; openBrowser?: boolean; onChange?: () => void; sessionManager?: UiSeedSessionManager; startRpcBridge?: (options: StartRpcOptions) => RpcClient; events?: EventStore;};export async function createUiRuntime( options: CreateUiRuntimeOptions,): Promise<UiRuntime> { let state: UiRuntimeStatus = { active: false, state: "starting", clients: 0 }; let qr = ""; let server: UiServer | undefined; let rpc: RpcClient | undefined; let sessionPath: string | undefined; let rpcState: string | undefined; const events = options.events ?? new EventStore(); const telemetry = new TelemetryAggregator(); const lifecycle = new LifecycleTracker(); const lifecycleTimer = setInterval(() => { for (const event of lifecycle.check()) publish(event); }, 5_000); if (typeof lifecycleTimer.unref === "function") lifecycleTimer.unref(); const publish = (input: Parameters<EventStore["append"]>[0]) => { const event = events.append(input); server?.publish(event); return event; }; if (options.sessionManager) { const seed = seedUiSession({ cwd: options.cwd ?? process.cwd(), sessionManager: options.sessionManager, }); sessionPath = seed.path; if (seed.warning) publish({ type: "log", level: "warning", message: seed.warning }); publish({ type: "state", state: "rpc-starting" }); rpcState = "starting"; rpc = (options.startRpcBridge ?? startRpc)({ sessionPath, cwd: options.cwd ?? process.cwd(), onState(next) { rpcState = next; publish({ type: "state", state: mapRpcState(next) }); state = currentStatus(); options.onChange?.(); }, onEvent(event) { const normalized = normalizeRpcEvent(event); if (normalized) publish(normalized); }, }); } const address = options.address ?? chooseLanAddress(); server = await startUiServer({ address, preferredPort: options.preferredPort, events, snapshotStatus: rpcState ? mapRpcState(rpcState) : "waiting", onBrowserMessage: async (message) => { await handleBrowserMessage(message, rpc, publish, telemetry, lifecycle); }, onClientState: () => { state = currentStatus(); options.onChange?.(); }, }); qr = await renderQr(server.publicUrl); writeSmokeUrl(server.publicUrl); state = currentStatus(); if (options.openBrowser !== false) await openBrowser(server.baseUrl); function currentStatus(): UiRuntimeStatus { if (!server) return { active: false, state: "stopped", clients: 0 }; return { active: server.state() !== "stopped", url: server.baseUrl, state: server.state(), clients: server.clients(), rpcState, sessionPath, }; } return { status: () => state, widgetLines: () => { if (!server || !state.url) return []; return renderUiWidget({ url: state.url, qr, state: state.state, sessionLabel: options.sessionLabel, clients: state.clients, rpcState: state.rpcState, sessionPath: state.sessionPath ? path.basename(state.sessionPath) : undefined, lastError: state.lastError, }); }, async redrawQr() { if (!server) return; qr = await renderQr(server.publicUrl); state = currentStatus(); options.onChange?.(); }, async open() { if (!server) return; await openBrowser(server.baseUrl); }, async stop(reason: string) { clearInterval(lifecycleTimer); const currentServer = server; const currentRpc = rpc; server = undefined; rpc = undefined; state = { active: false, state: "stopped", clients: 0 }; options.onChange?.(); await currentRpc?.close(reason); if (currentServer) await currentServer.close(reason); }, };}async function handleBrowserMessage( message: unknown, rpc: RpcClient | undefined, publish: (input: Parameters<EventStore["append"]>[0]) => unknown, telemetry: TelemetryAggregator, lifecycle: LifecycleTracker,): Promise<void> { if (!rpc || !isBrowserMessage(message)) return; if (message.type === "abort") { await abortCurrent(rpc); publish({ type: "state", state: "rpc-connected", message: "abort requested", }); return; } if (message.type === "cycle_model" || message.type === "cycle-model") { await cycleModel(rpc); publish({ type: "state", state: "rpc-connected", message: "model cycle requested", }); return; } if (message.type === "toggle-expand") { publish({ type: "log", level: "info", message: "toggle expand requested" }); return; } if (message.type === "lifecycle_heartbeat") { lifecycle.heartbeat(message.clientId); return; } if (message.type === "lifecycle_reconnect") { publish(lifecycle.reconnect(message.clientId)); return; } if (message.type === "lifecycle_close") { publish(lifecycle.close(message.clientId)); return; } if (message.type === "lifecycle_pagehide") { publish(lifecycle.pagehide(message.clientId)); return; } if (message.type === "telemetry_batch") { for (const event of message.events) telemetry.add(event); publish({ type: "log", level: "info", message: "browser digest will be sent", }); return; } if (message.type === "ui_response") { await rpc.send( extensionUiResponseCommand(message.id, responseInput(message)), ); return; } if (message.type === "widget_action") { publish({ type: "widget_action", widgetId: message.widgetId, label: message.label, payload: message.payload, }); return; } if (message.type === "widget_prompt") { const text = `[widget ${message.widgetId}] ${message.text}`; publish({ type: "widget_action", widgetId: message.widgetId, label: "prompt", payload: { text: message.text }, }); await sendPrompt(rpc, text); return; } if (message.type === "widget_notify") { publish({ type: "ui_notify", requestId: message.widgetId, message: message.message, }); return; } if (message.type === "widget_error") { publish({ type: "widget_error", widgetId: message.widgetId, message: message.message, }); return; } const parsed = parseComposerInput(message.text); if (parsed.kind === "bash") { publish({ type: "message", role: "user", text: message.text }); await runBash(rpc, parsed.command, parsed.excludeFromContext); return; } if (parsed.kind === "slash") { publish({ type: "message", role: "user", text: parsed.text }); await runSlashCommand(rpc, parsed.command, parsed.args); return; } publish({ type: "message", role: "user", text: parsed.text }); await sendPrompt(rpc, parsed.text, { digest: () => telemetry.digest(), clearDigest: () => telemetry.clear(), });}type BrowserMessage = | { type: "prompt"; text: string } | { type: "abort" } | { type: "cycle_model" } | { type: "cycle-model" } | { type: "toggle-expand" } | { type: "telemetry_batch"; events: TelemetryEvent[] } | { type: "lifecycle_heartbeat"; clientId: string } | { type: "lifecycle_reconnect"; clientId: string } | { type: "lifecycle_close"; clientId: string } | { type: "lifecycle_pagehide"; clientId: string } | ({ type: "ui_response"; id: string } & ( | { value: string } | { confirmed: boolean } | { cancelled: true } )) | { type: "widget_action"; widgetId: string; label: string; payload?: unknown; } | { type: "widget_prompt"; widgetId: string; text: string } | { type: "widget_notify"; widgetId: string; message: string } | { type: "widget_error"; widgetId: string; message: string };function isBrowserMessage(value: unknown): value is BrowserMessage { if (!value || typeof value !== "object") return false; const type = (value as { type?: unknown }).type; if (type === "prompt") return typeof (value as { text?: unknown }).text === "string"; if (type === "telemetry_batch") return Array.isArray((value as { events?: unknown }).events); if ( type === "lifecycle_heartbeat" || type === "lifecycle_reconnect" || type === "lifecycle_close" || type === "lifecycle_pagehide" ) return typeof (value as { clientId?: unknown }).clientId === "string"; if (type === "ui_response") return typeof (value as { id?: unknown }).id === "string"; if (type === "widget_action") return ( typeof (value as { widgetId?: unknown }).widgetId === "string" && typeof (value as { label?: unknown }).label === "string" ); if (type === "widget_prompt") return ( typeof (value as { widgetId?: unknown }).widgetId === "string" && typeof (value as { text?: unknown }).text === "string" ); if (type === "widget_notify" || type === "widget_error") return ( typeof (value as { widgetId?: unknown }).widgetId === "string" && typeof (value as { message?: unknown }).message === "string" ); return ( type === "abort" || type === "cycle_model" || type === "cycle-model" || type === "toggle-expand" );}function responseInput( message: Extract<BrowserMessage, { type: "ui_response" }>,) { if ("value" in message) return { value: message.value }; if ("confirmed" in message) return { confirmed: message.confirmed }; return { cancelled: true as const };}function writeSmokeUrl(url: string): void { const target = process.env.PI_UI_SMOKE_URL_FILE; if (!target) return; mkdirSync(path.dirname(target), { recursive: true }); writeFileSync(target, `${url}\n`, { encoding: "utf8" });}function mapRpcState(state: string) { if (state === "connected") return "rpc-connected"; if (state === "exit") return "rpc-dead"; return "rpc-starting";}export function normalizeRpcEvent( event: unknown,): Parameters<EventStore["append"]>[0] | undefined { if (isExtensionUiRequest(event)) return extensionUiEventFromRequest(event); if (isRpcMessageUpdate(event)) { return { type: "message", role: "assistant", text: assistantText(event.message), streamId: "assistant-stream", }; } if (isRpcToolEvent(event)) { return { type: "tool", phase: event.type.endsWith("start") ? "start" : event.type.endsWith("end") ? "end" : "update", toolCallId: event.toolCallId, name: event.toolName, }; } return undefined;}function assistantText(message: unknown): string { if (!message || typeof message !== "object") return ""; const content = (message as { content?: unknown }).content; if (!Array.isArray(content)) return ""; return content .map((item) => item && typeof item === "object" && typeof (item as { text?: unknown }).text === "string" ? (item as { text: string }).text : "", ) .join("");}function isRpcMessageUpdate( event: unknown,): event is { message: unknown; assistantMessageEvent: { delta: string } } { return ( !!event && typeof event === "object" && (event as { type?: unknown }).type === "message_update" && typeof (event as { assistantMessageEvent?: { delta?: unknown } }) .assistantMessageEvent?.delta === "string" );}function isRpcToolEvent( event: unknown,): event is { type: string; toolCallId: string; toolName: string } { return ( !!event && typeof event === "object" && typeof (event as { type?: unknown }).type === "string" && (event as { type: string }).type.startsWith("tool_execution_") && typeof (event as { toolCallId?: unknown }).toolCallId === "string" && typeof (event as { toolName?: unknown }).toolName === "string" );}deleted file mode 100644+0 / −87 text lines
#!/usr/bin/env nodeimport { existsSync, mkdirSync, writeFileSync } from "node:fs";import { resolve } from "node:path";import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";import { chromium } from "@playwright/test";import { createUiRuntime } from "../runtime.js";const args = new Set(process.argv.slice(2));const noBrowser = args.has("--no-browser");const outDir = resolve( process.cwd(), CONFIG_DIR_NAME, "tmp", "ui-phase1-smoke",);const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe";mkdirSync(outDir, { recursive: true });const runtime = await createUiRuntime({ sessionLabel: "ui: phase1-smoke", address: "127.0.0.1", cwd: process.cwd(), openBrowser: false,});try { const status = runtime.status(); if (!status.url) throw new Error("UI runtime did not expose a URL"); const url = status.url; const parsed = new URL(url); const tokenless = await fetch(`${parsed.origin}/api/status`); if (tokenless.status !== 401) throw new Error( `Expected tokenless /api/status 401, got ${tokenless.status}`, ); const shell = await fetch(url); if (!shell.ok) throw new Error(`Bare root shell failed: ${shell.status}`); const cookie = shell.headers.get("set-cookie") ?? ""; const authorized = await fetch(`${parsed.origin}/api/status`, { headers: { cookie }, }); if (!authorized.ok) throw new Error(`Authorized /api/status failed: ${authorized.status}`); let browserText = "skipped"; if (!noBrowser) browserText = await verifyBrowser(url); const summary = { url: redactUrl(url), state: status.state, tokenlessStatus: tokenless.status, authorizedStatus: authorized.status, browserText, }; const summaryPath = resolve(outDir, "summary.json"); writeFileSync(summaryPath, `${JSON.stringify(summary, null, "\t")}\n`); console.log(`url: ${summary.url}`); console.log(`summary: ${summaryPath}`);} finally { await runtime.stop("phase1 smoke complete");}async function verifyBrowser(url) { const browser = await chromium.launch({ headless: true, executablePath: existsSync(chromePath) ? chromePath : undefined, }); try { const page = await browser.newPage(); await page.goto(url); await page.waitForSelector("#ui-shell"); await page.waitForSelector("#ui-composer"); return await page.locator("#ui-progress").innerText(); } finally { await browser.close(); }}function redactUrl(value) { const tokenParam = "token" + "="; return value.replace( new RegExp(`${tokenParam}[A-Za-z0-9_-]+`), `${tokenParam}[redacted]`, );}deleted file mode 100644+0 / −38 text lines
#!/usr/bin/env nodeimport { spawnSync } from "node:child_process";if (process.platform === "win32") { console.error( "tmux-smoke is disabled on win32. Use scripts/zellij-smoke.mjs.", ); process.exit(2);}const tmux = process.env.TMUX_BIN ?? "tmux";const session = "ui-" + "smoke-" + Date.now().toString(36);run(tmux, ["-V"]);run(tmux, ["new-session", "-d", "-s", session, "pi -e extensions/ui/index.ts"]);console.log(`tmux session: ${session}`);console.log(`attach: ${tmux} attach -t ${session}`);console.log("manual checkpoints:");console.log("1. Send /ui and verify terminal widget shows URL + QR.");console.log( "2. Open URL in browser; verify exact URL works and /api/status without token returns 401.",);console.log( "3. Try /, /skill:, !, !!, Esc, Ctrl+O, Ctrl+P, card/form/raw widget, click widget action.",);console.log( "4. Scroll/click/select/background/return/send next prompt; verify digest appears once.",);console.log( "5. Send /ui off; verify browser disconnect and terminal UI restored as far as Pi exposes.",);console.log(`kill: ${tmux} kill-session -t ${session}`);function run(command, args) { const result = spawnSync(command, args, { stdio: "inherit", shell: false }); if (result.status !== 0) process.exit(result.status ?? 1);}deleted file mode 100644+0 / −269 text lines
#!/usr/bin/env nodeimport { spawnSync } from "node:child_process";import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync,} from "node:fs";import { resolve } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";if (process.platform !== "win32") { console.error( "zellij-smoke is the win32 smoke path. Use scripts/tmux-smoke.mjs on non-win32.", ); process.exit(2);}const args = new Set(process.argv.slice(2));const noBrowser = args.has("--no-browser");const noFallback = args.has("--no-fallback");const zellij = process.env.ZELLIJ ?? "zellij";const pi = process.env.PI_UI_SMOKE_PI ?? "pi.cmd";const session = process.env.PI_UI_SMOKE_SESSION ?? `ui-smoke-${Date.now().toString(36)}`;const cwd = process.cwd();const outDir = resolve(cwd, CONFIG_DIR_NAME, "tmp", "ui-zellij-smoke");const screenPath = resolve(outDir, `${session}.screen.txt`);const urlPath = resolve(outDir, `${session}.url.txt`);const env = { ...process.env, ZELLIJ_SESSION_NAME: session, MSYS_NO_PATHCONV: "1",};mkdirSync(outDir, { recursive: true });console.log(`zellij session: ${session}`);console.log(`cwd: ${cwd}`);run(zellij, ["--version"]);startZellijSession();await waitForSession();const pane = "terminal_0";console.log(`pane: ${pane}`);sendLine(pane, `cd /d ${cwd}`);await sleep(500);sendLine( pane, `set PI_UI_NO_AUTO_OPEN=1&& set "PI_UI_SMOKE_URL_FILE=${urlPath}"&& ${pi} -e extensions/ui/index.ts`,);await waitForPiReady(pane);sendLine(pane, "/ui");await waitForUiUrl(pane, screenPath);const firstScreen = safeRead(screenPath);const url = safeRead(urlPath).trim() || extractUiUrl(firstScreen);if (!url) { const fallback = noFallback ? { status: "skipped" } : runPhase1Fallback(); writeSummary({ session, pane, screenPath, url: undefined, status401: undefined, zellijAutomation: "url-not-found", fallback, }); console.error(`No /ui URL found in ${screenPath}.`); console.error(`attach: ${zellij} attach ${session}`); console.error(`kill: ${zellij} kill-session ${session}`); if (fallback.status === "passed") process.exit(0); process.exit(1);}const status401 = await probe401(url);console.log(`url: ${redactUrl(url)}`);console.log(`tokenless /api/status: ${status401}`);if (status401 !== 401) { console.error("Expected tokenless /api/status to return 401.");}let browserText = "skipped";if (!noBrowser) { browserText = await verifyBrowser(url); openBrowser(url);}rmSync(urlPath, { force: true });await sleep(2_000);sendLine(pane, "/ui off");await sleep(3_000);dump(pane, screenPath);writeSummary({ session, pane, screenPath, url: redactUrl(url), status401, browserText,});console.log(`screen: ${screenPath}`);console.log(`attach: ${zellij} attach ${session}`);console.log(`kill: ${zellij} kill-session ${session}`);if (status401 !== 401) process.exit(1);function startZellijSession() { const psCommand = [ "Start-Process", "-FilePath", quoteForPowerShell(zellij), "-ArgumentList", `@('attach','--create-background','${session.replaceAll("'", "''")}')`, "-WindowStyle", "Minimized", ].join(" "); run("powershell.exe", ["-NoLogo", "-NoProfile", "-Command", psCommand]);}async function waitForSession() { for (let attempt = 0; attempt < 20; attempt += 1) { const sessions = runCapture(zellij, ["list-sessions"], { allowFailure: true, }); if (sessions.includes(session)) return; await sleep(500); } throw new Error(`zellij session did not start: ${session}`);}function quoteForPowerShell(value) { return `'${value.replaceAll("'", "''")}'`;}async function waitForPiReady(paneId) { for (let attempt = 0; attempt < 40; attempt += 1) { dump(paneId, screenPath); const screen = safeRead(screenPath); if (screen.includes("builtin-tools") && screen.includes("gpt-")) return; await sleep(1_000); } throw new Error("Pi did not become ready in zellij pane");}async function waitForUiUrl(paneId, path) { for (let attempt = 0; attempt < 40; attempt += 1) { dump(paneId, path); if (safeRead(urlPath).trim() || extractUiUrl(safeRead(path))) return; await sleep(1_000); }}function sendLine(paneId, line) { const paneArgs = paneId ? ["-p", paneId] : []; run(zellij, ["action", "write-chars", ...paneArgs, line], { env }); run(zellij, ["action", "send-keys", ...paneArgs, "Enter"], { env });}function dump(paneId, path) { const paneArgs = paneId ? ["-p", paneId] : []; run(zellij, ["action", "dump-screen", ...paneArgs, "--path", path], { env });}async function probe401(uiUrl) { const parsed = new URL(uiUrl); const response = await fetch(`${parsed.origin}/api/status`); return response.status;}async function verifyBrowser(url) { const chromePath = "C:/Program Files/Google/Chrome/Application/chrome.exe"; const { chromium } = await import("@playwright/test"); const browser = await chromium.launch({ headless: true, executablePath: existsSync(chromePath) ? chromePath : undefined, }); try { const page = await browser.newPage(); await page.goto(url); await page.waitForSelector("#ui-shell"); await page.waitForSelector("#ui-composer"); return await page.locator("#ui-progress").innerText(); } finally { await browser.close(); }}function openBrowser(url) { spawnSync("cmd.exe", ["/d", "/s", "/c", "start", "", url], { stdio: "ignore", detached: true, });}function extractUiUrl(text) { const tokenParam = "token" + "="; return text .split(/\s+/) .find((part) => part.startsWith("http://") && part.includes(tokenParam));}function redactUrl(value) { const tokenParam = "token" + "="; return value.replace( new RegExp(`${tokenParam}[A-Za-z0-9_-]+`), `${tokenParam}[redacted]`, );}function safeRead(path) { try { return readFileSync(path, "utf8"); } catch { return ""; }}function runPhase1Fallback() { console.error( "Running Phase 1 browser smoke fallback outside zellij pane automation.", ); const commandArgs = [ "--import", "tsx", "extensions/ui/scripts/phase1-smoke.mjs", ]; if (noBrowser) commandArgs.push("--no-browser"); const result = spawnSync(process.execPath, commandArgs, { stdio: "inherit", shell: false, timeout: 120_000, }); return { status: result.status === 0 ? "passed" : "failed", exitCode: result.status, };}function writeSummary(summary) { const path = resolve(outDir, `${session}.summary.json`); writeFileSync(path, `${JSON.stringify(summary, null, "\t")}\n`); console.log(`summary: ${path}`);}function run(command, commandArgs, options = {}) { const result = spawnSync(command, commandArgs, { stdio: "inherit", shell: false, timeout: 60_000, ...options, }); if (result.status !== 0) process.exit(result.status ?? 1);}function runCapture(command, commandArgs, options = {}) { const { allowFailure, ...spawnOptions } = options; const result = spawnSync(command, commandArgs, { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], shell: false, timeout: 60_000, ...spawnOptions, }); if (!allowFailure && result.status !== 0) process.exit(result.status ?? 1); return result.stdout ?? "";}deleted file mode 100644+0 / −298 text lines
import { randomBytes } from "node:crypto";import { createServer, type IncomingMessage, type Server, type ServerResponse,} from "node:http";import { type WebSocket, WebSocketServer } from "ws";import type { EventStore } from "./events";import { listenHostFor, uiUrl } from "./network";import type { UiCommandInfo, UiConnectionStatus, UiEvent } from "./protocol";import { renderAppCss } from "./web/app.css";import { renderAppHtml } from "./web/app.html";import { renderAppJs } from "./web/app.js";export type UiServerState = "waiting" | "connected" | "inactive" | "stopped";export type UiServer = { baseUrl: string; publicUrl: string; port: number; token: string; state(): UiServerState; clients(): number; publish(event: UiEvent): void; close(reason: string): Promise<void>;};export type StartUiServerOptions = { address: string; token?: string; preferredPort?: number; onClientState?: (state: UiServerState) => void; events?: EventStore; snapshotStatus?: UiConnectionStatus; onBrowserMessage?: (message: unknown) => void | Promise<void>; commands?: UiCommandInfo[];};const COOKIE = "pi_ui_token";const MAX_BODY_BYTES = 1_000_000;export async function startUiServer( options: StartUiServerOptions,): Promise<UiServer> { const token = options.token ?? randomBytes(32).toString("base64url"); const host = listenHostFor(options.address); let currentState: UiServerState = "waiting"; let clientSeq = 0; let closed = false; const sockets = new Set<WebSocket>(); const wss = new WebSocketServer({ noServer: true }); const server = createServer((req, res) => { void dispatch(req, res, { token, events: options.events, snapshotStatus: options.snapshotStatus, commands: options.commands, state: () => currentState, clients: () => sockets.size, setState(next) { currentState = next; options.onClientState?.(next); }, }); }); server.on("upgrade", (req, socket, head) => { const url = new URL(req.url ?? "/", "http://127.0.0.1"); if (url.pathname !== "/ws" || !authorizedUrlOrRequest(url, req, token)) { socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n"); socket.destroy(); return; } wss.handleUpgrade(req, socket, head, (ws) => { const clientId = `client-${++clientSeq}`; sockets.add(ws); currentState = "connected"; options.onClientState?.("connected"); void options.onBrowserMessage?.({ type: "lifecycle_reconnect", clientId, }); const after = Number(url.searchParams.get("after") ?? 0); ws.send( JSON.stringify({ type: "events", events: options.events?.replayAfter(Number.isFinite(after) ? after : 0) ?? [], }), ); ws.on("message", (data) => { try { const message = JSON.parse(String(data)); if ( message && typeof message === "object" && !("clientId" in message) ) { message.clientId = clientId; } void options.onBrowserMessage?.(message); } catch { ws.send(JSON.stringify({ type: "error", message: "invalid json" })); } }); ws.on("close", () => { sockets.delete(ws); currentState = sockets.size > 0 ? "connected" : "inactive"; options.onClientState?.(currentState); void options.onBrowserMessage?.({ type: "lifecycle_close", clientId }); }); }); }); await listen(server, host, options.preferredPort ?? 0); const address = server.address(); if (!address || typeof address === "string") throw new Error("Failed to bind UI server"); const baseUrl = `http://127.0.0.1:${address.port}`; const publicUrl = uiUrl(options.address, address.port, token); return { baseUrl, publicUrl, port: address.port, token, state: () => currentState, clients: () => sockets.size, publish(event) { const payload = JSON.stringify({ type: "events", events: [event] }); for (const ws of sockets) { if (ws.readyState === ws.OPEN) ws.send(payload); } }, async close(reason) { void reason; if (closed) return; closed = true; currentState = "stopped"; options.onClientState?.("stopped"); for (const ws of sockets) ws.close(); sockets.clear(); wss.close(); await closeServer(server); }, };}type RouteContext = { token: string; events?: EventStore; snapshotStatus?: UiConnectionStatus; commands?: UiCommandInfo[]; state(): UiServerState; clients(): number; setState(state: UiServerState): void;};async function dispatch( req: IncomingMessage, res: ServerResponse, ctx: RouteContext,): Promise<void> { try { const url = new URL(req.url ?? "/", "http://127.0.0.1"); setSecurityHeaders(res); if (hasOversizedBody(req)) { return json(res, 413, { error: "body too large" }); } if (req.method === "GET" && url.pathname === "/") { return serveIndex(req, url, res, ctx); } if (!authorized(req, ctx.token)) return serveUnauthorized(res); if (req.method === "GET" && url.pathname === "/assets/app.js") { return text(res, 200, "text/javascript; charset=utf-8", renderAppJs()); } if (req.method === "GET" && url.pathname === "/assets/app.css") { return text(res, 200, "text/css; charset=utf-8", renderAppCss()); } if (req.method === "GET" && url.pathname === "/api/status") { return json(res, 200, { state: ctx.state(), clients: ctx.clients() }); } if (req.method === "GET" && url.pathname === "/api/snapshot") { return json( res, 200, ctx.events?.snapshot({ status: ctx.snapshotStatus ?? ctx.state(), commands: ctx.commands, }) ?? { version: 1, lastEventId: 0, status: ctx.snapshotStatus ?? ctx.state(), commands: ctx.commands ?? [], events: [], }, ); } return json(res, 404, { error: "not found" }); } catch (error) { return json(res, 500, { error: error instanceof Error ? error.message : String(error), }); }}function serveIndex( req: IncomingMessage, url: URL, res: ServerResponse, ctx: RouteContext,): void { void req; void url; res.setHeader( "Set-Cookie", `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`, ); res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(renderAppHtml());}function serveUnauthorized(res: ServerResponse): void { res.statusCode = 401; res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end( "<!doctype html><title>Unauthorized</title><h1>Unauthorized</h1><p>Open the exact /ui link or scan the current QR code again.</p>", );}function authorized(req: IncomingMessage, token: string): boolean { return ( req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token) );}function authorizedUrlOrRequest( url: URL, req: IncomingMessage, token: string,): boolean { return url.searchParams.get("token") === token || authorized(req, token);}function cookieAuthorized(req: IncomingMessage, token: string): boolean { return (req.headers.cookie ?? "") .split(/;\s*/) .some((cookie) => cookie === `${COOKIE}=${token}`);}function hasOversizedBody(req: IncomingMessage): boolean { const length = req.headers["content-length"]; return typeof length === "string" && Number(length) > MAX_BODY_BYTES;}function setSecurityHeaders(res: ServerResponse): void { res.setHeader("X-Content-Type-Options", "nosniff"); res.setHeader("Referrer-Policy", "no-referrer"); res.setHeader("Cross-Origin-Opener-Policy", "same-origin");}function json(res: ServerResponse, status: number, body: unknown): void { text(res, status, "application/json; charset=utf-8", JSON.stringify(body));}function text( res: ServerResponse, status: number, contentType: string, body: string,): void { res.statusCode = status; res.setHeader("Content-Type", contentType); res.end(body);}function listen(server: Server, host: string, port: number): Promise<void> { return new Promise((resolve, reject) => { const onError = (error: NodeJS.ErrnoException) => { server.off("error", onError); reject(error); }; server.once("error", onError); server.listen(port, host, () => { server.off("error", onError); resolve(); }); });}function closeServer(server: Server): Promise<void> { return new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())); });}deleted file mode 100644+0 / −63 text lines
import { uiError } from "./errors";export type UiSeedMethod = "active-branch" | "whole-tree";export type UiSeedResult = { path: string; method: UiSeedMethod; warning?: string;};export type UiSeedSessionManager = { getLeafId(): string | null; getSessionFile(): string | undefined; createBranchedSession(leafId: string): string | undefined;};export type UiSeedOptions = { cwd: string; sessionManager: UiSeedSessionManager; allowWholeTreeFallback?: boolean; forkWholeTree?: (sourcePath: string, cwd: string) => string | undefined;};export const WHOLE_TREE_WARNING = "Whole-tree session fork includes abandoned branches; active LLM context remains branch-clean.";export function seedUiSession(options: UiSeedOptions): UiSeedResult { const leafId = options.sessionManager.getLeafId(); if (!leafId) { throw uiError( "session_seed_failed", "Cannot seed UI session: no active leaf", { action: "Send at least one message in the terminal session, then run /ui again.", retryable: true, }, ); } const branched = options.sessionManager.createBranchedSession(leafId); if (branched) return { path: branched, method: "active-branch" }; if (options.allowWholeTreeFallback) { const source = options.sessionManager.getSessionFile(); const forked = source ? options.forkWholeTree?.(source, options.cwd) : undefined; if (forked) { return { path: forked, method: "whole-tree", warning: WHOLE_TREE_WARNING, }; } } throw uiError("session_seed_failed", "Cannot seed UI session", { action: "Use a persistent terminal session with an active branch, then run /ui again.", retryable: true, });}deleted file mode 100644+0 / −65 text lines
export type TelemetryEvent = | { type: "viewport"; device: string; width: number; height: number } | { type: "scroll"; y: number; dwellMs: number } | { type: "click"; target: string } | { type: "focus" | "blur"; target: string } | { type: "selection"; text: string } | { type: "widget_action"; widgetId: string; label: string } | { type: "form"; formId: string; state: "submit" | "abandon" } | { type: "error"; message: string } | { type: "pagehide" };export type TelemetryAggregatorOptions = { maxEvents?: number;};export class TelemetryAggregator { readonly #maxEvents: number; #events: TelemetryEvent[] = []; constructor(options: TelemetryAggregatorOptions = {}) { this.#maxEvents = options.maxEvents ?? 24; } add(event: TelemetryEvent): void { this.#events.push(redactEvent(event)); while (this.#events.length > this.#maxEvents) this.#events.shift(); } digest(): string { if (this.#events.length === 0) return ""; return ["Browser digest:", ...this.#events.map(formatEvent)].join("\n"); } clear(): void { this.#events = []; }}export function redactText(text: string): string { return text ? `[redacted ${text.length} chars]` : "";}function redactEvent(event: TelemetryEvent): TelemetryEvent { if (event.type === "selection") return { ...event, text: redactText(event.text) }; if (event.type === "error") return { ...event, message: redactText(event.message) }; return event;}function formatEvent(event: TelemetryEvent): string { if (event.type === "viewport") return `- viewport ${event.device} ${event.width}x${event.height}`; if (event.type === "scroll") return `- scroll y=${event.y} dwell=${event.dwellMs}ms`; if (event.type === "click") return `- click ${event.target}`; if (event.type === "focus") return `- focus ${event.target}`; if (event.type === "blur") return `- blur ${event.target}`; if (event.type === "selection") return `- selection ${event.text}`; if (event.type === "widget_action") return `- widget ${event.widgetId} action ${event.label}`; if (event.type === "form") return `- form ${event.formId} ${event.state}`; if (event.type === "error") return `- error ${event.message}`; return "- pagehide";}deleted file mode 100644+0 / −77 text lines
import path from "node:path";import type { UiServerState } from "./server";export type WidgetState = { url: string; qr: string; state: UiServerState | "starting" | "error"; sessionLabel: string; clients: number; rpcState?: string; sessionPath?: string; lastError?: string;};const WIDTH = 64;const CONTENT_WIDTH = WIDTH - 4;const OSC8_RE = /\u001b]8;;.*?\u001b\\|\u001b]8;;\u001b\\/g;export function osc8Link(url: string, label: string): string { return `\u001b]8;;${url}\u001b\\${label}\u001b]8;;\u001b\\`;}export function renderUiWidget(state: WidgetState): string[] { const session = state.sessionPath ? path.basename(state.sessionPath) : "pending"; const rows = [ "pi ui", osc8Link(state.url, "open browser ui"), `url: ${urlWithoutParams(state.url)}`, `session: ${state.sessionLabel}`, `state: ${state.state} · clients: ${state.clients} · rpc: ${state.rpcState ?? "not-started"}`, `file: ${session}`, "press ESC to stop · /ui off · mobile QR: /ui qr", ]; if (state.lastError) rows.push(`error: ${state.lastError}`); return [top(), ...rows.flatMap(row), bottom()];}function top(): string { return `┏${"━".repeat(WIDTH - 2)}┓`;}function bottom(): string { return `┗${"━".repeat(WIDTH - 2)}┛`;}function row(content: string): string[] { return wrap(content).map( (part) => `┃ ${part}${" ".repeat(Math.max(0, CONTENT_WIDTH - visibleLength(part)))} ┃`, );}function wrap(content: string): string[] { if (visibleLength(content) <= CONTENT_WIDTH) return [content]; const parts: string[] = []; let rest = content; while (visibleLength(rest) > CONTENT_WIDTH) { parts.push(rest.slice(0, CONTENT_WIDTH)); rest = rest.slice(CONTENT_WIDTH); } if (rest) parts.push(rest); return parts;}function visibleLength(content: string): number { return content.replace(OSC8_RE, "").length;}function urlWithoutParams(value: string): string { const url = new URL(value); url.search = ""; url.hash = ""; return url.toString();}deleted file mode 100644+0 / −101 text lines
import { defineTool, type ToolDefinition,} from "@earendil-works/pi-coding-agent";import { Type } from "typebox";import type { UiWidgetEvent } from "./protocol";import { WidgetStore } from "./widget-state";export type VisualToolsOptions = { store?: WidgetStore; publish?: (event: UiWidgetEvent) => void;};const mountParams = Type.Object({ title: Type.String(), fallback: Type.String(), html: Type.String(),});const updateParams = Type.Object({ widgetId: Type.String(), html: Type.String(),});const waitParams = Type.Object({ widgetId: Type.String(), prompt: Type.Optional(Type.String()),});export function createVisualTools( options: VisualToolsOptions = {},): ToolDefinition[] { const store = options.store ?? new WidgetStore(); return [ mountTool("ui_card", "Card", store, options.publish), mountTool("ui_table", "Table", store, options.publish), mountTool("ui_diagram", "Diagram", store, options.publish), mountTool("ui_form", "Form", store, options.publish), mountTool("ui_mockup", "Mockup", store, options.publish), mountTool("ui_html", "HTML", store, options.publish), defineTool({ name: "ui_update", label: "UI Update", description: "Update an existing trusted UI widget by id.", parameters: updateParams, async execute(_toolCallId, params) { const event = store.update(params.widgetId, { html: params.html }); options.publish?.(event); return { content: [{ type: "text", text: `Updated ${params.widgetId}` }], details: event, }; }, }), defineTool({ name: "ui_wait_action", label: "UI Wait Action", description: "Declare that the agent is waiting for a visible action from a trusted UI widget.", parameters: waitParams, async execute(_toolCallId, params) { return { content: [ { type: "text", text: `Waiting for action from ${params.widgetId}${params.prompt ? `: ${params.prompt}` : ""}`, }, ], details: params, }; }, }), ];}function mountTool( name: string, label: string, store: WidgetStore, publish: ((event: UiWidgetEvent) => void) | undefined,): ToolDefinition { return defineTool({ name, label: `UI ${label}`, description: `Render a trusted ${label.toLowerCase()} widget in the browser UI stream.`, parameters: mountParams, async execute(toolCallId, params) { const event = store.mount({ toolCallId, title: params.title, fallback: params.fallback, html: params.html, }); publish?.(event); return { content: [{ type: "text", text: params.fallback }], details: event, }; }, });}deleted file mode 100644+0 / −36 text lines
import { renderThemeCss } from "./theme.css.js";export function renderAppCss(): string { return `${renderThemeCss()}:root { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;}#ui-stream { min-height: 0; min-width: 0; padding: 12px; overflow: auto; overscroll-behavior: contain; scroll-padding-bottom: 180px; }.ui-event { border: 2px solid color-mix(in srgb, var(--nugu-line) 50%, transparent); background: var(--nugu-panel); padding: 8px; margin: 0 0 8px; white-space: pre-wrap; content-visibility: auto; contain-intrinsic-size: 80px; }.ui-event-user { border-width: 4px; border-color: var(--nugu-user); }.ui-visual-block-row { overflow: auto; contain: layout paint; }.ui-visual-block-row header { font-weight: 800; margin-bottom: 8px; }.ui-visual-fallback { color: var(--nugu-muted); margin-bottom: 8px; }.ui-visual-block-row iframe { display: block; width: 100%; height: min(60vh, 600px); max-height: 600px; border: 2px solid var(--nugu-line); background: var(--nugu-bg); }.ui-visual-error-hint { margin-top: 8px; font-weight: 800; }.ui-code, .ui-diff pre { overflow: auto; max-height: 60vh; padding: 8px; border: 2px solid var(--nugu-line); background: var(--nugu-bg); }.ui-diff summary { cursor: pointer; font-weight: 800; }.ui-expand-output { display: block; margin-top: 8px; font: inherit; border: 2px solid var(--nugu-line); background: var(--nugu-bg); color: var(--nugu-fg); }#ui-bottom { position: sticky; bottom: 0; z-index: 10; border-top: 4px solid var(--nugu-accent); background: var(--nugu-panel); box-shadow: 0 -8px 0 color-mix(in srgb, var(--nugu-bg) 85%, transparent); }#ui-meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 6px 8px; border-bottom: 2px solid var(--nugu-line); color: var(--nugu-muted); font-size: 12px; }#ui-meta span { border: 1px solid color-mix(in srgb, var(--nugu-line) 45%, transparent); padding: 2px 5px; }#ui-digest { color: var(--nugu-muted); }#ui-digest[data-pending="true"] { color: var(--nugu-accent); border-color: var(--nugu-accent); }#ui-composer { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 8px; }#ui-input-wrap { position: relative; min-width: 0; }#ui-input { width: 100%; max-height: 30vh; min-height: 42px; resize: vertical; font: inherit; background: var(--nugu-bg); color: var(--nugu-fg); border: 2px solid var(--nugu-line); padding: 8px; }#ui-command-menu { position: absolute; left: 0; right: 0; bottom: 100%; border: 2px solid var(--nugu-line); background: var(--nugu-bg); max-height: 40vh; overflow: auto; }.ui-command-item { display: block; width: 100%; padding: 6px 8px; border: 0; border-bottom: 1px solid color-mix(in srgb, var(--nugu-line) 35%, transparent); background: var(--nugu-bg); color: var(--nugu-fg); font: inherit; text-align: left; }.ui-command-item.is-selected { background: var(--nugu-fg); color: var(--nugu-bg); }.ui-dialog-controls { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }.ui-dialog-controls button { font: inherit; border: 2px solid var(--nugu-line); background: var(--nugu-bg); color: var(--nugu-fg); padding: 4px 8px; }.ui-dialog-controls textarea { min-width: min(100%, 420px); min-height: 80px; font: inherit; }#ui-send { font: inherit; background: var(--nugu-fg); color: var(--nugu-bg); border: 0; padding: 0 16px; }#ui-send:disabled { opacity: .5; }`;}deleted file mode 100644+0 / −28 text lines
export function renderAppHtml(): string { return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Pi UI</title><link rel="stylesheet" href="/assets/app.css"><script type="module" src="/assets/app.js"></script></head><body><div id="ui-shell"><header id="ui-top"><strong>PI</strong><span id="ui-progress">starting</span><span>/ui off in terminal</span></header><main id="ui-stream" aria-live="polite"></main><div id="ui-bottom"><div id="ui-meta"><span>model —</span><span>thinking —</span><span>ctx —</span><span>Esc abort · Ctrl+O expand · Ctrl+P model · / @ !</span><span id="ui-digest" role="status" aria-live="polite" data-pending="false">digest 0</span></div><form id="ui-composer"><div id="ui-input-wrap"><textarea id="ui-input" name="prompt" placeholder="Message Pi"></textarea><div id="ui-command-menu" hidden></div></div><button id="ui-send" type="submit">SEND</button></form></div></div></body></html>`;}deleted file mode 100644+0 / −246 text lines
import { renderCodeBlockComponentJs } from "./components/code-block.js";import { renderComposerComponentJs } from "./components/composer.js";import { renderDialogsComponentJs } from "./components/dialogs.js";import { renderDiffViewJs } from "./components/diff-view.js";import { renderDigestIndicatorJs } from "./components/digest-indicator.js";import { renderLongOutputJs } from "./components/long-output.js";import { renderVirtualStreamJs } from "./components/virtual-stream.js";import { renderVisualBlockComponentJs } from "./components/visual-block.js";import { renderTelemetryWorkerJs } from "./worker.js";export function renderAppJs(): string { return `const status = document.querySelector('#ui-progress');const meta = document.querySelector('#ui-meta');const stream = document.querySelector('#ui-stream');const form = document.querySelector('#ui-composer');const input = document.querySelector('#ui-input');const send = document.querySelector('#ui-send');const menu = document.querySelector('#ui-command-menu');let commands = [];let visibleCommands = [];let selectedCommandIndex = 0;let telemetryWorker;let lastEventId = 0;let socket;const statusItems = new Map();${renderComposerComponentJs()}${renderDialogsComponentJs()}${renderVisualBlockComponentJs()}${renderDigestIndicatorJs()}${renderCodeBlockComponentJs()}${renderDiffViewJs()}${renderLongOutputJs()}${renderVirtualStreamJs()}const telemetryWorkerSource = ${JSON.stringify(renderTelemetryWorkerJs())};function startTelemetryWorker() { if (!('Worker' in window)) return; const url = URL.createObjectURL(new Blob([telemetryWorkerSource], { type: 'text/javascript' })); telemetryWorker = new Worker(url); telemetryWorker.addEventListener('message', event => { if (event.data?.type === 'telemetry_batch') { setDigestIndicator(telemetryEventCount + (event.data.events || []).length); socket?.send(JSON.stringify(event.data)); } });}function trackTelemetry(event) { try { telemetryWorker?.postMessage({ type: 'telemetry', event }); } catch (_) {}}function deviceClass() { return innerWidth <= 520 ? 'phone' : innerWidth <= 900 ? 'tablet' : 'desktop'; }function targetLabel(target) { return target?.id || target?.name || target?.textContent?.trim()?.slice(0, 40) || target?.tagName || 'unknown'; }function authHeaders() { const token = new URL(location.href).searchParams.get('token'); return token ? { authorization: 'Bearer ' + token } : {};}async function fetchSnapshot() { const response = await fetch('/api/snapshot', { headers: authHeaders() }); if (!response.ok) throw new Error('snapshot failed: ' + response.status); const snapshot = await response.json(); setProgress(snapshot.status); commands = snapshot.commands || []; renderEvents(snapshot.events || []); lastEventId = snapshot.lastEventId || 0;}function connectSocket() { const token = new URL(location.href).searchParams.get('token'); const url = new URL('/ws', location.href); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; if (token) url.searchParams.set('token', token); url.searchParams.set('after', String(lastEventId)); socket = new WebSocket(url); socket.addEventListener('message', event => { const payload = JSON.parse(event.data); if (payload.type === 'events') renderEvents(payload.events || []); }); socket.addEventListener('open', () => { if (status.textContent === 'starting') setProgress('connected'); socket.send(JSON.stringify({ type: 'lifecycle_heartbeat' })); setInterval(() => socket?.readyState === WebSocket.OPEN && socket.send(JSON.stringify({ type: 'lifecycle_heartbeat' })), 5000); }); socket.addEventListener('close', () => { setProgress('disconnected'); });}function renderEvents(events) { const fragment = document.createDocumentFragment(); for (const event of events) { const synthetic = event.id > 9_000_000_000_000_000; if (!synthetic && event.id <= lastEventId) continue; if (!synthetic) lastEventId = event.id; applyInternalEvent(event); if (event.type === 'message' && event.role === 'user') finalizeStreamingRows(); if (!isStreamEvent(event)) continue; const row = document.createElement('article'); row.className = 'ui-event ui-event-' + (event.role || event.type); row.dataset.eventId = String(event.id); if (event.streamId) row.dataset.streamId = String(event.streamId); const eventText = event.text || event.message || event.state || ''; applyLongOutput(row, String(event.streamId || event.id), String(eventText)); const fence = String.fromCharCode(96).repeat(3); if (typeof eventText === 'string' && eventText.startsWith(fence)) { row.textContent = ''; const firstNewline = eventText.indexOf('\\n'); const language = eventText.slice(3, firstNewline).trim() || 'text'; renderCodeBlock(row, language, eventText.slice(firstNewline + 1).replace(new RegExp(fence + '\\\\s*$'), '')); } if (typeof eventText === 'string' && eventText.includes('+++ ') && eventText.includes('--- ')) { row.textContent = ''; renderDiffView(row, eventText); } if (event.type === 'ui_request') renderUiRequest(row, event); if (event.type && event.type.startsWith('widget_')) renderVisualBlock(row, event); const existing = event.streamId ? stream.querySelector('[data-stream-id="' + CSS.escape(String(event.streamId)) + '"]') : null; if (existing) existing.replaceWith(row); else fragment.append(row); } appendStreamRows(fragment); streamBatchChannel.port2.postMessage('flush'); stream.scrollTop = stream.scrollHeight;}function applyInternalEvent(event) { if (event.type === 'state') setProgress(event.state); if (event.type === 'log' && event.level === 'error') setProgress(event.message); if (event.type === 'ui_status') updateMetaStatus(event);}function setProgress(value) { status.textContent = value; status.dataset.state = String(value || 'unknown');}function updateMetaStatus(event) { const key = event.statusKey || event.key || event.requestId; const value = event.statusText || event.text || ''; if (!key) return; if (!value) statusItems.delete(String(key)); else statusItems.set(String(key), String(value)); renderMetaStatus();}function finalizeStreamingRows() { for (const row of stream.querySelectorAll('[data-stream-id]')) delete row.dataset.streamId;}function renderMetaStatus() { const digest = document.querySelector('#ui-digest'); const rows = [...statusItems.entries()].slice(-6); meta.textContent = ''; if (rows.length === 0) { for (const label of ['model —', 'thinking —', 'ctx —', 'Esc abort · Ctrl+O expand · Ctrl+P model · / @ !']) { const item = document.createElement('span'); item.textContent = label; meta.append(item); } } else { for (const [key, value] of rows) { const item = document.createElement('span'); item.textContent = key + ': ' + value; meta.append(item); } } if (digest) meta.append(digest);}function isStreamEvent(event) { return event.type === 'message' || event.type === 'tool' || event.type === 'error' || event.type === 'ui_request' || event.type === 'ui_notify' || String(event.type || '').startsWith('widget_');}input.addEventListener('input', renderCommandMenu);input.addEventListener('keydown', event => { const action = composerKeyAction({ key: event.key, ctrlKey: event.ctrlKey, shiftKey: event.shiftKey, menuVisible: !menu.hidden, }); if (action === 'menu-next') { event.preventDefault(); selectedCommandIndex = moveMenuIndex(selectedCommandIndex, 1, visibleCommands.length); renderCommandMenu(); } if (action === 'menu-prev') { event.preventDefault(); selectedCommandIndex = moveMenuIndex(selectedCommandIndex, -1, visibleCommands.length); renderCommandMenu(); } if (action === 'menu-select') { event.preventDefault(); selectCommand(selectedCommandIndex); } if (action === 'abort' || action === 'cycle-model' || action === 'toggle-expand') { event.preventDefault(); socket?.send(JSON.stringify({ type: action })); status.textContent = action; } if (action === 'submit') { event.preventDefault(); form.requestSubmit(); }});window.addEventListener('message', event => { const data = event.data; if (!data || typeof data !== 'object' || !String(data.type || '').startsWith('widget_')) return; trackTelemetry({ type: 'widget_action', widgetId: data.widgetId, label: data.label || data.type }); socket?.send(JSON.stringify(data)); renderEvents([{ id: Number.MAX_SAFE_INTEGER - 2, at: Date.now(), type: 'widget_action', widgetId: data.widgetId, label: data.label || data.type, payload: data.payload || data.text || data.message }]);});window.addEventListener('scroll', () => trackTelemetry({ type: 'scroll', y: scrollY, dwellMs: 0 }), { passive: true });window.addEventListener('click', event => trackTelemetry({ type: 'click', target: targetLabel(event.target) }), { passive: true });window.addEventListener('focus', event => trackTelemetry({ type: 'focus', target: targetLabel(event.target) }), true);window.addEventListener('blur', event => trackTelemetry({ type: 'blur', target: targetLabel(event.target) }), true);document.addEventListener('selectionchange', () => trackTelemetry({ type: 'selection', text: String(getSelection() || '') }));window.addEventListener('pagehide', () => { trackTelemetry({ type: 'pagehide' }); socket?.send(JSON.stringify({ type: 'lifecycle_pagehide' }));});form.addEventListener('submit', () => trackTelemetry({ type: 'form', formId: 'composer', state: 'submit' }));form.addEventListener('submit', event => { event.preventDefault(); const text = input.value.trim(); if (!text || !socket || socket.readyState !== WebSocket.OPEN) return; send.disabled = true; socket.send(JSON.stringify({ type: 'prompt', text })); input.value = ''; setDigestIndicator(0); send.disabled = false;});startTelemetryWorker();trackTelemetry({ type: 'viewport', device: deviceClass(), width: innerWidth, height: innerHeight });fetchSnapshot().then(connectSocket).catch(error => { setProgress('error'); renderEvents([{ id: Number.MAX_SAFE_INTEGER - 1, at: Date.now(), type: 'error', message: error.message }]);});`;}deleted file mode 100644+0 / −42 text lines
export function renderPlainCodeBlock(language: string, code: string): string { return `<pre class="ui-code" data-language="${escapeAttr(language)}"><code>${escapeHtml(code)}</code></pre>`;}export function renderCodeBlockComponentJs(): string { return `const highlightCache = new Map();function renderCodeBlock(container, language, code) { const pre = document.createElement('pre'); pre.className = 'ui-code'; pre.dataset.language = language || 'text'; const codeNode = document.createElement('code'); codeNode.textContent = code; pre.append(codeNode); container.append(pre); queueMicrotask(() => upgradeHighlight(pre, language || 'text', code));}async function upgradeHighlight(pre, language, code) { try { let highlighter = highlightCache.get('highlighter'); if (!highlighter) { const shiki = await import('shiki'); highlighter = await shiki.createHighlighter({ themes: ['github-dark'], langs: [language, 'text'] }); highlightCache.set('highlighter', highlighter); } pre.innerHTML = highlighter.codeToHtml(code, { lang: language, theme: 'github-dark' }); } catch (_) { /* plaintext stays visible */ }}`;}function escapeAttr(value: string): string { return escapeHtml(value).replaceAll('"', """);}function escapeHtml(value: string): string { return value .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">");}deleted file mode 100644+0 / −98 text lines
import type { UiCommandInfo } from "../../protocol";export type ComposerKeyAction = | "submit" | "newline" | "abort" | "toggle-expand" | "cycle-model" | "menu-next" | "menu-prev" | "menu-select" | "none";export type ComposerKeyInput = { key: string; ctrlKey?: boolean; shiftKey?: boolean; menuVisible?: boolean;};export function filterCommandItems( commands: UiCommandInfo[], input: string,): UiCommandInfo[] { const prefix = input.startsWith("/") ? input.slice(1).toLowerCase() : ""; return commands.filter((item) => item.name.toLowerCase().startsWith(prefix));}export function moveMenuIndex( current: number, delta: number, count: number,): number { if (count <= 0) return 0; return (current + delta + count) % count;}export function composerKeyAction(input: ComposerKeyInput): ComposerKeyAction { const normalized = input.key.toLowerCase(); if (input.menuVisible && input.key === "ArrowDown") return "menu-next"; if (input.menuVisible && input.key === "ArrowUp") return "menu-prev"; if (input.menuVisible && input.key === "Tab") return "menu-select"; if (input.ctrlKey && normalized === "o") return "toggle-expand"; if (input.ctrlKey && normalized === "p") return "cycle-model"; if (input.key === "Escape") return "abort"; if (input.key === "Enter" && input.shiftKey) return "newline"; if (input.key === "Enter") return "submit"; return "none";}export function renderComposerComponentJs(): string { return `function filterCommandItems(commands, input) { const prefix = input.startsWith('/') ? input.slice(1).toLowerCase() : ''; return commands.filter(item => item.name.toLowerCase().startsWith(prefix));}function moveMenuIndex(current, delta, count) { if (count <= 0) return 0; return (current + delta + count) % count;}function composerKeyAction(input) { const normalized = input.key.toLowerCase(); if (input.menuVisible && input.key === 'ArrowDown') return 'menu-next'; if (input.menuVisible && input.key === 'ArrowUp') return 'menu-prev'; if (input.menuVisible && input.key === 'Tab') return 'menu-select'; if (input.ctrlKey && normalized === 'o') return 'toggle-expand'; if (input.ctrlKey && normalized === 'p') return 'cycle-model'; if (input.key === 'Escape') return 'abort'; if (input.key === 'Enter' && input.shiftKey) return 'newline'; if (input.key === 'Enter') return 'submit'; return 'none';}function renderCommandMenu() { menu.innerHTML = ''; if (!input.value.startsWith('/')) { menu.hidden = true; selectedCommandIndex = 0; return; } visibleCommands = filterCommandItems(commands, input.value); menu.hidden = visibleCommands.length === 0; for (const [index, command] of visibleCommands.entries()) { const item = document.createElement('button'); item.type = 'button'; item.className = 'ui-command-item' + (index === selectedCommandIndex ? ' is-selected' : ''); item.textContent = '/' + command.name + (command.description ? ' — ' + command.description : ''); item.addEventListener('click', () => selectCommand(index)); menu.append(item); }}function selectCommand(index) { const command = visibleCommands[index]; if (!command) return; input.value = '/' + command.name + ' '; input.focus(); menu.hidden = true;}`;}deleted file mode 100644+0 / −55 text lines
export type DialogResponse = | { type: "ui_response"; id: string; value: string } | { type: "ui_response"; id: string; confirmed: boolean } | { type: "ui_response"; id: string; cancelled: true };export function dialogResponse( id: string, method: string, value: string | boolean | undefined,): DialogResponse { if (value === undefined) return { type: "ui_response", id, cancelled: true }; if (method === "confirm") return { type: "ui_response", id, confirmed: Boolean(value) }; return { type: "ui_response", id, value: String(value) };}export function renderDialogsComponentJs(): string { return `function dialogResponse(id, method, value) { if (value === undefined) return { type: 'ui_response', id, cancelled: true }; if (method === 'confirm') return { type: 'ui_response', id, confirmed: Boolean(value) }; return { type: 'ui_response', id, value: String(value) };}function renderUiRequest(row, event) { const controls = document.createElement('div'); controls.className = 'ui-dialog-controls'; if (event.method === 'select') { for (const option of event.options || []) { const button = document.createElement('button'); button.type = 'button'; button.textContent = option; button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, option)))); controls.append(button); } } else if (event.method === 'confirm') { for (const item of [['YES', true], ['NO', false]]) { const button = document.createElement('button'); button.type = 'button'; button.textContent = item[0]; button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, item[1])))); controls.append(button); } } else { const field = document.createElement('textarea'); field.value = event.prefill || ''; field.placeholder = event.placeholder || ''; const button = document.createElement('button'); button.type = 'button'; button.textContent = 'SEND'; button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, field.value)))); controls.append(field, button); } row.append(controls);}`;}deleted file mode 100644+0 / −45 text lines
export type DiffSummary = { files: number; additions: number; deletions: number;};export function diffSummary(diff: string): DiffSummary { let files = 0; let additions = 0; let deletions = 0; for (const line of diff.split("\n")) { if (line.startsWith("+++ ")) files += 1; else if (line.startsWith("+") && !line.startsWith("+++")) additions += 1; else if (line.startsWith("-") && !line.startsWith("---")) deletions += 1; } return { files, additions, deletions };}export function renderDiffViewJs(): string { return `function renderDiffView(container, diff) { const summary = diffSummary(diff); const details = document.createElement('details'); details.className = 'ui-diff'; const summaryNode = document.createElement('summary'); summaryNode.textContent = summary.files + ' files +' + summary.additions + ' -' + summary.deletions; details.append(summaryNode); const pre = document.createElement('pre'); pre.textContent = diff; details.append(pre); container.append(details); queueMicrotask(async () => { try { await import('pierre'); } catch (_) { /* plaintext diff stays visible */ } });}function diffSummary(diff) { let files = 0, additions = 0, deletions = 0; for (const line of diff.split('\\n')) { if (line.startsWith('+++ ')) files += 1; else if (line.startsWith('+') && !line.startsWith('+++')) additions += 1; else if (line.startsWith('-') && !line.startsWith('---')) deletions += 1; } return { files, additions, deletions };}`;}deleted file mode 100644+0 / −15 text lines
export function digestIndicatorText(count: number): string { return `digest ${count}`;}export function renderDigestIndicatorJs(): string { return `let telemetryEventCount = 0;function setDigestIndicator(count) { telemetryEventCount = count; const indicator = document.querySelector('#ui-digest'); if (!indicator) return; indicator.textContent = 'digest ' + count; indicator.dataset.pending = count > 0 ? 'true' : 'false';}`;}deleted file mode 100644+0 / −46 text lines
export type LongOutputModel = { id: string; text: string; truncated: boolean;};export function longOutputModel( id: string, text: string, expanded: Set<string>, limit = 4_000,): LongOutputModel { if (expanded.has(id) || text.length <= limit) return { id, text, truncated: false }; return { id, text: text.slice(0, limit), truncated: true };}export function toggleLongOutput( id: string, expanded: Set<string>,): Set<string> { const next = new Set(expanded); if (next.has(id)) next.delete(id); else next.add(id); return next;}export function renderLongOutputJs(): string { return `const expandedOutputs = new Set();function longOutputText(id, text, limit = 4000) { if (expandedOutputs.has(id) || text.length <= limit) return { text, truncated: false }; return { text: text.slice(0, limit), truncated: true };}function applyLongOutput(row, id, text) { const model = longOutputText(id, text); row.textContent = model.text; if (!model.truncated) return; const button = document.createElement('button'); button.type = 'button'; button.className = 'ui-expand-output'; button.textContent = 'expand output'; button.addEventListener('click', () => { expandedOutputs.add(id); row.textContent = text; }); row.append(button);}`;}deleted file mode 100644+0 / −31 text lines
export type VirtualWindowOptions = { selectedId: number; threshold?: number; radius?: number;};export function virtualWindow<T extends { id: number }>( events: T[], options: VirtualWindowOptions,): T[] { const threshold = options.threshold ?? 200; if (events.length <= threshold) return events; const radius = options.radius ?? 30; const index = events.findIndex((event) => event.id === options.selectedId); if (index === -1) return events.slice(-threshold); return events.slice(Math.max(0, index - radius), index + radius + 1);}export function renderVirtualStreamJs(): string { return `function appendStreamRows(fragment) { requestAnimationFrame(() => stream.append(fragment));}function maybeVirtualizeStream() { const rows = [...stream.children]; if (rows.length <= 500) return; for (const row of rows.slice(0, rows.length - 500)) row.remove();}const streamBatchChannel = new MessageChannel();streamBatchChannel.port1.onmessage = maybeVirtualizeStream;`;}deleted file mode 100644+0 / −71 text lines
import type { UiWidgetEvent } from "../../protocol";import { renderWidgetBridgeScript } from "./widget-bridge.js";export type VisualBlockShellInput = { widgetId: string; title: string; fallback: string; srcdoc: string;};export function visualBlockSummary(event: Partial<UiWidgetEvent>): string { if (event.type === "widget_error") { return [event.widgetId, "error", event.message, "agent: fix widget HTML/JS"] .filter(Boolean) .join(" · "); } return [event.title, event.widgetId, event.status, event.fallback] .filter(Boolean) .join(" · ");}export function renderVisualBlockShell(input: VisualBlockShellInput): string { return `<section class="ui-visual-block" data-widget-id="${escapeAttr(input.widgetId)}"><header>${escapeHtml(input.title)} <code>${escapeHtml(input.widgetId)}</code></header><div class="ui-visual-fallback">${escapeHtml(input.fallback)}</div><iframe title="${escapeAttr(input.title)}" srcdoc="${escapeAttr(renderWidgetBridgeScript(input.widgetId) + input.srcdoc)}"></iframe></section>`;}export function renderVisualBlockComponentJs(): string { return `function renderVisualBlock(row, event) { row.classList.add('ui-visual-block-row'); row.textContent = ''; const header = document.createElement('header'); header.textContent = [event.title, event.widgetId, event.status, event.label, event.message].filter(Boolean).join(' · '); row.append(header); if (event.fallback) { const fallback = document.createElement('div'); fallback.className = 'ui-visual-fallback'; fallback.textContent = event.fallback; row.append(fallback); } if (event.type === 'widget_mount' || event.type === 'widget_update') { const iframe = document.createElement('iframe'); iframe.title = event.title || event.widgetId; iframe.srcdoc = widgetBridgeScript(event.widgetId) + (event.html || ''); row.append(iframe); } if (event.type === 'widget_error') { const hint = document.createElement('div'); hint.className = 'ui-visual-error-hint'; hint.textContent = 'agent: fix widget HTML/JS'; row.append(hint); }}function widgetBridgeScript(widgetId) { return ${JSON.stringify(renderWidgetBridgeScript("__WIDGET_ID__"))}.replaceAll('__WIDGET_ID__', widgetId);}`;}function escapeAttr(value: string): string { return escapeHtml(value).replaceAll('"', """);}function escapeHtml(value: string): string { return value .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">");}deleted file mode 100644+0 / −81 text lines
export type WidgetBridgeMessage = | { type: "widget_action"; widgetId: string; label: string; payload?: unknown; } | { type: "widget_prompt"; widgetId: string; text: string } | { type: "widget_notify"; widgetId: string; message: string } | { type: "widget_error"; widgetId: string; message: string };export type WidgetAttributionEvent = { type: "widget_action"; widgetId: string; label: string; payload?: unknown; at: number;};export function widgetActionMessage( widgetId: string, label: string, payload?: unknown,): WidgetBridgeMessage { return { type: "widget_action", widgetId, label, payload };}export function attributionEventFromWidgetMessage( message: WidgetBridgeMessage, now: () => number = Date.now,): WidgetAttributionEvent { if (message.type === "widget_prompt") { return { type: "widget_action", widgetId: message.widgetId, label: "prompt", payload: { text: message.text }, at: now(), }; } if (message.type === "widget_notify") { return { type: "widget_action", widgetId: message.widgetId, label: "notify", payload: { message: message.message }, at: now(), }; } if (message.type === "widget_error") { return { type: "widget_action", widgetId: message.widgetId, label: "error", payload: { message: message.message }, at: now(), }; } return { ...message, at: now() };}export function renderWidgetBridgeScript(widgetId: string): string { return `<script>(() => { const widgetId = ${JSON.stringify(widgetId)}; function send(message) { parent.postMessage({ ...message, widgetId }, '*'); } window.pi = { action(label, payload) { send({ type: 'widget_action', label, payload }); }, prompt(text) { send({ type: 'widget_prompt', text }); }, steer(text) { send({ type: 'widget_prompt', text }); }, followUp(text) { send({ type: 'widget_prompt', text }); }, notify(message) { send({ type: 'widget_notify', message }); }, state() { return { widgetId }; }, on() {}, update(payload) { send({ type: 'widget_action', label: 'update', payload }); }, requestAttachment() { send({ type: 'widget_action', label: 'attachment-request' }); }, }; window.addEventListener('error', event => send({ type: 'widget_error', message: event.message }));})();</script>`;}deleted file mode 100644+0 / −33 text lines
export function renderThemeCss(): string { return `:root { color-scheme: dark light; --nugu-bg: #0b0d10; --nugu-fg: #f2f0e8; --nugu-muted: #979183; --nugu-line: #f2f0e8; --nugu-accent: #ffb000; --nugu-danger: #ff4d4d; --nugu-panel: #14171c; --nugu-user: #f2f0e8; background: var(--nugu-bg); color: var(--nugu-fg);}@media (prefers-color-scheme: light) { :root { --nugu-bg: #f2f0e8; --nugu-fg: #0b0d10; --nugu-muted: #5e5a52; --nugu-line: #0b0d10; --nugu-accent: #a85f00; --nugu-danger: #b00020; --nugu-panel: #ffffff; --nugu-user: #0b0d10; }}* { box-sizing: border-box; }body { margin: 0; min-height: 100vh; height: 100vh; overflow: hidden; background: var(--nugu-bg); color: var(--nugu-fg); }#ui-shell { min-height: 100vh; height: 100vh; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; }#ui-top { display: flex; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 3px solid var(--nugu-line); padding: 4px 8px; font-size: 11px; letter-spacing: .08em; text-transform: uppercase; }#ui-progress { color: var(--nugu-accent); }`;}deleted file mode 100644+0 / −56 text lines
import { redactText, type TelemetryEvent } from "../telemetry";export type TelemetryBatcherOptions = { maxBatch?: number;};export function createTelemetryBatcher(options: TelemetryBatcherOptions = {}) { const maxBatch = options.maxBatch ?? 12; let pending: TelemetryEvent[] = []; return { add(event: TelemetryEvent): TelemetryEvent[] { pending.push(redactRawEvent(event)); if (pending.length < maxBatch) return []; return flush(); }, flush, }; function flush() { const batch = pending; pending = []; return batch; }}export function renderTelemetryWorkerJs(): string { return `let pending = [];const maxBatch = 12;function redactText(text) { return text ? '[redacted ' + text.length + ' chars]' : ''; }function redact(event) { if (event.type === 'selection') return { ...event, text: redactText(event.text || '') }; if (event.type === 'error') return { ...event, message: redactText(event.message || '') }; return event;}function flush() { if (pending.length === 0) return; postMessage({ type: 'telemetry_batch', events: pending }); pending = [];}onmessage = event => { const message = event.data; if (!message || message.type !== 'telemetry') return; pending.push(redact(message.event)); if (pending.length >= maxBatch) flush();};setInterval(flush, 1000);`;}function redactRawEvent(event: TelemetryEvent): TelemetryEvent { if (event.type === "selection") return { ...event, text: redactText(event.text) }; if (event.type === "error") return { ...event, message: redactText(event.message) }; return event;}deleted file mode 100644+0 / −125 text lines
import type { UiWidgetEvent } from "./protocol";export type WidgetRecord = { widgetId: string; toolCallId: string; title: string; fallback: string; html: string; status: "mounted" | "updated" | "action" | "error"; audit: UiWidgetEvent[];};export type WidgetStoreOptions = { now?: () => number;};export type MountWidgetInput = { toolCallId: string; title: string; fallback: string; html: string;};export type WidgetActionInput = { toolCallId: string; label: string; payload?: unknown;};export class WidgetStore { readonly #now: () => number; #actions = 0; #widgets = new Map<string, WidgetRecord>(); constructor(options: WidgetStoreOptions = {}) { this.#now = options.now ?? Date.now; } mount(input: MountWidgetInput): UiWidgetEvent { const widgetId = widgetIdForToolCall(input.toolCallId); const event: UiWidgetEvent = { id: 0, at: this.#now(), type: "widget_mount", widgetId, toolCallId: input.toolCallId, title: input.title, fallback: input.fallback, html: input.html, status: "mounted", }; this.#widgets.set(widgetId, { widgetId, toolCallId: input.toolCallId, title: input.title, fallback: input.fallback, html: input.html, status: "mounted", audit: [event], }); return event; } update(widgetId: string, patch: { html: string }): UiWidgetEvent { const record = this.#require(widgetId); record.html = patch.html; record.status = "updated"; return this.#audit(record, { type: "widget_update", widgetId, toolCallId: record.toolCallId, html: patch.html, status: "updated", }); } action(widgetId: string, input: WidgetActionInput): UiWidgetEvent { const record = this.#require(widgetId); record.status = "action"; return this.#audit(record, { type: "widget_action", widgetId, toolCallId: input.toolCallId, actionId: `action-${++this.#actions}`, label: input.label, payload: input.payload, status: "action", }); } error(widgetId: string, message: string): UiWidgetEvent { const record = this.#require(widgetId); record.status = "error"; return this.#audit(record, { type: "widget_error", widgetId, toolCallId: record.toolCallId, message, status: "error", }); } get(widgetId: string): WidgetRecord | undefined { return this.#widgets.get(widgetId); } #audit( record: WidgetRecord, event: Omit<UiWidgetEvent, "id" | "at">, ): UiWidgetEvent { const full = { id: 0, at: this.#now(), ...event }; record.audit.push(full); return full; } #require(widgetId: string): WidgetRecord { const record = this.#widgets.get(widgetId); if (!record) throw new Error(`Unknown widget: ${widgetId}`); return record; }}export function widgetIdForToolCall(toolCallId: string): string { return `widget-${toolCallId.replaceAll(/[^a-zA-Z0-9_-]/g, "-")}`;}+22 / −2506 text lines
"extensions/ui": { "name": "@bugabinga/pi-ext-ui", "license": "MIT", "dependencies": { "@types/ws": "^8.18.1", "pierre": "^2.1.16", "qrcode": "^1.5.4", "shiki": "^4.3.0", "ws": "^8.21.0" }, "devDependencies": { "@marcfargas/pi-test-harness": "^0.6.1", "@playwright/test": "^1.61.0", "@types/qrcode": "^1.5.5", "tsx": "^4.20.6", "vitest": "^4.1.9" }, "peerDependencies": { "@earendil-works/pi-coding-agent": "*", "@earendil-works/pi-tui": "*", "typebox": "*" } }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "license": "MIT", "dependencies": { "@jridgewell/trace-mapping": "0.3.9" }, "engines": { "node": ">=12" } }, "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { "version": "0.3.9", "license": "MIT", "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-0.80.6.tgz", "node_modules/@esbuild/aix-ppc64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", "cpu": [ "ppc64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "aix" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-arm": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", "cpu": [ "arm" ], "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", "cpu": [ "arm" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", "cpu": [ "ia32" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", "cpu": [ "loong64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", "cpu": [ "mips64el" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", "cpu": [ "ppc64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", "cpu": [ "riscv64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", "cpu": [ "s390x" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/netbsd-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/netbsd-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openbsd-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openbsd-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openharmony-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "openharmony" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/sunos-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "sunos" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", "cpu": [ "ia32" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { "version": "0.28.1", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@fat/prompts": { "version": "0.0.3", "license": "MIT", "dependencies": { "kleur": "^4.0.1", "sisteransi": "^1.0.5" }, "engines": { "node": ">= 14" } }, "dev": true, "dev": true, "node_modules/@octokit/app": { "version": "14.1.0", "license": "MIT", "dependencies": { "@octokit/auth-app": "^6.0.0", "@octokit/auth-unauthenticated": "^5.0.0", "@octokit/core": "^5.0.0", "@octokit/oauth-app": "^6.0.0", "@octokit/plugin-paginate-rest": "^9.0.0", "@octokit/types": "^12.0.0", "@octokit/webhooks": "^12.0.4" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/app/node_modules/@octokit/openapi-types": { "version": "20.0.0", "license": "MIT" }, "node_modules/@octokit/app/node_modules/@octokit/plugin-paginate-rest": { "version": "9.2.2", "license": "MIT", "dependencies": { "@octokit/types": "^12.6.0" }, "engines": { "node": ">= 18" }, "peerDependencies": { "@octokit/core": "5" } }, "node_modules/@octokit/app/node_modules/@octokit/types": { "version": "12.6.0", "license": "MIT", "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "node_modules/@octokit/auth-app": { "version": "6.1.4", "license": "MIT", "dependencies": { "@octokit/auth-oauth-app": "^7.1.0", "@octokit/auth-oauth-user": "^4.1.0", "@octokit/request": "^8.3.1", "@octokit/request-error": "^5.1.0", "@octokit/types": "^13.1.0", "deprecation": "^2.3.1", "lru-cache": "npm:@wolfy1339/lru-cache@^11.0.2-patch.1", "universal-github-app-jwt": "^1.1.2", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/auth-app/node_modules/lru-cache": { "name": "@wolfy1339/lru-cache", "version": "11.0.2-patch.1", "license": "ISC", "engines": { "node": "18 >=18.20 || 20 || >=22" } }, "node_modules/@octokit/auth-oauth-app": { "version": "7.1.0", "license": "MIT", "dependencies": { "@octokit/auth-oauth-device": "^6.1.0", "@octokit/auth-oauth-user": "^4.1.0", "@octokit/request": "^8.3.1", "@octokit/types": "^13.0.0", "@types/btoa-lite": "^1.0.0", "btoa-lite": "^1.0.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/auth-oauth-device": { "version": "6.1.0", "license": "MIT", "dependencies": { "@octokit/oauth-methods": "^4.1.0", "@octokit/request": "^8.3.1", "@octokit/types": "^13.0.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/auth-oauth-user": { "version": "4.1.0", "license": "MIT", "dependencies": { "@octokit/auth-oauth-device": "^6.1.0", "@octokit/oauth-methods": "^4.1.0", "@octokit/request": "^8.3.1", "@octokit/types": "^13.0.0", "btoa-lite": "^1.0.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/auth-token": { "version": "4.0.0", "license": "MIT", "engines": { "node": ">= 18" } }, "node_modules/@octokit/auth-unauthenticated": { "version": "5.0.1", "license": "MIT", "dependencies": { "@octokit/request-error": "^5.0.0", "@octokit/types": "^12.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/openapi-types": { "version": "20.0.0", "license": "MIT" }, "node_modules/@octokit/auth-unauthenticated/node_modules/@octokit/types": { "version": "12.6.0", "license": "MIT", "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "node_modules/@octokit/core": { "version": "5.2.2", "license": "MIT", "dependencies": { "@octokit/auth-token": "^4.0.0", "@octokit/graphql": "^7.1.0", "@octokit/request": "^8.4.1", "@octokit/request-error": "^5.1.1", "@octokit/types": "^13.0.0", "before-after-hook": "^2.2.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/endpoint": { "version": "9.0.6", "license": "MIT", "dependencies": { "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/graphql": { "version": "7.1.1", "license": "MIT", "dependencies": { "@octokit/request": "^8.4.1", "@octokit/types": "^13.0.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/oauth-app": { "version": "6.1.0", "license": "MIT", "dependencies": { "@octokit/auth-oauth-app": "^7.0.0", "@octokit/auth-oauth-user": "^4.0.0", "@octokit/auth-unauthenticated": "^5.0.0", "@octokit/core": "^5.0.0", "@octokit/oauth-authorization-url": "^6.0.2", "@octokit/oauth-methods": "^4.0.0", "@types/aws-lambda": "^8.10.83", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/oauth-authorization-url": { "version": "6.0.2", "license": "MIT", "engines": { "node": ">= 18" } }, "node_modules/@octokit/oauth-methods": { "version": "4.1.0", "license": "MIT", "dependencies": { "@octokit/oauth-authorization-url": "^6.0.2", "@octokit/request": "^8.3.1", "@octokit/request-error": "^5.1.0", "@octokit/types": "^13.0.0", "btoa-lite": "^1.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/openapi-types": { "version": "24.2.0", "license": "MIT" }, "node_modules/@octokit/plugin-paginate-graphql": { "version": "4.0.1", "license": "MIT", "engines": { "node": ">= 18" }, "peerDependencies": { "@octokit/core": ">=5" } }, "node_modules/@octokit/plugin-paginate-rest": { "version": "11.4.4-cjs.2", "license": "MIT", "dependencies": { "@octokit/types": "^13.7.0" }, "engines": { "node": ">= 18" }, "peerDependencies": { "@octokit/core": "5" } }, "node_modules/@octokit/plugin-rest-endpoint-methods": { "version": "13.3.2-cjs.1", "license": "MIT", "dependencies": { "@octokit/types": "^13.8.0" }, "engines": { "node": ">= 18" }, "peerDependencies": { "@octokit/core": "^5" } }, "node_modules/@octokit/plugin-retry": { "version": "6.1.0", "license": "MIT", "dependencies": { "@octokit/request-error": "^5.0.0", "@octokit/types": "^13.0.0", "bottleneck": "^2.15.3" }, "engines": { "node": ">= 18" }, "peerDependencies": { "@octokit/core": "5" } }, "node_modules/@octokit/plugin-throttling": { "version": "8.2.0", "license": "MIT", "dependencies": { "@octokit/types": "^12.2.0", "bottleneck": "^2.15.3" }, "engines": { "node": ">= 18" }, "peerDependencies": { "@octokit/core": "^5.0.0" } }, "node_modules/@octokit/plugin-throttling/node_modules/@octokit/openapi-types": { "version": "20.0.0", "license": "MIT" }, "node_modules/@octokit/plugin-throttling/node_modules/@octokit/types": { "version": "12.6.0", "license": "MIT", "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "node_modules/@octokit/request": { "version": "8.4.1", "license": "MIT", "dependencies": { "@octokit/endpoint": "^9.0.6", "@octokit/request-error": "^5.1.1", "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/request-error": { "version": "5.1.1", "license": "MIT", "dependencies": { "@octokit/types": "^13.1.0", "deprecation": "^2.0.0", "once": "^1.4.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/types": { "version": "13.10.0", "license": "MIT", "dependencies": { "@octokit/openapi-types": "^24.2.0" } }, "node_modules/@octokit/webhooks": { "version": "12.3.2", "license": "MIT", "dependencies": { "@octokit/request-error": "^5.0.0", "@octokit/webhooks-methods": "^4.1.0", "@octokit/webhooks-types": "7.6.1", "aggregate-error": "^3.1.0" }, "engines": { "node": ">= 18" } }, "node_modules/@octokit/webhooks-methods": { "version": "4.1.0", "license": "MIT", "engines": { "node": ">= 18" } }, "node_modules/@octokit/webhooks-types": { "version": "7.6.1", "license": "MIT" }, "node_modules/@supabase/auth-js": { "version": "2.110.1", "license": "MIT", "dependencies": { "tslib": "2.8.1" }, "engines": { "node": ">=22.0.0" } }, "node_modules/@supabase/functions-js": { "version": "2.110.1", "license": "MIT", "dependencies": { "tslib": "2.8.1" }, "engines": { "node": ">=22.0.0" } }, "node_modules/@supabase/phoenix": { "version": "0.4.4", "license": "MIT" }, "node_modules/@supabase/postgrest-js": { "version": "2.110.1", "license": "MIT", "dependencies": { "tslib": "2.8.1" }, "engines": { "node": ">=22.0.0" } }, "node_modules/@supabase/realtime-js": { "version": "2.110.1", "license": "MIT", "dependencies": { "@supabase/phoenix": "0.4.4", "tslib": "2.8.1" }, "engines": { "node": ">=22.0.0" } }, "node_modules/@supabase/storage-js": { "version": "2.110.1", "license": "MIT", "dependencies": { "iceberg-js": "^0.8.1", "tslib": "2.8.1" }, "engines": { "node": ">=22.0.0" } }, "node_modules/@supabase/supabase-js": { "version": "2.110.1", "license": "MIT", "dependencies": { "@supabase/auth-js": "2.110.1", "@supabase/functions-js": "2.110.1", "@supabase/postgrest-js": "2.110.1", "@supabase/realtime-js": "2.110.1", "@supabase/storage-js": "2.110.1" }, "engines": { "node": ">=22.0.0" } }, "node_modules/@tsconfig/node10": { "version": "1.0.12", "license": "MIT" }, "node_modules/@tsconfig/node12": { "version": "1.0.11", "license": "MIT" }, "node_modules/@tsconfig/node14": { "version": "1.0.3", "license": "MIT" }, "node_modules/@tsconfig/node16": { "version": "1.0.4", "license": "MIT" }, "peer": true, "node_modules/acorn": { "version": "8.17.0", "license": "MIT", "bin": { "acorn": "bin/acorn" }, "engines": { "node": ">=0.4.0" } }, "node_modules/acorn-walk": { "version": "8.3.5", "license": "MIT", "dependencies": { "acorn": "^8.11.0" }, "engines": { "node": ">=0.4.0" } }, "node_modules/aggregate-error": { "version": "3.1.0", "license": "MIT", "dependencies": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/ansi-regex": { "version": "5.0.1", "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/ansi-styles": { "version": "4.3.0", "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, "node_modules/arg": { "version": "4.1.3", "license": "MIT" }, "node_modules/btoa-lite": { "version": "1.0.0", "license": "MIT" }, "node_modules/buffer": { "version": "6.0.3", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "license": "MIT", "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "license": "BSD-3-Clause" }, "node_modules/bundle-name": { "version": "3.0.0", "license": "MIT", "dependencies": { "run-applescript": "^5.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/camel-case": { "version": "4.1.2", "license": "MIT", "dependencies": { "pascal-case": "^3.1.2", "tslib": "^2.0.3" } }, "node_modules/camelcase": { "version": "5.3.1", "license": "MIT", "engines": { "node": ">=6" } "node_modules/chalk": { "version": "5.6.2", "license": "MIT", "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { "url": "https://github.com/chalk/chalk?sponsor=1" } }, "node_modules/change-case": { "version": "4.1.2", "license": "MIT", "dependencies": { "camel-case": "^4.1.2", "capital-case": "^1.0.4", "constant-case": "^3.0.4", "dot-case": "^3.0.4", "header-case": "^2.0.4", "no-case": "^3.0.4", "param-case": "^3.0.4", "pascal-case": "^3.1.2", "path-case": "^3.0.4", "sentence-case": "^3.0.4", "snake-case": "^3.0.4", "tslib": "^2.0.3" } }, "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", "node_modules/clean-stack": { "version": "2.2.0", "license": "MIT", "engines": { "node": ">=6" } }, "node_modules/cli-cursor": { "version": "4.0.0", "license": "MIT", "dependencies": { "restore-cursor": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cli-spinners": { "version": "2.9.2", "license": "MIT", "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cliui": { "version": "6.0.0", "license": "ISC", "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "node_modules/color-convert": { "version": "2.0.1", "license": "MIT", "dependencies": { "color-name": "~1.1.4" }, "engines": { "node": ">=7.0.0" } }, "node_modules/color-name": { "version": "1.1.4", "license": "MIT" }, "node_modules/create-require": { "version": "1.1.1", "license": "MIT" }, "node_modules/cross-spawn": { "version": "7.0.6", "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" }, "engines": { "node": ">= 8" } }, "peer": true, "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", "node_modules/default-browser": { "version": "4.0.0", "license": "MIT", "dependencies": { "bundle-name": "^3.0.0", "default-browser-id": "^3.0.0", "execa": "^7.1.1", "titleize": "^3.0.0" }, "engines": { "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser-id": { "version": "3.0.0", "license": "MIT", "dependencies": { "bplist-parser": "^0.2.0", "untildify": "^4.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/execa": { "version": "7.2.0", "license": "MIT", "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.1", "human-signals": "^4.3.0", "is-stream": "^3.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^5.1.0", "onetime": "^6.0.0", "signal-exit": "^3.0.7", "strip-final-newline": "^3.0.0" }, "engines": { "node": "^14.18.0 || ^16.14.0 || >=18.0.0" }, "funding": { "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, "node_modules/default-browser/node_modules/get-stream": { "version": "6.0.1", "license": "MIT", "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/human-signals": { "version": "4.3.1", "license": "Apache-2.0", "engines": { "node": ">=14.18.0" } }, "node_modules/default-browser/node_modules/is-stream": { "version": "3.0.0", "license": "MIT", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/mimic-fn": { "version": "4.0.0", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/npm-run-path": { "version": "5.3.0", "license": "MIT", "dependencies": { "path-key": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/onetime": { "version": "6.0.0", "license": "MIT", "dependencies": { "mimic-fn": "^4.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/path-key": { "version": "4.0.0", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/default-browser/node_modules/strip-final-newline": { "version": "3.0.0", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/define-lazy-prop": { "version": "3.0.0", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/deprecation": { "version": "2.3.1", "license": "ISC" }, "node_modules/dijkstrajs": { "version": "1.0.3", "license": "MIT" }, "node_modules/dot-case": { "version": "3.0.4", "license": "MIT", "dependencies": { "no-case": "^3.0.4", "tslib": "^2.0.3" } }, "node_modules/eastasianwidth": { "version": "0.2.0", "license": "MIT" }, "peer": true, "node_modules/esbuild": { "version": "0.28.1", "dev": true, "hasInstallScript": true, "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, "engines": { "node": ">=18" }, "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" } }, "node_modules/execa": { "version": "4.1.0", "license": "MIT", "dependencies": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.0", "onetime": "^5.1.0", "signal-exit": "^3.0.2", "strip-final-newline": "^2.0.0" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, "peer": true, "peer": true, "node_modules/human-signals": { "version": "1.1.1", "license": "Apache-2.0", "engines": { "node": ">=8.12.0" } }, "node_modules/iceberg-js": { "version": "0.8.1", "license": "MIT", "engines": { "node": ">=20.0.0" } }, "node_modules/ieee754": { "version": "1.2.1", "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "license": "BSD-3-Clause" }, "node_modules/indent-string": { "version": "4.0.0", "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/inherits": { "version": "2.0.4", "license": "ISC" }, "node_modules/is-absolute": { "version": "1.0.0", "license": "MIT", "dependencies": { "is-relative": "^1.0.0", "is-windows": "^1.0.1" }, "engines": { "node": ">=0.10.0" } }, "node_modules/is-docker": { "version": "3.0.0", "license": "MIT", "bin": { "is-docker": "cli.js" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/is-git-repository": { "version": "2.0.0", "license": "MIT", "dependencies": { "execa": "^4.0.3", "is-absolute": "^1.0.0" } }, "node_modules/is-inside-container": { "version": "1.0.0", "license": "MIT", "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" }, "engines": { "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-interactive": { "version": "2.0.0", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-relative": { "version": "1.0.0", "license": "MIT", "dependencies": { "is-unc-path": "^1.0.0" }, "engines": { "node": ">=0.10.0" } }, "node_modules/is-stream": { "version": "2.0.1", "license": "MIT", "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-unc-path": { "version": "1.0.0", "license": "MIT", "dependencies": { "unc-path-regex": "^0.1.2" }, "engines": { "node": ">=0.10.0" } }, "node_modules/is-unicode-supported": { "version": "1.3.0", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-windows": { "version": "1.0.2", "license": "MIT", "engines": { "node": ">=0.10.0" } }, "node_modules/is-wsl": { "version": "2.2.0", "license": "MIT", "dependencies": { "is-docker": "^2.0.0" }, "engines": { "node": ">=8" } }, "node_modules/is-wsl/node_modules/is-docker": { "version": "2.2.1", "license": "MIT", "bin": { "is-docker": "cli.js" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/isexe": { "version": "2.0.0", "license": "ISC" }, "node_modules/jsonwebtoken": { "version": "9.0.3", "license": "MIT", "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" }, "engines": { "node": ">=12", "npm": ">=6" } }, "node_modules/jsonwebtoken/node_modules/semver": { "version": "7.8.5", "license": "ISC", "bin": { "semver": "bin/semver.js" }, "engines": { "node": ">=10" } }, "peer": true, "peer": true, "node_modules/locate-path": { "version": "5.0.0", "license": "MIT", "dependencies": { "p-locate": "^4.1.0" }, "engines": { "node": ">=8" } }, "node_modules/lodash.debounce": { "version": "4.0.8", "license": "MIT" }, "node_modules/lodash.includes": { "version": "4.3.0", "license": "MIT" }, "node_modules/lodash.isboolean": { "version": "3.0.3", "license": "MIT" }, "node_modules/lodash.isinteger": { "version": "4.0.4", "license": "MIT" }, "node_modules/lodash.isnumber": { "version": "3.0.3", "license": "MIT" }, "node_modules/lodash.isplainobject": { "version": "4.0.6", "license": "MIT" }, "node_modules/lodash.isstring": { "version": "4.0.1", "license": "MIT" }, "node_modules/lodash.once": { "version": "4.1.1", "license": "MIT" }, "node_modules/log-symbols": { "version": "5.1.0", "license": "MIT", "dependencies": { "chalk": "^5.0.0", "is-unicode-supported": "^1.1.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "peer": true, "peer": true, "node_modules/octokit": { "version": "3.2.2", "license": "MIT", "dependencies": { "@octokit/app": "^14.0.2", "@octokit/core": "^5.0.0", "@octokit/oauth-app": "^6.0.0", "@octokit/plugin-paginate-graphql": "^4.0.0", "@octokit/plugin-paginate-rest": "11.4.4-cjs.2", "@octokit/plugin-rest-endpoint-methods": "13.3.2-cjs.1", "@octokit/plugin-retry": "^6.0.0", "@octokit/plugin-throttling": "^8.0.0", "@octokit/request-error": "^5.0.0", "@octokit/types": "^13.0.0", "@octokit/webhooks": "^12.3.1" }, "engines": { "node": ">= 18" } }, "node_modules/once": { "version": "1.4.0", "license": "ISC", "dependencies": { "wrappy": "1" } }, "node_modules/onetime": { "version": "5.1.2", "license": "MIT", "dependencies": { "mimic-fn": "^2.1.0" }, "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/open": { "version": "9.1.0", "license": "MIT", "dependencies": { "default-browser": "^4.0.0", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "is-wsl": "^2.2.0" }, "engines": { "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ora": { "version": "7.0.1", "license": "MIT", "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^4.0.0", "cli-spinners": "^2.9.0", "is-interactive": "^2.0.0", "is-unicode-supported": "^1.3.0", "log-symbols": "^5.1.0", "stdin-discarder": "^0.1.0", "string-width": "^6.1.0", "strip-ansi": "^7.1.0" }, "engines": { "node": ">=16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ora/node_modules/ansi-regex": { "version": "6.2.2", "license": "MIT", "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, "node_modules/ora/node_modules/emoji-regex": { "version": "10.6.0", "license": "MIT" }, "node_modules/ora/node_modules/string-width": { "version": "6.1.0", "license": "MIT", "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^10.2.1", "strip-ansi": "^7.0.1" }, "engines": { "node": ">=16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ora/node_modules/strip-ansi": { "version": "7.2.0", "license": "MIT", "dependencies": { "ansi-regex": "^6.2.2" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, "node_modules/p-limit": { "version": "2.3.0", "license": "MIT", "dependencies": { "p-try": "^2.0.0" }, "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-locate": { "version": "4.1.0", "license": "MIT", "dependencies": { "p-limit": "^2.2.0" }, "engines": { "node": ">=8" } }, "node_modules/pascal-case": { "version": "3.1.2", "license": "MIT", "dependencies": { "no-case": "^3.0.4", "tslib": "^2.0.3" } }, "node_modules/path-case": { "version": "3.0.4", "license": "MIT", "dependencies": { "dot-case": "^3.0.4", "tslib": "^2.0.3" } }, "node_modules/path-exists": { "version": "4.0.0", "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/pierre": { "version": "2.1.16", "license": "ISC", "dependencies": { "@fat/prompts": "^0.0.3", "@supabase/supabase-js": "^2.38.0", "change-case": "^4.1.2", "diff": "^5.1.0", "is-git-repository": "^2.0.0", "lodash.debounce": "^4.0.8", "node-fetch": "^3.3.2", "octokit": "^3.2.0", "open": "^9.1.0", "ora": "^7.0.1", "simple-git": "^3.20.0", "ts-node": "^10.9.1" }, "bin": { "pier": "dist/index.js", "piere": "dist/index.js", "pierr": "dist/index.js", "pierre": "dist/index.js", "pr": "dist/index.js" } }, "node_modules/pierre/node_modules/diff": { "version": "5.2.2", "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, "node_modules/pump": { "version": "3.0.4", "license": "MIT", "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "node_modules/qrcode": { "version": "1.5.4", "license": "MIT", "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" }, "engines": { "node": ">=10.13.0" } }, "node_modules/require-directory": { "version": "2.1.1", "license": "MIT", "engines": { "node": ">=0.10.0" } }, "node_modules/require-main-filename": { "version": "2.0.0", "license": "ISC" }, "node_modules/restore-cursor": { "version": "4.0.0", "license": "MIT", "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/run-applescript": { "version": "5.0.0", "license": "MIT", "dependencies": { "execa": "^5.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/run-applescript/node_modules/execa": { "version": "5.1.1", "license": "MIT", "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, "node_modules/run-applescript/node_modules/get-stream": { "version": "6.0.1", "license": "MIT", "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/run-applescript/node_modules/human-signals": { "version": "2.1.0", "license": "Apache-2.0", "engines": { "node": ">=10.17.0" } }, "node_modules/sentence-case": { "version": "3.0.4", "license": "MIT", "dependencies": { "no-case": "^3.0.4", "tslib": "^2.0.3", "upper-case-first": "^2.0.2" } }, "node_modules/set-blocking": { "version": "2.0.0", "license": "ISC" }, "node_modules/shebang-command": { "version": "2.0.0", "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" }, "engines": { "node": ">=8" } }, "node_modules/shebang-regex": { "version": "3.0.0", "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/signal-exit": { "version": "3.0.7", "license": "ISC" }, "node_modules/simple-git": { "version": "3.36.0", "license": "MIT", "dependencies": { "@kwsites/file-exists": "^1.1.1", "@kwsites/promise-deferred": "^1.1.1", "@simple-git/args-pathspec": "^1.0.3", "@simple-git/argv-parser": "^1.1.0", "debug": "^4.4.0" }, "funding": { "type": "github", "url": "https://github.com/steveukx/git-js?sponsor=1" } }, "node_modules/sisteransi": { "version": "1.0.5", "license": "MIT" }, "node_modules/snake-case": { "version": "3.0.4", "license": "MIT", "dependencies": { "dot-case": "^3.0.4", "tslib": "^2.0.3" } }, "node_modules/stdin-discarder": { "version": "0.1.0", "license": "MIT", "dependencies": { "bl": "^5.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/string_decoder": { "version": "1.3.0", "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" } }, "node_modules/string-width": { "version": "4.2.3", "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "engines": { "node": ">=8" } }, "node_modules/strip-ansi": { "version": "6.0.1", "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/strip-final-newline": { "version": "2.0.0", "license": "MIT", "engines": { "node": ">=6" } }, "node_modules/ts-node": { "version": "10.9.2", "license": "MIT", "dependencies": { "@cspotcode/source-map-support": "^0.8.0", "@tsconfig/node10": "^1.0.7", "@tsconfig/node12": "^1.0.7", "@tsconfig/node14": "^1.0.0", "@tsconfig/node16": "^1.0.2", "acorn": "^8.4.1", "acorn-walk": "^8.1.1", "arg": "^4.1.0", "create-require": "^1.1.0", "diff": "^4.0.1", "make-error": "^1.1.1", "v8-compile-cache-lib": "^3.0.1", "yn": "3.1.1" }, "bin": { "ts-node": "dist/bin.js", "ts-node-cwd": "dist/bin-cwd.js", "ts-node-esm": "dist/bin-esm.js", "ts-node-script": "dist/bin-script.js", "ts-node-transpile-only": "dist/bin-transpile.js", "ts-script": "dist/bin-script-deprecated.js" }, "peerDependencies": { "@swc/core": ">=1.2.50", "@swc/wasm": ">=1.2.50", "@types/node": "*", "typescript": ">=2.7" }, "peerDependenciesMeta": { "@swc/core": { "optional": true }, "@swc/wasm": { "optional": true } } }, "node_modules/ts-node/node_modules/diff": { "version": "4.0.4", "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, "node_modules/tsx": { "version": "4.22.4", "dev": true, "license": "MIT", "dependencies": { "esbuild": "~0.28.0" }, "bin": { "tsx": "dist/cli.mjs" }, "engines": { "node": ">=18.0.0" }, "optionalDependencies": { "fsevents": "~2.3.3" } }, "node_modules/tsx/node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "dev": true, "node_modules/universal-github-app-jwt": { "version": "1.2.0", "license": "MIT", "dependencies": { "@types/jsonwebtoken": "^9.0.0", "jsonwebtoken": "^9.0.2" } }, "node_modules/universal-user-agent": { "version": "6.0.1", "license": "ISC" }, "node_modules/untildify": { "version": "4.0.0", "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/upper-case": { "version": "2.0.2", "license": "MIT", "dependencies": { "tslib": "^2.0.3" } }, "node_modules/upper-case-first": { "version": "2.0.2", "license": "MIT", "dependencies": { "tslib": "^2.0.3" } }, "node_modules/util-deprecate": { "version": "1.0.2", "license": "MIT" }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "license": "MIT" }, "peer": true, "node_modules/which": { "version": "2.0.2", "license": "ISC", "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "bin/node-which" }, "engines": { "node": ">= 8" } }, "node_modules/which-module": { "version": "2.0.1", "license": "ISC" }, "node_modules/wrap-ansi": { "version": "6.2.0", "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" }, "engines": { "node": ">=8" } }, "node_modules/wrappy": { "version": "1.0.2", "license": "ISC" }, "peer": true, "node_modules/yargs": { "version": "15.4.1", "license": "MIT", "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" }, "engines": { "node": ">=8" } }, "node_modules/yargs-parser": { "version": "18.1.3", "license": "ISC", "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" }, "engines": { "node": ">=6" } }, "node_modules/yn": { "version": "3.1.1", "license": "MIT", "engines": { "node": ">=6" } },+0 / −8 text lines
for (const file of [ "extensions/ui/scripts/phase1-smoke.mjs", "extensions/ui/scripts/zellij-smoke.mjs",]) { const text = readFileSync(join(ROOT, file), "utf8"); assert(!text.includes('".pi/tmp/'), `${file}: hardcoded .pi/tmp`); assert(text.includes("CONFIG_DIR_NAME"), `${file}: missing CONFIG_DIR_NAME`);}