@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1281 @@
1
+ # DSH Remote — mobile web client
2
+
3
+ Self-contained mobile SPA for the `dsh-remote-mobile` plugin. It is served **only** by
4
+ the plugin's standalone server (port 3456 by default) at `/`, `/app.js` and `/styles.css`.
5
+ Open it on a phone on the same local network, pair once, and control a DeepSeek Harness
6
+ session from the browser.
7
+
8
+ No framework, no npm dependencies, no CDN, no webfonts, no build step, no hashed
9
+ filenames. Everything shipped is plain HTML, CSS, browser JS, a manifest and PNG/SVG
10
+ icons.
11
+
12
+ | File | Purpose | Shipped |
13
+ | --- | --- | --- |
14
+ | `index.html` | App shell, inline SVG icon sprite, pairing + chat markup. References `/app.js?v=20` and `/styles.css?v=20`. | yes |
15
+ | `styles.css` | Design tokens and all component styles (light/dark, safe-area aware, reduced-motion aware). | yes |
16
+ | `app.js` | Transport, state, screens, safe markdown renderer, syntax highlighter, PWA/voice/notifications/share features. | yes |
17
+ | `manifest.webmanifest` | Installable PWA metadata, maskable icons and the Android Web Share Target. | yes |
18
+ | `sw.js` | Versioned (`v20`) shell service worker: navigation fallback, prefetched shell, stale-while-revalidate static assets; never caches `/api/*`, `/ws`, `/remote-mobile/*` or `/share-target`. | yes |
19
+ | `favicon.svg` | Small tab icon (same dark tile + signal mark as the app logo). | yes |
20
+ | `icons/icon-192.png`, `icons/icon-512.png` | `any`-purpose app icons. | yes |
21
+ | `icons/icon-maskable-512.png` | Maskable icon (glyph inside the 80% safe circle). | yes |
22
+ | `icons/apple-touch-icon.png` | 180 px iOS home-screen icon. | yes |
23
+ | `mock-server.js` | **Development only.** Zero-dependency Node mock of `/api/*`, `/ws`, the PWA/static routes and `/share-target`, including a hand-rolled RFC 6455 WebSocket server. Published only so a checkout can run it; the plugin never imports or serves it. | yes (dev helper) |
24
+ | `README.md` | This file (implementation notes; not served by the plugin). | yes |
25
+
26
+ > Packaging note: the host `package.json` `files` list names every shipped mobile asset
27
+ > (`index.html`, `app.js`, `styles.css`, `manifest.webmanifest`, `sw.js`, `favicon.svg`,
28
+ > `icons/*.png`, `mock-server.js` and this README); keep it in step when adding assets.
29
+
30
+ ---
31
+
32
+ ## Running the mock (development)
33
+
34
+ From the plugin root:
35
+
36
+ ```powershell
37
+ cd mobile
38
+ node mock-server.js # or: node mock-server.js 3457
39
+ ```
40
+
41
+ The server prints:
42
+
43
+ ```
44
+ Local: http://localhost:3456/
45
+ Network: http://<lan-ip>:3456/
46
+ PIN: 1234 (rotates after a successful PIN pair)
47
+ One-tap: http://localhost:3456/?t=<random token>
48
+ ```
49
+
50
+ Then either open the one-tap token URL (the SPA pairs, cleans `?t=` from the address bar),
51
+ or open `/` and enter the PIN. The PIN shown at startup is always valid; after a
52
+ successful PIN pairing the mock rotates it and logs the new one, matching the protocol's
53
+ rotation rule. Set `RM_KEEP_PIN=1` to disable rotation while developing.
54
+
55
+ Behaviour to exercise:
56
+
57
+ 1. **Pair** with the PIN or token link. Rate limiting is wire-compatible (5 failures /
58
+ 5 min → `429 { error: "rate-limited", retryAfterMs }`); use
59
+ `RM_RATE_WINDOW_MS=20000` to watch the countdown without waiting five minutes.
60
+ 2. **Chat history** opens automatically; the seeded transcript exercises markdown,
61
+ inline code, a fenced `js` block, a pipe table, lists, a blockquote, a link, a tool
62
+ card, a settled `ask_user_question` card, a seeded image attachment (served by the mock
63
+ preview route) and a failed tool.
64
+ 3. **Attach a file** — tap the paperclip in the composer and choose **Take photo**,
65
+ **Photo library** or **File** from the source sheet (camera uses
66
+ `capture="environment"`; the library path is image-only). Each file uploads immediately
67
+ with progress; images render as thumbnails in the chip and user bubble (tap for the
68
+ lightbox), non-images stay as pills, and the reply acknowledges the names.
69
+ `RM_MAX_UPLOAD_BYTES` (default 32 MB) and `RM_UPLOAD_DELAY_MS` make the
70
+ upload/413/waiting states easy to exercise; `RM_BROKEN_PREVIEW_FIXTURE=1` adds a missing
71
+ history image so the broken-preview pill can be exercised.
72
+ 4. **Send a prompt** — e.g. `Deploy the mobile build to staging`. The mock streams tokens,
73
+ emits a `tool.start`/`tool.end` pair, then asks a two-question `ask_user_question`
74
+ batch (radio + multi-select + custom text). Answer it, then approve the approval card
75
+ and the run finishes; reject it and the mock reports the denial. Skipping the question
76
+ batch records a declined outcome.
77
+ 5. **Ask a blocking question** — send `Ask me a blocking question`. The mock emits a
78
+ `question.request` with no tool row, resends it once to exercise dedupe, then streams
79
+ the closing reply after you answer.
80
+ 6. **Cross-session fixture** — send `cross-session fixture test`. The mock emits a pending
81
+ approval for the active session, a pending approval and a question for non-active
82
+ sessions, then forces a `history` reload. The active approval renders inline; the other
83
+ two appear in the notice bar with `Open`, which switches to the owning session and
84
+ re-attaches the card there.
85
+ 7. **Stop** while a run is streaming to see the stop button and `session.status`.
86
+ 8. **Activity** tab shows step boundaries, the tool call (expandable input/output), the
87
+ question and its answers, the approval and its resolution, filtered by All / Tools /
88
+ Errors.
89
+ 9. **Sessions / Model / Agent preset** sheets read the `sessions`, `models` and `presets`
90
+ frames. The mock seeds two project workspaces plus one ungrouped session, so the sheet
91
+ shows the same project grouping, **Show archived (N)** control and **Ungrouped** section
92
+ the real Host drives. The ⋯ **Commands** sheet lists four demo Host commands (`compact`,
93
+ `feedback`, `goal`, `plan`) with argument hints and opens the command-input sheet for the
94
+ hinted ones. Creating a session inserts it and opens it. The overflow sheet also hosts the
95
+ **Auto / Light / Dark** appearance control (stored in `localStorage`, applied before
96
+ first paint on the next load). In the Model sheet, **V4.1 Flash** (default effort
97
+ `Medium`) and **Claude Sonnet 4.5** (no default effort) open the reasoning-effort
98
+ picker; picking an effort updates the chip, the ⋯ **Model** row trailing label and the
99
+ mock session, while the plain models still select immediately.
100
+ 10. Delete the `rm_session` cookie or use the menu's **Unpair this phone** to return to the
101
+ pairing screen.
102
+ 11. **PWA / offline shell** — on `localhost` (a secure context) the mock serves
103
+ `/manifest.webmanifest`, `/sw.js` (with `Service-Worker-Allowed: /`) and the icons, so
104
+ the installable/offline shell can be exercised. Add the app to a home screen and reload
105
+ offline: the cached shell paints and the reconnect banner takes over until the server is
106
+ back. The mock sends the same strict CSP as the Host so CSP regressions surface here.
107
+ 12. **Share target** — open
108
+ `http://localhost:3456/share-target?title=Title&text=Hello&url=https%3A%2F%2Fexample.com`
109
+ (or call it from `navigator.share`-style tooling). The mock mirrors the Host's
110
+ `302 /?share=<json>`; the SPA strips the parameter, opens the session and prefills the
111
+ composer. `?share_text=` / `?share_url=` / `?share_title=` are accepted as aliases.
112
+ 13. **Voice input** — needs a real browser API. Chrome on `localhost` may expose
113
+ dictation; iOS Safari exposes `SpeechRecognition` only in some versions. The mic button
114
+ is hidden automatically when the API is missing.
115
+ 14. **Background notifications (Web Push)** — the mock serves `GET /api/push/key`
116
+ (a real, freshly generated 65-byte P-256 VAPID key), the cookie-gated
117
+ `POST /api/push/subscribe|unsubscribe|test|report` routes, and acks `client.visibility`
118
+ over the socket. On `http://localhost:3456` (a secure context) the full lifecycle works
119
+ in Chrome, including a real push-service subscription: **⋯ → Background notifications**
120
+ (Off → Enabled), **Send test notification** (`{ok:true,sent:1,gone:0}`), then tap the
121
+ switch again to unsubscribe. Mock delivery is intentionally local: it never reaches a
122
+ real push service, so the test route reports success without a network send.
123
+
124
+ Mock environment variables:
125
+
126
+ | Variable | Effect |
127
+ |---|---|
128
+ | `PORT` / `HOST` | Listen port (default 3456) and bind address (default `0.0.0.0`). |
129
+ | `RM_PIN` | Fixed pairing PIN (default `1234`); it rotates after a successful pair unless `RM_KEEP_PIN=1`. |
130
+ | `RM_RATE_WINDOW_MS` / `RM_RATE_MAX` | PIN rate-limit window and failure count. |
131
+ | `RM_MAX_UPLOAD_BYTES` / `RM_UPLOAD_DELAY_MS` | Upload cap and artificial upload latency (413 / progress states). |
132
+ | `RM_BROKEN_PREVIEW_FIXTURE=1` | Adds a missing history image to exercise the broken-preview pill. |
133
+ | `RM_SEARCH_DISABLED=1` | Makes `sessions.search` answer `unavailable` like a Host without the index. |
134
+ | `RM_APPROVAL_READONLY=1` | Marks the demo device `canApprove:false`. |
135
+
136
+ `node dev/capture-screenshots.mjs` starts this mock on a private port, pairs a demo device and
137
+ regenerates `docs/screenshots/` from the current shell (used by the root README).
138
+ 15. The mock also serves `/favicon.svg` and returns `204` for `/favicon.ico`, matching the
139
+ production static table.
140
+
141
+ Environment variables: `PORT`, `HOST`, `RM_PIN`, `RM_RATE_WINDOW_MS`, `RM_RATE_MAX`,
142
+ `RM_KEEP_PIN`, `RM_MAX_UPLOAD_BYTES`, `RM_UPLOAD_DELAY_MS`,
143
+ `RM_BROKEN_PREVIEW_FIXTURE`. The mock is dev-only: it is not imported by the plugin, has no
144
+ auth beyond the demo cookie, keeps uploaded bytes in memory (never on disk) to serve
145
+ `/api/preview`, and must never be exposed beyond localhost/LAN development.
146
+
147
+ ---
148
+
149
+ ## Design notes
150
+
151
+ A calm, premium chat surface: warm off-white in light mode (`#F7F5F2`), near-black in
152
+ dark (`#161616`), system serif for assistant prose and headings, system sans for UI
153
+ chrome, and a single ink/paper accent for primary actions. No gradient bloom, no
154
+ glassmorphism, no webfonts, no icon sheet — only inline SVG.
155
+
156
+ ### Theme
157
+
158
+ - Every colour, radius, duration and type family is a custom property in `styles.css`:
159
+ `:root` is the light palette, `:root[data-theme="dark"]` the dark one, and
160
+ `color-scheme` follows the effective theme.
161
+ - **No inline theme bootstrap** (the Host CSP is `script-src 'self'`, so inline scripts
162
+ are blocked). `app.js` resolves the persisted preference
163
+ (`localStorage["dsh-remote-theme"]`, values `auto` / `light` / `dark`) on init, writes
164
+ `<html data-theme>` plus every `<meta name="theme-color">`, owns the Auto / Light / Dark
165
+ segmented control in the overflow sheet, follows `prefers-color-scheme` while Auto is
166
+ selected (live, without a reload), and keeps the choice across sessions. The first
167
+ paint uses the light default until the deferred script runs.
168
+ - `prefers-reduced-motion: reduce` collapses transitions/animations and renders the
169
+ streaming caret steady.
170
+
171
+ ### Typography and shape
172
+
173
+ - Assistant replies are plain system serif (`"Iowan Old Style", "Palatino Linotype",
174
+ Palatino, "Book Antiqua", Georgia, "Times New Roman", serif`) at 17.5 px / 1.55 with
175
+ no bubble; headings, lists, blockquotes, links and inline code tune to the palette.
176
+ UI labels use the system sans stack; code, durations and timestamps use
177
+ `ui-monospace`.
178
+ - User messages are right-aligned warm-gray bubbles (20 px radius). Composer is a
179
+ floating pill with a circular 44 px primary button: ink on paper in light, paper on
180
+ ink in dark. Cards use 14–24 px radii, 1 px hairlines and only very soft shadows.
181
+ Question cards use the same card language with serif question text, 46 px option rows
182
+ and a single Skip/Submit pair; resolved cards settle into the elevated surface.
183
+ - Attachments use a 44 px paperclip button inside the composer, full-width progress
184
+ chips above it (name, size, upload percentage/error, 44 px remove hit area) and
185
+ image thumbnails (or file pills for non-images) inside the user bubble, with a
186
+ full-screen lightbox on tap — paths are never shown.
187
+ - Spacing follows a 4 px rhythm with 18–22 px transcript gaps and generous empty
188
+ states. Every primary control (icon buttons, tabs, send/stop, sheet rows, jump pill,
189
+ approval buttons, PIN submit, per-message actions) reaches 44 px; secondary controls
190
+ get invisible hit-area expansion.
191
+ - Below the composer pill sits one compact meta row laid out as a three-track grid:
192
+ status note (left) · context-window meter (exactly centred on the viewport) ·
193
+ Queue/Steer selector and model/effort chip (right). It is intentionally small
194
+ (10–10.5 px labels) so the header can stay title + status only; the note truncates
195
+ on the left, the chip ellipsizes on the right, and the row never scrolls
196
+ horizontally on 320–412 px phones. The header is the matching symmetric row: a
197
+ non-interactive spacer exactly one icon button wide balances the two-button right
198
+ cluster, so the title block and its status line are truly centred (measured
199
+ centre offset 0 px at 320/360/390/412 in both themes) while long titles ellipsize
200
+ between the icon buttons.
201
+
202
+ ### Accessibility and input
203
+
204
+ - Icon buttons have `aria-label`s, tabs use `role="tab"` + `aria-selected`, sheets are
205
+ `role="dialog" aria-modal`, logs are live regions, focus is restored on sheet close,
206
+ `:focus-visible` uses a 2 px ink ring, and links are external
207
+ `rel="noopener noreferrer nofollow"`.
208
+ - Safe areas: `viewport-fit=cover` plus `env(safe-area-inset-*)` padding on the top bar,
209
+ composer and bottom sheets. A `visualViewport` listener feeds `--app-h` so the iOS
210
+ keyboard does not hide the composer.
211
+ - No hover dependence; all state is visible and actionable by tap. Haptics
212
+ (`navigator.vibrate`, when available) fire on send, approve/reject and theme changes.
213
+ - Tool cards, activity entries and the markdown renderer are keyboard-accessible:
214
+ expandable rows are buttons with `aria-expanded`, and every text/code copy control is
215
+ a real button.
216
+
217
+ ---
218
+
219
+ ## Behaviour notes
220
+
221
+ ### Pairing
222
+
223
+ - Boot probes `GET /api/state`. Paired → connect; unpaired → pairing screen.
224
+ - A `?t=<token>` link immediately `POST`s `/api/pair { token }`, then strips the query
225
+ string with `history.replaceState`. Expired/consumed tokens fall back to the PIN form.
226
+ - PIN entry is a single transparent numeric input over four styled digit slots
227
+ (16 px font avoids iOS focus zoom, `autocomplete="one-time-code"` supports SMS/Keychain
228
+ autofill). Four digits auto-submit.
229
+ - Wrong PIN shakes and clears; `429` starts a visible `m:ss` countdown and disables entry.
230
+
231
+ ### Connection
232
+
233
+ - `ws(s)://<host>/ws` with the pairing cookie. Close code `4401` returns to pairing with
234
+ "device no longer paired".
235
+ - Reconnect uses exponential backoff `0.5s → 8s` (jittered, attempts capped), with
236
+ `connected / reconnecting / offline` banner states driven by `navigator.onLine`.
237
+ - On every reconnect the SPA re-sends `sessions.list` and, for the active session,
238
+ `history.load { limit: 50 }`, refreshing model/preset lists if they were already loaded.
239
+ - **Heartbeat and fast resume (v18).** After `ready`, on socket open and on every
240
+ `visibilitychange`, the page sends `{type:"client.visibility", visible}` (only while the
241
+ socket is `OPEN`) so the Host can suppress Web Push while a phone page is foregrounded.
242
+ Any incoming frame refreshes `lastPong`, and a `ping` goes out every 5 s. While the app
243
+ is visible a watchdog ticks every 5 s: if no frame has arrived for 15 s or the socket is
244
+ not `OPEN`, it tears the socket down and reconnects immediately with the backoff reset.
245
+ Returning to a foregrounded page is the important path: if the socket is missing or the
246
+ last frame is older than 10 s, the SPA reconnects immediately (no backoff wait), and one
247
+ quiet "Reconnected" toast is shown when the gap exceeded 2 s. A session-creation timeout
248
+ whose socket is down also forces an immediate reconnect instead of leaving the banner
249
+ stale. Nothing tries to keep a frozen page alive — this is intentionally "background
250
+ disconnect + instant, correct recovery on resume".
251
+
252
+ ### Transcript and streaming
253
+
254
+ - `assistant.delta` chunks accumulate in one live assistant item; DOM painting is
255
+ coalesced into `requestAnimationFrame`, and only the live bubble is re-rendered — the
256
+ list is never rebuilt per token. `assistant.end` finalises the bubble and removes the cursor.
257
+ - Sending is optimistic: a local user bubble is appended immediately and reconciled when
258
+ `history`/`session.opened` arrives. Pending bubbles are deduped against durable `user`
259
+ items by trimmed text; live assistant text survives transcript reloads.
260
+ - History tool items and live `tool.start`/`tool.end` are deduped by `callId`. Tool
261
+ cards are **collapsed by default** (icon, tool name, status, duration, chevron); a tap
262
+ expands a monospace args preview and scroll-capped output with a smooth height/opacity
263
+ transition. Failures still auto-expand, and the expanded/collapsed state survives
264
+ re-renders and the tool's own `tool.end` refresh.
265
+ - Assistant replies render as plain serif prose; a small **Copy** action copies the
266
+ message text, and tapping the prose reveals the message timestamp. User bubbles reveal
267
+ their timestamp on tap as well. Code blocks keep their language label and copy button.
268
+ - Scroll is pinned to the bottom unless the user scrolls up; a "Jump to latest" /
269
+ "New messages" pill appears. Switching to Activity and back preserves the transcript.
270
+ - Empty states: no session, no messages, and a filtered-out activity feed each have
271
+ purposeful copy (starter prompts only fill the composer, they never send).
272
+
273
+ ### Activity
274
+
275
+ The tab shares the chat palette: compact All / Tools / Errors filter, a live indicator
276
+ (green while connected, muted while reconnecting), and a timeline of the active
277
+ session's step boundaries, tool calls, approvals and errors. Tool, approval and error
278
+ entries are collapsible with the same animated body used by chat tool cards; expanded
279
+ state is stored per entry id and survives live re-renders while the view is open.
280
+
281
+ ### Approvals
282
+
283
+ `approval.request` renders an approval card with tool name, reason/displayReason, optional
284
+ callId and Approve/Reject. Answering is one-tap: both buttons disable while unanswered.
285
+ `approval.resolved` updates the card in place with the outcome
286
+ (`allowed-once` / `rejected` / `cancelled` / `unavailable`) and updates the Activity entry.
287
+ Approvals for a non-active session are remembered and surfaced when that session is
288
+ opened; a toast flags them immediately.
289
+
290
+ ### Questions (`ask_user_question`)
291
+
292
+ - A question batch is a **first-class card**, never a collapsed tool chip. It renders a
293
+ header (question `header` or tool title), a status chip (`Needs answer` / `Waiting` /
294
+ `Answered` / `Skipped` / `Unavailable`), each question in serif with its detail text,
295
+ radio rows for single-select, checkbox rows for `multiSelect`, an optional "Other"
296
+ text input per question, and one Skip/Submit pair for the whole batch.
297
+ - `question.request` creates a card keyed by `requestId` (works even when no `tool.start`
298
+ preceded it). A `tool.start` carrying `question` creates the same card keyed by
299
+ `callId`; a later `question.request` with the same callId merges into it, so a batch
300
+ is never duplicated. Duplicate/retried requests refresh the card without losing the
301
+ draft.
302
+ - Draft selections and custom text are stored on the transcript item, so they survive
303
+ re-renders (including a duplicate `question.request`). Submit is enabled once any
304
+ question has a selection or custom text; unanswered questions are omitted from the
305
+ answer batch. Skip sends an empty `answers` array (see the assumptions below).
306
+ - After `question.answer` the card locks into **Waiting for Harness…** until
307
+ `question.resolved` or `tool.end` arrives. Then it becomes a read-only card showing the
308
+ chosen labels and custom text (or `Skipped` / `No longer available`).
309
+ - Settled history rows (`kind: "tool"` with a `question` payload) render read-only; the
310
+ answer batch is parsed from the JSON `output` when possible and otherwise falls back to
311
+ **Answered**. The question is also recorded in the Activity feed.
312
+ - Pending questions for a non-active session are remembered in a client map and
313
+ re-attached to the transcript when that session is opened.
314
+
315
+ ### Cross-session interactions
316
+
317
+ - `sessionId` is authoritative: an approval/question whose `sessionId` differs from the
318
+ active session is stored in the client maps but **never** appended to the transcript.
319
+ Deduplication (tool.start + question.request twins) only merges items of the same
320
+ session, and `appendMessage` has a defensive boundary that refuses a foreign approval or
321
+ question. This prevents a card from the wrong session appearing inline.
322
+ - The notice bar is a direct child of the six-row `.app` grid on row 3 (between the tabs
323
+ and the connection banner): full-width, safe-area margins, warning surface, first owner
324
+ name and `(+N)` when more interactions are pending, with a 44 px **Open** action. It is
325
+ re-rendered whenever approvals/questions arrive, resolve or a session opens, and removes
326
+ itself when nothing foreign is pending.
327
+ - **Open** calls `openSession` for the owning session; `replaceTranscript` + the pending
328
+ maps re-attach the card inline there, with normal answer actions (the stale
329
+ `otherSession` flag is recomputed against the current active session, so a re-attached
330
+ card never keeps the foreign-session meta/Open row). Approval actions are equal-width
331
+ 46 px buttons in both themes (the primary button carries a transparent 1 px border so
332
+ it matches the ghost button's border box).
333
+ - The active session's own pending approval/question renders inline immediately and is
334
+ re-attached after a `history` reload by the same maps.
335
+
336
+ ### Attachments
337
+
338
+ - The paperclip button opens one hidden `<input type="file" multiple>` (no `accept`
339
+ filter, so images and arbitrary files are both selectable; on mobile the OS picker
340
+ offers Photos/Files). It is positioned inside the composer and is disabled while
341
+ offline or without an active session.
342
+ - On selection each file is queued and uploaded **sequentially** to
343
+ `POST /api/upload` (raw bytes) with `x-dsh-session`, `x-dsh-filename` and
344
+ `x-dsh-media-type` headers and the device cookie. `XMLHttpRequest` supplies real
345
+ per-file progress; Send is disabled while any upload is queued/running. Chips above the
346
+ composer show name, size, progress, errors and a remove control (removing an in-flight
347
+ file aborts its request). Files over the 32 MB client limit fail immediately with the
348
+ size message; a server `413` is surfaced on the chip as well.
349
+ - After upload the chip shows `Uploaded` (image chips get a small thumbnail), and a
350
+ successful response (validated for `name`/`path`/`relativePath`/`size`/`mediaType`) is
351
+ kept as the attachment object. Failed uploads block sending until removed (or retried by
352
+ selecting the file again).
353
+ - Image attachments render as rounded, `object-fit: cover` thumbnails inside the user
354
+ bubble (two per row, single images capped around 220 px high); non-image files stay as
355
+ file pills. Tapping a thumbnail opens a full-screen lightbox (dark backdrop, safe-area
356
+ padding, filename caption) that closes on the image/backdrop, the 44 px close button or
357
+ Escape. A thumbnail that cannot load is replaced by a `Preview unavailable` file pill.
358
+ - Optimistic images use `URL.createObjectURL(file)` for an immediate thumbnail; those
359
+ composer URLs are revoked on remove, send and clear. After a history reload the same
360
+ image is requested from
361
+ `GET /api/preview?session=<sessionId>&path=<encodeURIComponent(path)>` using the current
362
+ session; on error the bubble falls back to the file pill.
363
+ - Sending includes the successful upload objects as `attachments` on the `prompt` frame.
364
+ The optimistic user bubble keeps the message text plus image thumbnails/file-name pills
365
+ (never paths), and the chips clear only after the frame has been written to the socket.
366
+ If the send fails, the optimistic bubble is removed (its object URLs revoked), the
367
+ message is restored and the uploaded files stay attached. Attachment-only messages get
368
+ an `is-attachment-only` bubble with reduced padding.
369
+ - History user rows now carry `attachments: [{path,name,mediaType}]` (the mock does) with
370
+ the synthetic "Attached files…" block already stripped from `text`; the SPA uses those
371
+ entries to rebuild thumbnails/pills after a reload. Attachments are session-scoped:
372
+ switching sessions, unpairing or losing auth aborts uploads, clears the tray and revokes
373
+ outstanding bubble object URLs.
374
+ - Media type falls back to an extension map when the picker reports none, and the
375
+ filename header is sanitised to Latin-1/header-safe characters (the UI keeps the
376
+ original name).
377
+
378
+ ### Installable app and service worker (B7)
379
+
380
+ - `manifest.webmanifest` declares `name` / `short_name` "DSH Remote", `display`
381
+ `standalone`, `orientation` `portrait`, `scope` and `start_url` `/`, the warm light
382
+ `theme_color` / `background_color` (`#F7F5F2`), 192/512 `any` icons, a 512 maskable icon
383
+ and a `share_target` (`action: "/share-target"`, `method: "GET"`, `title`/`text`/`url`
384
+ params). `index.html` links the manifest, `/favicon.svg`, the 180 px
385
+ `apple-touch-icon`, two media-scoped `theme-color` metas (light/dark) and
386
+ `mobile-web-app-capable` next to the Apple meta tags.
387
+ - Icons are generated from the app's own logo language — a `#141210` ink tile with the
388
+ cream signal mark — at 192, 512, 512 maskable (glyph inside the central 80% safe circle)
389
+ and 180 apple-touch. They share the asset palette rather than a separate brand.
390
+ - `sw.js` is a zero-dependency classic worker with a versioned cache (`dsh-remote-v20`).
391
+ Install precaches `/`, `/app.js?v=20`, `/styles.css?v=20`, the manifest, favicon and all
392
+ icons, then `skipWaiting()`. Activate deletes older `dsh-remote-*` caches and calls
393
+ `clients.claim()`. Fetch: navigation → network first, caching the shell and falling back
394
+ to cached `/` (including `?share=` deep links) when offline; same-origin versioned/shell
395
+ assets → cache-first plus stale-while-revalidate; everything else is left to the
396
+ browser. It never intercepts or caches `/api/*`, `/ws`, `/remote-mobile/*`,
397
+ `/share-target`, `sw.js`, non-GET requests, cross-origin requests or opaque responses.
398
+ - Registration runs only when `'serviceWorker' in navigator` and
399
+ `window.isSecureContext` (HTTPS or localhost; plain-HTTP LAN URLs intentionally skip
400
+ it), with `{ scope: '/', updateViaCache: 'none' }` and a silent failure path. The
401
+ `controllerchange` listener reloads **once** when an update activates (guarded by
402
+ `swReloading`), and does not reload on the first install's `clients.claim()`.
403
+ - Theme: the previous inline `<head>` bootstrap was removed because the Host CSP allows
404
+ only `script-src 'self'`. `app.js` resolves the stored Auto/Light/Dark preference on
405
+ init and updates every `theme-color` meta; the root keeps `data-theme="light"` until
406
+ then.
407
+
408
+ ### Voice input (B8)
409
+
410
+ - A 44 px mic button sits in the composer (`#btn-mic`, `i-mic` sprite symbol). It is
411
+ feature-detected as `SpeechRecognition || webkitSpeechRecognition`; when neither exists
412
+ the button stays `hidden` — no dead control and no console noise.
413
+ - Tapping starts continuous recognition with `interimResults = true` and
414
+ `lang = navigator.language || 'en-US'`. Interim text is composed **after** whatever the
415
+ composer already contained (existing draft preserved; a single space joins segments);
416
+ final results append with a space. Tapping the mic again, sending, opening a sheet,
417
+ switching to Activity, reconnecting, hiding the page or switching sessions stops it and
418
+ commits the pending interim words into the composer first.
419
+ - Listening state: accent (ink pill) mic + pulse, `aria-pressed="true"`, placeholder
420
+ "Listening…"; the pulse is disabled by `prefers-reduced-motion`.
421
+ - `not-allowed` / `service-not-allowed` / `no-speech` / `network` / `audio-capture` are
422
+ mapped to short toasts and stop cleanly; `onend` restarts at most six times while the
423
+ user still wants dictation, and `aborted` (our own stop) never toasts.
424
+
425
+ ### Background notifications — Web Push (v18)
426
+
427
+ - **Why push.** Page-level `new Notification()` only fires while the SPA is alive and
428
+ hidden; a backgrounded phone freezes the page, so approvals, questions and finished
429
+ replies were silently missed. v18 moves delivery to the browser Push API: the Host sends
430
+ an encrypted payload to the phone's push service, the service worker shows it even when
431
+ the page is frozen, and tapping it re-opens the right session.
432
+ - **Requirements.** Push needs a secure context — HTTPS (Tailscale Serve or a trusted TLS
433
+ proxy) or `http://localhost`/`127.0.0.1`. Plain HTTP over the LAN has no service worker
434
+ and therefore no push; the menu row says **Needs HTTPS**. The user must grant
435
+ notification permission on the installed app/tab. iOS requires a Home Screen install and
436
+ iOS 16.4+; on Android Chrome, Web Push needs Google Play services present.
437
+ - **Menu row.** ⋯ → **Background notifications** now reports the real state: `Enabled`
438
+ (subscribed), `Off`, `Needs HTTPS`, `Unsupported`, `Permission denied`, or
439
+ `Subscription error` (with "tap to retry"). Enabling happens only on that tap: the SPA
440
+ checks `isSecureContext`, `serviceWorker`, `PushManager` and `Notification`, requests
441
+ permission, fetches `GET /api/push/key`, decodes the base64url VAPID key to bytes, calls
442
+ `registration.pushManager.subscribe({userVisibleOnly:true, applicationServerKey})`,
443
+ POSTs `subscription.toJSON()` to `/api/push/subscribe`, and toasts
444
+ "Background notifications on". Disabling calls `subscription.unsubscribe()` and then
445
+ `POST /api/push/unsubscribe` with the old endpoint before toasting
446
+ "Background notifications off". A **Send test notification** row sits below it, enabled
447
+ only while subscribed, and POSTs `/api/push/test`
448
+ (toast "Test notification sent" / "No subscription on the Host — enable again.").
449
+ - **Re-sync, never auto-prompt.** After every `ready` (start and reconnect) and when the
450
+ menu opens, the page reads `pushManager.getSubscription()`. When permission is already
451
+ granted and a subscription exists it is re-POSTed idempotently, but the SPA never asks
452
+ for permission on its own. A subscription that the Host pruned (404/410 on delivery) is
453
+ recovered by the service worker's `pushsubscriptionchange` handler or the next manual
454
+ enable. `subscribe()` is bounded by a 15 s timeout so a browser without a reachable push
455
+ service cannot leave the row stuck on "Enabling…".
456
+ - **Fallback (no doubles).** If the page is hidden, permission is granted, and there is no
457
+ live push subscription (unsupported/denied/not enabled), the old
458
+ `new Notification()` path still fires for approvals, questions and reply-finished with
459
+ the same per-tag/session dedupe. With a live subscription the service worker is the only
460
+ notifier, so nothing double-alerts. The tab title still gets the `● ` attention prefix.
461
+
462
+ ### Service-worker push handlers (v18)
463
+
464
+ - `push`: parses `event.data.json()` defensively (empty/malformed payloads still notify
465
+ with a fallback title/body), then
466
+ `registration.showNotification(title, { body, tag, icon:'/icons/icon-192.png',
467
+ badge:'/icons/icon-192.png', data:{ url, sessionId, kind } })`. The Host's `tag`
468
+ replaces a repeat notification for the same approval/question instead of stacking.
469
+ - `notificationclick`: closes the notification, focuses an existing same-origin app window
470
+ and `postMessage({type:'open-session', sessionId})`; without one it
471
+ `clients.openWindow(payload.url)` (`/?session=<id>`), so a cold tap opens the session
472
+ after pairing/ready.
473
+ - `pushsubscriptionchange`: best effort — GET `/api/push/key`, re-subscribe with the
474
+ decoded VAPID key, POST the new subscription; failure is retried on the next app start.
475
+ - The existing cache/install/activate/fetch behaviour is unchanged and still never touches
476
+ `/api/*`, `/ws`, `/remote-mobile/*` or `/share-target`.
477
+
478
+ ### Deep links and resume routing (v18)
479
+
480
+ - `/?session=<id>` is read on boot but consumed only after the `sessions` frame confirms
481
+ the id exists; the SPA opens that session once and strips the parameter with
482
+ `history.replaceState`. Unknown ids are left alone, and on an unpaired phone the link
483
+ waits until pairing completes (never auto-opens across the pairing screen). A
484
+ `{type:'open-session', sessionId}` message from the service worker takes the same path,
485
+ with a short retry window if the sessions frame is still in flight.
486
+
487
+
488
+ ### Camera and share target (B10 / B11)
489
+
490
+ - The paperclip now opens a source sheet with **Take photo** / **Photo library** / **File**.
491
+ One hidden file input is reconfigured per choice: `accept="image/*" capture="environment"`
492
+ for the camera, `accept="image/*" multiple` for the library, and no filter for generic
493
+ files. The existing sequential `/api/upload` pipeline is unchanged; the 44 px attach
494
+ button is fully inside the composer row (verified with bounding-box checks in earlier
495
+ passes; the composer has `overflow: visible` and the button has explicit 44 px
496
+ min-width/height).
497
+ - Web Share Target support: on boot the SPA reads `?share=<urlencoded JSON
498
+ {title,text,url}>`, with `?share_text=` / `?share_url=` / `?share_title=` as defensive
499
+ aliases. Title, text and URL are joined with newlines, a URL already present in the text
500
+ is not duplicated, the parameter is stripped with `history.replaceState`, and the result
501
+ becomes the composer draft (the view snaps to Chat). If no session is open yet the draft
502
+ is retained until one is opened/created, then applied. The Host side is
503
+ `GET /share-target` → `302 /?share=<json>` (already in `server.js`).
504
+
505
+ ### Markdown, code and safety
506
+
507
+ - `renderMarkdown` builds DOM nodes; **no untrusted text ever reaches `innerHTML`**. Text is
508
+ written with `textContent`, which is the escaping boundary. Supported subset: headings,
509
+ bold/italic (including `***`), inline code, fenced code, ordered/unordered lists with one
510
+ level of nesting, pipe tables with alignment markers, blockquotes, horizontal rules and
511
+ links. Unknown constructs stay literal.
512
+ - Links are accepted only for `http:`, `https:`, `mailto:` and same-origin relative paths.
513
+ - Fenced code with `js/ts/json/sql/bash/python/rust/html/css` is highlighted with a
514
+ priority-ordered sticky-regex tokenizer (comments, strings, keywords, numbers,
515
+ functions/variables/tags/attributes) that writes token text through `textContent`.
516
+ Unknown or missing languages render as plain code. Code blocks have a copy button with
517
+ a `execCommand` fallback for non-secure-context LAN pages.
518
+ - Reason about token rendering as "server/model text is hostile": it is always data.
519
+
520
+ ### State model
521
+
522
+ One active session at a time. `sessions` and `session.status` drive the drawer/running
523
+ indicator; `models`/`presets` are cached per connection; the Activity feed is per active
524
+ session and cleared on switch. Sheets are single-instance, re-renderable, animated and
525
+ drag-to-dismiss from the grabber.
526
+
527
+ ---
528
+
529
+ ### Session management (Batch C)
530
+
531
+ - The Sessions sheet mirrors the desktop's project grouping: one collapsible section per
532
+ registered project workspace (in Host display order) with a title, truncated root path,
533
+ folder glyph, member count and a persisted collapsed state
534
+ (`localStorage["dsh-remote-projects.v1"]`, default expanded), then an **Ungrouped**
535
+ section for sessions that belong to no workspace. Within a section, pinned sessions lead
536
+ followed by the Host's newest-first order. When the Host reports no workspaces (older
537
+ build, or a deployment without the workspace registry) the sheet falls back to flat
538
+ **Pinned** / **Recent** sections.
539
+ - Archived sessions are **hidden by default**, exactly like the desktop's default filter. A
540
+ centered **Show archived (N)** control above the list switches to showing them (grayed,
541
+ with the **Archived** tag) inside their project; **Hide archived** switches back. Archived
542
+ rows still open, but open read-only. The search filter forces project sections open while
543
+ a query is present and hides sections with no match.
544
+ - Rows show the running/idle dot, title, updated time + preset, a small pin marker, an
545
+ **Archived** tag and the active check.
546
+ - The search box keeps the old instant local title/preset filter. Typing ≥3 characters also
547
+ schedules a debounced (350 ms) `sessions.search`; `sessions.found` renders a **Messages**
548
+ section with title + snippet (result rows already in the session list are skipped). When
549
+ this deployment answers `unavailable`, the SPA disables message search for the sheet
550
+ lifetime, keeps the local filter and explains once (no retry spam, no broken UI).
551
+ - Session menu (⋯) row actions: **Rename** (sheet with pre-filled input, Save disabled while
552
+ blank, note that the desktop may shorten titles), **Pin/Unpin**, **Archive/Unarchive**
553
+ (second tap when a run is active sends `stopActivity: true`; the first tap only explains
554
+ the stop), and **Fork session** (second tap confirms; the fork arrives as a new
555
+ `session.opened`, and stale live state is dropped first). Rename updates the header/list
556
+ from `session.updated` and tolerates the following `sessions` refresh.
557
+ - Archived session rendering: a slim banner above the composer ("Archived session —
558
+ unarchive to continue") with an inline **Unarchive** action, send/mic/attach disabled,
559
+ stop hidden, transcript readable, queue/steer hidden. The menu also offers Unarchive.
560
+ - Live-only queue/steer UI is derived from `agentAvailable`; rename/pin/archive/fork stay
561
+ available for cold sessions. A `not-live` error becomes "This session is not live on the
562
+ desktop yet."; `forbidden` explains the device's approval restriction.
563
+
564
+ ### Reasoning-effort picker (v17)
565
+
566
+ - The Host `models` frame may carry `reasoning: { efforts: [{id,name,description}],
567
+ defaultEffort }` on a catalog entry; it is absent for models without an effort control.
568
+ `model.select` accepts `reasoningEffort` (an effort `id`; omitted/null = Host default),
569
+ and the selected effort is echoed in `sessions` rows and `session.opened.session` as
570
+ `model: { provider, model, reasoningEffort }`.
571
+ - The Model sheet shows a subtle trailing tag with the effort that applies (the current
572
+ effort for the active model, otherwise the advertised default, or `Default` when there
573
+ is none) plus a chevron. Tapping a reasoning-capable model opens a second sheet scoped
574
+ to that session and model: **Provider default** is offered only when `defaultEffort` is
575
+ absent, followed by every effort (name + optional description). The active effort is
576
+ marked (`aria-current`, check) and the advertised default carries a `Default` tag.
577
+ Choosing a row sends `model.select { sessionId, provider, model, reasoningEffort }`
578
+ (null for Provider default), closes the sheet and toasts
579
+ `Model set to V4.1 Flash · High` (or `· Default`). Models without `reasoning` keep the
580
+ immediate `model.select` behaviour.
581
+ - The bottom-right composer chip and the ⋯ menu **Model** row show `Label` alone when the
582
+ model has no effort control and `Label · EffortName` when one is active; both ellipsize
583
+ inside their shrinkable containers on 320–412 px. The chip updates optimistically on tap
584
+ and again from the server's `sessions` refresh / reopened session. The picker is scoped:
585
+ a sheet opened for one session can never emit a selection for another.
586
+ - The mock catalog advertises `V4.1 Flash` (efforts low/medium/high, `defaultEffort:
587
+ "medium"`), `Claude Sonnet 4.5` (efforts with `defaultEffort: null`, so Provider default
588
+ is offered) and plain `DeepSeek Chat`, `DeepSeek Reasoner` and `Qwen 2.5 Coder 32B`
589
+ entries, so both branches are exercisable in the dev mock.
590
+
591
+ ### Queue and steering
592
+
593
+ - Queue state is stored only for the active session from `session.opened.queue`, `queue`
594
+ and `queue.changed`; frames for another session are dropped (strict scoping). A compact
595
+ strip above the composer shows "N queued" (green dot, collapse chevron) and expands to
596
+ the items, each with a **Queued / Steering / Context** tag and two-line text preview.
597
+ - Tapping an item opens an action sheet: **Steer now** (only a queued item while the agent
598
+ is running), **Edit message** (textarea sheet, Save → `queue.update action:"edit"`), and
599
+ **Remove from queue** (tap-again confirm → `action:"remove"`). Optimistic local removal is
600
+ reconciled by the server's `queue.changed`/`queue` frames.
601
+ - While a session is running and live, the composer meta row shows a **Queue / Steer**
602
+ segmented control (queue is the default; forced back to queue whenever the run ends, the
603
+ session is archived or the agent is unavailable). Sending includes `mode: "queue" |
604
+ "steer"`. A rejected steer (`bad-request`) rolls back the optimistic bubble, restores the
605
+ text, flips to Queue and toasts. The strip disappears when the queue is empty, and a
606
+ cold/non-live session never shows queue UI.
607
+
608
+ ### Image limits (Batch D)
609
+
610
+ - `ready.limits.image` and `{type:"limits",image}` are stored (`null` allowed, unknown
611
+ fields ignored). The attachment sheet adds a hint when limits exist:
612
+ "Photos go straight to the model · up to N photos · M MB each" (maxImages/maxBytes).
613
+ - Before upload, image picks are pre-checked: an image over `maxBytes` is skipped with
614
+ "Image is larger than the N MB limit"; images beyond `maxImages` (counting images already
615
+ attached/uploading) are skipped with "Only N photos per message". Non-image files and the
616
+ existing upload pipeline are unchanged.
617
+
618
+ ### Approval context and device permission
619
+
620
+ - `approval.request` may now carry `argsPreview` (≤600 chars), `argsKind`
621
+ (`command|write|edit|other`) and `detail {kind,path?}`. The approval card renders an
622
+ uppercase context tag (Command / File write / Edit / Details), the optional path, and a
623
+ monospace preview collapsed to the first 6 lines; tapping the preview or the Show
624
+ more/less control expands it. The block is omitted entirely when the fields are absent.
625
+ Pending replay uses the same `approval.request` path, so restored approvals render
626
+ identically; the Activity entry shows the same label + preview.
627
+ - `ready.device` / `/api/state` may include `canApprove` (default true). When it is false,
628
+ approval cards stay expanded with full details but Approve/Reject are disabled and a
629
+ read-only note appears ("This device can't answer approvals — answer on the desktop or
630
+ another phone."); `approval.answer` is never sent, one-tap is blocked, and the Activity
631
+ row adds a read-only note. `deviceCanApprove()` defaults true for older Hosts (a ready
632
+ frame that omits the flag preserves the `/api/state` value).
633
+ - `error.code: "forbidden"` shows that same approval-permission guidance as a toast.
634
+
635
+ ### Context meter (Batch C3; moved to the composer meta row in v16, centred in v17)
636
+
637
+ - `session.opened.context` and `{type:"context",sessionId,…}` both feed one compact meter
638
+ on the **composer meta row** directly under the input — not in the header, which now
639
+ carries only the session title and status line. It reads `527k / 1M` in tabular
640
+ monospace next to a thin 56 px track (40 px at ≤380 px), with an `est.` pill when
641
+ `basis === "estimated"`. It is hidden for `basis: "unknown"`, missing windows or null
642
+ context, and frames for another session are dropped (strict scoping). Above 85% the
643
+ label, bar and `est.` pill switch to the warning palette.
644
+ - The meta row is `display:grid; grid-template-columns:minmax(0,1fr) auto minmax(0,1fr)`
645
+ with the meter as the auto centre track. Both side tracks resolve to the same width,
646
+ so the meter's bounding-box centre is the viewport centre line within ±1 px (measured
647
+ 0.0 px offset at 320/360/390/412) even when the note is long or the right cluster is
648
+ wide. The note is start-aligned with `min-width:0` and ellipsizes; the right cluster
649
+ (`Queue/Steer` + model/effort chip) is end-aligned, `min-width:0`, and the chip
650
+ ellipsizes, so neither can push the centre off. On the narrowest phones (≤380 px)
651
+ the decorative track is dropped while Queue/Steer shares the row (the `11.2k / 1M`
652
+ numbers stay) so the control fits inside its side track without moving the centre. The decorative `aria-hidden`
653
+ track/label fragments are backed by a `role="group"` `aria-label`
654
+ ("Context: … of … tokens used (…%, estimated)").
655
+ - The header is a symmetric flex row (`[drawer + spacer] · title · [compose, more]`):
656
+ the spacer is exactly one 44 px icon button wide, so the title block and the centred
657
+ status line sit on the viewport centre line without absolute positioning. The topbar
658
+ is 52 px tall in both themes and long titles ellipsize between the icon clusters.
659
+ - Refresh is event-driven, never a poll: `context.get` after opening a session, after each
660
+ `assistant.end`, when returning to the app, and for the active session on reconnect
661
+ resync. Stale responses for other sessions are ignored. Above 85% the label, bar and
662
+ `est.` pill switch to the warning palette (warm amber in both themes).
663
+
664
+ ### Changed-files review (Batch C3)
665
+
666
+ - The Activity view now has a **Changes** panel above the event stream. On session open,
667
+ after each `assistant.end`, on resume and on reconnect the SPA sends
668
+ `changes.list {limit:10}`; only the active session's `changes` frame is rendered.
669
+ - Each event is a small card: `Turn N · X files · +a −d`, with per-file rows (monospace
670
+ path, `+a/−d` or `binary`/`large`). An event with `available:false` shows
671
+ **“diff unavailable (session not live)”**.
672
+ - Tapping a file sends `changes.diff {seq,index}` and opens a diff sheet that starts in a
673
+ loading state. Text diffs render monospace lines with green/red tints for `+`/`-` and
674
+ context lines in both themes, `coarse` explains a whole-file hunk, binary/oversized get
675
+ explicit notes, and `error.code:"unavailable"` renders a “diff unavailable” state. The
676
+ renderer caps output at 1200 lines (with a truncation note) so a huge diff cannot create
677
+ thousands of nodes; the lines scroll inside the sheet.
678
+
679
+ ### Commands palette (v20)
680
+
681
+ - The ⋯ menu has a **Commands** row (only with an active session). It sends
682
+ `commands.list`; the sheet shows a spinner until the frame arrives and always rebuilds
683
+ through `buildSheet()` (clearing the body), so the loading row cannot survive under the
684
+ loaded list. A lost/refused reply times out after 10 s with “The Harness did not answer in
685
+ time — try again.” `available:false` explains why without executing anything: `not-live` →
686
+ “Commands need a live agent — send a message first…”, otherwise “Commands are not
687
+ available for this session.”
688
+ - The list mirrors the Host command registry for the live Agent (preset-mounted commands
689
+ included): typically `/compact`, `/goal`, `/plan`, `/feedback`, plus any future command.
690
+ `/export` (desktop-only ZIP download) and `/permission` (sandbox/approval policy switch,
691
+ including `danger-full-access`) are hidden by the bridge and refused if sent — a paired
692
+ phone must not be able to widen its own sandbox, and a device marked `canApprove:false`
693
+ must not be able to disable the approval gate. Rows show the command name, description and
694
+ the argument hint on its own line (2-line clamped description; the input sheet carries the
695
+ full hint).
696
+ - Tapping a command with an argument hint opens a **command-input** sheet headed by the
697
+ command name: an input pre-focused with the hint as placeholder and a **Run command**
698
+ action that sends `commands.execute { line: "/name <args>" }`. Commands without a hint keep
699
+ the double-tap confirmation before sending the bare `/name`. `command.result` toasts
700
+ `name — success/error` (with short trimmed text) and reloads `history.load` for the active
701
+ session because the Host logs the command event; context and changes are refreshed too.
702
+ `forbidden` / `not-live` / `bad-request` map to friendly toasts and clear the pending
703
+ command.
704
+
705
+ ### App lock (Batch E2, client-side privacy gate)
706
+
707
+ - The ⋯ menu has a **Privacy → App lock** switch. It is shown only when
708
+ `'PublicKeyCredential' in window` **and** `window.isSecureContext`; otherwise the row is
709
+ disabled and explains that it needs HTTPS (Tailscale) and a biometric-capable browser.
710
+ - Enabling runs on the tap gesture: `navigator.credentials.create` with a 32-byte challenge,
711
+ `rp {name:"DSH Remote", id: location.hostname}`, a random 16-byte user id,
712
+ ES256/RS256 params (−7/−257), `authenticatorAttachment:"platform"`,
713
+ `userVerification:"required"`, `residentKey:"preferred"`, 60 s timeout and no attestation.
714
+ On success the credential id (base64url), device id, enabledAt and unlockedAt are stored
715
+ under `localStorage["dsh-remote-applock.v1"]` (one entry per device; a credential from a
716
+ different device id is ignored). Toast “App lock on”.
717
+ - Lock behaviour: a cold start of the installed app is **always locked** until verified;
718
+ after a successful assertion there is a 5-minute grace, but returning after the app was
719
+ hidden for 30+ seconds locks again. The decision is a pure function
720
+ (`appLockShouldLock`) and is driven by `visibilitychange`/resume. The lock panel is an
721
+ opaque full-screen dialog; the app is `inert`, `aria-hidden` and `visibility:hidden`
722
+ behind it, and Unlock runs `navigator.credentials.get` with the stored credential id,
723
+ `transports:["internal"]`, `userVerification:"required"` and a 60 s timeout. Failure or
724
+ cancel shows “Could not verify — try again.” and stays locked.
725
+ - Disabling the row also requires a successful assertion first; only then is the stored
726
+ state removed and the overlay hidden (toast “App lock off”). Unreadable/corrupt lock state
727
+ fails open (usable) and logs nothing; every WebAuthn call is try/caught. The panel always
728
+ shows the recovery note: “Can't unlock? Revoke this device from the desktop pairing panel
729
+ and pair again.” The pairing cookie is never touched.
730
+ - **Honest limitation:** this is a client-side deterrent/privacy gate for the installed app,
731
+ not server enforcement. The pairing cookie/session remains authoritative, so a determined
732
+ attacker with the device/browser profile can still use the API; the real recovery is the
733
+ desktop pairing panel's revoke. WebAuthn requires a secure context (HTTPS via Tailscale
734
+ Serve or localhost), which is exactly why the row is disabled on plain-HTTP LAN URLs.
735
+
736
+ ## Protocol assumptions, deviations and TODOs
737
+
738
+ These are the places where the SPA had to make a choice because `PROTOCOL.md` is silent.
739
+ None change the wire format; all are client-side heuristics.
740
+
741
+ 1. **`history.hasMore` has no cursor/offset.** The protocol only sends `limit`, so older
742
+ pages cannot be requested deterministically. For now `hasMore` is ignored and only the
743
+ most recent history is rendered. *TODO:* add `before`/`cursor` to `history.load` if
744
+ pagination is wanted, then wire a "Load earlier messages" affordance.
745
+ 2. **No acknowledgements for `prompt`, `model.select`, `preset.select` or `stop`.** The UI
746
+ is optimistic: model/preset labels update on tap, optimistic user bubbles reconcile via
747
+ history, and stop stays "Stopping…" until `session.status { running: false }`. Failures
748
+ surface through `error` frames and toasts.
749
+ 3. **`sessions.create` has no documented response.** The SPA waits for the resulting
750
+ `sessions`/`session.opened` frames and times out after 12 s with a toast.
751
+ 4. **Approvals are not part of `HistoryItem`.** Pending approvals are kept in a client map
752
+ and re-attached to the transcript on `history` reload; resolved approvals live only in
753
+ the current view/Activity feed until the transcript reloads.
754
+ 5. **`assistant.delta.reasoning` is treated as an incremental chunk** (same as `text`).
755
+ Reasoning renders in a collapsed `<details>` block; if the Harness ever sends full
756
+ snapshots instead, this needs a flag.
757
+ 6. **Auto-open heuristic:** on first connect the SPA opens `ready.activeSessionId`, then
758
+ the last session stored in `localStorage`, then the first session in `sessions`.
759
+ `session.status` is authoritative for the running indicator; `assistant.start` only
760
+ shows the typing state and clears on first delta.
761
+ 7. **Activity is per active session.** Switching sessions clears the feed; global
762
+ cross-session event history is not reconstructed from frames.
763
+ 8. **Service worker + offline shell.** `sw.js` (cache `dsh-remote-v20`) now precaches the
764
+ shell and serves it offline, but only in a secure context: HTTPS or `localhost`. Plain
765
+ `http://<lan-ip>:3456/` deliberately does not register a worker, so the "offline-ish"
766
+ reconnect/banner/resync behaviour still applies there. Bump the cache name **and** the
767
+ `?v=` references together when the shell changes; the page reloads at most once when an
768
+ update activates.
769
+ 9. **WS close `4401`** is the only auth-loss signal handled; other close codes follow the
770
+ normal reconnect policy.
771
+ 10. **Mock-only:** fixed `1234` PIN at boot, in-memory state, no token signing, and a
772
+ single-connection-friendly global active session. The real Host owns auth, pairing and
773
+ persistence; the mock exists only to drive this SPA end to end.
774
+ 11. **Question frames are a protocol extension.** `question.request`, `question.resolved`,
775
+ `question.answer` and the `question` payload on `tool.start`/history tool items are
776
+ implemented exactly as specified to this SPA. The host-side bridge and `PROTOCOL.md`
777
+ are owned by the Lead; nothing else in the wire format changed.
778
+ 12. **Skip semantics.** `question.answer` has no explicit decline flag, so Skip sends
779
+ `answers: []`. The Host is expected to treat that as `question.resolved` with
780
+ `outcome: "declined"`. If the bridge prefers a different signal, this is the single
781
+ place to align.
782
+ 13. **Duplicate question frames.** `tool.start` may carry the batch and `question.request`
783
+ may follow for the same call; the SPA dedupes by `requestId`/`callId`, merges the
784
+ payloads and preserves the draft. A duplicate `question.request` only refreshes the
785
+ card. Interactive questions live in a client map (like approvals) so they survive a
786
+ `history` reload; settled history rows render read-only.
787
+ 14. **Answer batch shape.** Answers are sent as `{ id, selected: [labels], custom? }`;
788
+ unanswered questions are omitted and `custom` is omitted when empty. Resolved answers
789
+ are matched to questions by `id` and custom text is shown as `Other: …`. History
790
+ `output` JSON is parsed tolerantly (`{answers}` wrapper or a bare array) and falls
791
+ back to **Answered** when it cannot be parsed.
792
+ 15. **Uploads/attachments/previews are a protocol extension.** `POST /api/upload` (raw
793
+ bytes, device cookie, `x-dsh-session` / `x-dsh-filename` / `x-dsh-media-type` headers),
794
+ the `attachments` array on the `prompt` frame, history user attachments
795
+ (`{path,name,mediaType}`) and `GET /api/preview?session=…&path=…` are being added by
796
+ the Host. The SPA sends the upload response objects back verbatim and never renders
797
+ paths; the Host appends them to the prompt text for the agent. Preview requests use
798
+ the current session id and only for png/jpeg/webp/gif; any other type or an error
799
+ falls back to a file pill.
800
+ 16. **Filename header sanitisation.** HTTP header values are byte strings, so
801
+ `x-dsh-filename` replaces control/non-Latin-1 characters with `_` (the original
802
+ name stays in the UI/chips). If the Host prefers percent-encoded UTF-8 names, this is
803
+ the one place to align.
804
+ 17. **Size limit.** Files over 32 MB are rejected client-side before upload, and a server
805
+ `413` is also surfaced on the chip. The Host is the authority; the client guard is a
806
+ fast-fail courtesy.
807
+ 18. **Attachment-only sends.** A message may have files and no text; the SPA sends
808
+ `text: ""` plus `attachments`. The Host must accept that combination (the mock does).
809
+ Unanswered failed uploads block sending until removed.
810
+ 19. **Object-URL lifecycle.** Composer thumbnails use a blob URL that is revoked on
811
+ remove/send/clear; the optimistic bubble gets its own blob URL (so the thumbnail
812
+ survives the chip teardown) which is revoked when a history reload replaces that
813
+ message, on session switch, reset or unpair. History thumbnails use `/api/preview`
814
+ instead of blobs.
815
+ 20. **History attachment metadata.** User history items carry
816
+ `attachments: [{path,name,mediaType}]` with the synthetic "Attached files…" block
817
+ already stripped from `text`. The mock emits this shape; older hosts that omit it
818
+ simply render no previews/pills.
819
+ 21. **Session scoping is client-side.** An approval/question is rendered inline only when
820
+ its `sessionId` equals `S.activeSessionId`; otherwise it is kept in the pending maps
821
+ and surfaced by the notice bar. A frame without `sessionId` is treated as belonging
822
+ to the active session (there is nothing to scope it against). Duplicate question
823
+ frames only merge within the same session, and `appendMessage` refuses a foreign
824
+ approval/question as a defensive boundary. The notice bar itself is client-only.
825
+ 22. **Web Share Target contract (B11).** `manifest.share_target` is
826
+ `{ action: "/share-target", method: "GET", params: { title, text, url } }`. The Host
827
+ route answers `302 /?share=<encodeURIComponent(JSON)>` (mirrored in `server.js` and the
828
+ mock). The SPA additionally accepts `?share_text=`, `?share_url=` and `?share_title=`
829
+ as defensive aliases; those aliases are a client convenience, not part of the manifest
830
+ contract. The draft is prepared but never auto-sent.
831
+ 23. **PWA static serving requirements (B7).** The Host must keep serving `/sw.js` from the
832
+ site root with `Service-Worker-Allowed: /` and no HTTP caching, the manifest with
833
+ `application/manifest+json`, the PNG/SVG icons, and the CSP `worker-src 'self'`
834
+ (already true in the frozen `server.js`/CSP). The host-owned `package.json` `files`
835
+ list must also include the new PWA assets (reported to the Lead; not edited here).
836
+ 24. **Background notifications are Web Push (v18).** The service worker handles `push`,
837
+ `notificationclick` and `pushsubscriptionchange`; the page owns the subscription
838
+ lifecycle and reports `client.visibility`. The old page-level `Notification` path is
839
+ kept only as a fallback when the page is hidden, permission is granted and no push
840
+ subscription is live, so the two paths never double-alert. Permission is requested only
841
+ on the menu row's user gesture; on boot the SPA re-POSTs an existing subscription but
842
+ never prompts. Mock delivery is local by design (the test route answers without a real
843
+ network push), and platforms without a push service surface the `Subscription error`
844
+ state rather than pretending to work.
845
+ 25. **Voice uses the browser's Web Speech service (B8).** Recognition is network-backed on
846
+ most platforms, deliberately feature-detected, and continuous mode is approximated by
847
+ restarting `onend` up to six times while the user is still listening. There is no
848
+ offline fallback and no audio ever leaves the SPA's own APIs.
849
+ 26. **Theme boot moved into app.js (B7/CSP).** The Host CSP allows only `script-src 'self'`,
850
+ so the old inline `<head>` theme bootstrap was removed. `app.js` applies the persisted
851
+ Auto/Light/Dark preference on init and updates all `theme-color` metas; the very first
852
+ paint is the light default until the deferred script runs.
853
+
854
+ ---
855
+
856
+ ## Verification performed
857
+
858
+ ### Project grouping, archived filter and command palette (v20, current)
859
+
860
+ Verified against the installed plugin on `127.0.0.1:3456`:
861
+
862
+ - `node --check mobile\app.js` and `node --check mobile\sw.js` → exit 0.
863
+ - `node dev\spa-check.mjs` → `PASS spa check (964 helpers, 64 cached ids, v20)`; page refs,
864
+ `CACHE` and `PRECACHE` all agree on v20.
865
+ - `node dev\static-check.mjs` → `/app.js?v=20 200 text/javascript; charset=utf-8` (323,911
866
+ bytes), `/styles.css?v=20 200 text/css` (85,744 bytes), manifest + 3 PWA icons +
867
+ `/share-target` OK.
868
+ - `node dev\ui-check.mjs` (paired headless Chrome, 412×915): project-grouped Sessions sheet
869
+ with title/root path/count, **Ungrouped** section, collapse/expand round-trip persisted in
870
+ `dsh-remote-projects.v1`, zero archived rows in the default list, **Show archived (N)**
871
+ reveals them and **Hide archived** hides them again, and the Commands sheet lists
872
+ `compact/feedback/goal/plan` (no `/export` or `/permission`) with no surviving loading
873
+ spinner; argument commands open the input sheet; zero console errors.
874
+ - Live protocol: `commands.list` returned the four benign Host commands with hints, without
875
+ `/export` or `/permission`; `/compact` and `/goal` executed (`command.result name`
876
+ preserved) and an unknown command was refused `forbidden` (`dev/commands-live.mjs`). Every
877
+ `ready`/`sessions` frame carried `workspaces` and session rows carried `workspaceId`;
878
+ `dev/session-features-live.mjs` still passes rename/search/pin/archive/cold guards.
879
+ - `node dev\layout-probe.mjs` at 320, 360 and 412 px: `scrollWidth === innerWidth`,
880
+ `titleCenterOffset 0`, `meterCenterOffset 0`, `offenders []` (the grouped sheet did not
881
+ disturb the centred header/footer or introduce overflow).
882
+
883
+ ### Background Web Push + fast-resume resilience (v18)
884
+
885
+ Run from a checkout of this plugin:
886
+
887
+ - `node --check mobile\app.js` → exit 0; `node --check mobile\sw.js` → exit 0;
888
+ `node --check mobile\mock-server.js` → exit 0.
889
+ - `node dev\static-check.mjs` → `/app.js?v=20 200 text/javascript; charset=utf-8 bytes
890
+ 312522`; `/styles.css?v=20 200 text/css; charset=utf-8 bytes 83860`;
891
+ `PASS static asset + header check` (exit 0; CSP, PWA surface, `Service-Worker-Allowed`).
892
+ - `node dev\spa-check.mjs` → `PASS spa check (930 helpers, 64 cached ids, v18)`; page refs,
893
+ `CACHE` and `PRECACHE` all agree on v18.
894
+ - `node dev\server-smoke.mjs` → `PASS bridge image attachment checks`, `PASS approval
895
+ context checks`, `PASS transport smoke test` (frozen server untouched).
896
+ - **Service-worker VM harness** (stub `self`/`caches`/`clients`/`registration.showNotification`/
897
+ `pushManager`, run with Node `vm`): **15/15 PASS**, actual lines:
898
+ - handler presence; install precaches the v18 shell; activate deletes older caches;
899
+ fetch never intercepts `/api/`, `/ws`, non-GET; versioned shell still cache-first.
900
+ - `push` renders title/body/tag/data/icon/badge; empty payload and malformed JSON still
901
+ notify with fallback copy; hostile types are sanitised.
902
+ - `notificationclick` closes + focuses + `postMessage({type:'open-session',sessionId})`;
903
+ falls back to `clients.openWindow('/?session=…')`; ignores cross-origin clients.
904
+ - `pushsubscriptionchange` GETs `/api/push/key`, subscribes with the decoded key and POSTs
905
+ `/api/push/subscribe`; disabled key is a best-effort no-op.
906
+ - **Static integration harness**: **15/15 PASS** — v18 coherence, push endpoint wiring,
907
+ subscription lifecycle (`/api/push/*`, `applicationServerKey`, `userVisibleOnly`,
908
+ `toJSON`, unsubscribe), menu states (`Enabled/Off/Needs HTTPS/Unsupported/Permission
909
+ denied/Subscription error`), no-auto-prompt sync on `ready`/reconnect, page-notification
910
+ fallback gating, `client.visibility` on ready/socket-open/visibilitychange, `lastPong` on
911
+ every frame, watchdog constants (`5000/15000/10000/2000`) and conditions, session-timeout
912
+ reconnect, `?session=` parse/consume/strip/open + SW `open-session` message, zero
913
+ `console.*` in app.js/sw.js, no inline scripts or handlers, mock push routes and
914
+ visibility ack.
915
+ - **Headless Chrome drive** (`Chrome/157.0.8103.38`, mock server paired through
916
+ `POST /api/pair`): boot reached **Ready** with **`consoleMessages: []`** and
917
+ **`exceptions: []`** after ~8 s; two `{"type":"client.visibility","visible":true}` frames
918
+ were captured on the socket (socket-open + ready); `GET /api/push/key` returned
919
+ `enabled:true` with a **65-byte** decoded key; the service worker was active with a
920
+ `pushManager`. Driven lifecycle:
921
+ - menu row **Off** ("Off — enable background alerts"), test row disabled;
922
+ - `Browser.grantPermissions(notifications)` then tap → **Enabled**, real FCM
923
+ subscription created, toast "Background notifications on";
924
+ - **Send test notification** → toast "Test notification sent" (mock `{ok,sent:1}`);
925
+ - tap again → subscription `null`, toast "Background notifications off", rows back to Off.
926
+ - **Resume recovery**: emulated offline + closed the socket + simulated a hidden page for
927
+ 2.6 s, then online + visible → reconnected from `Ready` in **105 ms** with one
928
+ "Reconnected" toast and `client.visibility` false→true frames (3 socket instances).
929
+ - **Deep link**: `/?session=sess-api` opened "API refactor notes" and the URL became `/`.
930
+ - **Not verified here:** a real Host→push-service delivery (encrypted RFC 8291 payload on a
931
+ locked phone) and iOS 16.4+ installed-app push; the mock never sends over the network and
932
+ the Host was not restarted. The SW/notification rendering was driven through the VM
933
+ harness and the real subscription lifecycle through Chrome; page-level fallback was
934
+ covered statically (it requires a hidden page without a subscription).
935
+
936
+ ### Header/footer alignment + reasoning-effort picker (v17)
937
+
938
+ Run from a checkout of this plugin:
939
+
940
+ - `node --check mobile\app.js` → exit 0; `node --check mobile\sw.js` → exit 0;
941
+ `node --check mobile\mock-server.js` → exit 0.
942
+ - `node dev\static-check.mjs` → `/app.js?v=17 200 text/javascript; charset=utf-8 bytes
943
+ 293567`; `/styles.css?v=17 200 text/css; charset=utf-8 bytes 83860`;
944
+ `PASS static asset + header check` (exit 0; v17 ref pair, CSP, PWA surface and
945
+ `Service-Worker-Allowed` intact).
946
+ - `node dev\spa-check.mjs` → `PASS spa check (887 helpers, 64 cached ids, v17)` (exit 0;
947
+ index.html + sw.js version refs, CACHE and PRECACHE all agree).
948
+ - `node dev\server-smoke.mjs` → `PASS bridge image attachment checks`, `PASS approval
949
+ context checks`, `PASS transport smoke test` (exit 0; the frozen server is untouched).
950
+ - **CDP geometry of the checkout** (bundled `mobile/mock-server.js` + a throwaway probe in a
951
+ temp dir outside the checkout; paired through `POST /api/pair`, `Emulation.setDeviceMetrics
952
+ Override` + `Emulation.setEmulatedMedia`). At 320, 360, 390 and 412 CSS px in dark **and**
953
+ light `prefers-color-scheme`:
954
+ - `.titleblock` centre − `innerWidth/2` = **0.0 px** at all eight width/theme pairs;
955
+ `.session-sub` (status line) centre offset also **0.0 px**; `.topbar` height **52 px**.
956
+ - `.context-meter` centre − `innerWidth/2` = **0.0 px** at all eight pairs (headroom
957
+ exists because the two `1fr` grid tracks resolve equal around the auto centre track).
958
+ - `document.scrollWidth === innerWidth` (320/320, 360/360, 390/390, 412/412) and the
959
+ model/effort chip is fully inside the viewport (`chip.right` 298/338/366/388 ≤ vw).
960
+ - Stress states at every width: (a) long title + long note + long effort chip, and
961
+ (b) running (Queue/Steer visible, chip hidden, decorative track dropped) — both keep
962
+ `.titleblock` and `.context-meter` centre offsets at **0.0 px**, the note stays inside
963
+ its own grid track and truncates (80–123 px across the cases) and
964
+ `scrollWidth === innerWidth`. `document.querySelectorAll('body *')`
965
+ reports no viewport overflow except one mock-fixture `<code>` element inside a
966
+ horizontally scrollable `pre.md-codeblock` (clipped by its parent, so no document
967
+ overflow; the same data-dependent element appears on the live v16 shell).
968
+ - `node dev\layout-probe.mjs` against the live plugin at WIDTH 320/360/390/412 →
969
+ `scrollWidth === innerWidth` and `appWidth === innerWidth` for all four. The live v16
970
+ transcript still yields one clipped `<code>` offender (over 221/181/155/133 px, all inside
971
+ the horizontal-scroll `pre`); rerun against the then-deployed shell to confirm the same on
972
+ v17.
973
+ - **Reasoning picker driven end to end** against the mock over CDP (click flows, not just
974
+ static checks): menu → Model → `V4.1 Flash` → `High` produced toast
975
+ `Model set to V4.1 Flash · High`, chip `V4.1 Flash · High`, and the model row tag
976
+ `High`; reopening the sheet marked `High` active (`aria-current`) with `Default` on
977
+ `Medium`. `Claude Sonnet 4.5` (no `defaultEffort`) rendered a **Provider default** row;
978
+ choosing it toasted `Model set to Claude Sonnet 4.5 · Default` and the chip fell back to
979
+ `Claude Sonnet 4.5`. A plain model (`Qwen 2.5 Coder 32B`) selected immediately, closed
980
+ the sheet and toasted `Model set to Qwen 2.5 Coder 32B.` (no drill-in sheet).
981
+ - Screenshots were captured during development and are not shipped in the repository.
982
+ - **Not verified here:** physical iOS/Android/WebKit; the live server was not restarted or
983
+ modified, so the official layout probe above still measures the deployed v16 shell. The
984
+ `est.`/≥85% meter states and the light theme were exercised through DOM state and CDP
985
+ media emulation rather than a real device setting; no browser console output, inline
986
+ script or network endpoint was added.
987
+
988
+ ### Frontend polish — context-meter move + bottom-row cleanup (v16)
989
+
990
+ Run from a checkout of this plugin:
991
+
992
+ - `node --check mobile\app.js` → exit 0; `node --check mobile\sw.js` → exit 0;
993
+ `node --check mobile\mock-server.js` → exit 0.
994
+ - `node dev\static-check.mjs` → `/app.js?v=16 200 text/javascript; charset=utf-8 bytes
995
+ 286015`; `/styles.css?v=16 200 text/css; charset=utf-8 bytes 81605`;
996
+ `PASS static asset + header check` (exit 0; the single v16 ref pair, CSP, PWA surface
997
+ and `Service-Worker-Allowed` header are intact).
998
+ - `node dev\spa-check.mjs` → `PASS spa check (866 helpers, 64 cached ids, v16)` (exit 0;
999
+ the new `context-est` cached id exists and index.html/sw.js version refs agree).
1000
+ - `node dev\server-smoke.mjs` → `PASS bridge image attachment checks`, `PASS approval
1001
+ context checks`, `PASS transport smoke test` (exit 0; the frozen server is untouched).
1002
+ - **Headless-Chrome layout verification of the checkout.** The checkout's `mobile/` folder
1003
+ was served by the bundled `mobile/mock-server.js` (paired through `POST /api/pair`,
1004
+ then driven over CDP with a throwaway script outside the checkout). At 320, 360, 390 and
1005
+ 412 CSS px in dark **and** light `prefers-color-scheme`, every state reported
1006
+ `scrollWidth === innerWidth` (320/320, 360/360, 390/390, 412/412), `.app` width equal
1007
+ to the viewport and `offenders: []` — including running (note + meter + Queue/Steer),
1008
+ and the synthetic worst case with the note, meter, Queue/Steer **and** model chip all
1009
+ visible, plus the `est.` badge and >85% warning palette. The meta row measured 21 px
1010
+ tall idle, 38 px while running (one row) and the top bar 52 px in both themes.
1011
+ Screenshots were captured during development and are not shipped in the repository.
1012
+ - `node dev\layout-probe.mjs` against the **live v15 plugin** at `WIDTH=320,360,390,412`
1013
+ → `scrollWidth === innerWidth`, `appWidth === innerWidth`, `offenders: []` for all
1014
+ four (pre-sync baseline: the live server still answers `?v=15`). Re-run it after the
1015
+ checkout is deployed to assert the same on v16.
1016
+ - **Not verified here:** physical iOS/Android devices and WebKit. The estimated-basis
1017
+ badge/warning colours were exercised by forcing that DOM state (the mock always serves
1018
+ `basis:"usage"`), and light theme through CDP media emulation rather than a real OS
1019
+ `prefers-color-scheme` toggle. No browser console output, inline script or network
1020
+ endpoint was added.
1021
+
1022
+ ### Batch C3/E2 — context, changes, commands, app lock (v10)
1023
+
1024
+ Run from a checkout of this plugin after syncing the live
1025
+ plugin:
1026
+
1027
+ - `node --check mobile\app.js` → exit 0; `node --check mobile\sw.js` → exit 0;
1028
+ `node --check mobile\mock-server.js` → exit 0.
1029
+ - `node dev\static-check.mjs` → `/app.js?v=10 200 text/javascript; charset=utf-8 bytes
1030
+ 283660`; `/styles.css?v=10 200 text/css; charset=utf-8 bytes 80037`;
1031
+ `PASS static asset + header check` (exit 0; PWA surface + service-worker header intact).
1032
+ - `node dev\server-smoke.mjs` → `PASS transport smoke test` (exit 0).
1033
+ - Static integration + lock-state-machine harness → **PASS**, actual lines:
1034
+ - `S->C C3 frames: 5 handlers + mock emitters present`
1035
+ - `C->S C3 frames: 5 emitters + mock handlers; refresh hooks; strict scoping`
1036
+ - `UI: context meter, changes panel, diff view, lock overlay + disabled row styles present`
1037
+ - `Commands palette + diff sheet (1200-line cap, unavailable copy) present`
1038
+ - `lock state machine: cold-start locked -> assertion unlock -> 5-min grace -> inactivity
1039
+ relock -> disabled` (the extracted `appLockShouldLock` executed in Node for: cold start
1040
+ → true; verified within grace → false; +5 min + 1 ms → true; hidden 30 s → true; hidden
1041
+ 29 999 ms → false; disabled → false)
1042
+ - `lock wiring: WebAuthn create/get params, platform+UV, disable-requires-assertion, cold
1043
+ start/resume, fail-open`
1044
+ - `v10 refs + SW v10, zero console.*, no inline scripts/handlers`
1045
+ - Mock WebSocket protocol run (real masked RFC 6455 client) → **PASS**:
1046
+ `session.opened.context` = `{used:11214, window:1000000, basis:"usage"}`;
1047
+ `context.get` → `11214/1000000 usage`; `changes.list` → 2 items (first 2 files, second
1048
+ `available:false`); `changes.diff` text `src/app.ts` 6 lines with `+`/`-`, binary
1049
+ `assets/logo.png`, unknown coordinates → `error unavailable`; `commands.list` →
1050
+ `compact`; `commands.execute /compact` → `command.result compact success "Compacted 4
1051
+ history items (~909 tokens)."`; unknown command → `error forbidden`; following
1052
+ `history.load` includes the command event.
1053
+ - **Headless browser limitation:** Chromium/Edge still cannot start in this sandbox (Mojo
1054
+ named-pipe restriction), so real WebAuthn (`credentials.create/get`), the lock overlay,
1055
+ permission prompts and synthetic-frame UI rendering were not driven in a browser. The
1056
+ lock state machine was executed directly from the source in Node; the mock protocol run
1057
+ covers every C3 frame shape; WebAuthn platform behaviour is documented as a device
1058
+ spot-check (requires a secure context + biometric authenticator).
1059
+
1060
+ ### Batch C/D — session management, queue/steer, image limits, approval context (v9)
1061
+
1062
+ Run from a checkout of this plugin after syncing the v8
1063
+ plugin and bumping to v9:
1064
+
1065
+ - `node --check mobile\app.js` — **passes** (also `node --check mobile\sw.js` and
1066
+ `node --check mobile\mock-server.js`).
1067
+ - `node dev\static-check.mjs` — **PASS static asset + header check**; served
1068
+ `/app.js?v=9` (253,581 bytes) and `/styles.css?v=9` (74,671 bytes), `no-store`, correct
1069
+ content types, PWA surface intact.
1070
+ - `node dev\server-smoke.mjs` — **PASS transport smoke test**; the frozen server contract
1071
+ was not modified.
1072
+ - Static integration harness (Node): all 7 new S→C frame cases + handler functions present
1073
+ and referenced by the mock (`session.updated`, `sessions.found`, `session.pinned`,
1074
+ `session.archived`, `queue`, `queue.changed`, `limits`); all 11 C→S emitters present
1075
+ (`session.rename`, pin/unpin, archive/unarchive, fork, `sessions.search`, `queue.list`,
1076
+ `queue.update` edit/remove/steer, prompt mode); queue strip / archived banner / prompt
1077
+ mode / pin-archive-fork icons / v9 refs / 9 new style selectors present; limits +
1078
+ approval-context + `canApprove` + `forbidden` paths present; SW cache bumped to
1079
+ `dsh-remote-v9`; zero `console.*`, zero inline scripts/handlers. **PASS Batch C/D static
1080
+ integration check.**
1081
+ - Mock WebSocket protocol run (real masked RFC 6455 client, port ephemeral), actual output:
1082
+ - `ready` → `canApprove=true`, image limits `{maxImages:4,maxBytes:5242880,...}`,
1083
+ `queue:[]`; sessions rows carry `pinned`, `archived`, `agentAvailable` (release pinned,
1084
+ design archived); `session.opened.queue` present.
1085
+ - `session.rename` → `session.updated "Release checklist v2"` + `sessions`; pin/unpin →
1086
+ `session.pinned true/false`; archive/unarchive → `session.archived true/false`;
1087
+ `session.fork` → new `(fork)` session; `sessions.search "release"` → 2 results with
1088
+ snippets; `queue.list` → 0 items.
1089
+ - Deploy turn: `question.request` 2 questions answered → `approval.request`
1090
+ `argsKind=command`, `argsPreview` 8 lines, `detail.path=scripts\deploy.ps1`.
1091
+ - Running session: queued prompt → `queue.changed` item placement `queued`; edit →
1092
+ updated text; remove → item gone; steer while idle → `error bad-request`; archive while
1093
+ running without `stopActivity` → `error bad-request`; with `stopActivity:true` →
1094
+ `session.archived`; `limits` → maxImages 4 / maxBytes 5242880.
1095
+ - **PASS mock Batch C/D protocol run.**
1096
+ - Headless Chromium could not be used in this sandbox (the earlier documented
1097
+ named-pipe/Mojo restriction still blocks browser startup), so synthetic-frame browser
1098
+ checks for the new UI states were not re-run. The UI paths (approval args with/without
1099
+ preview, `canApprove=false` disabled buttons + note, queue strip expansion, archived
1100
+ read-only composer, sessions grouping) are covered by the static integration harness and
1101
+ the mock protocol run, and are documented as device spot-checks.
1102
+
1103
+ ### Batch B — phone-native features (v8)
1104
+
1105
+ Run from a checkout of this plugin:
1106
+
1107
+ - `node --check mobile\app.js` — **passes** (also `node --check mobile\mock-server.js` and
1108
+ `node --check mobile\sw.js`).
1109
+ - `node dev\static-check.mjs` — **PASS static asset + header check**; served
1110
+ `/app.js?v=8` (214,685 bytes) and `/styles.css?v=8` (67,225 bytes), `no-store` and
1111
+ correct content types.
1112
+ - `node dev\server-smoke.mjs` — **PASS transport smoke test**; the frozen server contract
1113
+ was not modified.
1114
+ - Custom `RemoteMobileServer` HTTP check on an ephemeral port (same stub bridge pattern as
1115
+ `dev/static-check.mjs`), actual output:
1116
+ - `GET /` → `200 text/html`, CSP `script-src 'self'`, manifest/apple-touch/favicon links,
1117
+ v8 refs, both light/dark `theme-color` metas, **no inline scripts**.
1118
+ - `/manifest.webmanifest` → `200 application/manifest+json; charset=utf-8`, 876 bytes;
1119
+ JSON parses, `display: standalone`, `share_target` action/method/params and a maskable
1120
+ icon.
1121
+ - `/sw.js` → `200 text/javascript`, 4,756 bytes, `Service-Worker-Allowed: /`,
1122
+ `cache-control: no-cache`.
1123
+ - `/icons/icon-192.png` (9,626 B), `/icons/icon-512.png` (27,264 B),
1124
+ `/icons/icon-maskable-512.png` (18,615 B), `/icons/apple-touch-icon.png` (6,394 B) →
1125
+ `200 image/png` with valid PNG signatures; `/favicon.svg` → `200 image/svg+xml`.
1126
+ - `/share-target?title=t&text=x&url=https%3A%2F%2Fexample.com` → `302`,
1127
+ `Location: /?share=%7B%22title%22%3A%22t%22%2C…%7D`, payload round-trips exactly.
1128
+ - **PASS PWA + share-target HTTP check.**
1129
+ - Service-worker logic exercised in a Node `vm` harness with stubbed `caches`/`fetch`:
1130
+ install precached all 9 shell entries and called `skipWaiting`; activate deleted
1131
+ `dsh-remote-v7`, kept `dsh-remote-v8` and unrelated caches and called `clients.claim`;
1132
+ `/api/*`, `/ws`, `/remote-mobile/*`, `/share-target` and cross-origin requests bypass the
1133
+ worker; navigation is network-first, caches `/`, and falls back offline (including a
1134
+ `?share=` deep link); `/app.js?v=8` is cache-first with a background revalidation fetch;
1135
+ a fresh `?v=` asset is fetched and stored. **PASS service worker logic harness.**
1136
+ - Static integration checks: all 19 new functions are defined; zero `console.*` calls in
1137
+ `app.js`; zero inline `<script>` tags in `index.html`; both v8 refs present; manifest
1138
+ icons/share target valid; zero external HTTP(S) asset URLs in the shipped files.
1139
+ - **Headless-browser limitation in this sandbox:** Chrome/Edge headless can no longer start
1140
+ (`mojo platform_channel.cc: Access is denied` — the confined sandbox blocks the named
1141
+ pipes Chromium needs for IPC). Earlier batches' headless CDP passes are recorded below;
1142
+ for Batch B the browser-dependent states (SW install/offline, live voice, real
1143
+ notifications, share-sheet handling) were therefore reviewed in code and covered by the
1144
+ VM/HTTP harnesses, not re-driven in a browser. This is an environment limitation, not a
1145
+ failing assertion.
1146
+
1147
+ ### Earlier batches (v7 and before)
1148
+
1149
+ - `node --check app.js` — passes.
1150
+ - `node --check mock-server.js` — passes. The mock gained the `ask_user_question` demo flow,
1151
+ the `/api/upload` endpoint + prompt attachment echo, the settled-history fixtures for
1152
+ those extensions, and the cross-session fixture prompt; every other frame/endpoint still
1153
+ matches `PROTOCOL.md` (Batch B adds static/PWA routes and `/share-target` to the mock
1154
+ only).
1155
+ - `index.html` references `/app.js` / `/styles.css` (versioned), the manifest, favicon and
1156
+ apple-touch icon; no CDN, no webfonts, no external icon sheet, no inline scripts.
1157
+ - Mock HTTP smoke: `/health`, `/` and the static assets; wrong PIN → `401`; correct PIN →
1158
+ `200` + `Set-Cookie`; a one-tap `?t=` token pairs once and the query is then stripped.
1159
+ - Full SPA end-to-end pass in headless Chromium (driven over CDP) at 390 × 844, DPR 2 with
1160
+ touch emulation, against `node mock-server.js`: **74 assertions, zero failures**, zero
1161
+ console errors and zero uncaught exceptions (only the deliberate `401` / `429` network
1162
+ responses from the negative tests).
1163
+ - Pairing: serif headline, refined PIN slots, wrong-PIN inline error, PIN pairing, token
1164
+ pairing after unpair, `429` rate-limit countdown with disabled entry.
1165
+ - Transcript: plain serif assistant prose (no bubble), right-aligned warm user bubble,
1166
+ headings / lists / blockquote / inline code / pipe table / fenced `js` block, language
1167
+ label + copy, per-assistant copy action, tap-to-reveal timestamps, no horizontal
1168
+ overflow.
1169
+ - Tool cards: collapsed by default; tap expands args + output with real height and opacity;
1170
+ tap collapses; live `pwsh` call appears collapsed; failures keep auto-expanding.
1171
+ - Theme: Auto / Light / Dark control in the overflow sheet, `data-theme`, `color-scheme`
1172
+ and `theme-color` all update; dark palette tokens apply; the choice persists across a
1173
+ reload; theme is applied by `app.js` on init (the inline bootstrap was removed for
1174
+ CSP); Auto follows `prefers-color-scheme` live; reduced-motion collapses transitions
1175
+ and the caret blink.
1176
+ - Sheets and Activity: sessions drawer, new-session preset sheet and model sheet open
1177
+ from their buttons and close cleanly; Activity renders entries, live indicator,
1178
+ expandable rows and compact All / Tools / Errors filter.
1179
+ - Streaming and approvals: streaming caret, optimistic user bubble, stop button, approval
1180
+ card with ≥44 px Approve/Reject, one-tap approve resolving in place.
1181
+ - 44 px primary targets throughout, and `scrollWidth <= innerWidth` at the 390 px viewport.
1182
+ - Screenshots captured during that pass: light/dark pairing, chat top and bottom, expanded
1183
+ tool, sheets, Activity, streaming, approval and rate-limit states.
1184
+ - Screenshot review confirmed the intended composition: 58 px top bar, centred Chat/Activity
1185
+ switch, 700 px max transcript column, 17.5 px serif prose, floating pill composer with a
1186
+ 44 px circular send button, fixed 844 px shell, no clipping or overflow.
1187
+ - **Question-card pass** (same headless Chromium harness, against the mock question flow):
1188
+ **38 assertions, zero failures**, zero console errors and zero uncaught exceptions.
1189
+ - Settled history `ask_user_question` row renders as a read-only question card (no inputs),
1190
+ answers parsed from the JSON `output` (`Staging`, `Unit tests`, `Other: Also run the
1191
+ linter`), and `ask_user_question` never appears as a tool chip.
1192
+ - `Deploy…` produces a two-question batch: stacked questions, 2 radio options, 3 checkbox
1193
+ options, 2 custom inputs, Skip/Submit pair, Submit disabled until answered, 46 px rows.
1194
+ - Selecting radio + checkboxes + custom text, Submit → **Waiting for Harness…** with
1195
+ disabled actions → resolved read-only card showing chosen labels and custom text; the
1196
+ Activity timeline records `Question answered`.
1197
+ - Skip on a later batch resolves as `declined` with every answer shown as **Skipped**.
1198
+ - A request-only `question.request` (no tool row) renders an answerable card, adds no tool
1199
+ entry, survives a duplicate request re-render with its draft intact, and resolves
1200
+ read-only.
1201
+ - Light and dark question cards both verified, no horizontal overflow.
1202
+ - Question screenshots: light history/pending/draft/waiting/resolved, dark resolved/pending/
1203
+ skipped, request-only and resolved states, plus the Activity entry.
1204
+ - **Attachment pass** (same headless Chromium harness, against the mock upload endpoint with
1205
+ a 1 MB server limit and a 700 ms delay to make progress observable): **41 assertions, zero
1206
+ failures**, zero console errors and zero uncaught exceptions (only the deliberate `413`
1207
+ network response from the error-path test).
1208
+ - 44 px paperclip in the composer, hidden multi-file input, no chips before selection; send
1209
+ enabled with text, disabled while files upload, restored when all uploads complete.
1210
+ - Two files upload sequentially with a per-file progress chip; names/sizes show; removing a
1211
+ chip works; chips render in both light and dark.
1212
+ - Send keeps the message text and shows image thumbnails + non-image file names in the
1213
+ optimistic bubble, clears the chips, the mock logs the upload and the assistant reply
1214
+ echoes the attachment name; no upload paths ever appear in the DOM.
1215
+ - Reload restores image thumbnails (via `/api/preview`) and non-image file pills from
1216
+ history metadata.
1217
+ - Server `413` surfaces as an error chip ("too large"), blocks send, and can be removed;
1218
+ a >32 MB file is rejected client-side without any request; a forced send failure removes
1219
+ the optimistic bubble, restores the text and keeps the uploaded file; an attachment-only
1220
+ send works and clears chips.
1221
+ - No horizontal overflow, zero console errors/exceptions.
1222
+ - Attachment screenshots: uploading, chips light/dark, sent bubble, history reload, 413 error,
1223
+ client-limit guard and attachment-only send.
1224
+ - **Inline-preview pass** (same headless Chromium harness, with the broken-preview fixture
1225
+ enabled): **31 assertions, zero failures**, zero console errors and zero uncaught
1226
+ exceptions (only the deliberate `404` from the seeded broken preview).
1227
+ - Seeded history image loads through `/api/preview?session=sess-release&path=…`; the
1228
+ non-image attachment stays a pill; the missing image falls back to a
1229
+ `Preview unavailable` pill.
1230
+ - Tap opens the full-screen lightbox with the full image and filename caption; the 44 px
1231
+ close button and Escape both dismiss it.
1232
+ - Paperclip bounding-box checks pass at 390 px and 320 px width and with a grown
1233
+ multi-line composer: 44×44 size, fully inside the composer box, icon inside the
1234
+ button, no clipping ancestor and the hit-test at its centre resolves to the button.
1235
+ - Optimistic bubble uses a `blob:` thumbnail (loaded), chip removal and send revoke the
1236
+ composer object URLs, non-image attachments stay pills, chips clear on send.
1237
+ - Dark-mode thumbnails and lightbox verified; history reload switches the uploaded
1238
+ image to `/api/preview` and leaves no `blob:` images; an attachment-only message shows
1239
+ just the preview with reduced bubble padding.
1240
+ - No horizontal overflow and no unexpected network entries.
1241
+ - Inline-preview screenshots: seeded history (thumbnail + broken fallback + pill), history
1242
+ lightbox, 320 px composer, optimistic thumbnail, optimistic lightbox, dark previews,
1243
+ dark lightbox, history-reload preview and attachment-only preview.
1244
+ - **Cross-session notice/scoping pass** (headless Chromium, mock fixture with an active
1245
+ approval plus a foreign approval and question): **38 assertions, zero failures**, zero
1246
+ console errors and zero uncaught exceptions.
1247
+ - Notice bar is grid row 3 between the tabs and the transcript, 6-row app grid,
1248
+ bounding boxes show no overlap with the transcript or composer, no horizontal
1249
+ overflow, text/action not clipped, 44 px Open; shows `(+1)` for the second foreign item.
1250
+ - Only the active-session approval is inline; the foreign approval/question never appear
1251
+ in the active transcript. The active approval survives a `history`/session reopen.
1252
+ - Approval card stays inside the transcript column with 16 px padding, equal-width
1253
+ 46 px Reject/Approve buttons and wrapped reason at 390 light, 390 dark and 320 both
1254
+ themes.
1255
+ - Open switches to the foreign approval's session, the card is re-attached and
1256
+ answerable there; approving it advances the notice; Open again re-attaches the release
1257
+ approval, then the design question, which is answerable in its own session. The notice
1258
+ removes itself when no foreign interactions remain.
1259
+ - Cross-session screenshots: notice light/dark, 320 dark/light, opened API approval,
1260
+ release approval resolved, design question and its resolved state.
1261
+
1262
+ ## Not covered here
1263
+
1264
+ The real Host bridge, auth/signing and desktop pairing panel are owned by other halves of
1265
+ the plugin (`index.js`, `server.js`, `auth.js`, `bridge.js`, `client.js`), and the
1266
+ `question.*` frames, `POST /api/upload` + `prompt.attachments`, history user attachments,
1267
+ `GET /api/preview` and `PROTOCOL.md` are being added on the host side by the Lead. This
1268
+ client consumes the documented frames/endpoints (including those extensions) and assumes
1269
+ those halves implement them faithfully.
1270
+
1271
+ Batch B additionally depends on host-owned packaging/serving: `package.json` `files` must
1272
+ ship the manifest, service worker, favicon and icon PNGs (the frozen `server.js` static
1273
+ table and CSP already serve/support them). The mock was extended with those static routes
1274
+ and `/share-target`, but the mock is dev-only and not part of the package. Real-device
1275
+ states that cannot be asserted without a physical/emulated browser — iOS Add-to-Home-Screen
1276
+ notification permission, the Android share sheet, live microphone permission, and
1277
+ offline-then-update service-worker activation — are implemented defensively and documented
1278
+ above; Web Push was driven end-to-end in headless Chrome against the mock (real push-service
1279
+ subscription, test push, unsubscribe), but a *real Host push delivery* (encrypted RFC 8291
1280
+ payload arriving on a locked phone) and iOS 16.4+ installed-app behaviour still need a phone
1281
+ spot-check.