Add UI extension design and roadmap
2ff6020a149e83123337edabd6ad1cda8732c4cf
Oliver Krylow <o.krylow@isp-insoft.de> ·
unsigned
- Parent 1: 54de08e53746
bugabingas pi extensions
2ff6020a149e83123337edabd6ad1cda8732c4cf
Oliver Krylow <o.krylow@isp-insoft.de> ·
unsigned
+1307 / −0 text lines
new file mode 100644+358 / −0 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 a forked 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.- Forked 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: Forked RPC Session and Basic Web Stream**Outcome:** Browser UI talks to a forked persistent Pi RPC session and renders a basic ordered stream plus composer.**Why now:** This proves `/ui` is a real Pi frontend, not a companion page.**Scope:**- Fork active terminal session branch into a persistent web session where possible.- Spawn `pi --mode rpc --session <fork>` 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 session fork/RPC flags.**Verification:**- Automated: fork path selected; parent recorded; JSONL parser splits LF only; event sequence monotonic; reconnect replays or snapshots; RPC death produces actionable event.- 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 fork 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; 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, and explicit height negotiation.**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.new file mode 100644+949 / −0 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.- Use Pi fork semantics where possible.- 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 ├─ fork active terminal session branch into new persistent session ├─ spawn `pi --mode rpc --session <fork>` 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,- forked 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 session forking rather than ad-hoc JSON rewriting where possible.Preferred:```textsource = terminal ctx.sessionManager.getSessionFile()forked = SessionManager.forkFrom(source, ctx.cwd)spawn pi --mode rpc --session forked```The fork 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 forked 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 death as a stream error with fix instructions.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.- 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:- fork path selected when source session file exists,- full branch preserved,- 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`,- 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 forked 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 full-branch seeding may require `SessionManager.forkFrom` availability and behavior verification.- 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. Forked 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.