Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

docs: mobile chat view design

reviewe145b06b0f69
diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.md
new file mode 100644
index 000000000..dc3f2ea94
--- /dev/null
+++ b/docs/mobile-chat-view.md
@@ -0,0 +1,175 @@
+# Mobile chat view — design (2026-09-27)
+
+Bring the desktop ⌘M chat view (#943–#957) to *nodeterm mobile* (`nodeterm-ios`), with a Claude-mobile
+feel: the session transcript rendered as markdown, a composer, a live "working" indicator, and Plan /
+Question cards that answer the agent's prompts — over **both** transports (direct SSH and the E2EE
+relay), in one delivery.
+
+## 1. Context (measured, 2026-09-27)
+
+- **iOS today** (`nodeterm-ios` origin/main 43bcf5c): no markdown and no transcript view anywhere; a
+ session opens only as a SwiftTerm terminal (`Features/Session/SessionView.swift`). A Claude-style
+ composer already exists (`Terminal/DictationComposer.swift`: `+` attach via PhotosPicker/fileImporter,
+ mic via `Services/SpeechDictation.swift` + Whisper/Parakeet/Apple engines, ▲ send). SPM deps:
+ SwiftTerm, Citadel, Sodium, WhisperKit, FluidAudio.
+- **Transports**: `SSHTransport` (Citadel) with `Services/HostCommands.swift` (`run`/`stream`, reused
+ session) — exec, file reads, tmux send-keys, SFTP uploads to `~/.nodeterm/uploads/`, answer-file
+ writes. `RelayTransport` (E2EE NaCl) calls a fixed RPC set served by desktop
+ `src/main/remote/host-service.ts` `onRpc` (pty.*, fs.* jailed to shared roots, git.*, projects.*,
+ node.*). **No transcript, chat-send or permission-answer RPC exists.** Server Edition has no relay
+ host service (SSH-only for the phone).
+- **Status to the phone**: the agent-status mirror (`core/agent-status-mirror.ts` → `agent-status.json`
+ / per-SSH-project `~/.nodeterm/agent-status-<projectId>.json`), polled every 4 s over SSH
+ (`Services/AgentStatusMonitor.swift`), relay `projects.list` every 30 s off-LAN, plus APNs/Live
+ Activities. The mirror carries state/sessionId/account/hibernated and inbox events; **no transcript
+ path, no `held` (plan vs question), no model/effort**.
+- **Approvals today** (`Services/InboxApproval.swift`): allow/deny via the plain-word answer file
+ (`~/.nodeterm/pending/<id>.answer`) when a pendingId exists, else tmux send-keys (digits/Escape/Enter).
+ No structured answers (plan mode / revise / question answers / free text); SSH only.
+- **Build reality**: SwiftUI cannot be compiled on this Linux server; a Linux Swift 6.1.2 toolchain
+ (`/root/.cache/swift/swift-6.1.2-RELEASE-ubuntu24.04`) compiles and tests **pure logic** in a scratch
+ SwiftPM harness. iOS CI (`.github/workflows/ios-build.yml`) has been billing-blocked since 2026-09-14.
+- **Reusable desktop core**: `core/transcript-reader.ts` (`parseChatWindow`, paged `ChatTranscriptResult`
+ with `olderCursor`/`key`/`unmatchedResults`/`at`, grow-on-no-complete-line), `core/chat-tool-body.ts`
+ (plan/question bodies), `core/remote-ssh/transcript-window.ts` (`transcriptPageCommand`, POSIX sh,
+ one round trip, size in the same reply), `core/remote-transcript-locate.ts`,
+ `core/agents/permission-decision.ts` (`buildPermissionDecision`, `answerHeldPermission`, revision-5
+ gate), `transcript-ipc.ts` `readChatPage`.
+
+## 2. Decision: one wire format, two producers
+
+Rejected: (2) phone parses on both transports (relay ships raw JSONL; still needs a desktop answer RPC;
+the TS parser must stay for desktop ⌘M anyway, so drift risk just moves); (3) a host-side helper parses
+for SSH (POSIX sh can't parse JSON; node is not guaranteed on hosts — Claude ships as a standalone
+binary).
+
+Chosen: the phone always consumes the same **`ChatPage`** JSON. The desktop produces it for relay
+hosts (reusing core unchanged); the phone produces it itself on SSH hosts (Swift port of the parser),
+so SSH works with no desktop running. **Golden fixtures** generated by the TS implementation lock the
+Swift port to byte-identical output.
+
+## 3. Data & transport
+
+### 3.1 Wire format
+
+```
+ChatPage {
+ version: 1
+ messages: ChatMessage[] // desktop shape: role, parts (text | thinking | tool{name,arg,result,
+ // summary,body,questions,id}), key (byte offset), at (ms)
+ found: boolean
+ olderCursor: number | null
+ unmatchedResults: {id, result}[]
+ model?: string // from the latest assistant record
+ effort?: string // from the latest assistant record (`effort` field)
+}
+ChatStatus { state, held?: {pendingId, toolName, questions?}, hibernated, paused, dropped,
+ sessionEnded, structuredAnswers: boolean }
+```
+
+`version` lets the phone refuse a newer shape honestly.
+
+### 3.2 Relay producer (desktop, this repo)
+
+New verbs in `host-service.ts` `onRpc`, all behind the existing relay project-scope jail; the phone
+sends **only `nodeId`** (plus paging/answer payload) — cwd, account, agent, transcript path and remote
+routing are resolved host-side from the desktop's own registry (node ids are attacker-controllable;
+never trust phone-supplied paths).
+
+| verb | params | does |
+|---|---|---|
+| `chat.page` | `{nodeId, before?, maxBytes?}` | `readChatPage` (paged, remote-aware, grok unpaged) + `model`/`effort` |
+| `chat.status` | `{nodeId}` | agent state + `held` + shell-owned-pane flags + whether structured answers are supported (revision gate) |
+| `chat.send` | `{nodeId, text}` | desktop send gate (`canSendFromChat` + `agentProcessInPane` + no held request) then `sendText` |
+| `agent.answer` | `{nodeId, pendingId, answer: PermissionAnswer}` | `answerHeldPermission` (pending file is the source of truth; revision gate; no `setMode auto`) |
+
+Limits: page ≤ 5 MB (existing clamp), text ≤ 64K chars, answer ≤ 64K chars. Unknown verb on an older
+desktop → the phone shows "Update nodeterm on your computer".
+
+### 3.3 SSH producer (phone, `nodeterm-ios`)
+
+- **Locate**: run the desktop's `remote-transcript-locate` command string (ported verbatim as a
+ builder), validate the path with a Swift port of `isSafeRemoteTranscriptPath`.
+- **Read**: run `transcriptPageCommand` verbatim; parse the framed reply (strict: size/start/end
+ consistency, newline present) and the byte window with the Swift `parseChatWindow` (1-byte
+ lookbehind, partial-line drop, grow-on-no-complete-line up to 5 MB, tool-result carry, plan/question
+ bodies, `at`, model/effort).
+- **Held**: list `~/.nodeterm/pending/*.json` over SSH (bounded read), map by the payload's
+ `session_id` to the node, `tool_name` → plan/question; hook-script revision read from the installed
+ script's marker; revision < 5 → no answer controls.
+- **Send**: the desktop tmux paste plan — `load-buffer -b nt -` (text on **stdin**), copy-mode cancel
+ guard, `paste-buffer -d -p -r`, `send-keys Enter` — on the `node-terminal`/`nodeterm-rmt` socket the
+ session lives on. ESC bytes stripped.
+- **Answer**: Swift port of `buildPermissionDecision` (validates against the pending request file),
+ written atomically (`umask 077`, tmp + mv) from stdin; `pendingId` regex-validated before any path.
+
+### 3.4 Live updates & paging (both transports)
+
+- First open: 256 KB tail; scroll near top → 512 KB older pages; merge by `key`; carried tool results;
+ unconfirmed optimistic sends kept until the transcript has them; "Beginning of conversation" at
+ `olderCursor == null`.
+- While the Chat screen is visible and the agent is working: tail re-read every 2 s, single-flight,
+ skipped when the size is unchanged; none when the screen is hidden or the app is backgrounded.
+ Status comes from the existing 4 s mirror poll (SSH) / `chat.status` (relay).
+
+## 4. Screen & interaction (iOS)
+
+- **Entry**: a **Chat | Terminal** switch in the session screen's top bar; default Chat for
+ chat-capable agents (claude, grok), last choice remembered per node. Tapping an Inbox question /
+ approval opens that session in Chat.
+- **Thread**: user messages right-aligned in a neutral bubble; assistant unbubbled full-width. Markdown
+ via **MarkdownUI** (`gonzalezreal/swift-markdown-ui`, the one new dependency — `AttributedString
+ (markdown:)` has no block elements): code blocks horizontally scrollable with Copy; links open in
+ Safari; relative/file links ignored. Tool calls as compact chips (tap → result sheet); thinking
+ collapsed. Under each assistant response: Copy + relative time; long-press → Copy / Share.
+ Scroll-to-bottom button when away from the bottom.
+- **Plan card**: full plan markdown + *Approve · previous mode* / *Approve · accept edits* / *Approve ·
+ ask before edits* / *Revise…* (inline text field). **Question card**: options (single / multi),
+ Other field, Submit. Large touch targets; haptic on send. No controls when structured answers are
+ unsupported → an "Answer in Terminal" banner with a button to switch tabs.
+- **Composer**: reuse `DictationComposer` (+ attach, mic, ▲). A **model · effort** chip above it; tap →
+ `/model` via the send path, then switch to Terminal. Locked (with the reason) while working, while a
+ prompt is held, or when the pane is shell-owned. Attach: SFTP on SSH; disabled with a reason on relay
+ (no upload RPC — out of scope).
+- **Working row**: the existing mascot animation + "Claude is working…", shown optimistically on send.
+- **iPad**: same view, readable max line width.
+
+## 5. Safety & failure handling
+
+- Never type blindly into a pane: send and `/model` only when the state is `done` or unknown **and** no
+ held request exists **and** an agent process owns the pane; the gate is re-asked at send time. Relay:
+ the desktop decides. Text only via stdin; ESC stripped.
+- Answers validated against the host's pending request file; Swift and TS builders locked by golden
+ fixtures; `setMode auto` unrepresentable; expired ticket / old hook → "Couldn't send — answer in the
+ terminal", never a false "sent".
+- Distinct states: transcript not found / unreadable / unsupported on this connection / desktop too old;
+ network loss keeps the thread with a "Reconnecting" banner and pauses live reads; failed older page →
+ retry row, thread kept.
+- Cost: live reads only on a visible Chat screen while working; nothing in the background.
+
+## 6. Testing & verification
+
+- **Golden fixtures**: a desktop script cuts anonymized slices from real transcripts on this server
+ (huge image lines, multi-byte chars at window edges, cross-page tool results, plan/question,
+ model/effort), runs them through the TS parser/pager/tool-body/decision builder, and writes
+ `fixtures/chat/*.json`. A desktop test fails if the fixtures drift from the current TS output. The
+ same fixtures are copied into `nodeterm-ios`; the Swift parser and decision builder must match them
+ exactly in the Linux Swift harness.
+- **Desktop**: unit tests for the four relay verbs (scope jail, limits, nodeId resolution, send gate,
+ revision gate).
+- **iOS pure logic** (Linux harness): parser, paging/merge, send gate, decision builder, held derivation,
+ SSH command builders (run under a real `/bin/sh`).
+- **Not verifiable here**: SwiftUI compile, layout, device behavior. Owed on a Mac (`xcodebuild` +
+ device checklist in the iOS PR); no "tests green" claim for UI.
+
+## 7. Delivery
+
+1. **Desktop PR** (`nodeterm`, branch `feat/mobile-chat`): relay verbs, golden-fixture generator + drift
+ test, this doc, CLAUDE.md. Safe to merge first — no existing phone calls these verbs.
+2. **iOS PR** (`nodeterm-ios`): Swift parser + decision builder + `ChatPage` model, SSH & relay data
+ sources, Chat screen, cards, composer integration, MarkdownUI. Mac build + device checklist in the PR.
+
+## 8. Out of scope (YAGNI)
+
+Voice conversation, thumbs/retry/read-aloud, relay file upload, Codex/Gemini chat view (no desktop
+chat view either), Android.