@deep-podder/dsh-remote-mobile 0.0.5 → 0.0.7

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.
Files changed (46) hide show
  1. package/PROTOCOL.md +97 -9
  2. package/README.md +49 -12
  3. package/SECURITY.md +8 -0
  4. package/auth.js +16 -0
  5. package/bridge.js +336 -9
  6. package/client.js +6 -1
  7. package/docs/api-notes.md +12 -4
  8. package/docs/engineering-audit.md +252 -0
  9. package/docs/reference-chat-demo.md +41 -0
  10. package/docs/screenshots/chat-light.png +0 -0
  11. package/docs/screenshots/commands-dark.png +0 -0
  12. package/docs/screenshots/pairing-light.png +0 -0
  13. package/docs/screenshots/sessions-light.png +0 -0
  14. package/docs/verification.md +40 -4
  15. package/index.js +1 -1
  16. package/mobile/README.md +81 -35
  17. package/mobile/app.js +4268 -906
  18. package/mobile/index.html +28 -17
  19. package/mobile/lib/away.js +45 -0
  20. package/mobile/lib/constants.js +5 -0
  21. package/mobile/lib/errors.js +42 -0
  22. package/mobile/lib/format.js +94 -0
  23. package/mobile/lib/lock.js +21 -0
  24. package/mobile/manifest.webmanifest +24 -0
  25. package/mobile/mock-server.js +442 -17
  26. package/mobile/model/history.js +119 -0
  27. package/mobile/model/question.js +318 -0
  28. package/mobile/model/turns.js +57 -0
  29. package/mobile/styles/base.css +143 -0
  30. package/mobile/{styles.css → styles/components.css} +1170 -826
  31. package/mobile/styles/overrides.css +269 -0
  32. package/mobile/styles/tokens.css +169 -0
  33. package/mobile/sw.js +28 -4
  34. package/package.json +34 -20
  35. package/protocol.js +87 -0
  36. package/push-policy.js +58 -0
  37. package/server/frames/activity.js +110 -0
  38. package/server/frames/connection.js +21 -0
  39. package/server/frames/history.js +23 -0
  40. package/server/frames/interactions.js +77 -0
  41. package/server/frames/prompts.js +29 -0
  42. package/server/frames/queue.js +58 -0
  43. package/server/frames/sessions.js +201 -0
  44. package/server/frames/settings.js +38 -0
  45. package/server/frames/subagents.js +50 -0
  46. package/server.js +341 -423
@@ -0,0 +1,252 @@
1
+ # Engineering health and modularity audit
2
+
3
+ Scope: the whole repository at `48d1af5` (0.0.6). Method: size/complexity measurement of every
4
+ shipped file, seam-by-seam reading of the Host, bridge, server, client module and phone SPA,
5
+ test-surface mapping (which frames/methods the checks touch), and a docs/release hygiene pass.
6
+ This is a maintainer note, not a public contract.
7
+
8
+ > **Post-audit status.** The follow-up work landed the Now list and most of the Next list:
9
+ > compressed static assets + size budgets, sheet focus trap/inert, refreshed docs, a `node:test`
10
+ > unit suite (pairing/auth + HTTP upload), shared `protocol.js` with a server/mock/PROTOCOL parity
11
+ > check, SPA ES modules (`lib/*`, `model/*`), an error taxonomy with `?debug=1`, the 30 frame
12
+ > handlers moved into `server/frames/*`, the stylesheet split into four cascade-ordered files, and
13
+ > `npm run check` / `test:unit` / `check:ui`. CI was intentionally skipped. Still deferred:
14
+ > splitting `bridge.js` by domain (highest risk, no user-visible gain yet), splitting `client.js`
15
+ > (the DSH module loader expects one factory), `checkJs`/JSDoc expansion, markdown extraction from
16
+ > `app.js`, and `<dialog>` migration (the sheets now trap focus and mark the page inert instead).
17
+
18
+ ## Scorecard
19
+
20
+ | Area | Grade | Basis |
21
+ |---|---|---|
22
+ | Architecture (plane separation) | B+ | Host/client/SPA split is explicit and honest; `index.js` is a clean 108-line composition root |
23
+ | Modularity (within planes) | C | Three monoliths: SPA (11.4k lines), server class (2.6k), bridge (3.1k) |
24
+ | Code quality | B- | Readable, heavily commented, no dead functions; mixed style and a few very large functions |
25
+ | Type safety | C- | No TypeScript or checkJs; JSDoc concentrated in `bridge.js`, sparse elsewhere |
26
+ | Testing | B+ | 22 check scripts, ~645 assertion sites, strong behavioral coverage; thin unit layer |
27
+ | CI / tooling | D | No CI, no `npm test`, no linter, no formatter, no type check |
28
+ | Security | A- | Tight auth/CSP/CORS/rate limits, scrubbed logs, secrets isolated; sheet focus escapes remain |
29
+ | Performance | B- | Excellent SW caching; first-load is 363 KB JS + 92 KB CSS uncompressed |
30
+ | Accessibility | C+ | New question/composer work is strong; global sheets lack a focus trap/inert |
31
+ | Documentation / onboarding | A- | AGENT + `.agent/` + PROTOCOL + SECURITY are unusually good; `verification.md` is stale |
32
+ | Dependency hygiene | A | Zero runtime dependencies; one vendored MIT QR library with its license |
33
+ | Release discipline | B | Version invariants enforced by `release-check`; publish is manual, no provenance, no CI |
34
+
35
+ Overall: **solid product-level rigor in a codebase that is becoming hard to change.** The security,
36
+ documentation and test *breadth* are above average for a plugin of this size; the weak axis is
37
+ decomposition and automated quality gates.
38
+
39
+ ## Measured shape
40
+
41
+ | File | Lines | Notes |
42
+ |---|---:|---|
43
+ | `mobile/app.js` | 11,445 | One IIFE, 441 top-level functions, 117-key state object, 1,141 `S.` refs, 113 listeners |
44
+ | `mobile/styles.css` | 4,426 | 595 top-level selectors, 109 custom properties, 29 sections, 14 `!important`, no `@layer` |
45
+ | `bridge.js` | 3,056 | One factory, 31 public methods, 107 functions, ~130 JSDoc blocks |
46
+ | `mobile/mock-server.js` | 2,742 | Fixture server; mirrors all 30 production frame cases |
47
+ | `server.js` | 2,625 | One class, 80 methods, 431-line `handleFrame`, 190-line `handleHttp` |
48
+ | `client.js` | 662 | One module factory, inline style object, settings panel + approval dock |
49
+ | `push.js` / `auth.js` / `qr.js` / `index.js` | 490 / 264 / 50 / 102 | Focused, well-separated modules |
50
+ | Host + SPA + client | ~26,000 | ~34.7k lines including checks, docs, vendor |
51
+
52
+ SPA function shape is healthier than the file size suggests: average 25 lines, only 13 functions
53
+ over 100 lines. The hotspots are `replaceTranscript` (170 lines, ~82 branch tokens),
54
+ `normalizeHistoryItem` (115), `buildSessionsSheet` (291), `renderMarkdown` (121) and
55
+ `buildMenuSheet` (207). No never-referenced functions were found in the SPA or bridge;
56
+ `server.handlePairingRoute` is used by `index.js`.
57
+
58
+ ## Findings
59
+
60
+ ### F1 — The phone SPA is a single 11.4k-line IIFE (high)
61
+ Evidence above. Sections are coherent (`State`, `Questions`, `Sheets`, …), but they all share one
62
+ closure, one mutable `S`, and `refs`/`el` at a distance. Pure logic (history normalisation,
63
+ markdown, question model, formatting) cannot be exercised with `node:test`.
64
+ Risk: merge conflicts, regressions in unrelated screens, slow onboarding, no unit-level safety net.
65
+ Recommendation: extract leaf, dependency-free modules first — `lib/format.js`, `lib/markdown.js`,
66
+ `lib/errors.js`, `model/history.js`, `model/question.js` — then feature views. Native ES modules
67
+ keep the no-build rule; the service-worker precache list and `spa-check` must learn the module
68
+ list. Do not attempt a big-bang split.
69
+
70
+ ### F2 — `server.js` is a god object with a 431-line frame switch (high)
71
+ It owns HTTP routing, WebSocket upgrades, cookies, static serving, uploads, previews, push
72
+ endpoints, desktop loopback API, state persistence, heartbeat and broadcast fan-out. `handleFrame`
73
+ alone has 30 cases and ~240 branch tokens.
74
+ Recommendation: keep `RemoteMobileServer` as the composition/transport facade and move handlers
75
+ into modules: `server/http/{static,pairing,push,desktop,upload}.js`,
76
+ `server/ws/frames/{session,prompt,queue,approval,question,command}.js` (a `Map<type, handler>`),
77
+ `server/state.js` for the atomic state file. This is mechanical and testable against the existing
78
+ `server-smoke` suite.
79
+
80
+ ### F3 — `bridge.js` spans too many Host services (medium)
81
+ 31 methods and 107 functions cover sessions, prompts, queue, approvals, questions, commands,
82
+ changes, context, attachments, uploads, models, presets and workspaces. Cohesion is "the Host
83
+ adapter", but comprehension and targeted testing suffer.
84
+ Recommendation: split by domain (`bridge/sessions.js`, `prompts.js`, `approvals.js`,
85
+ `questions.js`, `attachments.js`, `commands.js`) around an injected context that owns services,
86
+ logging and pending maps. Keep the public method names stable so `server.js` does not change.
87
+
88
+ ### F4 — The mock is a second protocol implementation (medium)
89
+ `mobile/mock-server.js` (2,742 lines) handles exactly the same 30 frame types as `server.js`.
90
+ That parity is why the SPA checks are possible, but limits, clamps and fixtures are duplicated and
91
+ have already drifted subtly (fork `atSeq` emulation, history paging, upload failure hooks).
92
+ Recommendation: extract shared constants/catalog (`protocol/limits.js`, `protocol/frames.js`) that
93
+ both import, and add a deterministic parity check that compares the frame sets. Treat the mock as
94
+ a fixture, not as protocol documentation.
95
+
96
+ ### F5 — No CI and no package scripts (high, process)
97
+ There are 22 `dev/*.mjs` checks and ~645 assertion sites, all run by hand. `package.json` has no
98
+ `scripts`; there is no `.github/`. The release gate is human discipline plus `release-check`.
99
+ Recommendation: `npm` scripts for syntax, deterministic checks and UI checks; a GitHub Actions
100
+ workflow with Node 22/24 for the Host/transport checks and a second job with Chrome for
101
+ `question-ui-check`/`composer-ui-check`; live checks stay manual (they mutate a Host). Add
102
+ `--provenance` to the publish command when the account allows it.
103
+
104
+ ### F6 — No linter, formatter or type checking (medium)
105
+ Style differs between host (no semicolons) and SPA (semicolons); JSDoc coverage is 41/441 in the
106
+ SPA, 1/23 in `client.js`, 39/80 methods in `server.js`. `node --check` catches syntax only.
107
+ Recommendation: adopt `node --test` first (built in), then a pinned `oxlint`/`oxfmt` via `npx` in
108
+ CI without adding runtime dependencies. For the host, a `jsconfig.json` with `checkJs` on the pure
109
+ modules (`auth.js`, `qr.js`, `push.js`, `protocol/`) is a low-risk start.
110
+
111
+ ### F7 — Tests are broad but unit-thin, and one HTTP path is uncovered (medium)
112
+ All 30 frame cases and 29/31 bridge methods are referenced by checks; question (52) and composer
113
+ (50) checks are genuinely end-to-end. Gaps: no unit tests for pure helpers; `POST /api/upload` has
114
+ no deterministic coverage (only the live image check); sheet accessibility is untested; voice,
115
+ app-lock/WebAuthn and the service-worker update flow are static/manual only.
116
+ Recommendation: a `node:test` suite for `normalizeAnswerBatch`, `wireQuestion`, history mapping,
117
+ formatting and question-model functions; a fake-bridge upload test; a keyboard/focus assertion for
118
+ each sheet.
119
+
120
+ ### F8 — Sheets declare `aria-modal` without trapping focus (medium)
121
+ `openSheet` moves focus in, restores it on close and handles Escape, but Tab can leave the sheet
122
+ and the background is not `inert`. The lightbox and app-lock dialogs are better.
123
+ Recommendation: either migrate sheets to `<dialog>` + `showModal()` (focus trap, Escape, backdrop
124
+ for free) or add a small focus loop plus `inert` on the app root while open. Add a Tab-cycle check
125
+ to `ui-check`.
126
+
127
+ ### F9 — First load is uncompressed and unbudgeted (medium)
128
+ `serveStatic` sends `no-store` and no `content-encoding`; `app.js` is 363 KB and `styles.css`
129
+ 92 KB. The service worker makes repeat loads cheap, but first load and every shell version bump
130
+ pay full price. CSP is strict except `style-src 'unsafe-inline'` (inline style attributes) and a
131
+ broad `connect-src ws: wss:`.
132
+ Recommendation: gzip text assets with `node:zlib` (zero deps), keep `no-store`; add size budgets to
133
+ `release-check` (e.g. app ≤ 400 KB, CSS ≤ 110 KB) so growth is deliberate.
134
+
135
+ ### F10 — Documentation drift (low-medium)
136
+ `docs/verification.md` still describes v1 on Harness 0.2.2-rc.1 and `?v=20`; `.agent/architecture.md`
137
+ does not mention history paging, per-session drafts, branch-from-message or the live timeline.
138
+ Recommendation: refresh both at release time; add a docs checkbox to the release workflow and a
139
+ "last verified" line to research notes (`docs/api-notes*.md`).
140
+
141
+ ### F11 — CSS is one flat global namespace (medium-low)
142
+ 4,426 lines, 595 selectors, 109 tokens, 14 `!important`, no `@layer` and no per-feature files.
143
+ Generic class names (`.row`, `.btn`, `.tool`) are global.
144
+ Recommendation: introduce `@layer tokens, base, components, utilities` (cheap, no build) and split
145
+ by feature when a feature is next touched; avoid CSS-in-JS/build tooling.
146
+
147
+ ### F12 — Manual invariants are well enforced but scattered (low)
148
+ Package version lives in six files and the shell version in two more; `release-check` already
149
+ fails on drift. That is good, but every release edits eight constants.
150
+ Recommendation: derive the Host `VERSION` from `package.json` via an import attribute where
151
+ possible; keep the SPA fallback and SW cache version separate (they track *shell* changes, not
152
+ package releases).
153
+
154
+ ### F13 — Error handling is resilient but opaque (low-medium)
155
+ The Host consistently returns protocol errors and degrades on missing services. In the SPA,
156
+ `onServerError` is 91 lines/31 branch tokens and there are ~42 best-effort catch blocks; a few
157
+ swallow failures with only a comment.
158
+ Recommendation: a `mobile/lib/errors.js` mapping code → message/action, and a debug-only hook
159
+ (`?debug=1` or a global flag) that records swallowed errors for field diagnosis without logging
160
+ content.
161
+
162
+ ### F14 — `client.js` mixes two surfaces and inline styling (low)
163
+ 662 lines in one factory: settings page, approval dock, shared inline style object. It works and
164
+ is small enough, but the registration module is also the component library.
165
+ Recommendation: split the factory body into `client/settings-panel.js` and
166
+ `client/approval-dock.js` with a shared `client/styles.js`, still one registration id.
167
+
168
+ ### F15 — Vendored QR library has no provenance note (low)
169
+ `vendor/qrcode.js` is 1,802 lines with its license. There is no version/source/update note.
170
+ Recommendation: record upstream, version and patch status in `vendor/README` and the release
171
+ checklist.
172
+
173
+ ## What is healthy (do not "fix")
174
+
175
+ - Plane separation and `index.js` wiring; `auth.js` (290 lines) and `push.js` (490 lines) are
176
+ focused, defensive, and covered by vectors/smoke tests.
177
+ - Security posture: HMAC cookies, constant-time compares, PIN lockout, loopback/desk-key policy,
178
+ CSP, scrubbed logs, secret isolation. Keep the fail-closed defaults.
179
+ - Protocol discipline: `PROTOCOL.md` as the contract, additive frames, `release-check` invariants.
180
+ - Test breadth: the behavioral checks catch real regressions (the question-card and composer
181
+ suites each found genuine bugs). Keep them.
182
+ - Docs and onboarding: `AGENT.md` + `.agent/` is better than most repositories this size.
183
+
184
+ ## Prioritized roadmap
185
+
186
+ **Now (low risk, high payoff)**
187
+ 1. CI + `package.json` scripts (F5).
188
+ 2. gzip for static text + asset size budgets (F9).
189
+ 3. Sheet focus trap or `<dialog>` migration + a Tab-cycle test (F8).
190
+ 4. Refresh `verification.md` and `.agent/architecture.md` (F10).
191
+ 5. Seed `node:test` with pure functions and add a deterministic upload test (F6/F7).
192
+
193
+ **Next (contained refactors)**
194
+ 6. Shared protocol constants/catalog for server + mock, with a parity check (F4).
195
+ 7. Extract SPA leaf modules (`dom`, `format`, `markdown`, `errors`, history/question models) and
196
+ update the SW precache + `spa-check` (F1).
197
+ 8. Extract server frame/HTTP handlers into modules behind the existing facade (F2).
198
+ 9. Error taxonomy module and debug hook (F13).
199
+ 10. CSS `@layer` adoption (F11).
200
+
201
+ **Later (only when the pain is real)**
202
+ 11. Split `bridge.js` by domain (F3).
203
+ 12. Split `client.js` (F14) and add vendor provenance (F15).
204
+ 13. JSDoc/`checkJs` expansion (F6).
205
+ 14. Reassess virtualization only after measuring real transcripts.
206
+
207
+ ## Target module map (no build step)
208
+
209
+ ```
210
+ index.js composition root
211
+ server/
212
+ index.js facade: listen, peers, broadcast, state
213
+ http/{static,pairing,push,desktop,upload}.js
214
+ ws/{upgrade,frames/index,frames/*}.js
215
+ state.js
216
+ bridge/
217
+ index.js facade returned to the server
218
+ sessions.js prompts.js approvals.js questions.js attachments.js commands.js
219
+ protocol/
220
+ limits.js frames.js shared by server and the dev mock
221
+ mobile/
222
+ app.js transport + state + boot (composition root)
223
+ lib/{dom,format,markdown,errors}.js
224
+ model/{history,question,session}.js
225
+ views/{transcript,question,plan-review,composer}.js
226
+ client/
227
+ index.js registration only
228
+ settings-panel.js approval-dock.js styles.js
229
+ ```
230
+
231
+ Native ES modules preserve the zero-dependency, no-build contract. The service worker must
232
+ precache the new module URLs (and `spa-check` must check them).
233
+
234
+ ## Metrics to keep visible
235
+
236
+ | Metric | Today | Budget |
237
+ |---|---:|---|
238
+ | `mobile/app.js` | 363 KB | ≤ 400 KB |
239
+ | `mobile/styles.css` | 92 KB | ≤ 110 KB |
240
+ | Top-level SPA functions | 441 | track, trend down per feature |
241
+ | Functions > 100 lines | 13 | ≤ 10 |
242
+ | Deterministic checks | 9 | grow with features |
243
+ | Live/browser checks | 13 | manual only |
244
+ | First-load text (gzip) | ~460 KB raw | ≤ 120 KB compressed |
245
+
246
+ ## Method appendix
247
+
248
+ Measurements were produced with small Node scripts over the working tree: line counts per file,
249
+ top-level function spans by indentation, branch-token counts, `S.`/`refs.`/listener counts, CSS
250
+ selector/token/`!important` counts, server/bridge method inventories, frame-case comparison between
251
+ `server.js` and `mobile/mock-server.js`, and a search of `dev/*.mjs` for each frame type and bridge
252
+ method. No files were modified to produce this audit.
@@ -0,0 +1,41 @@
1
+ # Reference: `deepseek-ai/chat-demo`
2
+
3
+ Notes from reading <https://github.com/deepseek-ai/chat-demo> (commit `5d5dd75`, 2026-11-13) for
4
+ ideas the phone SPA can use. The demo is a React 18 + zustand + rspack *static* DeepSeek chat
5
+ client: IndexedDB history, SSE streaming, markdown AST (GFM, math, Mermaid), message branches,
6
+ read-aloud, per-session drafts and search citations. It has no Host and no remote-control surface,
7
+ so nothing here maps one-to-one; only the interaction ideas were reused, re-implemented in the
8
+ phone's zero-dependency DOM code.
9
+
10
+ ## Adopted
11
+
12
+ | Demo idea | Where it lives in the demo | Phone implementation |
13
+ |---|---|---|
14
+ | Render markdown on a measured-cost throttle instead of every frame: time the render, wait `cost × 2` (capped) before the next one, merge all intermediate text | `components/markdown/useThrottleMarkdownRender.ts`, `Markdown.tsx` | `paintLiveMarkdown` in `mobile/app.js`: rAF still paints the newest text; the markdown re-parse is limited to once per cost window, capped at 500 ms, and the final render always runs in `finalizeLive` |
15
+ | Sticky-follow the bottom with a `ResizeObserver` on both the content and the scroller, and release the follow state only on an upward user scroll | `components/messages/MessageList.tsx` | `bindScroll` observes `#chat-scroll` and `#messages`; `onChatScroll` compares against the previous `scrollTop` so a reflow cannot silently unpin the reader |
16
+ | Mobile viewport: track `visualViewport`, ignore pinch zoom, reset to the CSS height on blur, recalibrate a frame later for Safari | `app/viewport.ts` (`useMobileViewport`) | `syncViewportHeight`: `--app-h` follows `visualViewport.height` only while an editable is focused, is removed otherwise (falls back to `100dvh`), and skips `scale !== 1` |
17
+ | Keep a failed attachment in place with an inline retry that re-queues the same file | `services/chat/drafts.ts` (`retryDraftAttachment`), `ChatInput.tsx` | `retryAttachment` in `mobile/app.js` plus the retry chip in `renderAttachments`; covered by `dev/composer-ui-check.mjs` (mock `RM_UPLOAD_FAIL_FIRST=1`) |
18
+ | Thinking/tool timeline presentation: a live active state, elapsed time and a folded summary | `components/messages/ReplyArea.tsx`, `view.ts` (`getAreaTitle`, `getTotalThinkingSeconds`), `ReplyArea.module.css` | `reasoningLabel`/`refreshReasoningHeader` in `mobile/app.js`: pulsing dot, shimmering `Thinking · Ns` clock, `Thought for N seconds`; the block opens while reasoning is active and folds when the answer starts. Tool cards are nested as steps inside that block, and running tools add a shimmer plus a live elapsed timer until the Host duration arrives. Covered by `dev/composer-ui-check.mjs` |
19
+ | Per-session composer drafts, cleared on send | `services/chat/drafts.ts` (`Map<sessionId, Draft>`) | `S.drafts` + `rememberComposerDraft`/`restoreComposerDraft`: text only and memory only; attachments stay session-bound because uploads are tied to the active session. Covered by `dev/composer-ui-check.mjs` |
20
+ | Branching an answer from a message | `components/messages/BranchSwitcher.tsx`, `services/chat/branches.ts` | DSH cannot version answers in place, so the message sheet offers **Branch from here** and sends `session.fork { atSeq }` for durable `seq:<n>` rows; the fork opens as a new session. Covered by `dev/composer-ui-check.mjs` and `dev/server-smoke.mjs` |
21
+ | Failed work keeps an inline retry instead of disappearing (upload errors in the demo) | `services/chat/drafts.ts`, `ChatInput.tsx`, `services/chat/describe.ts` | Generalised to prompts: a websocket write failure or a Host `error` carrying the frame's `requestId` marks the optimistic bubble failed with **Retry** / **Discard**; attachment chips already had retry. Covered by `dev/composer-ui-check.mjs` |
22
+ | Paste/drop files into the composer | `ChatInput.tsx` (`onPaste`, `DragMask`) | `onComposerPaste` + `bindComposerDrop` in `mobile/app.js`; composer highlights while dragging. Covered by `dev/composer-ui-check.mjs` |
23
+ | Read the whole conversation, not just the newest page | full history from IndexedDB | `history.load` now accepts up to 500 and reports best-effort `hasMore`; the transcript renders **Load earlier messages** and preserves the reading position. Covered by `dev/composer-ui-check.mjs` with `RM_LONG_HISTORY=1` |
24
+
25
+ ## Considered, not adopted
26
+
27
+ - **Edit / regenerate / continue.** Branching is covered by forks, but the Host has no in-place
28
+ edit, regenerate or continue call, so these stay unavailable rather than being simulated badly.
29
+ - **Read aloud.** Deliberately dropped on product grounds; the demo's full read-aloud service is
30
+ much larger than a play/stop toggle and was not requested.
31
+ - **Chinese/English UI.** Deliberately deferred; the phone shell stays English.
32
+ - **Search citations, math (KaTeX), Mermaid, Prism language packs.** These pull dependencies and
33
+ parsing weight against the plugin's zero-dependency budget; the Host already renders a richer
34
+ transcript on the desktop.
35
+ - **IndexedDB history, SSE transport.** The Host is the source of truth and the wire is WebSocket;
36
+ caching transcripts on the phone would add a second copy of conversation data at rest.
37
+
38
+ ## Guardrails
39
+
40
+ The demo is MIT-licensed, but this is a different architecture (React vs plain DOM, server stream vs
41
+ SSE). Only the interaction patterns above were reused; no demo code was copied.
Binary file
Binary file
Binary file
Binary file
@@ -1,8 +1,8 @@
1
1
  # Internal verification log
2
2
 
3
3
  **Status: maintainer notes, not part of the public contract.** This file preserves the
4
- manual verification evidence gathered while building v1 on the installed
5
- **DeepSeek Harness 0.2.2-rc.1 Desktop profile**. Re-run the deterministic checks in
4
+ manual verification evidence gathered while building the plugin on the installed
5
+ **DeepSeek Harness 0.2.2-rc.3 Desktop profile**. Re-run the deterministic checks in
6
6
  [README.md](../README.md) before a release and refresh this log; live probes are manual and
7
7
  mutate the Host, so they are not CI checks.
8
8
 
@@ -51,8 +51,10 @@ mutate the Host, so they are not CI checks.
51
51
  context, read-only device) verified with a protocol-level mock run (all frames and
52
52
  rejections) plus static integration checks; batch B PWA/voice/notification paths are
53
53
  covered by the static/PWA checks and the HTTP surfaces listed above.
54
- - Static assets are versioned `?v=20` and served `no-store`, with the service worker cache
55
- bumped in step so an installed phone cannot pin an older bundle.
54
+ - Static assets carry a content-derived `?v=<hash>` revision (source placeholder `?v=1`) and are served `no-store`, with the service worker cache
55
+ bumped in step so an installed phone cannot pin an older bundle. Text assets are precompressed:
56
+ `app.js` is served as ~82 KB gzip (from 363 KB) with `vary: accept-encoding`; `release-check`
57
+ enforces raw/gzip size budgets and a 124 KB gzipped first-load shell.
56
58
  - Command palette over the live protocol (v20): `commands.list` for a live `standard` Agent
57
59
  returned `compact, feedback, goal, plan` with argument hints (`/goal`/`/plan` hints);
58
60
  `/compact` compacted 4 history items (~909 tokens), `/goal` reported "No goal is currently
@@ -68,6 +70,15 @@ mutate the Host, so they are not CI checks.
68
70
  default list (explicit **Show archived (N)** control), persists collapsed projects, and
69
71
  forces sections open while searching. `dev/ui-check.mjs` asserts all of this against
70
72
  headless Chrome with zero console errors.
73
+ - Project grouping on create (bug fixed): a chat created from the phone in a registered project
74
+ folder was listed as **Ungrouped** on the desktop, because `sessions.create` sent only `cwd`
75
+ and DSH's `sessionController.create` attaches a session to a project only for `workspaceId`.
76
+ `dev/changes-bridge-check.mjs` now asserts the bridge sends `workspaceId` for a chosen project
77
+ and for a `cwd` that is exactly a project root (and `cwd` alone otherwise), plus
78
+ `attachSessionToWorkspace` success/`not-found`/misfiled-refusal with no path echoed;
79
+ `dev/server-smoke.mjs` asserts the `sessions.create { workspaceId }` pass-through and the
80
+ `session.attach` → `session.attached` + `sessions` refresh. Confirming it in the live desktop
81
+ sidebar needs a paired phone (manual) after the plugin reload is picked up.
71
82
  - Web Push hardening (v20): a subscription endpoint must be HTTPS on a known browser push
72
83
  provider (FCM/Mozilla/WNS/Apple) or an operator-configured suffix
73
84
  (`PA_REMOTE_MOBILE_PUSH_HOSTS`), so a paired device cannot use the Host as an HTTPS request
@@ -85,6 +96,31 @@ mutate the Host, so they are not CI checks.
85
96
  30-second hidden relock → disable requires assertion) is executed headlessly, and the
86
97
  WebAuthn request parameters (`platform`, `userVerification: required`, ES256/RS256) are
87
98
  asserted by the static harness; real biometric prompts remain a device spot-check.
99
+ - Question card parity (v26): `dev/question-ui-check.mjs` runs 52 headless assertions against the
100
+ bundled mock (pager, numbering, recommended badge/preselection, single-select custom encoding,
101
+ per-question skip, batch validation with `aria-invalid` and live-region announcement, dismissal,
102
+ plan-review intent, field growth). The mobile composer is covered by
103
+ `dev/composer-ui-check.mjs` with 132 assertions (upload retry, sticky follow, turn
104
+ disclosure: `Thinking · Ns` / `Thought Ns` heading with the tool summary on the sub line
105
+ (`Working · tool — cmd` → `Used 1 tool`), folded detail, reveal-on-tap Copy, live tool
106
+ timer, per-session drafts, branch fork, rejected-prompt retry, history paging, paste/drop,
107
+ the New session sheet, and the durable-order fixture: tools recorded before their assistant
108
+ row must fold into that row with no top-level `.tool` cards). Both drive Chrome without a
109
+ Host. The settled-card fold (summary line, open-on-answer, fold/reopen, history cards start
110
+ folded) adds a further 9 checks to `dev/question-ui-check.mjs` (62 total), and
111
+ `dev/unit/turns.test.mjs` pins the grouping in both recording orders (7 cases).
112
+ - Durable-order fix over the live protocol (regression found on a real session): the Host
113
+ returns `[tools…, assistant]` for a loaded page, so the first grouping pass rendered every
114
+ tool as a top-level card. After the two-directional grouping, a headless probe against the
115
+ running plugin opened the real session and found **0 top-level tool cards**, 51 cards all
116
+ inside `.turn-detail`, and one folded line (`Used 51 edit, pwsh, read, write +2`).
117
+ `dev/composer-ui-check.mjs` now seeds and asserts the same shape without a Host.
118
+ - Branch-from-message over the live Host: `dev/fork-live.mjs` creates a throwaway session, sends
119
+ one tiny prompt, forks at the user message's `seq`, verifies the fork history stops at that
120
+ boundary, archives both sessions and revokes its device.
121
+ - History paging: `dev/composer-ui-check.mjs` with `RM_LONG_HISTORY=1` seeds 120 older events,
122
+ loads a larger tail, and asserts the reader's anchor position is preserved and the button hides
123
+ once history is exhausted.
88
124
  - Not verified automatically: the rendered desktop panel/dock appearance, real service
89
125
  worker install/offline behaviour, actual microphone input, live in-app notifications and
90
126
  Android share-sheet delivery (no browser control in the build session); the HTTP and wire
package/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { createBridge } from './bridge.js'
5
5
  import { RemoteMobileServer } from './server.js'
6
6
 
7
- const VERSION = '0.0.5'
7
+ const VERSION = '0.0.7'
8
8
 
9
9
  /**
10
10
  * @param {object} ctx Cordis host context
package/mobile/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # DSH Remote — mobile web client
2
2
 
3
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`.
4
+ the plugin's standalone server (port 3456 by default) at `/`, `/app.js` and the `/styles/*.css` modules.
5
5
  Open it on a phone on the same local network, pair once, and control a DeepSeek Harness
6
6
  session from the browser.
7
7
 
@@ -11,11 +11,14 @@ icons.
11
11
 
12
12
  | File | Purpose | Shipped |
13
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 |
14
+ | `index.html` | App shell, inline SVG icon sprite, pairing + chat markup. References `/app.js?v=1` and the four `/styles/*.css?v=1` modules; the server rewrites `?v=1` to a content-hash revision at startup. | yes |
15
+ | `styles/*.css` | Four cascade-ordered stylesheets: tokens, base, components, overrides (light/dark, safe-area and reduced-motion aware). | yes |
16
+ | `app.js` | ES module composition root: transport, state, screens, safe markdown renderer, syntax highlighter, PWA/voice/notifications/share features. Imports `lib/*` and `model/*`. | yes |
17
+ | `lib/constants.js`, `lib/errors.js`, `lib/format.js` | Pure SPA helpers: tuning constants, error taxonomy/debug hook, formatting. | yes |
18
+ | `model/question.js`, `model/history.js`, `model/turns.js` | Pure wire models: question drafts/answer encoding, durable history rows, transcript turn grouping (tools fold into their assistant row in either recording order). | yes |
19
+ | `../protocol.js` | Shared wire limits and frame catalog (served as `/protocol.js`; also imported by the Host and the mock). | yes |
17
20
  | `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 |
21
+ | `sw.js` | Versioned (`v27`) shell service worker: navigation fallback, prefetched shell, stale-while-revalidate static assets; never caches `/api/*`, `/ws`, `/remote-mobile/*` or `/share-target`. | yes |
19
22
  | `favicon.svg` | Small tab icon (same dark tile + signal mark as the app logo). | yes |
20
23
  | `icons/icon-192.png`, `icons/icon-512.png` | `any`-purpose app icons. | yes |
21
24
  | `icons/icon-maskable-512.png` | Maskable icon (glyph inside the 80% safe circle). | yes |
@@ -24,7 +27,7 @@ icons.
24
27
  | `README.md` | This file (implementation notes; not served by the plugin). | yes |
25
28
 
26
29
  > 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`,
30
+ > (`index.html`, `app.js`, `styles/*.css`, `lib/*.js`, `model/*.js`, `protocol.js`, `manifest.webmanifest`, `sw.js`, `favicon.svg`,
28
31
  > `icons/*.png`, `mock-server.js` and this README); keep it in step when adding assets.
29
32
 
30
33
  ---
@@ -184,24 +187,24 @@ glassmorphism, no webfonts, no icon sheet — only inline SVG.
184
187
  chips above it (name, size, upload percentage/error, 44 px remove hit area) and
185
188
  image thumbnails (or file pills for non-images) inside the user bubble, with a
186
189
  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.
190
+ - Spacing follows a 4 px rhythm with 14 px transcript gaps (down from 22) and generous empty
191
+ states. Every primary control (icon buttons, the Activity toggle, send/stop, sheet rows,
192
+ jump pill, approval buttons, PIN submit, per-message actions) reaches 44 px; secondary
193
+ controls get invisible hit-area expansion.
194
+ - The header is one symmetric row — drawer · Activity · title/status · new ·
195
+ overflow — with a non-interactive spacer exactly one icon button wide on the left, so the
196
+ title block and its status line are truly centred (measured centre offset 0 px at
197
+ 320/360/390/412 in both themes) while long titles ellipsize between the icons.
198
+ - Below the composer pill sits one compact meta row that only appears when it has something
199
+ to say: upload progress/failures, offline/reconnecting, archived, a running turn (with the
200
+ Queue/Steer selector and the context warning). When the session is simply Ready the row
201
+ collapses, so the transcript gets the space; the model/effort chip also stays in the
202
+ session menu.
201
203
 
202
204
  ### Accessibility and input
203
205
 
204
- - Icon buttons have `aria-label`s, tabs use `role="tab"` + `aria-selected`, sheets are
206
+ - Icon buttons have `aria-label`s; the Activity view is a header toggle (`aria-pressed`,
207
+ `aria-controls`) and the two views are labelled regions; sheets are
205
208
  `role="dialog" aria-modal`, logs are live regions, focus is restored on sheet close,
206
209
  `:focus-visible` uses a 2 px ink ring, and links are external
207
210
  `rel="noopener noreferrer nofollow"`.
@@ -257,14 +260,29 @@ glassmorphism, no webfonts, no icon sheet — only inline SVG.
257
260
  - Sending is optimistic: a local user bubble is appended immediately and reconciled when
258
261
  `history`/`session.opened` arrives. Pending bubbles are deduped against durable `user`
259
262
  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.
263
+ - History tool items and live `tool.start`/`tool.end` are deduped by `callId`. A turn's
264
+ tools are **folded into one quiet line**, thinking-first like the desktop client: the
265
+ heading is the reasoning duration (`Thinking · 4s` while it streams, `Thought 12s` once it
266
+ settled) and the tool work is the dim sub line (`Used 21 Shell, Edit`, or `Working · Shell
267
+ — git status` while one runs). A tool-only turn promotes that summary to the heading.
268
+ Tapping the line reveals the reasoning markdown and the per-tool cards; the cards
269
+ themselves are collapsed by default (icon, tool name, status, duration, chevron) and a
270
+ tap expands a monospace args preview and scroll-capped output. Failures still
271
+ auto-expand, and every expanded/collapsed state survives re-renders and the tool's own
272
+ `tool.end` refresh.
273
+ - **Tools fold into their turn in either recording order.** DSH writes `tool/start`/`tool/end`
274
+ as they happen and the assistant prose row only when the turn's text is known, so durable
275
+ history arrives as `[tools…, assistant]` while a live stream produces `[assistant,
276
+ tools…]`. `model/turns.js` (`groupTurns`) joins both shapes; tools whose prose row is
277
+ outside the loaded page fold into an assistant-less turn line instead of rendering as a
278
+ stack of top-level cards (the regression behind the durable-order dispatch).
279
+ - Assistant replies render as plain serif prose (16 px / 1.45, down from 17.5 / 1.55);
280
+ **Copy** and the timestamp stay out of the transcript until the message is tapped. User
281
+ bubbles reveal their timestamp on tap as well. Code blocks keep their language label and
282
+ copy button.
283
+ - Settled questions and approvals collapse to one summary line — `✓ Answered · Staging +1
284
+ more`, `✓ Approved · pwsh — npm run build` — and expand back to the full card on tap. A
285
+ card answered live stays open for that visit; one rebuilt from history starts folded.
268
286
  - Scroll is pinned to the bottom unless the user scrolls up; a "Jump to latest" /
269
287
  "New messages" pill appears. Switching to Activity and back preserves the transcript.
270
288
  - Empty states: no session, no messages, and a filtered-out activity feed each have
@@ -272,9 +290,11 @@ glassmorphism, no webfonts, no icon sheet — only inline SVG.
272
290
 
273
291
  ### Activity
274
292
 
275
- The tab shares the chat palette: compact All / Tools / Errors filter, a live indicator
293
+ The view shares the chat palette: compact All / Tools / Errors filter, a live indicator
276
294
  (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
295
+ session's step boundaries, tool calls, approvals and errors. It is reached from the
296
+ header's Activity toggle (a single icon button with an unseen-activity dot) rather than a
297
+ second tab row; tapping it again returns to the chat. Tool, approval and error
278
298
  entries are collapsible with the same animated body used by chat tool cards; expanded
279
299
  state is stored per entry id and survives live re-renders while the view is open.
280
300
 
@@ -319,7 +339,7 @@ opened; a toast flags them immediately.
319
339
  Deduplication (tool.start + question.request twins) only merges items of the same
320
340
  session, and `appendMessage` has a defensive boundary that refuses a foreign approval or
321
341
  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
342
+ - The notice bar is a direct child of the six-row `.app` grid on row 3 (between the header
323
343
  and the connection banner): full-width, safe-area margins, warning surface, first owner
324
344
  name and `(+N)` when more interactions are pending, with a 44 px **Open** action. It is
325
345
  re-rendered whenever approvals/questions arrive, resolve or a session opens, and removes
@@ -543,12 +563,22 @@ drag-to-dismiss from the grabber.
543
563
  a query is present and hides sections with no match.
544
564
  - Rows show the running/idle dot, title, updated time + preset, a small pin marker, an
545
565
  **Archived** tag and the active check.
566
+ - The New session sheet is explicit about what it will create: a **Project** chip row
567
+ (`No project` + one chip per project), a working-directory box/recent-cwd chips for the
568
+ ungrouped case, and an **Agent preset** list where tapping a row only *selects* it (the
569
+ deployment default starts selected and keeps its **Default** tag). Nothing is created
570
+ until the footer **Start session** button is tapped; its caption names the preset and the
571
+ project (`Plan · Think · Check · dsh-remote-mobile`).
546
572
  - The search box keeps the old instant local title/preset filter. Typing ≥3 characters also
547
573
  schedules a debounced (350 ms) `sessions.search`; `sessions.found` renders a **Messages**
548
574
  section with title + snippet (result rows already in the session list are skipped). When
549
575
  this deployment answers `unavailable`, the SPA disables message search for the sheet
550
576
  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
577
+ - Session menu (⋯) row actions: **Project / Change project** (project picker; sends
578
+ `session.attach` so a chat created before the phone named a project — or in a project folder
579
+ typed by hand — moves out of **Ungrouped** on the desktop too; the Host validates that the
580
+ session's folder is the project root, so a refusal is explained without echoing Host paths),
581
+ **Rename** (sheet with pre-filled input, Save disabled while
552
582
  blank, note that the desktop may shorten titles), **Pin/Unpin**, **Archive/Unarchive**
553
583
  (second tap when a run is active sends `stopActivity: true`; the first tap only explains
554
584
  the stop), and **Fork session** (second tap confirms; the fork arrives as a new
@@ -746,8 +776,9 @@ None change the wire format; all are client-side heuristics.
746
776
  is optimistic: model/preset labels update on tap, optimistic user bubbles reconcile via
747
777
  history, and stop stays "Stopping…" until `session.status { running: false }`. Failures
748
778
  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.
779
+ 3. **`sessions.create` response.** The SPA waits for the `sessions` + `session.opened`
780
+ frames that follow it and turns into a retry state on a matching `requestId` error,
781
+ with a 25 s fallback sheet.
751
782
  4. **Approvals are not part of `HistoryItem`.** Pending approvals are kept in a client map
752
783
  and re-attached to the transcript on `history` reload; resolved approvals live only in
753
784
  the current view/Activity feed until the transcript reloads.
@@ -1201,6 +1232,21 @@ Run from a checkout of this plugin:
1201
1232
  - Light and dark question cards both verified, no horizontal overflow.
1202
1233
  - Question screenshots: light history/pending/draft/waiting/resolved, dark resolved/pending/
1203
1234
  skipped, request-only and resolved states, plus the Activity entry.
1235
+ - **Chat density pass** (same headless Chromium harness, after the reference chat was
1236
+ reviewed): one quiet activity line per turn, settled cards folded, single header row and a
1237
+ conditional composer meta row. `dev/composer-ui-check.mjs` (127 checks) and
1238
+ `dev/question-ui-check.mjs` (62 checks) assert it, zero console errors:
1239
+ - the live turn shows `Thinking · Ns` with the detail folded; a running tool takes the line
1240
+ as `Working · pwsh` with `git status --short` on the quiet sub line; tool cards stay
1241
+ folded until the line is tapped; the finished turn reads `Used 1 pwsh`, drops the sub
1242
+ line and keeps the 812 ms duration on the card;
1243
+ - **Copy** and the timestamp are hidden until the message body is tapped;
1244
+ - a settled question card from history renders one summary line (`Answered`, `Staging +1
1245
+ more`) with its body hidden; a card answered live stays open, folds on tap, reopens on a
1246
+ second tap;
1247
+ - the header is one row (drawer · Activity · title/status · new · overflow) and the
1248
+ Activity toggle round-trips both views without a tab row;
1249
+ - the composer meta row is absent while idle and returns with Queue/Steer while a turn runs.
1204
1250
  - **Attachment pass** (same headless Chromium harness, against the mock upload endpoint with
1205
1251
  a 1 MB server limit and a 700 ms delay to make progress observable): **41 assertions, zero
1206
1252
  failures**, zero console errors and zero uncaught exceptions (only the deliberate `413`