Baton
CLAUDE.md14 starsChanged 11 days agoMITView on GitHub
- Plan before code: All code changes must be preceded by a detailed proposal (which files, what changes, why). Only modify code after explicit user confirmation. - Concise comments: Keep code comments minimal — only what's necessary to understand non-obvious logic. Detailed design/architecture notes belong in CLAUDE.md, not inline. - Browser regression evidence workflow: For ordering, missing-message, duplicate-message, recovery, or spinner regressions, first enable DevTools Preserve log and export the complete HAR. Copy the untouched HAR locally, extract every WebSocket…
- Reads credentials
In this repository2 other files it gives its agents.
- packageSkill
- testflightSkill
The file
We split this CLAUDE.md into the rules it gives an agent
7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 5
Plan before code: All code changes must be preceded by a detailed proposal (which files, what changes, why).
- Distinctive: line 6
Concise comments: Keep code comments minimal — only what's necessary to understand non-obvious logic.
- Very specific: line 87
Create new agent sessions from the New Session view through detached claude --bg
- Very specific: line 127
Commit only takes the staged set the user saw (stagedId).
- Very specific: line 185
Every turn end is completed, background tasks or not.
- Very specific: line 263
Always-on: launchd (macOS), systemd user service + loginctl enable-linger (Linux), Task Scheduler (Windows)
- Distinctive: line 507
No cookies, no server middleware — static files publicly accessible
≈ “Common” is an estimate: at least 1 in 5 of the 26,980 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Baton — Project Context
Workflow Rules
- Plan before code: All code changes must be preceded by a detailed proposal (which files, what changes, why). Only modify code after explicit user confirmation.
- Concise comments: Keep code comments minimal — only what's necessary to understand non-obvious logic. Detailed design/architecture notes belong in CLAUDE.md, not inline.
- Browser regression evidence workflow: For ordering, missing-message, duplicate-message, recovery, or spinner regressions, first enable DevTools Preserve log and export the complete HAR. Copy the untouched HAR locally, extract every WebSocket frame and every messages API response, then replay the exact captured payload through the real frontend test harness until the browser result is reproduced exactly. Only after that may the root cause be reported or business code be changed. Keep HARs and extracted diagnostics local and untracked; never commit API keys or other captured credentials.
What is this
Baton is a cross-platform app + bridge + server that lets you view local agent sessions from your phone or desktop. Claude Code supports viewing and interaction; Codex supports history, real-time monitoring, and interaction with existing Sessions. Three components:
- bridge/ — Node.js script running on macOS/Linux/Windows (always-on, auto-start), normalizes Claude Code and Codex JSONL
- server/ — AWS Lambda (FastAPI) + DynamoDB + WebSocket API GW, relays between bridge and app
- web/ + src-tauri/ — Static HTML/CSS/JS frontend, packaged as native app via Tauri v2 (Android/iOS/Desktop)
Brand name "Baton" is only in user-facing places. Internal code uses generic names so renaming is easy.
Core Design Principle
DynamoDB is the durable browsing cache; WebSocket is the real-time path:
- DDB: device/project/session metadata plus normalized message history
- WS: real-time messages, streaming previews, permissions, and control actions
- App localStorage: local auth/nav state cache
Current Status
Phase 1: COMPLETE ✅
- bridge.mjs syncs session metadata to DDB via HTTP POST
- bridge.mjs watches .jsonl files, detects new messages in real-time
- Deployed to ap-northeast-1 (Baton), verified 300+ sessions
Codex Phase 1 + Phase 2: COMPLETE
- Runtime adapters discover Claude Code and Codex into one Device → Project → Session catalog.
- Codex metadata and recent/running history sync on Bridge startup; older empty DDB partitions
use REST
needSync→ WSsync_session→ adapter → DDB →sync_complete. - Codex uses
codex:<nativeSessionId>storage IDs and the existing Claude-compatible project hash. - Runtime icons and normalized message/tool rendering are complete.
- Codex watcher monitors every configured
CODEX_HOME/sessionsroot and pushes append-only updates through the same WS ack, HTTP fallback, frame-limit, and watermark semantics as Claude. - Codex rollout-only status updates support
running/completed; interaction resume recovers daemon-owned approval waits even though the startup catalog cannot infer them from JSONL alone. - Codex Phase 3 interaction prefers the managed app-server Unix WebSocket when present and falls
back to
codex app-server --stdio: existing Sessions usethread/resume+turn/start; new Sessions usethread/start+turn/start. A resumed active turn is adopted so pending approvals and later deltas keep streaming; a new user turn waits in the same per-session queue. - Codex and Claude share
StreamFramer: first delta is immediate, later deltas use the same 50ms batch window, whileLiveTurnStreamassigns the turn-levelseq. The frontend usesTurnEventQueue → StreamCoordinator → StreamingDomRendererfor ordered consumption, authority reconciliation, and progressive reveal. - Codex user/assistant live rows are broadcast immediately; the rollout watcher persists matching rows without rebroadcast and remains the fallback when no live row was observed.
- Codex command/file/permissions/MCP approval variants are implemented. Automatic pending-request recovery immediately after a Bridge restart, before any send resumes the thread, remains Phase 3 work.
- Detailed status and validation:
docs/codex.md.
Phase 2A: COMPLETE ✅ — Backend + API Verification
- Server REST read endpoints (devices, projects, sessions, messages)
- WebSocket API Gateway + relay (subscribe, broadcast, heartbeat)
- Bridge WS connection + real-time push
- Web viewer (web/) with dark theme, diff2html, markdown, file badges, Agent stats
Phase 2B: COMPLETE ✅ — Send Messages + Images + Device Routing
⚠️ Originally built on tmux send-keys; superseded by Phase 2E (headless) — tmux is deleted. The image/device pieces below still stand.
- Message sending (was tmux send-keys → now headless stream-json pool, see Phase 2E)
- Permission prompt detection + approval UI
- Image upload via S3 +
baton-bridge:protocol - Auto-create regular sessions through headless
--session-id - Device routing for multi-bridge setups
Phase 2C: COMPLETE ✅ — Native App (Tauri v2)
- Tauri v2 wraps web/ as native app, zero web code changes
- Android, iOS (TestFlight), macOS builds
Phase 2D: COMPLETE ✅ — Claude Agents Support
- Bridge discovers agent identity through
claude agents --json --all; roster.json determines active daemon ownership, while jobs/state.json only supplies the current blocked question - Agent sessions display [Agent] badge + Working/Needs input/Completed status
- Send messages to agent sessions: was
claude agentsTUI navigation over tmux; now headlessclaude -p --resume <agentSessionId>handles agent sessions like any other (works via_pool.send) - Create new agent sessions from the New Session view through detached
claude --bg - Bridge respects permissions.defaultMode: bypassPermissions (no false permission prompts)
Phase 2E: COMPLETE ✅ — tmux removed, headless is the only send path
tmux is fully deleted. The entire send/permission/launch stack now goes through
the headless stream-json process pool (bridge/headless.mjs ClaudePool). Do not
reintroduce tmux; extend the pool for future Claude interaction work.
Done:
bridge/tmux.mjsdeleted entirely (send-keys, capture-pane, launch, TUI nav, wizard detection,hasTmux, stale-session cleanup).projectHashToPathmoved intosession.mjs(pure path util, not tmux).getClaudeProcesseswas tmux-only and dropped —getRunningInfoinsession.mjshas its ownps auxparser.- Server bridge-install script (
/api/install) no longer auto-installs tmux. - Existing-session send → headless streaming (
handleHeadlessSend→_pool.send), the primary happy path. Works today. - Stream ordering —
stream-framer.mjsonly batches UTF-8-safe incremental chunks and block boundaries.LiveTurnStreamis the single shared-event outlet and assigns one contiguous, turn-localseqacross user authority, blocks, deltas, tool input, permission events, authority messages, and terminalstream_end.TurnEventQueueconsumes only contiguousturnId + seq;StreamCoordinatorowns turn/block state and authority reconciliation;StreamingDomRendererapplies operations without rebuilding correct DOM. Late join resumes atseq=1 messages(user), the next complete block/permission checkpoint, or terminal authority. Seedocs/streaming-render-design.md. - Reply placement by turn identity — Web generates
turnIdbefore send and stores it directly on the optimistic user bubble asdata-anchor. Bridge and Server preserve the sameturnIdon every shared event andsend_message_result; the renderer locates the exact anchor withoutclientId/streamIdbinding, text matching, timestamp ownership, or nearest-pending heuristics. Authority uses UUID/native ID to confirm or patch nodes inside that same turn. - Permission bridge DONE —
onControlRequest→ apppermission_request {kind:tool|ask|plan};handlePermissionReply {requestId, decision, answerText}→_pool.replyControl. Ordinary tools allow/deny; AskUserQuestion/ExitPlanMode answer via deny + answerText inmessage(CC's only answer channel on--permission-prompt-tool stdio, verified CC 2.1.211 — a structuredcontrol_responseanswer is force-converted to deny); cancel = deny +interrupt:true. Answer renders in the tool-card OUT (green), cancel shows warning (yellow). A still-pending control_request is re-pushed on (re)subscribe (reveal_permission). Frontendweb/js/components/permission.jsfully rewritten (oldarrow:/type:/escapeprotocol + client-side heuristic detection deleted). - New Session / new agent / create project DONE — regular sessions mint a UUID, acknowledge
it before spawning headless with
--session-id, and then stream the first turn. Background agents launch throughclaude --bg. Creating a project seeds an empty PROJ row and enters the new-Session input view. - Stall Rescue +
stall.mjsfully deleted;command_output(tmux capture) path deleted (bridge/server/frontend);streamModeflag deleted;permissions.mjs+needsPermission+ per-directory permission reads deleted.
Git Graph + Commit/Push: COMPLETE
- Git page header shows
project › branch ↑N ↓Mfrom the existing porcelain status; the branch text is display-only. - Graph (below Changes, collapsed by default) draws real parent topology with an incremental lane layout
(
web/js/git/graph-layout.js); scope is Auto (HEAD + upstream) / All / one branch and never checks out. - Everything stays on the
git_statusaction: read-onlyrefs/history/commit_files, commit-targetdiff, andcommit/push. History pages over fixed head OIDs with--topo-order+--skip; commits and file lists share a first-parent base; subdirectory projects are scoped with pathspec /--relative. - Commit only takes the staged set the user saw (
stagedId); push never forces, publishes with-u origin, and fails fast on SSH prompts. The commit bar is one state-driven button (Commit / Push / Publish). - Graph view state, the first page per scope and the branch list reuse the Changes IndexedDB cache
(stale-while-revalidate). Checkout / Stash & Switch / Pull are deferred. Details:
docs/git-history-design.md.
Mobile Notifications: COMPLETE
- Finished runs and
needs_inputalert as project · session + summary; tapping opens the session. One Settings switch (default on). Localtauri-plugin-push: iOS registers with APNs; Android runs a foreground service ("Baton is running in the background") polling the event feed natively (5s foreground / 15s background; WebView timers are throttled in background). - Source is only the
BridgeSessionsstream (Bridge writes each approval asneeds_input+agentDetail) →NotificationWorker. Devices are onePUSH_DEVICErow per<environment>:<token>. Before alerting it skips interrupted turns and sessions a visible, focused app is viewing (notify_check→notify_seenwithin 2 s on theROOT#subscription). A turn started outside Baton also skips while the user is at that computer: Bridge attacheslocalIdleSec(presence.mjs: own pty atime, macOSHIDIdleTime, Windows Interactive helper task) and the worker drops it under 120 s. Sessions Baton has driven (batonSessions), daemon agents and Baton's own terminals never set it, so their alerts are unchanged. - iOS pushes carry only the event's feed key and a placeholder; the
NotificationServiceextension fetches the text from the user's own server (/api/notifications/event, credentials in the shared$(AppIdentifierPrefix)com.batonai.sharedkeychain group). They go through the shared, stateless APNs relay (push-relay/, own AWS account, IAM-auth Function URL, holds the APNs key); stacks only know its URL (PushRelayUrl,PUSH_RELAY_URLfor install.sh). The release script keeps the extension's CFBundleVersion in step with the app's. Device Farm public iOS devices strip the push entitlement. Details:docs/mobile-notifications.md.
Phase 3: LATER — Production polish
- Harden the existing persisted
~/.baton-bridge/synced.jsonrecovery path
Deployed Environment
API URL and API key live in .env.local (gitignored). When you need them,
read that file — do not hardcode them in committed code. Variables:
BATON_API_URL, BATON_API_KEY. See .env.local.example for the
template. S3 bucket / ECR repo / AWS account id are derived automatically by
server/install.sh from the stack name + aws sts get-caller-identity.
- Region: ap-northeast-1
- Stack: Baton
- DDB Tables:
Baton-bridge-sessions,Baton-bridge-messages - Deploy:
cd server && ./install.sh --region ap-northeast-1 --stack Baton
Key Technical Decisions
Bridge
- Watches
~/.claude/projects/<project-hash>/<session-id>.jsonl readableProjectName()resolves hash back to real path by walking filesystempreview/ Session title:custom-title > ai-title > summary > first prompt > last-prompt, in the Bridge list and the open-Session title alike. CC's resume list putslast-promptfirst; Baton deliberately does not follow it. Until a Baton-created Session's transcript has a prompt (a forked Skill writes none until it finishes), the Bridge uses the prompt it sent.- Filters: skips empty/no-preview files, subagent sessions
- Session
status: three-state (running/needs_input/completed), one field, no parallelagentState. Displayed as Running (green) / Needs input (amber) / Done (grey). Three sources map into this single enum:- busy pool-owned (headless): pool lifecycle events push status via the sync-sessions HTTP
path —
_pool.send→running;control_request→needs_input; turnresult→completed(orneeds_inputif a control_request is still pending).ws.mjssyncPoolStatus. Every turn end iscompleted, background tasks or not. Acompletedwrite also carriesbackgroundAgentswhile background agents still run (the pool'slocal_agenttasks, else CC's own~/.claude/sessionsrecord readingbusy, re-read after 1 s); the worker skips that Done, so only the report-back turn after the last agent alerts, and a hold released without a running write in between (heldForAgents) alerts the last reply. Background Bash and Monitor never hold it: CC does not mark long-running ones (servers, persistent Monitors), so each Bash report-back turn alerts. Alerts stack per session (iOS thread, Android group). Acontrol_requestoutside a pool turn (a background agent, or a turn CC started itself) goes to the pool'sonControlRequest, so it still reaches the app asneeds_inputinstead of blocking CC forever. - external CC (terminal/VS Code, not pool-owned):
getSessionStatus()(startup sync +checkStopped) first uses CC's own~/.claude/sessions/<pid>.jsonrecord (busy/waiting/idle/shell→ running/needs_input/completed/completed; terminal since 2.1.119, SDK/VS Code since 2.1.269), trusted only for a pid listed as a claude process and, on Linux, the sameprocStart(killed processes leave records behind; Windows skips it). Without a record, it and the watcher'sstatusFromEntry()read the jsonl tailstop_reason(tool_use/null → running; structuredAskUserQuestion/ExitPlanMode→needs_input;end_turn/interrupt/no-process →completed). - daemon agent: while its worker is present in
roster.json,mapAgentState()maps--jsonworking/blocked/done → running/needs_input/completed. Inactive historical--allentries preserve agent identity only; status falls back to process + jsonl. - Precedence when a session matches more than one source: busy pool-owned >
roster-active daemon agent > external/jsonl.
watcher/
checkStoppedskip status writes for busy pool-owned (poolOwns()) and daemon-agent sessions. - subagent threads: a root row shows the effective status (own status OR any child
runningAgentCount/needsInputAgentCount). An interrupted subagent's tail stays non-terminal forever, so unless.meta.jsonsaysfinished:true(CC never writesfalse) a child trusts its tail only while its parent's own status is running, CC's record for the root readsbusy/waiting(it stays so while foreground or background subagents run, also at a prompt), the pool still lists a background agent, or it was written in the last 15s. A stopped agent never getsfinished:true, so a child is also completed when its spawner's transcript last reports it in a<task-notification>rather than a laterresumedAgentId. A child last written before the earliest live CC process of its root Session started (its~/.claude/sessions/<pid>.json, pool processes included) died with an earlier process and is completed too. While a root's own status holds (unchanged or pool/daemon-owned),checkStoppedapplies both end rules to its tracked active children with one stat each. Only CC's own rows count (claudeTaskEvent(): enqueued notifications, notification prompts,SendMessageresults), not tool output quoting them;claudeSubagentEnded()scans incrementally; the watcher rechecks active children when that notification is appended, after the root's own write. CC (2.1.322+) also writes a notification it already reported through a hand-back, or one replayed at resume, and never answers it: while CC's record readsidlethat row meanscompleted, notrunning.inspectActiveSession()re-derives the counts on everycheckStoppedpass and sends them, becausesync-sessionstreats missing counts as "unchanged". getRunningInfo():ps aux+--resumearg extraction → exact session ID + project cwd (used by external detection). VS Code CC (no--resume) → project-level + mtime>5min → completed.- Legacy
idle/stoppedvalues in old DDB rows are normalized tocompleted/Done by the frontend'sstatusLabel/statusClassfallback (no migration script; re-derived on next sync).
- busy pool-owned (headless): pool lifecycle events push status via the sync-sessions HTTP
path —
projectHashToPath()(insession.mjs): reverse hash to real directory path (validates each segment exists)- Claude Agents support:
- Agent identity source is
claude agents --json --all. Its working/blocked/done state is authoritative only whileroster.jsonstill contains that worker; stopped or headless-taken-over agents remain in--allwith stale state indefinitely, so they keepisAgent/name but derive status from process + jsonl.getAgentsJson()caches the resolved catalog for 3s and returns the last-good cache on CLI failure. Filter tokind === 'background';kind:"interactive"entries are not agents. agentDetail(the blocked question shown on the card) is the ONE field still read fromjobs/<sid[:8]>/state.json'sneeds—--json'swaitingForis almost always null.getDaemonRunningSessionIds(): reads~/.claude/daemon/roster.json→ active worker sessionIds (still used to detect a done-agent resumed as a normal CC session).- Agent status poll (
watcher.pollAgentStates, everyAGENTS_POLL_INTERVAL_MS): diffsgetAgentsJson()vs_jobsState, pushes changed agents. Empty_jobsStateon startup → first poll full-pushes every agent (heals DDB + covers every version-update restart). Replaced the oldfs.watch(state.json)(missed transitions since state.json lags). - Status paths that key off live CC processes (
checkStopped) skip roster-active daemon agents and busy pool-owned sessions. Precedence: busy pool-owned > roster-active daemon > external/jsonl. - Worktree project-hash normalization: a session that
cds into<proj>/.claude/worktrees/<name>has its jsonl moved to a new project dir, producing a 2nd DDB row for one sessionId.normalizeProjectHash()strips--claude-worktrees-*at every POST site (keeps real hash for on-disk reads) → one session, one row, under the parent project. Seedocs/claude-code-bridge.md. - Send to agent / new agent / reveal pending input: existing agents resume through headless
claude -p --resume <agentSessionId>; new agents launch throughclaude --bg; pendingcontrol_requeststate is re-pushed onreveal_permission. - Permissions are enforced by CC itself (bypass mode → no prompt); the bridge no longer reads settings — see the Permission Detection section.
- Agent identity source is
- Slash commands are runtime-aware. Claude's primary catalog comes from the current CLI's
no-persistence
initializecontrol response, including environment-filtered commands, descriptions, argument hints and model choices.commands.mjsonly scans custom commands and Skills as an old-version fallback; there is no static Claude built-in list./usage,/cost,/stats,/status, and bare/configopen the local four-tab Settings panel. Codex usescodex-commands.mjs: the mobile catalog starts from the complete 44-command popup observed in Codex 0.147, then preserves that presentation order while filtering only commands without a complete phone equivalent. The current macOS Bridge exposes 33 built-ins; Linux exposes 32 because/appis host-platform specific. IDE/TUI presentation commands,/approve,/side, and/pluginsare filtered.$CODEX_HOME/prompts/*.mdlegacy prompts are appended in name order. Codex Skills come from app-serverskills/list; selecting one composes$name, andturn/start.inputcarries the matching structured Skill item. The app preserves Bridge order and caches by device + runtime + project. Details:docs/api.md+docs/codex.md. - Config:
~/.baton-bridge/config.json, auto-created from CLI args- Tool previews are always enabled; historical
toolPreviewssettings have no effect. Clients usetool_detailsto load full content from the original JSONL.
- Tool previews are always enabled; historical
- Always-on: launchd (macOS), systemd user service +
loginctl enable-linger(Linux), Task Scheduler (Windows) - Deployed bridge runs from
~/.baton-bridge/(copied), NOT the workspacebridge/. Local dev:cp bridge/*.mjs ~/.baton-bridge/+ restart service. - Auto-update: startup and WebSocket reconnect check
/api/versiononce. Existing four-minute heartbeat replies includebridgeVersion; only a different non-dev version triggers another check, so normal heartbeats add no REST requests and there is no dedicated update timer. On change, Bridge resolves the S3 package through/api/install, stages and validates it, then restarts even with active terminal sessions. Existing terminal/agent processes may be interrupted; they do not defer updates. Checks never overlap and network requests have timeouts.install.shuploads the Bridge package before exposing its version through CloudFormation; both API and WS Lambdas receiveAppVersion. Bridge WS connections reportbridgeVersionfor fleet verification. /api/versionreadsAPP_VERSIONenv (= semantic + git hash, set per build). Managed by CFN (AppVersionparam in template, passed by install.sh). Lambda env overrides image ENV, so the CFN param MUST stay wired or the version freezes and auto-update silently stops.- Initial sync: merge all runtime catalogs, upload full Session metadata, then sync active + recent 24h messages with concurrency 2.
await syncSessions()thenawait reconcile()(recount aggregates at that definite completion point). - Periodic check (5min):
checkStopped()— detects disappeared CC processes viaps aux→completed(skips roster-active daemon agents + busy pool-owned sessions) - Watcher: fs.watch detects jsonl changes → sync metadata only on status change, new session, or ai-title
- Status cache:
lastKnownStatusMap prevents redundant sync POSTs (only sends on change) - Debounce: busy Map per session dedup fs.watch duplicate events
- Line-number tracking per session (not UUID set), lightweight
- Images: sharp compress 1280px JPEG (quality=90) → upload S3 via Lambda → store key in message
- Batching: by byte size (≤4MB/POST), with 200ms delay between batches
- WS ack:
wsSendWithAckwaits for servermessages_ackreply (5s timeout), falls back to HTTP POST to DDB if no ack
Server
- FastAPI in Docker Lambda, API Key auth. API Gateway checks
x-api-keyon/api/*; WS$connectcompares?apiKey=with the deployment key, which both Lambdas read from API Gateway by name (server/src/api_key.py, cached 5 min; a failed lookup keeps the last value, and with no value REST/WS answer 503 rather than guess an account) — the key is never stored in a table. Their IAMapigateway:GET /apikeyscan read every key in the region: the API key depends on the stage and so on the API Lambda, so the Lambdas cannotRefits ID. - DDB
accountId= SHA256(apiKey)[:16] — raw key never stored.install.shpins it as theAccountIdstack parameter (deploy stops if the key cannot be read), and only the current key maps to it; any other key still gets its own empty account.install.sh --rotate-keyskips the build and keeps the deployed template and every other parameter, passing only a newApiKeyName(<stack>-api-key-<timestamp>), so CloudFormation replaces the key (an API key's value cannot be changed in place) and the data stays; every device then signs in with the new Start URL. WebSockets opened with the old key are not closed (API Gateway ends them within 2h). - Sign-in / install tokens: Setup's Start URL, QR code and install command
(
/auth/install?t=…) share one token from/api/auth/start-token, valid 10 minutes (deploy output: 12h) and reusable until then. Token rows name the key instead of holding it, so a rotated key retires them;/auth/exchange-tokenreturns the current key. - The key lives only in the Bridge's
~/.baton-bridge/config.json(0600); service definitions no longer pass--key, and older ones are rewritten at startup. - Removing a device (home long-press →
/api/bridge/delete-device) sendsdevice_removedand closes its Bridge sockets, then deletes its DEV#/PROJ#/SESS# rows. The Bridge removes its launchd/systemd/Task Scheduler entry andconfig.json, then exits 0 (no restart). A Bridge that is offline at the time comes back and re-adds the device; remove it again. install.sh: ECR → S3 → CodeBuild (arm64) → CloudFormation- Bridge install script (
/api/install): exportsXDG_RUNTIME_DIRfor Ubuntu SSH compatibility (tmux auto-install removed in Phase 2E)
Message Flow (WS single path + DDB cache)
- Claude watcher normally pushes new messages through WS; startup, fallback, oversized authoritative copies, and on-demand history use HTTP
- Lambda broadcasts ordinary watcher messages and writes their final fields to DDB. Runtime-owned
messages{noCache:true}are broadcast only; the later JSONL watcher copy owns persistence. - Bridge extracts: uuid, parentUuid, type, content, timestamp, toolUseResult
(drops model/usage/cwd/version). Tool IN/OUT always keeps
the first 500 Unicode characters per text field, Edit keeps paths and status,
thinking signatures are omitted, and
toolUseResultkeeps only numeric Agent duration/tool-count statistics. Failed Edit results retain their error preview. This same prepared representation is reused for HTTP, WS and live authority; a module-local WeakSet skips repeated processing of the same message object. - Block-level
truncatedmeans on-demand tool content, independently of transport truncation/recovery. A final structured input event replaces any incomplete streamed JSON preview when its block stops.tool_detailsreads original JSONL in a worker with a single-file, file-version-keyed tool index, then replies only to the requesting client using the existing text-frame protocol. The frontend caches complete details per device/session/tool; missing expected output is retryable. Failed detail loads expand the available local preview. Seedocs/tool-preview.mdfor the rendering and rollout contract. - Content blocks preserved: text, image (compressed), document, thinking, tool_use, tool_result
- App opens session → REST from DDB (instant, <100ms) + WS subscribe for real-time
- WS subscribe + buffer during REST load → merge/dedup → resolve running state from newer applied
WS lifecycle or
/messages.status→ render → subsequent WS direct append - A REST snapshot replaces the local tail, except live prompts (
live:user:Claude,codex:user:Codex) newer than the snapshot's last non-metadata message and absent from it: thosenoCacherows reach DDB only after the JSONL/rollout watcher persists them under the same identity, so dropping them made the sent message vanish mid-turn. Other live rows are not kept — e.g.live_interrupt_*persists under its native UUID after a Bridge restart and would duplicate (history-snapshot.jsreplaceHistoryTail). When a snapshot still drops live rows (e.g. refresh while the final reply is revealing, before the watcher persisted it), the existing turn-end recovery re-fetches; a mergedcompletedwith no outstanding turn clears the spinner. - Claude's live interrupt is sent on ESC, but CC flushes the partial reply after acking it. A
still-revealing block has no identity yet (
elementOrder= newest), so an interrupt restored into a stream row is always appended last (message-dom.js), matchingcreateBlock. - Server broadcasts to ALL app connections subscribed to a sessionId (multi-device)
- See
docs/claude-code-bridge.mdfor full protocol and flow diagrams
DynamoDB Schema
Single-table design — BridgeSessions holds three entity types keyed by SK prefix:
BridgeSessions PK: accountId (SHA256(apiKey)[:16])
SK: DEV#<device> entityType=device — one row per device
→ sessionCount, projectCount, os, lastActive, runtimeCapabilities
SK: PROJ#<device>#<projectHash> entityType=project — one row per project
→ sessionCount, projectName, lastActive (aggregates)
SK: SESS#<device>#<projectHash>#<sid> entityType=session — the real session row
→ status (running/needs_input/completed), preview, model, size, lastActive,
runtime, nativeSessionId, modelProvider, clientSource, cliVersion,
isAgent, agentName, agentDetail
GSI accountId-activeStatus-index (sparse, ProjectionType ALL):
activeStatus = "running" | "needs_input" (active sessions)
| "done#<lastActive>" (every completed session)
→ homepage Active Sessions = between("needs_input","running"); c<n<r so
completed/done# are excluded. Completed Sessions = begins_with("done#") desc limit 20.
BridgeMessages PK: sessionId SK: timestamp#uuid
Attributes: uuid, type, content (JSON), timestamp, optional stopReason/toolUseResult
TTL: 90 daysCount consistency (aggregates drift; DDB-self-consistent, not disk-truth):
- Bridge calls reconcile right after
await syncSessions()(a definite completion point — all SESS# writes are awaited-done; no timer guessing) and again when a brand-new project first appears in the watcher. NOT periodic. - The incremental
statusDeltaADD path still maintainssessionCount(+1 onfrom:'new'); aggregate status deltas are now unread (reconcile owns those numbers).
API Summary
REST
POST /api/bridge/sync-sessions — bridge uploads session metadata
POST /api/bridge/sync-messages — startup/fallback/on-demand message history
POST /api/bridge/reconcile — recount DEV#/PROJ# from SESS# + prune orphan PROJ# (device row == list length)
POST /api/bridge/create-project — seed an empty project row
POST /api/bridge/delete — delete Session/Project metadata and reconcile
GET /api/bridge/devices — device list (projectCount/sessionCount from aggregates; running/needsInput live)
GET /api/bridge/projects?device=X — project list
GET /api/bridge/sessions?device=X&project=Y — session list
GET /api/bridge/active-sessions — homepage: active (running+needs_input) + 20 most-recent completed (recentSessions)
GET /api/bridge/messages?session=X&after=ts&device=D&project=P — messages + current Session status
POST /api/bridge/command-catalog — bridge stores the full project command catalog in S3
GET /api/bridge/command-catalog/{ref} — app reads the account-scoped command catalog
POST /api/bridge/video-prepare — video preview: HEAD dedup + presigned PUT URL (bridge streams to S3)
GET /api/bridge/video-url/{key} — video preview: presigned GET URL (no-store; browser streams from S3)
GET /api/install — bridge install script (sets up always-on service)
POST /api/auth/start-token — 10-minute token for Setup's Start URL / QR / install command
GET /auth/install?t=… — install script for a token (public; the token stands in for the key)
POST /api/bridge/delete-device — remove a device and make its Bridge uninstall itself
GET /api/version — app and Bridge release versionsWebSocket (real-time)
App → Server: { action: "subscribe", sessionId }
App → Server: { action: "unsubscribe", sessionId }
App → Server → Bridge: { action: "send_message", sessionId, text, device }
{ action: "send_message", projectHash, runtime, text, device } — new session
App → Server → Bridge: { action: "permission_reply", sessionId, requestId, decision, answerText?, device }
App → Server → Bridge: { action: "list_commands", projectHash, runtime, sessionId?, device, requestId }
Bridge → Server → App: { action: "send_message_result", ok, sessionId? }
Bridge → Server → App: { action: "command_catalog_ready", requestId, runtime, device, projectHash, revision, catalogRef? }
Server → App: { action: "messages", sessionId, messages }
Server → Bridge: { action: "sync_session", sessionId, runtime, nativeSessionId }
Bridge → Server → App: { action: "sync_complete", sessionId, status, count }Full protocol: docs/api.md
Send Messages Architecture
Approach: headless stream-json process pool (bridge/headless.mjs ClaudePool). One
persistent claude -p --input-format stream-json --output-format stream-json process per
session, fed over a kept-open stdin. Single-writer per session → no jsonl double-write.
Replaced the old tmux send-keys approach (deleted in Phase 2E). Full design: docs/headless-streaming.md.
Message Sending
- Viewer → WS → Server → Bridge →
handleHeadlessSend→_pool.send→ CC stdin - Streaming back:
stream_delta(typewriter preview) +stream_end; full assistant/user lines arrive as authoritativemessages(uuid-deduped against the jsonl copy) - Optimistic rendering + dedup + timestamp update
Reliable WS Delivery (app side, web/js/ws.js)
- Sends must survive a dead socket. User actions (
send_message/interrupt/create_project) usewsSendReliable, not barewsSend(which drops frames when not OPEN): queues to_wsSendQueue(array, ordered) + reconnects, flushed ononopenafter re-subscribe. iOS suspends the socket in background into a zombie (reads OPEN, frames vanish, noclose). On foreground (app.jsrefreshForegroundView→resumeSessionForeground) a non-OPEN socket reconnects; an OPEN one gets aheartbeatprobe (the server answers app heartbeats) and is rebuilt if no frame arrives within 5s. The foreground history refresh isfresh: it replaces a still-open/messagesbarrier instead of reusing it, carrying its captured WS events over, because a request started before suspension may never settle and an open barrier swallows live frames./messagesalso times out after 20s and takes the existing REST-failure path. - Bridge turn frames must survive reconnect too.
LiveTurnStreamsends throughwsSendWhenConnected, which queues frames while the Bridge socket is not OPEN and flushes them in order after reconnect. A frame may not consume a turnseqand then disappear. - Lost app frames are recovered, not waited on. API Gateway closes a WS after 10 minutes with
no client→server traffic, and the realtime data socket never sends; frames posted around such
closes, or via a gone Lambda target, vanish silently. While a Session is open and visible the app
pings both sockets every 25s and rebuilds one with no frame for 15s. The ping is
{action:"realtime_ping"}, answered{action:"realtime_pong"}by a MOCK route on both WebSocket APIs (no Lambda, no DDB);heartbeatstays Lambda-routed for the Bridge (TTL,bridgeVersion) andpingbelongs to the preview keepalive. Against a stack without the route, the control socket keeps probing withheartbeatand the data socket never times out, so an older stack is never mistaken for a dead socket. A turn seq gap triggers a ping on both sockets; once both pongs have arrived (each socket alive and drained over the client link) and ≥3s passed, the frame is treated as lost andrefreshSessionMessages()resumes the turn at the next checkpoint. A heldstream_endkeeps the gapped-end path. A running turn with no frame for 60s (no permission prompt) is checked against REST;completedsettles it, covering a lost tail orstream_end. - History rows rejoin their stream row by message order. REST/DDB rows carry no
turnId, so untagged assistant rows between a turn's prompt and the next prompt belong to that turn's stream row; recovered children are inserted by message order, and class-only matching may reuse only a stream block without identity (message-dom.js). - No duplicate/stuck bubbles. Each optimistic bubble carries a monotonic send
seq.reconcileEchoedPending()(end ofupdateLastTurn) retires a pending when (1) its echo is present (covers echoes that arrived viabufferAndFetch, whichtryDedupskips), or (2)seq < lastDeliveredSeq— a later send was already confirmed, so this earlier one was swallowed by a busy-CC send and never reached jsonl (echo never comes).lastDeliveredSeqis a persistent watermark bumped intryDedup/resolvePending(ok)/echo-match, so orphan detection survives the confirmed pending being removed; reset withpendingSentMessageson every session switch.isImagebubbles are never auto-orphaned (attachments, no matchable text). Without this an orphan has nodata-tsand sticks to the bottom forever. New-session banner:body.new-session #contentis flex-centered, so.ws-banneris pinnedposition:absolute; top:0instead of being pulled to the middle.
Scroll-to-bottom on session open (no flash / no "stopping short of the bottom")
- Order matters: clamp BEFORE scroll.
clampOverflowcollapses long messages (adds.clamped→ max-height 4.5em), shrinking total height. Initial render clamps before scrolling.state.stickBottomis follow intent, not a near-bottom measurement: a real drag/wheel sequence clears it when the sequence starts. After the bottom button has been visible, its first visible→hidden transition immediately restores follow and scrolls to the physical bottom; later movement in that same gesture keeps following unless it leaves the hidden-button range again. Detect the transition inside the shared button updater because touchpointermovemay observe the newscrollTopbeforescroll. AResizeObserveron the current.messagescontainer keeps real OUT/markdown/diff/image height changes pinned only while follow intent remains active, so deliberate upward scrolling is not overridden. Streaming never uses smooth scrolling because continuously arriving frames would compete with the animation. - diff2html is committed atomically.
tool.jsrenders and highlights each diff inside a detached staging element, then replaces the visible.diff-containerchildren in one synchronous commit. The loading placeholder remains stable while the viewer module loads; users never see the zero-height/partially drawn diff, and no estimated height or resize observer is needed. After the commit and clamp, the view scrolls once only whenstate.stickBottomstill records follow intent, so a user who scrolled upward during loading is not pulled back.
Permission Detection + User Interaction (headless, bridge-driven)
- Bridge
onControlRequest(CC'scontrol_request, precise — no client-side heuristic) → apppermission_request {kind, requestId, questions?/plan?/input}. App repliespermission_reply {requestId, decision:allow|deny|answer, answerText?}. - Ordinary tools (Bash/Edit/Write/MCP): allow →
control_response{allow, updatedInput}; deny →{deny, message}. (defaultMode:bypassPermissions→ CC never asks, no prompt.) - AskUserQuestion/ExitPlanMode (
requires_user_interaction): answer via{deny, message: answerText}— CC's only answer channel on--permission-prompt-tool stdio(a structuredcontrol_responseanswer is force-converted to deny, verified CC 2.1.211). Multi-question wizard sendsquestion → answerper line. Cancel ={deny, interrupt:true}→[Interrupted]. - Answer renders in the tool-card OUT (
toolStatetreats it as non-error → green; cancel → yellow), not a separate bubble. A still-pending prompt is re-shown on refresh/reconnect (reveal_permission→ bridge re-push). web/js/components/permission.jsfully rewritten; oldarrow:/type:/escapeprotocol +checkPendingPromptsclient detection deleted.
Image Sending
- S3 upload +
protocol - Bridge downloads → replaces with absolute path → CC Read tool reads it
- Multi-image staging + gallery + paste support
File / Video Preview (click a file link in a message)
- Click file link →
openFile()→ WSrequest_file→ bridgehandleRequestFile(ws.mjs) reads from disk. - Text/image: bridge base64s + POSTs to Lambda (
/upload-file→files/{key},/upload-image→images/{key}), repliesfile_ready {key}; frontend GETs/api/bridge/file|image/{key}(served base64-as-text from S3). Binary text files (NUL byte in first 8KB) →binary fileerror. - Video (
.mp4/.m4v/.mov/.webm/.mkv/.avi, ≤5GB): base64-through-Lambda is impossible (API GW 6MB limit), so the bridge streams the file straight to S3 via a presigned PUT.POST /video-prepare {key}→ server HEADsvideos/{key}: exists →{exists:true}(skip upload, dedup by content-hash key so it survives bridge restarts), else returns presigned PUT URL → bridgefs.createReadStreampiped tofetch(PUT, {duplex:'half'})(flat memory regardless of size). Bridge repliesfile_ready {video:true, key}; frontend callsGET /api/bridge/video-url/{key}for a short-lived presigned GET URL and plays it in a<video>element streaming directly from S3 (Range/seek supported). No CloudFront/IAM change — Lambda already has S3 Get/Put; presigning uses those creds. - Markdown documents render like GitHub (
web/js/components/markdown-document.js, lazy-loaded): raw HTML is kept and cleaned by bundled DOMPurify with GitHub's allowlist pluspicture/source;breaks:false;user-content-heading anchors;> [!NOTE]alerts;#gh-light-mode-onlyimages hidden andprefers-color-schemefixed to dark. Baton's own markup (code, Mermaid, KaTeX, image placeholders) bypasses the sanitizer as nonce slots. Relativeimg src/source srcset/ links resolve against the document directory;/xresolves like GitHub from the repository root: the nearest folder from the document upward (within the project) whose.gitBridge can read, probed only when the document uses/paths and cached per folder only on a definite answer; otherwise the project root (derived from the path + project hash). Real absolute paths (under the project/repository root, a common filesystem root such as/Users/or/home/, or any/xin a document outside the project) stay absolute, since agent-written documents use them. Links follow chat semantics:file.ext:12/#L12open at a line (DOMPurify's URI rule is extended to keep them), other schemes such astel:are left to the browser, and#user-content-xand#xboth reach the heading. SVGs whose own CSS usesprefers-color-schemeare fetched (cache: 'no-store', since the<img>preload's cached copy lacks CORS headers) and rewritten to dark, because WebKit evaluates it against the OS appearance. Image URLs are kept for the open file, so Code/Preview toggles send no requests; pending images draw nothing until loaded. Markdown/HTML files open in Preview unless a line or tool location is targeted.```mathfences render through the shared KaTeX loader; Mermaid uses the chat component (blocks outside#contentare observed against the viewport).:shortcode:emoji come fromemoji-shortcodes.js, generated from gemoji byscripts/generate-emoji-shortcodes.mjsand loaded only when a document contains one. Folder links (docs/, or a link Bridge reports as a directory) open the project file browser when the path is inside the current project. Chat messages still escape raw HTML. - HTML documents: relative CSS/JS/images are inlined, then rendered in a sandboxed opaque-origin iframe. In the iOS app they instead load into the native preview WKWebView through
navigate {url, html}→loadHTMLString(html, baseURL:)(like SwiftChat's generated apps): the base URL is a virtualhttps://<sha256(device, project, path)[:32]>.baton.local/<name>, never fetched, so each file gets its own origin whose site storage persists across reopening. Native failure falls back to the iframe. - Office (
.docx/.pptx/.xlsx, plus legacy.doc/.ppt/.xls): rendered in the browser by@silurus/ooxml0.89.0 (Rust/WASM, canvas), loaded on demand from jsDelivr like PDF.js/Mermaid (web/js/components/office-preview.js); no server conversion. The viewer module, thefile-urlrequest and the download start together. Word uses the progressive scroll viewer, decks the scroll viewer, both with the shared two-finger zoom (pdf-pinch.js); Excel keeps the library's tabs and zoom bar. Legacy.doc/.ppt/.xlsopen in the same viewers through the experimental@silurus/ooxml-legacy-officereaders (same version, loaded via jsDelivr+esmbecause its entry imports the viewer package by name; worker module + WASM URLs passed explicitly); unsupported content rejects and offers the download. Project files are uploaded through the existingdownloadoperation first, so Bridge is unchanged. The viewer is destroyed on close, including mid-load. Details:docs/api.md. - Attachment cache (
web/js/components/attachment-cache.js): Office files, images and PDFs fetched in one request (≤ 8 MB) are kept in IndexedDB by attachment key (account-scoped), so reopening one sends no request at all. Files uploaded from this device are stored at upload time. A key never changes content (see content IDs below), so entries never go stale. Images and other files have separate 500 MB budgets (kind by extension), so one large PDF cannot evict the images; oldest-opened evicted first within each. Every image shown throughgetImageUrl(chat, Markdown/file previews, the image viewer;images/<key>for message images, the attachment key otherwise) is read from here as a Blob URL and stored after its singlefetchdownload, so reopening or restarting sends neither theimage-urlrequest nor an S3 download; if fetching or IndexedDB fails it falls back to the presigned URL. Blob URLs are released when evicted from the 200-entry memory map unless still shown; HTML previews (opaque-origin iframe) getdata:URLs instead; text previews uploaded to S3 (over 300 KB; their key is derived from path + content) count toward the file budget, while inline text, files over 100 MB, larger range-loaded PDFs, videos and audio are not cached. Any cache failure is a plain miss. - Content IDs / upload dedup (
web/js/components/content-hash.js,bridge/content-hash.mjs): like Git LFS and Docker registries, an upload's ID is the SHA-256 of the whole file and the storage verifies it. Key = first 32 hex digits + extension.file-prepare {contentHash}(64 hex) HEADsattachments/<account>/<key>withChecksumMode=ENABLED: only an object whose S3-verifiedChecksumSHA256equals the hash (base64 vs hex) and whose size matches is reused →{key, exists:true}, nothing uploaded, the card simply reaches 100%. A missing object gets a presigned PUT signed withChecksumSHA256(both the accelerated URL andfallbackUrl; the client must send exactly the returned headers), so S3 answers400 BadDigestto any other bytes and a content key always holds its content. Any other object at that key (prefix collision, no checksum) keeps a random key and is never overwritten. Requests withoutcontentHash(older clients, hashing unavailable) keep random keys, so deploy order does not matter. The app hashes in 4 MB slices with hash-wasm, bundled as a 7 KB gzip SHA-256-only chunk (web/js/components/sha256.js) loaded on the first upload; WebCrypto has no streaming digest. Bridge streams the file and persists path + size + mtime + ctime + inode → hash in~/.baton-bridge/file-hashes.json(1000 entries; like Git's index, ctime catches copies that keep mtime, and files changed < 2 s ago are not remembered), so unchanged project files are neither re-read nor re-uploaded after a restart. OnBadDigest(file edited while preparing) Bridge forgets that hash, skips the fallback URL and reports the file as changed. Shared content keeps the first uploader's S3 name, sofile-url?name=passes the attachment link name (project files: the name from their path). Videos keep their ownvideos/keys.
Session Launch (headless)
- Existing session with no live CC process →
_pool.sendspawns a headlessclaude -p --resume <id>; the persistent process becomes the single writer. No tmux, no wait-for-ready, no trust-dialog handling (headless inherits the folder's trust state). - Idle reap (10min) + LRU cap (16) manage the pool; a reaped session re-spawns with
--resumeon the next message, context intact and configuration reloaded. A process with background tasks (background_tasks_changed, CC ≥ 2.1.203) is neither reaped nor evicted, and the task ending restarts its idle clock; in-pmode~/.claude/sessions/<pid>.jsonreadsidlewhile background work runs, and CC keeps running after EOF until that work ends. Once CC reportsuser_message_uuids, aresultwithout them (a turn CC started itself) consumes no input. (No morecleanStaleSessions/apeek_*tmux naming — all deleted in Phase 2E.) - New regular Session: Bridge mints a UUID, sends
send_message_resultfirst, then starts headless with--session-id <id>so the app subscribes before stream frames arrive. - New Codex Session: Bridge calls
thread/start, returns the storage Session ID, then starts the first turn on the same cwd-scoped app-server client. - New background agent: Bridge launches
claude --bg, resolves the full Session ID, and lets the agent poll/watcher publish metadata and messages.
Device Routing
- Bridge WS connection includes
deviceparameter - Server stores
deviceName, filters send_message/permission_reply forwarding by device - Viewer sends messages with
device: appState.device
Web Deployment
Web Pages (served from FastAPI Lambda)
web/landing.html— API key input, URL?key=auto-login, localStorage (_akbtoa obfuscated)web/index.html— Session viewer (auth guard redirects to landing if no key)web/setup.html— Bridge install command + QR code + connected devices list- Top bar: Baton logo + Setup gear icon
- Favicon: inline data:image/svg+xml (all pages unified)
Auth Flow
- Key stored in localStorage (
_ak= btoa,_as= server URL) - No cookies, no server middleware — static files publicly accessible
- API calls use
x-api-keyheader from localStorage - API Gateway
ApiKeyRequired: false— auth handled by FastAPI layer
Deployment
- Dockerfile:
COPY web/ web/→ FastAPIStaticFilesmount install.sh: copiesweb/to Docker build context, deploys via CodeBuild- Deploy output: single setup URL with embedded token (12h TTL, reusable until then)
Three-State Session Status
running→ Running (green): a turn is generating (jsonlstop_reason: tool_use/null, or pool turn in flight, or agentworking)needs_input→ Needs input (amber, reuses.badge.idle): the ball is in the user's court (poolcontrol_request, agentblocked, or terminalAskUserQuestion/ExitPlanMode).completed→ Done (grey, reuses.badge.stopped): turn finished / no process / stale. Also the fallback for legacyidle/stopped/unknown values.- Homepage: Active Sessions = running + needs_input (regular + agent); Completed Sessions =
20 most-recent completed of any type. Device/Project rows show
N running · N needs input(needsInputCount).completedis not shown on the device rows.
Light / Dark Theme
- Two palettes with identical token names:
web/css/themes/dark.css(:root, the default, values match the original dark UI) andlight.css(:root[data-theme="light"]). Components reference semantic tokens (--canvas,--surface,--surface-elevated,--text-secondary,--spinner, ...), never raw colors; a value that only one theme needs still gets a token whose dark value is the old literal, so Dark stays pixel-identical. - Light layering mirrors Dark: white page,
#f6f8fatop bar/cards/inputs,#eaeef2raised headers. Secondary text is lighter than a straight mapping (#6e7781) and bold tool names lighter still (--tool-label), because mid-grey on white reads close to black. - Settings → Appearance offers System / Light / Dark (default Dark).
web/public/theme-init.jsruns before first paint on every page: the preference islocalStorage['baton-theme'], else the native copy (window.__BATON_NATIVE_THEME__/BatonAndroid.getTheme()), else dark;systemresolves throughprefers-color-schemeand follows its changes.data-themeis the resolved palette,data-theme-preferencethe choice.theme.jsdispatchesthemechange; xterm, Mermaid, diff2html, Markdown theme images and file icons re-render on it. Switching never reloads the page. - Native sync (
theme-native.js): AndroidBatonAndroid.setTheme(system bar icons, app night mode, splash;uiModeis inconfigChanges, so no Activity restart), iOSbatonAppearancemessage (window style, status bar, preview webviews), desktopappearance_set(src-tauri/src/appearance.rs: Tauri theme, window/webview backgrounds, macOS tab strip, saved toappearance.jsonfor the next launch). - Cold-start launch screens follow the app's choice, not the system's: Android 12+ uses the app night mode;
iOS renders the LaunchScreen skeleton into light and dark snapshots per orientation
(
Library/SplashBoard/Snapshots/<bundle> - {DEFAULT GROUP}/*.ktx, Apple'sAAPLcontainer with ASTC, LZFSE-compressed on iOS 18).main.mmkeeps the system's originals inApplication Support/BatonLaunchSnapshots, classifies each by its first ASTC void-extent block, and on launch and every switch copies the chosen appearance's snapshot over the other one (System restores the originals). Unrecognised files leave the snapshots untouched; the first cold start after an app update still uses the freshly rendered system pair. - The image viewer keeps a backdrop of its own (
--media-backdrop); videos and QR codes stay black/white.
Native App (Tauri v2)
Tauri v2 wraps web/ static frontend as native app, zero web code changes.
Architecture
src-tauri/at project root (sibling to web/, bridge/, server/)frontendDist: "../web"— directly serves static HTML/CSS/JSwithGlobalTauri: true— JS accesses native API viawindow.__TAURI__- Bundle identifier:
com.batonai.app - Built-in dev server (no http-server needed), hot-reload
- Android system Back: each page registers Tauri's
onBackButtonPress(listeners survive page loads); at the rootMainActivity'sBatonAndroid.moveTaskToBack()backgrounds the app. - macOS tabs (
src-tauri/src/macos_tabs.rs, Tauriunstablemulti-webview, macOS target only): each Overlay-titlebar window has a 41pttabs.htmlstrip webview in the traffic-light row and one content webview per tab below it (own page, draft, WS), hidden when inactive. The frame view'ssetCustomTitlebarHeight:makes AppKit itself centre the traffic lights on the strip — never move the buttons afterwards; AppKit re-lays them out on every move/resize. A window's own webview needsset_auto_resize(false), or Tauri stretches it under the strip on resize. Commands must takeWebview, notWebviewWindow(that extractor fails once a window has children). Rust owns tab order/selection/titles and pushesmacos-tabsto the strip; pages report titles fromupdateBreadcrumb. Preview tunnels and native preview views are owned per webview label.
Targets
- Android: primary
- iOS: secondary (TestFlight)
- Desktop (macOS/Win/Linux): bonus, same config
Commands
# Dev
npm run dev:android / dev:ios / tauri:dev
# Release (all four platforms have ready-made scripts in scripts/)
npm run build:android — release APK (aarch64)
npm run release:ios — build + bump CFBundleVersion + upload TestFlight
npm run release:ios:cloud — trigger Xcode Cloud archive → TestFlight (any OS, e.g. Linux)
npm run build:mac — signed + notarized universal macOS DMG
npm run build:windows — cross-compiled Windows NSIS installer (.exe)
npm run package — Android/macOS/Windows into release/<version>/ (Linux uses GitHub Actions)The local macOS release script reads signing values from .env.local
(gitignored). See docs/package.md for GitHub Actions secrets, the
pushed-commit requirement, and platform-specific outputs.
Xcode Cloud (iOS from Linux): product "Baton" is connected to github.com/zhu-xiaowei/Baton;
workflow "Default" is manual-start only, pinned to Xcode 26.6 (Xcode 27 rejects the iOS 14.0
deployment target), and archives baton_iOS for TestFlight. src-tauri/gen/apple/ci_scripts/ci_post_clone.sh
installs Node + Rust, builds dist/, and patches the Rust build phase PATH in the CI checkout.
tauri-options.mjs supplies the tauri/custom-protocol feature and --lib
argument that tauri ios build adds on macOS; without the feature, the archived
app attempts to load the devUrl at localhost:5173.
Push the current commit to the connected GitHub repository before triggering.
The cloud release script increments CFBundleVersion in project.yml and Info.plist,
commits and pushes the new version, then starts the workflow. If a version was
prepared but no cloud run started, retrying reuses it. Xcode Cloud assigns its own
build number during export. Use node scripts/release-ios-cloud.mjs --dry-run
to check the expected next number and align Xcode Cloud's Next Build Number
in App Store Connect if necessary. The post-clone script rejects a mismatch
before installing toolchains or archiving.
Native Features (planned)
- QR scan login:
tauri-plugin-barcode-scanner - Biometric auth:
tauri-plugin-biometric
Live State (headless native — was "tmux capture-pane Live State")
CC has many intermediate states not written to jsonl (thinking animation/content, permission
waiting, tool progress). The old plan was to scrape them with tmux capture-pane. Headless
delivers them natively as stream events (content_block_delta text/thinking, control_request
for permissions, result for turn end) — no pane scraping needed. All wired: typewriter text +
thinking preview (stream_delta, per-tick thinking timer), permission control_request → app
prompt, turn-end (stream_end).
Stall Rescue — REMOVED in Phase 2E (headless makes it unnecessary)
The old problem: a multi-question AskUserQuestion (tab-bar wizard ☐ header1 ☐ header2 ✔ Submit)
held its entire tool_use in CC's memory and never wrote it to jsonl until Submit, so the bridge
saw nothing and the session looked permanently running. The tmux workaround (stall.mjs
checkStalledSessions + capture-pane wizard detection + Escape to force-flush + hiding the
synthetic rejection pair in watcher.mjs) is deleted.
Under headless this can't happen: CC pushes the full questions[] up front via a control_request
(requires_user_interaction), wired to the app prompt (permission bridge, DONE). stall.mjs and
watcher.mjs's synthetic-pair filter / stallRescued tagging are fully deleted.
Known Issues / TODO
- Real-time Edit diff hydration lifecycle: fixed the intermittent mobile state where an expanded
Editedcard showed only its border until session reload. Diff data now survives DOM replacement under a stable content key, initialization is tracked per element, visible tool nodes hydrate after every timeline mutation, and the registry is cleared at session boundaries. Keep regression coverage for replacement during lazy import, streaming adoption, fallback rendering, and session cleanup. - WS oversized messages: API Gateway WS single-frame cap is 32768B (exceeding it drops the connection with code 1009).
realtime-delivery.mjschecks the envelope size and sends a transport-truncated copy over WS (truncateToBytes()inextract.mjs, byte-aware, with message-leveltruncated: trueandnoCache: true). HTTP persists the prepared authoritative message with compact tool previews. The server skips DDB writes fornoCache, so the transport copy cannot overwrite the HTTP version. HTTP also caps each message toDDB_ITEM_LIMIT(360KB). These transport limits andstream_end.recoveryRequiredremain separate from intentional tool previews. - VS Code CC status precision: VS Code extension launches CC without
--resumeflag. CC ≥ 2.1.269 is matched exactly through its~/.claude/sessions/<pid>.jsonrecord; older versions (and Windows) fall back to the mtime heuristic (5 min timeout → completed). - Unstructured terminal questions: external terminal turns that end with plain assistant text do not expose a reliable waiting-for-input signal. Structured
AskUserQuestionandExitPlanModeare detected asneeds_input. - Concurrent regular-session control: Claude has no lock for a normal terminal or VS Code session. A send to a session another live CC process holds (its
~/.claude/sessions/<pid>.json) returnsclaude_active_writer; the App's takeover modal SIGTERMs that pid and then resumes. An idle pooled process that missed another client's turn is resumed again first. A terminal that opens the session while a Baton turn runs still forks it (undetected). Daemon agents are safe because Web takeover stops the roster worker first.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

