repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Add UI extension design and roadmap

2ff6020a149e83123337edabd6ad1cda8732c4cf

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

unsigned

Browse filesCompare with HEAD

Changed files (2)

+1307 / −0 text lines

Diff layout

docs/super/roadmaps/2026-07-01-ui-extension-roadmap.md

Added
new file mode 100644

+358 / −0 text lines

1# UI Extension Roadmap
2
3> **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.
4
5**Goal:** Build `/ui`, a persistent browser Pi frontend backed by a forked RPC session while terminal Pi remains independent.
6
7**Design Spec:** [`docs/super/specs/2026-07-01-ui-extension-design.md`](../specs/2026-07-01-ui-extension-design.md)
8
9**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.
11---
13## Phase 1: `/ui` Runtime Shell, LAN Server, Terminal Widget
15**Outcome:** `/ui` starts and stops a runtime with a token-authenticated LAN web server and minimal terminal widget.
17**Why now:** This creates the visible entry point, mobile link/QR path, and lifecycle shell every later phase uses.
19**Scope:**
21- Register `/ui`, `/ui off`, `/ui status`, `/ui open`, and `/ui qr`.
22- Start/stop one runtime per terminal session.
23- Bind LAN HTTP server with random token auth, same-origin CORS, and 401 handling.
24- Render terminal widget with OSC link, QR, host/port, session label, ESC help, `/ui off`, and connection state.
25- Restore terminal UI on `/ui off`, ESC, or session shutdown.
27**Out of scope:**
29- RPC subprocess.
30- Forked session history.
31- Full Pi web composer.
32- Visual widgets and telemetry.
34**Key files/areas likely affected:**
36- `extensions/ui/index.ts`: extension registration and commands.
37- `extensions/ui/server.ts`: HTTP server and token auth.
38- `extensions/ui/terminal-widget.ts`: terminal minimized widget.
39- `extensions/ui/qr.ts`: QR generation.
40- `extensions/ui/errors.ts`: typed startup/shutdown errors.
41- `extensions/ui/__tests__/`: harness and server tests.
43**Dependencies:**
45- Pi extension command/widget APIs.
46- QR generation dependency decision.
48**Verification:**
50- 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.
51- 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.
52- Visual: open browser link and bad-token URL; confirm authenticated page and precise 401 page are visibly distinct and understandable.
53- Visual: scan QR from phone on same LAN and see the same authenticated startup page.
55**Phase boundary health:** Terminal Pi still works independently; the browser page is only a shell, but start/stop/auth/restore are complete and testable.
57**Risks:**
59- Terminal APIs may not fully hide existing UI; mitigate by minimizing as far as APIs allow and documenting limitations.
60- LAN address detection may fail; mitigate with actionable stream/terminal error and `/ui status` diagnostics.
62**Context notes:** Keep startup work inside `/ui`; extension load must stay cheap and side-effect-free.
64## Phase 2: Forked RPC Session and Basic Web Stream
66**Outcome:** Browser UI talks to a forked persistent Pi RPC session and renders a basic ordered stream plus composer.
68**Why now:** This proves `/ui` is a real Pi frontend, not a companion page.
70**Scope:**
72- Fork active terminal session branch into a persistent web session where possible.
73- Spawn `pi --mode rpc --session <fork>` with normal extensions/skills/settings.
74- Parse RPC stdout as LF-delimited JSONL and capture stderr separately.
75- Implement server event bus, snapshot, replay buffer, WebSocket stream, and RPC stdin queue.
76- Render basic browser shell: top state strip, central stream, tiny status strip, composer.
77- Send normal prompts from browser and show user/assistant/tool/error stream items.
79**Out of scope:**
81- Complete slash-command parity.
82- Rich diffs/highlighting.
83- Visual widget tools.
84- Telemetry digest.
86**Key files/areas likely affected:**
88- `extensions/ui/session-seed.ts`: fork/fallback session seeding.
89- `extensions/ui/rpc.ts`: subprocess bridge and command queue.
90- `extensions/ui/protocol.ts`: event types, snapshots, replay.
91- `extensions/ui/web/`: initial browser shell, stream, composer, worker.
92- `extensions/ui/__tests__/rpc.test.ts`: parser, queue, death, stderr.
94**Dependencies:**
96- Phase 1.
97- Verified Pi session fork/RPC flags.
99**Verification:**
101- Automated: fork path selected; parent recorded; JSONL parser splits LF only; event sequence monotonic; reconnect replays or snapshots; RPC death produces actionable event.
102- Visual: open `/ui` and see seeded terminal history in the central stream with dominant `YOU` blocks.
103- Visual: send a browser prompt and watch user message, assistant stream, and tool lifecycle appear in order.
104- Visual: kill RPC process and confirm browser shows a clear, actionable stream error while terminal widget updates state.
106**Phase boundary health:** `/ui` becomes minimally useful as a browser Pi session; missing advanced syntax is visible but not broken.
108**Risks:**
110- Exact active-branch fork APIs may differ; mitigate by failing with actionable error rather than ad-hoc corrupt JSON rewriting.
111- RPC event shapes may need normalization; mitigate with typed protocol tests before UI assumptions spread.
113**Context notes:** Keep the stream deterministic and boring; defer polish until behavior is correct.
115## Phase 3: Pi Syntax, Commands, Keybindings, and Extension UI
117**Outcome:** Browser composer and controls match normal Pi interaction expectations.
119**Why now:** After the RPC path works, parity features can be layered without confusing transport failures with UI behavior.
121**Scope:**
123- Slash command autocomplete and execution.
124- `/skill:*`, prompt templates, model/thinking controls, compact/session commands where RPC supports them.
125- `@` file/image references and attachment flow.
126- `!`/`!!` bash behavior or explicit equivalent web mapping.
127- Enter, Shift+Enter, Esc abort, Ctrl+O expand/collapse, Ctrl+P model cycle.
128- Render RPC extension UI requests: select, confirm, input, editor, notify, status/title/widget/editor text.
129- Keep desktop chrome minimal; add tap targets only where mobile needs them.
131**Out of scope:**
133- Full-JS visual widgets.
134- Telemetry.
135- Pierre/Shiki polish.
137**Key files/areas likely affected:**
139- `extensions/ui/web/components/`: composer, autocomplete, dialogs, stream selection.
140- `extensions/ui/rpc.ts`: command adapters.
141- `extensions/ui/protocol.ts`: extension UI request/response events.
142- `extensions/ui/web/worker.js.ts`: batched input/event dispatch.
144**Dependencies:**
146- Phase 2.
147- RPC command availability check.
149**Verification:**
151- Automated: composer parsing for `/`, `/skill:*`, `@`, `!`, `!!`; keybindings dispatch expected RPC commands; dialogs return selected values.
152- Visual: type `/` and visually verify command autocomplete, skill entries, and prompt templates look and behave like Pi.
153- Visual: invoke select/confirm/input/editor flows and confirm dialogs appear in stream or modal form with clear action targets.
154- Visual: use Ctrl+P, Ctrl+O, Esc, Enter, Shift+Enter and see immediate visible state changes.
155- Visual: on phone width, confirm essential controls remain visible without desktop button clutter.
157**Phase boundary health:** Web UI now behaves like a normal Pi frontend for text, commands, tools, and extension UI; richer widgets remain additive.
159**Risks:**
161- Some terminal-only semantics may lack RPC equivalents; mitigate with explicit web mappings or visible unsupported errors.
162- Mobile controls can bloat desktop; mitigate by CSS/media-gated tap targets.
164**Context notes:** Preserve Pi syntax over inventing web-only controls.
166## Phase 4: Trusted Visual Widgets and `window.pi`
168**Outcome:** Agents can create, update, and receive actions from trusted full-JS visual widgets embedded in the stream.
170**Why now:** Widget actions require stable stream, composer, RPC, and extension UI foundations.
172**Scope:**
174- Register visual tool families for web RPC session: card, table, diagram, form/control, mockup/prototype, raw HTML/CSS/JS, update/patch, wait-for-action.
175- Render bounded visual blocks with stable widget ids, title, fallback text, lifecycle state, expand/collapse, and response expectation.
176- Expose `window.pi` methods for widget action/result, prompt/steer/follow-up, state, widget events, payload update, local notify, and attachment request.
177- Attribute every widget-originated action/prompt visibly in the stream.
178- Audit `window.pi` calls in details available to the agent.
179- Deliberately no sandbox or separate permission wall; full-JS widgets are trusted agent output, constrained by layout/lifecycle boundaries and visible attribution.
181**Out of scope:**
183- Telemetry digest beyond widget action events needed for actions.
184- Pierre/Shiki rendering polish.
185- Heavy virtualization.
187**Key files/areas likely affected:**
189- `extensions/ui/visual-tools.ts`: tool registration and fallback text.
190- `extensions/ui/web/components/`: visual block, widget bridge, errors.
191- `extensions/ui/protocol.ts`: widget lifecycle/action events.
192- `extensions/ui/errors.ts`: widget runtime/action errors.
194**Dependencies:**
196- Phase 3.
197- User decision: no sandbox; trust boundary is visual attribution/audit, not containment.
199**Verification:**
201- Automated: stable widget ids; fallback text returned; mount/update/action/error events; `window.pi` method routing; widget errors become human+agent actionable stream errors.
202- 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.
203- Visual: click widget controls and confirm resulting action is visibly attributed to that widget before reaching agent/session.
204- Visual: trigger a widget JS error and confirm the block shows widget id/tool call id plus human action and agent fix hint.
205- Visual: inspect expanded metadata and see `full JS / trusted`, lifecycle, fallback, ids, and audit details.
207**Phase boundary health:** Visual widgets are useful and honest about trust; later telemetry/perf can improve observability and scale without changing the bridge contract.
209**Risks:**
211- Trusted full JS can leak data or impersonate actions; accepted by design, mitigated only through visible attribution, audit, and no silent widget-originated prompts.
212- CSS/layout interference can damage page usability; mitigate with document/layout boundary, containment, overflow, and explicit height negotiation.
214**Context notes:** Do not reintroduce sandbox planning unless user changes the threat model.
216## Phase 5: Telemetry Digest and Browser Lifecycle Errors
218**Outcome:** Browser behavior is summarized for the agent on the next prompt, and inactive/closed/disconnected clients produce actionable state.
220**Why now:** Telemetry needs stable stream item/widget ids and working prompt submission.
222**Scope:**
224- Track scroll dwell, clicks/taps, pointer summaries, focus/blur, inactive time, viewport/device class, selected text, widget actions, form abandon/submit, and error visibility.
225- Aggregate locally into capped digest; redact obvious secrets from selected text/input fields.
226- Show inspectable “telemetry digest will be sent” when non-empty.
227- Attach digest once to next accepted user prompt, then clear.
228- Detect visibility changes, pagehide, heartbeat loss, WebSocket close, stale clients, and browser crash/disconnect symptoms.
229- Render human-facing and agent-facing lifecycle errors with retry safety.
231**Out of scope:**
233- Multi-tab single-socket optimization.
234- Advanced analytics UI.
235- Rendering polish.
237**Key files/areas likely affected:**
239- `extensions/ui/telemetry.ts`: digest aggregation and redaction.
240- `extensions/ui/web/worker.js.ts`: off-hot-path tracking.
241- `extensions/ui/server.ts`: heartbeat/client state.
242- `extensions/ui/web/components/`: digest indicator and lifecycle stream errors.
244**Dependencies:**
246- Phase 4.
248**Verification:**
250- Automated: scroll/click/focus/pagehide aggregate; digest cap/redaction; digest attaches once; heartbeat timeout states; disconnect errors include action/fix/retryability.
251- Visual: scroll, click, select text, background tab, return, and see an inspectable digest indicator near the composer/status.
252- Visual: send next prompt and confirm digest appears in/with the prompt context once, then disappears.
253- Visual: close tab, disable phone Wi-Fi, and kill browser; confirm top strip/stream errors say exactly what happened and what to do.
255**Phase boundary health:** The UI remains functional if telemetry fails; errors are visible and actionable rather than silent.
257**Risks:**
259- Telemetry can feel creepy/noisy; mitigate with digest-only, inspectable, capped, prompt-gated behavior.
260- Browser close detection is best-effort; mitigate with heartbeat timeout as source of truth.
262**Context notes:** Keep raw telemetry out of agent context; only digest crosses on user prompt.
264## Phase 6: Nugu Polish, Diffs, Highlighting, and Performance
266**Outcome:** The UI reaches accepted visual direction and handles long streams/code/diffs without blocking.
268**Why now:** Polish and scale are safest after core behavior and event contracts stabilize.
270**Scope:**
272- Apply Nugu semantic theme with `prefers-color-scheme` dark/light.
273- Strengthen terminal-like web layout: no sidebars by default, dominant user anchors, tiny top/status strips, brutal minimal styling.
274- Integrate Pierre for diffs with collapsed summary, expanded file views, anchors, copied hunks, and annotations where needed.
275- Integrate Shiki lazy/cached highlighting with plain text immediate fallback.
276- Add truncation, lazy expansion, virtualization threshold, `content-visibility`, `requestAnimationFrame` batching, `MessageChannel` chunks, and worker parsing for high-volume streams.
277- Ensure responsive widget/container behavior on desktop and phone.
279**Out of scope:**
281- New feature semantics.
282- Multi-tab SharedWorker optimization unless required by measured pain.
284**Key files/areas likely affected:**
286- `extensions/ui/web/app.css.ts`: Nugu theme and layout.
287- `extensions/ui/web/components/`: diff, code, long output, stream virtualization.
288- `extensions/ui/web/worker.js.ts`: batching and parsing.
289- `extensions/ui/package.json`: Pierre/Shiki deps.
291**Dependencies:**
293- Phase 5.
295**Verification:**
297- 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.
298- Visual: compare dark and light system themes and confirm Nugu semantics, dominant `YOU` messages, tiny status, and no useless side chrome.
299- Visual: render real edit diffs and code blocks; confirm plain text appears immediately, then upgrades to Pierre/Shiki without layout jump.
300- Visual: load a long tool-output stream and confirm scrolling, expansion, and selection remain smooth.
301- Visual: verify the same stream and widgets on phone width remain bounded and readable.
303**Phase boundary health:** Behavior should not change, only visual quality and scale; tests remain green against existing contracts.
305**Risks:**
307- Highlight/diff deps can slow startup; mitigate with lazy loading and immediate plaintext fallback.
308- Virtualization can break anchors/selection; mitigate with tests around selected item and replayed stream state.
310**Context notes:** Measure before adding more complexity; keep no-framework default.
312## Phase 7: Package Hardening, E2E, Manual Playbook
314**Outcome:** The extension is packaged, documented, and verified through automated and manual real-Pi/browser flows.
316**Why now:** Final hardening should validate the whole assembled system, not unstable intermediate APIs.
318**Scope:**
320- Finalize standalone package metadata, peer/dev deps, README, and no cross-extension imports.
321- Complete unit, harness, browser component, and E2E coverage around critical flows.
322- Harden shutdown cleanup: subprocess, server, sockets, timers, widgets, terminal restore.
323- Run and maintain manual testing playbook with real terminal, tmux, desktop browser, and phone.
324- Document known limitations: terminal minimization API limits, trusted full JS, LAN HTTP not encrypted, RPC unsupported semantics.
326**Out of scope:**
328- New UI features beyond spec.
329- Automatic RPC restart.
330- Old-browser support.
332**Key files/areas likely affected:**
334- `extensions/ui/package.json`: package and scripts.
335- `extensions/ui/README.md`: usage, security/trust, troubleshooting.
336- `extensions/ui/__tests__/`: full test suite.
337- Playwright/E2E test area chosen during detailed planning.
338- `docs/super/specs/2026-07-01-ui-extension-design.md`: only if implementation discovers spec corrections.
340**Dependencies:**
342- Phase 6.
344**Verification:**
346- 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.
347- 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.
348- Visual: capture or record final dark/light desktop and phone checkpoints for future regression comparison.
349- Visual: intentionally trigger failure cases and confirm each visible error has human action, agent hint, retryability, and related ids/session/log path.
351**Phase boundary health:** This is the release boundary; project should be green, documented, and manually reproducible.
353**Risks:**
355- E2E flakiness from real subprocess/browser timing; mitigate with fake-RPC tier plus smaller real-RPC smoke tests.
356- Manual playbook drift; mitigate by keeping it tied to visible checkpoints from this roadmap.
358**Context notes:** Do not expand scope during hardening; file discovered enhancements as later specs.

docs/super/specs/2026-07-01-ui-extension-design.md

Added
new file mode 100644

+949 / −0 text lines

1# UI Extension Design
2
3Date: 2026-07-01
4Status: Approved
5
6## Goal
7
8Create 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.
9
10The 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.
12## Non-goals
14- Do not replace Pi core.
15- Do not make the terminal and web sessions mirror each other live.
16- Do not make the web UI ephemeral by default.
17- Do not prevent parallel terminal/web use, even if both edit the same cwd.
18- Do not limit scope to a companion view; web UI must be a normal Pi frontend.
20## User decisions
22- Use RPC, not SDK in-process.
23- `/ui` minimizes the terminal Pi UI as much as extension APIs allow; `/ui off` restores it.
24- Web Pi session is independent and can run in parallel with terminal Pi.
25- Web session is persistent and normal.
26- Seed web session with full terminal active branch.
27- Use Pi fork semantics where possible.
28- Allow parallel edit races.
29- Mobile support uses LAN HTTP + random token.
30- Show QR code in terminal widget.
31- Agent-injected snippets may use full JS.
32- Full JS gets `window.pi` access by default.
33- Do not sandbox full-JS widgets; use visible attribution/audit and layout boundaries instead.
34- Include accepted mockup direction in this spec.
35- Theme must use Nugu semantics and respect system dark/light preference.
36- Prefer modern Chrome/Firefox APIs; no old-browser support.
38## Architecture
40```text
41terminal pi session
42 └─ /ui command
43 ├─ fork active terminal session branch into new persistent session
44 ├─ spawn `pi --mode rpc --session <fork>` subprocess
45 ├─ start LAN HTTP/WebSocket server with random token
46 ├─ show terminal widget: OSC link, QR, ESC cancel, /ui off help
47 └─ keep terminal session independent
49browser
50 ├─ GET snapshot
51 ├─ WebSocket event stream
52 ├─ Pi-capable composer
53 ├─ central stream renderer
54 ├─ full-JS visual widgets
55 └─ telemetry digest sent on next user message
56```
58### Runtime model
60`/ui` starts one web runtime per terminal Pi session unless an existing runtime is already active. The runtime contains:
62- local HTTP server bound for LAN access,
63- token-authenticated browser app,
64- WebSocket event channel,
65- spawned Pi RPC subprocess,
66- forked persistent session file,
67- in-memory event store and replay buffer,
68- telemetry aggregator,
69- terminal TUI minimizer state.
71`/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.
73### Terminal UI while active
75The terminal Pi UI is reduced to one custom widget as much as extension APIs permit. The widget shows:
77- clickable OSC 8 link,
78- QR code for mobile,
79- host/port,
80- session id/name,
81- “press ESC to cancel UI mode”,
82- “run `/ui off` to restore terminal UI”,
83- connection state: waiting, connected, inactive, disconnected, RPC dead.
85ESC in terminal while UI mode is active calls the same shutdown path as `/ui off`.
87## Session seeding
89Use Pi session forking rather than ad-hoc JSON rewriting where possible.
91Preferred:
93```text
94source = terminal ctx.sessionManager.getSessionFile()
95forked = SessionManager.forkFrom(source, ctx.cwd)
96spawn pi --mode rpc --session forked
97```
99The 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.
101The 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>`.
103If 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.
105## RPC subprocess
107The web runtime spawns Pi in RPC mode with normal extension/skill/settings discovery enabled.
109Requirements:
111- do not pass `--no-extension`, `--no-skills`, or `--no-session`,
112- pass the forked session via `--session`,
113- inherit cwd,
114- inherit normal environment,
115- parse stdout strictly as JSONL split on LF only,
116- capture stderr separately for diagnostics,
117- restart only by explicit user action, not automatically,
118- expose RPC death as a stream error with fix instructions.
120RPC commands used by the web UI:
122- `prompt`, `steer`, `follow_up`, `abort`,
123- `get_state`, `get_messages`, `get_commands`, `get_session_stats`,
124- `set_model`, `cycle_model`, `set_thinking_level`, `cycle_thinking_level`,
125- `compact`, `new_session`, `switch_session`, `fork`, `clone`,
126- `bash`, `abort_bash`,
127- `export_html`, `set_session_name`.
129RPC extension UI requests are rendered as normal stream items or dialogs:
131- `select`, `confirm`, `input`, `editor`,
132- `notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`.
134## Web transport
136### Binding and auth
138Use LAN HTTP with random token.
140- Bind to `0.0.0.0` or selected LAN interface.
141- Prefer a stable port if configured; otherwise port `0`.
142- Generate a 32-byte base64url token.
143- URL format: `http://<lan-ip>:<port>/?token=<token>`.
144- First HTML load requires query token and sets a `SameSite=Strict` cookie.
145- API and WebSocket require `Authorization: Bearer <token>` or auth cookie.
146- Never log the token except inside the terminal widget link/QR.
147- Restrict CORS to same origin.
149This follows the diff-review token pattern, but changes binding from `127.0.0.1` to LAN for mobile.
151### Browser lifecycle awareness
153The extension must quickly learn:
155- page close,
156- tab inactive,
157- browser crash,
158- network disconnect,
159- WebSocket close,
160- stale client heartbeat.
162Mechanisms:
164- browser sends heartbeat every few seconds while visible,
165- server marks client inactive on missed heartbeats,
166- browser sends `visibilitychange` events,
167- browser uses `pagehide` and `navigator.sendBeacon()` or `fetch(..., { keepalive: true })` for best-effort close notice,
168- server times out missing clients,
169- RPC continues unless `/ui off` or explicit stop occurs.
171Human-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.
173## Event and data flow
175```text
176RPC stdout JSONL
177 -> server parser
178 -> typed event bus
179 -> ordered event store
180 -> replay ring buffer
181 -> browser WebSocket
182 -> worker parse/batch
183 -> main-thread render store
184 -> stream components
186browser input
187 -> command builder
188 -> server auth
189 -> RPC stdin queue
190 -> RPC prompt/steer/follow_up/etc.
191```
193### Event model
195Every server-side event sent to browsers has:
197- `seq`: monotonically increasing number,
198- `time`: server timestamp,
199- `source`: `rpc | ui | telemetry | server`,
200- `type`: stable string,
201- `payload`: JSON payload,
202- optional `rpcId`, `messageId`, `toolCallId`, `entryId`, `widgetId`.
204Browsers 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.
206### Queues
208Server queues:
210- one RPC stdin command queue to serialize writes and correlate responses,
211- one RPC stdout event queue from JSONL parser,
212- one browser replay ring buffer,
213- one telemetry digest queue per browser/client,
214- one visual-widget event queue per widget id.
216Browser queues:
218- Worker receives WebSocket messages,
219- Worker parses and batches events,
220- main thread applies batches on `requestAnimationFrame`,
221- high-volume token/tool updates coalesce by message/tool id,
222- telemetry events aggregate off the hot render path.
224Do not depend on `scheduler.postTask`; support is limited. Use `requestAnimationFrame`, `MessageChannel`, and normal microtasks.
226## Web UI shell
228The shell is deterministic, stream-first, brutal, minimal, and Nugu-themed.
230Layout:
232- tiny top strip: Pi mark, running/disconnected state, `/ui off`,
233- central stream: all important things appear here,
234- bottom status strip: model, thinking, context,
235- bottom composer: normal Pi input syntax.
237No permanent sidebars by default. Contextual inspectors may appear only when a message/tool/widget is selected.
239### Stream item types
241The central stream renders:
243- user messages,
244- assistant text/thinking,
245- tool call/update/result,
246- visual widgets,
247- extension UI dialogs,
248- notifications,
249- warnings/errors,
250- permission prompts,
251- compaction/retry/status events,
252- telemetry digest when it will affect the next user prompt.
254User messages must visually dominate as primary anchors: strong border, high contrast, distinct spacing, and clear “YOU” label.
256Tool 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.
258### Composer
260The composer must preserve Pi syntax and expectations:
262- `/` commands and command autocomplete,
263- `/skill:*` skill invocation,
264- prompt templates,
265- `@` file/image references,
266- `!` and `!!` bash behavior where RPC supports it or equivalent web command flow,
267- Enter to submit,
268- Shift+Enter newline,
269- Esc abort when running,
270- paste handling,
271- image/file attachment.
273The 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.
275### Status
277Persistent status is intentionally tiny:
279- selected model,
280- thinking level,
281- context usage.
283Everything else appears where it matters:
285- notifications/warnings/errors in stream,
286- permission prompts in stream/dialog,
287- queued prompts near composer only when non-empty and understandable,
288- widget expand/collapse on the widget itself,
289- connection state in top strip and stream error when broken.
291## Accepted mockup
293The accepted direction is “terminal-like web”: pure stream plus Pi-capable composer, with Nugu/system-theme refinements.
295Key review notes incorporated:
297- messages, tools, and visuals all live in the main middle stream,
298- user messages must stand out strongly,
299- avoid useless side chrome and implementation detail labels,
300- status belongs near the composer and must be meaningful,
301- normal Pi syntax must work exactly as expected,
302- redundant buttons should be removed on desktop,
303- use Nugu and system theme,
304- use modern CSS so agent HTML still flows inside deterministic layout,
305- use Pierre/Shiki for beautiful diffs/highlighting,
306- browser close/inactive/crash errors must be detected and actionable.
308Representative mockup fragment:
310```html
311<style>
312.nugu-ui {
313 --bg: #070706;
314 --panel: #11100d;
315 --text: #f3efe5;
316 --muted: #9d9486;
317 --accent: #ff6a2a;
318 --minor: #2a2722;
319 --warn: #ffd35a;
320 --focus: #fff;
321 font: 14px ui-monospace, SFMono-Regular, Menlo, monospace;
322 background: var(--bg);
323 color: var(--text);
324 border: 4px solid var(--focus);
325 min-height: 580px;
326 display: grid;
327 grid-template-rows: 34px minmax(0, 1fr) 128px;
328}
329@media (prefers-color-scheme: light) {
330 .nugu-ui {
331 --bg: #f8f5ee;
332 --panel: #eee7d8;
333 --text: #17140f;
334 --muted: #70695f;
335 --accent: #b84722;
336 --minor: #d8cfc0;
337 --warn: #9c6a00;
338 --focus: #111;
339 }
340}
341.nugu-ui .top {
342 display: flex;
343 align-items: center;
344 justify-content: space-between;
345 border-bottom: 3px solid var(--minor);
346 padding: 0 12px;
347 background: var(--panel);
348 color: var(--muted);
349}
350.nugu-ui .stream {
351 max-width: 960px;
352 margin: auto;
353}
354.nugu-ui .row {
355 display: grid;
356 grid-template-columns: 92px minmax(0, 1fr);
357 gap: 14px;
358 margin: 0 0 14px;
359}
360.nugu-ui .who {
361 color: var(--muted);
362 text-align: right;
363 padding-top: 12px;
364 font-weight: 1000;
365}
366.nugu-ui .bubble {
367 border: 3px solid var(--minor);
368 background: var(--panel);
369 padding: 13px;
370 min-width: 0;
371}
372.nugu-ui .user {
373 border: 5px solid var(--focus);
374 background: var(--focus);
375 color: var(--bg);
376 box-shadow: 8px 8px 0 var(--accent);
377 font-size: 17px;
378 font-weight: 900;
379}
380.nugu-ui .visual {
381 border: 4px solid var(--accent);
382 background: var(--panel);
383 color: var(--text);
384 box-shadow: 8px 8px 0 var(--focus);
385 padding: 18px;
386 container-type: inline-size;
387 overflow: auto;
388 contain: layout paint;
389}
390.nugu-ui .bottom {
391 border-top: 4px solid var(--focus);
392 background: var(--panel);
393}
394.nugu-ui .status {
395 display: flex;
396 align-items: center;
397 justify-content: space-between;
398 padding: 7px 12px;
399 border-bottom: 2px solid var(--minor);
400 color: var(--muted);
401}
402.nugu-ui .editor {
403 border: 4px solid var(--focus);
404 background: var(--bg);
405 min-height: 58px;
406 padding: 10px;
407 color: var(--text);
408 box-shadow: 6px 6px 0 var(--minor);
409}
410</style>
411<div class="nugu-ui">
412 <div class="top">
413 <div class="brand">π</div>
414 <div>running</div>
415 <div>/ui off</div>
416 </div>
417 <main class="mid">
418 <div class="stream">
419 <div class="row">
420 <div class="who">YOU</div>
421 <div class="bubble user">I want Nugu, modern web, all Pi syntax.</div>
422 </div>
423 <div class="row">
424 <div class="who">TOOL</div>
425 <div class="bubble">Pierre diff / Shiki code block</div>
426 </div>
427 <div class="row">
428 <div class="who">VISUAL</div>
429 <div class="visual">Constrained full-JS widget</div>
430 </div>
431 </div>
432 </main>
433 <div class="bottom">
434 <div class="status">
435 <div><strong>sonnet</strong> · medium · ctx 31%</div>
436 <div>Esc abort · Ctrl+O expand · Ctrl+P model · / · @ · !</div>
437 </div>
438 <div class="composer"><div class="editor">Message Pi…</div></div>
439 </div>
440</div>
441```
443## Visual widget system
445Agents get UI tools injected into the web RPC session. Tool names are implementation detail, but tool families are:
447- visual message/card,
448- structured data/table,
449- diagram,
450- form/control,
451- mockup/prototype,
452- raw HTML/CSS/JS widget,
453- update/patch existing widget,
454- wait for widget user action.
456Every visual has:
458- stable `widgetId`,
459- title/label,
460- fallback text for agent context and terminal export,
461- expand/collapse state,
462- lifecycle: mounted, updated, action, closed, errored,
463- whether it expects user response,
464- telemetry summary scope.
466### Full JS policy
468Full JS widgets are allowed by default. They receive `window.pi` inside their execution context.
470`window.pi` exposes controlled methods:
472- send a widget action/result,
473- request agent prompt/steer/follow-up,
474- read current widget state,
475- subscribe to widget-scoped events,
476- update the widget payload,
477- show a local notification,
478- request file/image attachment through host UI.
480Full-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:
482- visual blocks show “full JS / trusted” in expanded metadata,
483- widget errors identify widget id and tool call id,
484- all widget-originated prompts/actions are visibly attributed in stream,
485- `window.pi` calls are audited in details available to the agent.
487### Layout constraints for agent HTML
489Agent HTML must flow inside deterministic stream layout.
491- Mount each widget in a bounded visual block.
492- Do not use iframe sandboxing or a separate permission wall for full JS.
493- Use `iframe srcdoc`, Shadow DOM, or equivalent document/layout boundary only to keep CSS, layout, and lifecycle contained.
494- Container gets fixed stream width, `max-width: 100%`, overflow boundary, and resize observer.
495- Host applies a minimal reset and Nugu CSS variables.
496- Widget document receives theme variables and container dimensions.
497- Use CSS containment: `contain: layout paint`, `content-visibility` where safe.
498- Use container queries for responsive widget internals.
499- Widget cannot resize the whole page except through explicit host height negotiation.
501## Diffs and code highlighting
503Use modern high-quality rendering:
505- Pierre for file diffs, preferably SSR/preload where possible.
506- Shiki for code highlighting, lazy and cached.
507- Show plain text immediately for long code, then upgrade async.
508- Never block startup on Shiki cold init.
509- Large tool/code outputs use truncation, lazy expansion, and virtualized rendering.
510- Diffs must support collapsed summary, expanded file-level view, line anchors, copied hunks, and annotations where needed.
512## Telemetry
514The browser tracks user behavior transparently and summarizes it for the agent on the next user message.
516Tracked classes:
518- scroll position and scroll dwell by stream item,
519- click/tap positions and target ids,
520- pointer movement summaries,
521- focused/blurred tab time,
522- inactive time,
523- viewport size and device class,
524- selected text,
525- widget action events,
526- form dwell/abandon/submit,
527- error visibility and whether user saw it.
529Rules:
531- collect locally in browser/worker,
532- aggregate into digest, not raw spam,
533- show “telemetry digest will be sent” when non-empty,
534- attach digest to next user prompt as hidden or visible context according to implementation choice, but it must be inspectable by user,
535- cap digest size,
536- redact obvious secrets from selected text and input fields,
537- do not send telemetry while no user prompt is sent,
538- clear sent digest after successful prompt acceptance.
540Example digest:
542```text
543UI telemetry since last message:
544- Viewed visual widget visual-42 for 18s.
545- Clicked Approve in visual-42.
546- Scrolled bash tool result tool-17 to bottom.
547- Tab inactive for 4m12s.
548- Form requirements-form abandoned after editing field “scope”.
549```
551## Error model
553Errors are first-class stream items and must be actionable.
555Every error has:
557- `code`,
558- severity,
559- human title,
560- precise human description,
561- human action,
562- agent hint,
563- source component,
564- retryability,
565- related ids/session path/log path.
567Human error example:
569```text
570Browser disconnected
571No heartbeat from Chrome for 12s. The RPC session is still running.
572Action: reload the QR/link page, or run /ui off to stop it.
573```
575Agent error example:
577```text
578ui_widget_render_failed
579Widget visual-42 threw ReferenceError: foo is not defined.
580Fix: call ui_update_widget with corrected JS, or replace widget with fallback HTML.
581```
583Error categories:
585- server bind failure,
586- no LAN address,
587- QR generation failure,
588- RPC spawn failure,
589- RPC JSON parse failure,
590- RPC process exit,
591- WebSocket disconnect,
592- browser inactive/closed/crashed,
593- auth failure,
594- widget render/runtime failure,
595- telemetry send failure,
596- session fork failure,
597- unsupported terminal OSC.
599## Performance architecture
601Browser target: current Chrome and Firefox only.
603Use:
605- normal WebSocket, not `WebSocketStream` because it is experimental/nonstandard,
606- HTTP snapshot + WebSocket events,
607- Dedicated Worker for WS parsing and telemetry aggregation,
608- optional SharedWorker later for multi-tab single-socket behavior,
609- native `EventTarget` as in-page event bus,
610- `BroadcastChannel` for same-browser tab coordination,
611- Web Locks only if multi-tab write coordination becomes necessary,
612- Web Components for message/tool/visual cards,
613- no framework by default,
614- CSS Grid/Flex, container queries, CSS containment,
615- `content-visibility: auto` for long stream items,
616- virtualization after a configurable item threshold,
617- `requestAnimationFrame` batching for DOM updates,
618- `MessageChannel` for cooperative chunks,
619- `OffscreenCanvas` only for heavy canvas widgets/diagrams.
621Avoid:
623- React/Vue/Angular,
624- old-browser polyfills,
625- `scheduler.postTask` as required dependency,
626- WebSocketStream,
627- main-thread JSON parsing for high-volume streams,
628- unbounded DOM growth,
629- layout measurement loops.
631## Package structure
633```text
634extensions/ui/
635 package.json
636 index.ts
637 server.ts
638 rpc.ts
639 session-seed.ts
640 terminal-widget.ts
641 qr.ts
642 protocol.ts
643 errors.ts
644 telemetry.ts
645 visual-tools.ts
646 web/
647 index.html.ts
648 app.css.ts
649 app.js.ts
650 worker.js.ts
651 components/*.ts
652 __tests__/
653 harness.test.ts
654 server.test.ts
655 rpc.test.ts
656 telemetry.test.ts
657 e2e.test.ts
658 README.md
659```
661Extension package requirements:
663- standalone package,
664- peer-depend on `@earendil-works/pi-coding-agent`,
665- dev-depend on `@marcfargas/pi-test-harness`,
666- include harness test,
667- no imports from other `@bugabinga/pi-ext-*` extensions,
668- startup fast: no blocking network, subprocess, or FS scans during `session_start`.
670Runtime startup work happens in `/ui` command, not extension load.
672## Commands
674### `/ui`
676Start UI mode. If already active, show current link/QR/status.
678Optional future args:
680- `--host <ip|0.0.0.0>`
681- `--port <port>`
682- `--local`
683- `--no-open`
684- `--no-qr`
685- `--session <path>`
687Argument autocomplete is required if subcommands/options are implemented.
689### `/ui off`
691Stop UI mode and restore terminal UI.
693### `/ui status`
695Show server URL, browser count, RPC status, web session path, last error.
697### `/ui open`
699Open browser again using desktop opener.
701### `/ui qr`
703Re-render QR/link widget.
705## Testing strategy
707### Unit tests
709Server/auth:
711- token required for `/`, APIs, and WebSocket,
712- query token sets cookie,
713- Bearer auth works,
714- bad token gets 401,
715- LAN URL generation chooses expected address,
716- body size limits,
717- CORS same-origin only.
719RPC bridge:
721- JSONL parser splits LF only,
722- parse errors become actionable events,
723- command ids correlate with responses,
724- stdin command queue serializes writes,
725- stdout events keep order,
726- subprocess exit generates typed error,
727- stderr is captured without leaking token.
729Session seed:
731- fork path selected when source session file exists,
732- full branch preserved,
733- parent session recorded,
734- display name set,
735- ephemeral source fallback behaves as specified,
736- failure gives actionable error.
738Event store:
740- monotonic sequence,
741- snapshot includes current state,
742- replay after reconnect,
743- replay miss triggers snapshot,
744- high-volume updates coalesce correctly.
746Telemetry:
748- scroll/click/focus/pagehide events aggregate,
749- digest size cap,
750- digest redaction,
751- digest attaches once to next prompt,
752- inactive/browser closed states detected.
754Visual tools:
756- widget ids stable,
757- fallback text returned to agent,
758- full-JS widget mount event emitted,
759- widget action flows to agent/web stream,
760- widget runtime error creates human+agent actionable error.
762Theme/rendering:
764- Nugu dark/light variables emitted,
765- `prefers-color-scheme` works,
766- stream item classes render expected roles,
767- user message has dominant styling.
769### Pi extension harness tests
771Use the real Pi extension runtime.
773- extension loads without side effects,
774- `/ui` command registers,
775- `/ui off/status/open/qr` commands register,
776- `/ui` starts runtime from command, not `session_start`,
777- terminal widget appears,
778- `/ui off` clears widget and restores UI state,
779- duplicate `/ui` is idempotent,
780- session_shutdown cleans subprocess/server/timers,
781- ESC terminal input cancels UI mode,
782- visual tools register only for the web RPC session as designed.
784### Web unit/component tests
786Use browser-capable tests where possible.
788- WebSocket worker batches events,
789- components render message/tool/visual/error/notice rows,
790- selected item expand/collapse,
791- keyboard shortcuts dispatch expected commands,
792- composer handles Enter/Shift+Enter/Esc,
793- command autocomplete renders slash commands and skills,
794- `@` references and `!` bash parsing match Pi expectations,
795- mobile layout hides nothing essential,
796- iframe widget bridge exposes `window.pi`,
797- widget height negotiation stays bounded.
799### E2E tests
801Use Playwright with real server and fake or real RPC subprocess depending on test tier.
803Critical flows:
805- run `/ui`, obtain URL/token, open browser,
806- QR URL and link route to same authenticated page,
807- initial snapshot shows forked session history,
808- send prompt from web, observe RPC events stream,
809- invoke slash command,
810- invoke `/skill:*`,
811- test command autocomplete,
812- attach `@` file/image reference,
813- run `!` bash equivalent,
814- model cycle via Ctrl+P,
815- expand/collapse via Ctrl+O,
816- abort via Esc,
817- tool call start/update/end renders,
818- visual full-JS widget mounts and sends action,
819- telemetry digest appears and is attached to next prompt,
820- tab inactive/active changes state,
821- close tab triggers heartbeat lost,
822- kill RPC subprocess shows actionable error,
823- kill/restart browser reconnects through snapshot/replay,
824- `/ui off` disconnects browser and restores terminal UI.
826## Manual testing playbook
828Run this in a real terminal with tmux and a real browser, not only automated tests.
830### Setup
8321. Open tmux session.
8332. Start real `pi` in `C:/Users/okr/Workspace/dotfiles/pi-ext`.
8343. Confirm repo has visible session history.
8354. Run `/ui`.
8365. Verify terminal becomes minimal widget with OSC link, QR, ESC help, `/ui off` help, connection state.
8376. Open desktop browser link.
8387. Scan QR from phone on same LAN.
840### Startup/session
842- Verify web loads with token.
843- Verify bad/missing token gets precise 401 page.
844- Verify web session is a persistent normal Pi session.
845- Verify web session history is seeded from the terminal active branch.
846- Verify terminal and web sessions can both receive prompts independently.
847- Verify web session appears in Pi session list with clear name and parent link.
849### Pi syntax/composer
851- Type normal prompt, verify response.
852- Use `/` autocomplete.
853- Invoke a prompt template command.
854- Invoke `/skill:<name>`.
855- Use `@` file reference.
856- Attach image/file if available.
857- Run `!pwd` or equivalent user bash.
858- Verify `!!` exclude-from-context behavior if supported.
859- Paste multi-line text.
860- Use Shift+Enter newline and Enter send.
862### Keybindings/status
864- Esc aborts running agent.
865- Ctrl+P cycles model.
866- Change thinking level if key/command is available.
867- Ctrl+O expands/collapses selected tool/visual block.
868- Verify status shows model, thinking, context usage.
869- Verify warnings/errors/notifications appear as stream items.
870- Verify permission/confirm/select/input/editor extension UI requests are usable.
872### Tools and stream
874- Ask agent to run `bash`, `read`, `grep`, `find`, `ls`, `edit` on safe files.
875- Verify tool start/update/end render live.
876- Verify long tool output is collapsed and expandable.
877- Verify edit diffs render beautifully with Pierre.
878- Verify code blocks highlight with Shiki after lazy upgrade.
879- Verify compaction/retry events display clearly.
881### Visual widgets
883- Ask agent to create a visual card.
884- Ask for a form with controls.
885- Ask for a diagram/prototype/mockup.
886- Ask for full HTML/CSS/JS interactive widget.
887- Click widget buttons and verify actions reach agent/stream.
888- Verify widget can update itself through `window.pi`.
889- Intentionally create widget JS error and verify human+agent error guidance.
890- Verify widget remains bounded and responsive on desktop and phone.
892### Telemetry
894- Scroll stream and tool output.
895- Click visual widget.
896- Select text.
897- Leave tab inactive for at least 30 seconds.
898- Return and send next prompt.
899- Verify telemetry digest is shown/inspectable and attached once.
900- Verify digest does not include obvious secret-like input.
902### Browser/mobile lifecycle
904- Close browser tab; terminal/web status should detect close/heartbeat loss.
905- Reopen link; snapshot/replay restores state.
906- Put phone browser in background; inactive state detected.
907- Disable phone Wi-Fi briefly; disconnect is clear and recoverable.
908- Kill browser process; server detects stale heartbeat.
910### Failure handling
912- Start `/ui` when preferred port is busy.
913- Start `/ui` with no LAN address if possible.
914- Kill RPC subprocess.
915- Break WebSocket auth token.
916- Force malformed RPC line in fake/dev mode if available.
917- Verify every failure gives exact action for human and fix hint for agent.
919### Shutdown/restore
921- Run `/ui status`.
922- Run `/ui qr`.
923- Run `/ui open`.
924- Press ESC in terminal widget.
925- Start again, then run `/ui off`.
926- Verify server stops, browser disconnects, RPC exits, terminal UI restores, and web session persists.
928## Open implementation risks
930- Extension APIs cannot truly replace the whole terminal UI; design intentionally minimizes terminal UI instead.
931- Exact full-branch seeding may require `SessionManager.forkFrom` availability and behavior verification.
932- RPC mode does not support some interactive-only UI methods; web must emulate or degrade.
933- `!`/`!!` exact terminal semantics may need explicit web-side mapping to RPC `bash`.
934- Full JS widgets are powerful and risky; attribution/audit is mandatory.
935- Mobile LAN HTTP is token-protected but not encrypted.
937## Planning recommendation
939This is large enough for a phased roadmap, not a single implementation plan.
941Suggested phases:
9431. Extension command + terminal widget + LAN auth server + QR.
9442. Forked RPC subprocess + event bridge + basic web stream/composer.
9453. Pi syntax, commands, skills, keybindings, status, extension UI protocol.
9464. Visual tools and full-JS widget bridge.
9475. Telemetry digest and lifecycle detection.
9486. Nugu polish, Pierre/Shiki rendering, virtualization/perf.
9497. Complete tests and manual playbook hardening.