Skip to content

fix(agent,cli): rewrite future-cli --args to --stdin on Windows to avoid cmd.exe JSON corruption - #2

Merged
ace331 merged 1 commit into
mainfrom
worktree-fix-windows-tool-args
Jul 14, 2026
Merged

ace331 merged 1 commit into
mainfrom
worktree-fix-windows-tool-args

Conversation

@ace331

@ace331 ace331 commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Problem

On Windows, cmd /c strips double quotes from the command string. When the model calls future-cli tools call --args '{"prompt":"hello world"}', cmd.exe removes the " characters and the JSON is corrupted. Common manifestations:

  1. Values with spaces → arg splitting: --args '{prompt:a beautiful fox}' becomes argv fragments ['{prompt:a', 'beautiful', 'fox}'] — the CLI only sees the first fragment
  2. Values with commas → false field splits: {prompt:hello, world} is interpreted as two fields
  3. Nested structures → completely broken

Root Cause

The data flow has two layers of quote processing between the model and the CLI:

  • cmd.exe: strips " characters and splits on unprotected spaces
  • JSON parser: expects valid JSON with quoted keys and values

These are fundamentally incompatible — JSON requires " for structure, but cmd.exe treats " as a quoting character to strip.

Fix (Three Parts)

Part 1: CLI — Rejoin split argv elements

When --args value fragments across multiple argv elements (due to cmd.exe space splitting), join adjacent non-flag elements before parsing.

Part 2: CLI — Depth-aware comma splitting

Replace naive body.split(",") with splitTopLevel() that tracks brace/bracket depth. Add recursive parseCmdValue() for nested objects and arrays.

Part 3: Agent — Rewrite --args to --stdin on Windows

In sandbox/mod.rs, detect future-cli tools call --args commands and rewrite them to pipe JSON through a temp file:

(type "temp.json" | future-cli tools call ... --stdin ...) & del "temp.json"

This completely bypasses cmd.exe's quote processing — JSON never appears on the command line.

Testing

  • 20/20 CLI tests pass (parseToolArgs with all recovery paths)
  • 114/114 Rust tests pass (existing + sandbox tests)
  • TypeScript type check: clean
  • Rust format + clippy: clean (only pre-existing warning in llm/helpers.rs)

🤖 Generated with Claude Code

…oid cmd.exe JSON corruption

cmd.exe strips double quotes from command strings, which irreversibly
corrupts JSON passed via `future-cli tools call --args`. This causes
the common error: "--args must be a JSON object" on Windows when JSON
values contain spaces, commas, or nested structure.

Three-part fix:

1. CLI: Rejoin split argv elements after --args (cmd.exe turns spaces
   inside JSON values into argument boundaries).

2. CLI: Improve parseCmdObject with brace/bracket depth-aware comma
   splitting (splitTopLevel) and recursive value parsing (parseCmdValue)
   to recover nested JSON structures.

3. Agent (Windows): Detect `future-cli tools call --args` in bash
   commands, extract the JSON, write to temp file, and rewrite to
   `type <file> | ... --stdin` + cleanup. This bypasses cmd.exe quote
   processing entirely for all JSON complexity levels.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
huichen pushed a commit that referenced this pull request Jul 14, 2026
…handling, and more

Bug fixes:
- Navigation observer: poll 500ms instead of 15s for non-navigating actions.
  One fix resolves click file:// timeout, selector click timeout, and press
  15s delay (bugs #1, #2, #3).
- Snapshot: collect text content from h1-h6, p, li, td, th, dt, dd, label,
  span, div, pre, code, blockquote (bug #4).
- CdpError: changed from plain object to class extends Error so it serialises
  as a readable message instead of '[object Object]' (bug #8).

Improvements:
- Snapshot: textarea/input name priority aria-label > placeholder > associated
  label > name > value[:30] (bug #10).
- Tabs: all actions now return { tabs: [...], tabCount: N } for consistent
  output (bug #6).
- Start: when endpoint already reachable, returns already_running with note
  instead of silently switching (bug #7).
- Type: returns both ref (typed) and resolved selector (bug #9).
- Scroll: new scroll command with direction/amount/ref arguments (bug #11).

Defense in depth:
- tools.ts catch block: extract .message from non-Error objects as fallback.
@ace331
ace331 marked this pull request as ready for review July 14, 2026 08:11
@ace331
ace331 merged commit aa5d27b into main Jul 14, 2026
@ace331
ace331 deleted the worktree-fix-windows-tool-args branch July 14, 2026 08:11
tallcode added a commit that referenced this pull request Jul 15, 2026
Two Unix borrows from opencode and Claude Code's shell layers.

#1 login-shell env hydration (fixes "command not found"):
A GUI launched from the Finder/dock inherits a minimal PATH
(/usr/bin:/bin), so `bash -c` never sees tools the user installed via
their shell rc (nvm/pyenv/conda, Homebrew, npm-global) — which is why
`future ...` came back "command not found". At startup, before any
thread or the tokio runtime (set_var is only sound single-threaded), run
`$SHELL -l -i -c` once to dump `env` between markers, then take PATH from
it and additively merge any vars the launcher didn't already set. 5s
timeout + spawn-failure fallback keep a hanging rc from blocking startup.
No-op on Windows (GUI processes already get the full registry PATH).
Mirrors what VS Code / fix-path do. Verified: starting with PATH=
/usr/bin:/bin, the agent logs "hydrated PATH from login shell (/bin/zsh)".

#2 Unix shell resolution:
shell_invocation no longer hardcodes "bash". It honors $SHELL when it is
bash/zsh (both POSIX-compatible with the `( … ) 2>&1` wrapper), else
probes bash then zsh on PATH, else falls back to sh. Never fish/nu —
their syntax would break the wrapper. os_hint now names the actual
resolved shell (e.g. zsh on macOS) instead of always saying "bash";
bash and zsh share command-line syntax so no separate syntax rules are
needed — only an accurate name.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
huichen pushed a commit that referenced this pull request Jul 16, 2026
…handling, and more

Bug fixes:
- Navigation observer: poll 500ms instead of 15s for non-navigating actions.
  One fix resolves click file:// timeout, selector click timeout, and press
  15s delay (bugs #1, #2, #3).
- Snapshot: collect text content from h1-h6, p, li, td, th, dt, dd, label,
  span, div, pre, code, blockquote (bug #4).
- CdpError: changed from plain object to class extends Error so it serialises
  as a readable message instead of '[object Object]' (bug #8).

Improvements:
- Snapshot: textarea/input name priority aria-label > placeholder > associated
  label > name > value[:30] (bug #10).
- Tabs: all actions now return { tabs: [...], tabCount: N } for consistent
  output (bug #6).
- Start: when endpoint already reachable, returns already_running with note
  instead of silently switching (bug #7).
- Type: returns both ref (typed) and resolved selector (bug #9).
- Scroll: new scroll command with direction/amount/ref arguments (bug #11).

Defense in depth:
- tools.ts catch block: extract .message from non-Error objects as fallback.
huichen pushed a commit that referenced this pull request Jul 16, 2026
Two Unix borrows from opencode and Claude Code's shell layers.

#1 login-shell env hydration (fixes "command not found"):
A GUI launched from the Finder/dock inherits a minimal PATH
(/usr/bin:/bin), so `bash -c` never sees tools the user installed via
their shell rc (nvm/pyenv/conda, Homebrew, npm-global) — which is why
`future ...` came back "command not found". At startup, before any
thread or the tokio runtime (set_var is only sound single-threaded), run
`$SHELL -l -i -c` once to dump `env` between markers, then take PATH from
it and additively merge any vars the launcher didn't already set. 5s
timeout + spawn-failure fallback keep a hanging rc from blocking startup.
No-op on Windows (GUI processes already get the full registry PATH).
Mirrors what VS Code / fix-path do. Verified: starting with PATH=
/usr/bin:/bin, the agent logs "hydrated PATH from login shell (/bin/zsh)".

#2 Unix shell resolution:
shell_invocation no longer hardcodes "bash". It honors $SHELL when it is
bash/zsh (both POSIX-compatible with the `( … ) 2>&1` wrapper), else
probes bash then zsh on PATH, else falls back to sh. Never fish/nu —
their syntax would break the wrapper. os_hint now names the actual
resolved shell (e.g. zsh on macOS) instead of always saying "bash";
bash and zsh share command-line syntax so no separate syntax rules are
needed — only an accurate name.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
huichen pushed a commit that referenced this pull request Jul 16, 2026
…handling, and more

Bug fixes:
- Navigation observer: poll 500ms instead of 15s for non-navigating actions.
  One fix resolves click file:// timeout, selector click timeout, and press
  15s delay (bugs #1, #2, #3).
- Snapshot: collect text content from h1-h6, p, li, td, th, dt, dd, label,
  span, div, pre, code, blockquote (bug #4).
- CdpError: changed from plain object to class extends Error so it serialises
  as a readable message instead of '[object Object]' (bug #8).

Improvements:
- Snapshot: textarea/input name priority aria-label > placeholder > associated
  label > name > value[:30] (bug #10).
- Tabs: all actions now return { tabs: [...], tabCount: N } for consistent
  output (bug #6).
- Start: when endpoint already reachable, returns already_running with note
  instead of silently switching (bug #7).
- Type: returns both ref (typed) and resolved selector (bug #9).
- Scroll: new scroll command with direction/amount/ref arguments (bug #11).

Defense in depth:
- tools.ts catch block: extract .message from non-Error objects as fallback.
huichen pushed a commit that referenced this pull request Jul 16, 2026
Two Unix borrows from opencode and Claude Code's shell layers.

#1 login-shell env hydration (fixes "command not found"):
A GUI launched from the Finder/dock inherits a minimal PATH
(/usr/bin:/bin), so `bash -c` never sees tools the user installed via
their shell rc (nvm/pyenv/conda, Homebrew, npm-global) — which is why
`future ...` came back "command not found". At startup, before any
thread or the tokio runtime (set_var is only sound single-threaded), run
`$SHELL -l -i -c` once to dump `env` between markers, then take PATH from
it and additively merge any vars the launcher didn't already set. 5s
timeout + spawn-failure fallback keep a hanging rc from blocking startup.
No-op on Windows (GUI processes already get the full registry PATH).
Mirrors what VS Code / fix-path do. Verified: starting with PATH=
/usr/bin:/bin, the agent logs "hydrated PATH from login shell (/bin/zsh)".

#2 Unix shell resolution:
shell_invocation no longer hardcodes "bash". It honors $SHELL when it is
bash/zsh (both POSIX-compatible with the `( … ) 2>&1` wrapper), else
probes bash then zsh on PATH, else falls back to sh. Never fish/nu —
their syntax would break the wrapper. os_hint now names the actual
resolved shell (e.g. zsh on macOS) instead of always saying "bash";
bash and zsh share command-line syntax so no separate syntax rules are
needed — only an accurate name.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
huichen pushed a commit that referenced this pull request Jul 16, 2026
…handling, and more

Bug fixes:
- Navigation observer: poll 500ms instead of 15s for non-navigating actions.
  One fix resolves click file:// timeout, selector click timeout, and press
  15s delay (bugs #1, #2, #3).
- Snapshot: collect text content from h1-h6, p, li, td, th, dt, dd, label,
  span, div, pre, code, blockquote (bug #4).
- CdpError: changed from plain object to class extends Error so it serialises
  as a readable message instead of '[object Object]' (bug #8).

Improvements:
- Snapshot: textarea/input name priority aria-label > placeholder > associated
  label > name > value[:30] (bug #10).
- Tabs: all actions now return { tabs: [...], tabCount: N } for consistent
  output (bug #6).
- Start: when endpoint already reachable, returns already_running with note
  instead of silently switching (bug #7).
- Type: returns both ref (typed) and resolved selector (bug #9).
- Scroll: new scroll command with direction/amount/ref arguments (bug #11).

Defense in depth:
- tools.ts catch block: extract .message from non-Error objects as fallback.
huichen pushed a commit that referenced this pull request Jul 16, 2026
Two Unix borrows from opencode and Claude Code's shell layers.

#1 login-shell env hydration (fixes "command not found"):
A GUI launched from the Finder/dock inherits a minimal PATH
(/usr/bin:/bin), so `bash -c` never sees tools the user installed via
their shell rc (nvm/pyenv/conda, Homebrew, npm-global) — which is why
`future ...` came back "command not found". At startup, before any
thread or the tokio runtime (set_var is only sound single-threaded), run
`$SHELL -l -i -c` once to dump `env` between markers, then take PATH from
it and additively merge any vars the launcher didn't already set. 5s
timeout + spawn-failure fallback keep a hanging rc from blocking startup.
No-op on Windows (GUI processes already get the full registry PATH).
Mirrors what VS Code / fix-path do. Verified: starting with PATH=
/usr/bin:/bin, the agent logs "hydrated PATH from login shell (/bin/zsh)".

#2 Unix shell resolution:
shell_invocation no longer hardcodes "bash". It honors $SHELL when it is
bash/zsh (both POSIX-compatible with the `( … ) 2>&1` wrapper), else
probes bash then zsh on PATH, else falls back to sh. Never fish/nu —
their syntax would break the wrapper. os_hint now names the actual
resolved shell (e.g. zsh on macOS) instead of always saying "bash";
bash and zsh share command-line syntax so no separate syntax rules are
needed — only an accurate name.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
huichen pushed a commit that referenced this pull request Jul 16, 2026
…handling, and more

Bug fixes:
- Navigation observer: poll 500ms instead of 15s for non-navigating actions.
  One fix resolves click file:// timeout, selector click timeout, and press
  15s delay (bugs #1, #2, #3).
- Snapshot: collect text content from h1-h6, p, li, td, th, dt, dd, label,
  span, div, pre, code, blockquote (bug #4).
- CdpError: changed from plain object to class extends Error so it serialises
  as a readable message instead of '[object Object]' (bug #8).

Improvements:
- Snapshot: textarea/input name priority aria-label > placeholder > associated
  label > name > value[:30] (bug #10).
- Tabs: all actions now return { tabs: [...], tabCount: N } for consistent
  output (bug #6).
- Start: when endpoint already reachable, returns already_running with note
  instead of silently switching (bug #7).
- Type: returns both ref (typed) and resolved selector (bug #9).
- Scroll: new scroll command with direction/amount/ref arguments (bug #11).

Defense in depth:
- tools.ts catch block: extract .message from non-Error objects as fallback.
huichen pushed a commit that referenced this pull request Jul 16, 2026
Two Unix borrows from opencode and Claude Code's shell layers.

#1 login-shell env hydration (fixes "command not found"):
A GUI launched from the Finder/dock inherits a minimal PATH
(/usr/bin:/bin), so `bash -c` never sees tools the user installed via
their shell rc (nvm/pyenv/conda, Homebrew, npm-global) — which is why
`future ...` came back "command not found". At startup, before any
thread or the tokio runtime (set_var is only sound single-threaded), run
`$SHELL -l -i -c` once to dump `env` between markers, then take PATH from
it and additively merge any vars the launcher didn't already set. 5s
timeout + spawn-failure fallback keep a hanging rc from blocking startup.
No-op on Windows (GUI processes already get the full registry PATH).
Mirrors what VS Code / fix-path do. Verified: starting with PATH=
/usr/bin:/bin, the agent logs "hydrated PATH from login shell (/bin/zsh)".

#2 Unix shell resolution:
shell_invocation no longer hardcodes "bash". It honors $SHELL when it is
bash/zsh (both POSIX-compatible with the `( … ) 2>&1` wrapper), else
probes bash then zsh on PATH, else falls back to sh. Never fish/nu —
their syntax would break the wrapper. os_hint now names the actual
resolved shell (e.g. zsh on macOS) instead of always saying "bash";
bash and zsh share command-line syntax so no separate syntax rules are
needed — only an accurate name.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
huichen pushed a commit that referenced this pull request Jul 16, 2026
…handling, and more

Bug fixes:
- Navigation observer: poll 500ms instead of 15s for non-navigating actions.
  One fix resolves click file:// timeout, selector click timeout, and press
  15s delay (bugs #1, #2, #3).
- Snapshot: collect text content from h1-h6, p, li, td, th, dt, dd, label,
  span, div, pre, code, blockquote (bug #4).
- CdpError: changed from plain object to class extends Error so it serialises
  as a readable message instead of '[object Object]' (bug #8).

Improvements:
- Snapshot: textarea/input name priority aria-label > placeholder > associated
  label > name > value[:30] (bug #10).
- Tabs: all actions now return { tabs: [...], tabCount: N } for consistent
  output (bug #6).
- Start: when endpoint already reachable, returns already_running with note
  instead of silently switching (bug #7).
- Type: returns both ref (typed) and resolved selector (bug #9).
- Scroll: new scroll command with direction/amount/ref arguments (bug #11).

Defense in depth:
- tools.ts catch block: extract .message from non-Error objects as fallback.
huichen pushed a commit that referenced this pull request Jul 16, 2026
Two Unix borrows from opencode and Claude Code's shell layers.

#1 login-shell env hydration (fixes "command not found"):
A GUI launched from the Finder/dock inherits a minimal PATH
(/usr/bin:/bin), so `bash -c` never sees tools the user installed via
their shell rc (nvm/pyenv/conda, Homebrew, npm-global) — which is why
`future ...` came back "command not found". At startup, before any
thread or the tokio runtime (set_var is only sound single-threaded), run
`$SHELL -l -i -c` once to dump `env` between markers, then take PATH from
it and additively merge any vars the launcher didn't already set. 5s
timeout + spawn-failure fallback keep a hanging rc from blocking startup.
No-op on Windows (GUI processes already get the full registry PATH).
Mirrors what VS Code / fix-path do. Verified: starting with PATH=
/usr/bin:/bin, the agent logs "hydrated PATH from login shell (/bin/zsh)".

#2 Unix shell resolution:
shell_invocation no longer hardcodes "bash". It honors $SHELL when it is
bash/zsh (both POSIX-compatible with the `( … ) 2>&1` wrapper), else
probes bash then zsh on PATH, else falls back to sh. Never fish/nu —
their syntax would break the wrapper. os_hint now names the actual
resolved shell (e.g. zsh on macOS) instead of always saying "bash";
bash and zsh share command-line syntax so no separate syntax rules are
needed — only an accurate name.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
tallcode added a commit that referenced this pull request Aug 7, 2026
…typed payloads, adopt @future-os/rpc (#112)

* feat(rpc): scaffold future-rpc crate as single proto codegen owner

First batch of the typed-RPC milestone (audit rec #1 / P1 #2): create the
future-rpc workspace crate that owns the generated proto code for
proto/future.proto, emitting both tonic server and client modules. The
per-crate checked-in copies in agent/, channels/ and gui/src-tauri/ stay
untouched this batch — consumers migrate in later batches.

- build.rs regenerates under REGENERATE_PROTO=1 (same opt-in pattern as the
  existing crates); output checked into src/generated/proto.rs so normal
  builds never need protoc
- smoke tests cover RpcResponse/StreamEvent wire round-trip
- README records the contract rules (field-number stability, payload field
  20, one-way dependency direction, gui version alignment)

Zero behavior change: the crate has no consumers yet.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(rpc): move payload carriers into future-rpc with Deserialize

Batch 2 of the typed-RPC milestone: pure move of the big-read-command
payload structs from agent/src/rpc/payloads.rs into the future-rpc crate,
preparing the shared decode layer.

- All structs gain Deserialize alongside Serialize plus serde aliases for
  the legacy snake_case spellings, so both the agent's encode path and the
  clients' JSON fallback land in the same types (parity by construction)
- New strip_legacy_aliases helper: the migration window dual-writes
  canonical + legacy keys and serde rejects duplicate field names, so
  decoders strip duplicates before deserializing (aliases still accept
  legacy-only JSON from pre-migration agents)
- replay_event_payload splits: the crate keeps the wire struct, the agent
  keeps the SseEvent→payload adapter (SseEvent is agent-internal)
- agent re-exports future_rpc::payloads; all 14 call sites compile
  unchanged

Tests: the file's existing unit tests move with it; added dual-casing
round-trip (inject → strip → deserialize → re-serialize equals canonical)
and legacy-only decode coverage. Zero behavior change: the agent emits
identical JSON.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(proto): add typed ResponsePayload/EventPayload oneofs at field 20

Batch 3 of the typed-RPC milestone: the wire schema for the migration.
Purely additive — all existing field numbers untouched, no consumer breaks.

- RpcResponse.payload (ResponsePayload) with 16 typed response members:
  the four big reads (get_state/list_sessions/get_session_entries/
  get_events_since, reusing the former doc-only messages) plus prompt ack,
  list_models, get_agent_info, get_commands, compact, shell, cycle_model,
  sync_future_models, refresh_skills, get_session_events_since,
  get_session_stats, get_runtime_metrics
- EventPayload shared by StreamEvent/ProjectedRunEvent/ReplayEvent (all at
  field 20) with 14 typed event kinds — one member list decoded identically
  on live, replay and projection-snapshot paths
- ApprovalRequestInfo extended with the full approval card (risk_level,
  summary, requested_action, sandbox_boundary, save_suggestion, reviewer,
  extras catch-all) so the event and get_state pendingApprovals share one
  message
- null-semantics fields promoted to proto3 optional (wire-compatible):
  RunStateSnapshot.epoch/run_sequence/last_event_idx, RunTerminalInfo.error,
  SessionSummary.session_name/first_message, SessionEntry.thinking/meta/
  tool_calls/output_tokens/duration_ms; SessionEntry gains content_is_object
  so decoders can re-inflate content into the exact original JSON value
- Only future-rpc's generated code is regenerated this batch; agent/
  channels/GUI keep their checked-in copies until their adoption batches

Tests: typed oneof round-trip (RpcResponse with SessionState payload,
StreamEvent with ToolEnd payload). Full workspace gate green; no behavior
change (no consumer reads the new fields yet).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(rpc,agent): dual-write typed payloads for the four big read commands

Batch 4 of the typed-RPC milestone: the codec goes live and the agent
becomes the first consumer of future-rpc.

future-rpc:
- encode.rs: JSON payload Value -> typed ResponsePayload for get_state /
  list_sessions / get_session_entries / get_events_since. Defensive by
  contract: unknown commands or shape mismatches return None so clients
  fall back to the JSON `data` string; nothing panics. Value-typed
  fields travel as serialized-JSON strings (source_meta, entry content/
  meta/tool_calls, approval action/requested_action/sandbox_boundary/
  save_suggestion + an extras catch-all) and are re-inflated on decode;
  SessionEntry.content_is_object discriminates display text from the
  session_info object.
- decode.rs: response_data (typed-first, JSON fallback, canonical
  dual-casing Value with the migration aliases re-injected so downstream
  consumers see exactly what `data` carries) + typed getters
  (decode_get_state / decode_list_sessions / decode_session_entries /
  decode_events_since).
- parity.rs: wire-parity round-trips for all four commands (encode ->
  typed -> decode == original fixture) across the full fallback matrix:
  dual-write, data-only (old agent), typed-only (future). Fixtures pin
  null-vs-absent semantics (interrupted run's runSequence null, epoch
  omitted), object source_meta, a full approval card, session_info
  object content and projection snapshots.

agent:
- grpc/mod.rs now re-exports future_rpc::proto (single codegen owner);
  the checked-in generated copy and the build.rs codegen block are gone.
- execute_command dual-writes: RpcResponse.payload populated via
  future_rpc::encode alongside the unchanged JSON `data`.
- StreamEvent / ProjectedRunEvent construction sites gain payload: None
  (event typing lands in a later batch).
- New test proves the agent's real read-command envelopes always encode.

proto: SessionState.session_file/session_id/session_name/
parent_session_id promoted to optional (wire-compatible) to preserve
their null-vs-absent JSON semantics.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(rpc,agent): typed payloads for all remaining Tier-1 responses

Batches 5+6 of the typed-RPC milestone (merged — same mechanical codec
work): prompt ack, list_models, get_agent_info, get_commands, compact,
shell, cycle_model, sync_future_models, refresh_skills,
get_session_stats, get_runtime_metrics, get_session_events_since. All 16
ResponsePayload members now dual-write.

- payloads_ext.rs: serde carriers for the ad-hoc json! shapes, lifted so
  encode and decode share one definition. Wire casing preserved per
  command (camelCase; prompt ack and refresh_skills stay snake_case).
  null-vs-absent pinned exactly: runtime-metrics activeRunId/
  eventJournalError serialize as JSON null (the agent emits null, not
  omission, for Option fields built with json!), cycle_model isScoped is
  omitted on the empty-catalog edge, session-stats cost rides as a raw
  JSON number so the int-vs-float representation survives the JSON path.
- RunAck/RunAcceptedState move from agent runtime into the crate (agent
  re-exports; BusyPolicy stays agent-side as command input).
- encode.rs/decode.rs gain the 12 new command arms; decode exposes typed
  getters (decode_prompt_ack / decode_list_models) with JSON fallback.
- proto: ModelEntry.description/description_en and Command.name_zh/
  description_zh promoted to optional (the catalog/skill fields are
  Option on the agent side and emit JSON null — parity pins it), fixtures
  cover the null cases.
- Agent test now proves every real sessionless + session-scoped read
  envelope encodes (get_agent_info, list_models, get_commands,
  refresh_skills added alongside the batch-4 set).

Untyped commands (trivial acks, get_messages/get_fork_messages) stay on
the JSON `data` string by design; clients fall back automatically.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(rpc,agent): typed payloads for the 14 stream event kinds

Batch 7 of the typed-RPC milestone: the streaming half of the wire
contract. The agent now dual-writes StreamEvent.payload /
ProjectedRunEvent.payload / ReplayEvent.payload alongside the unchanged
JSON `data` string, on the live stream, the atomic-attach replay tail,
and projection snapshots.

- event_payloads.rs: serde carriers for the event vocabulary (text_chunk,
  user_message, thinking_start/delta/end, agent_start/end, tool_start/
  delta/end, usage, error, approval_decision). skip_serializing_if mirrors
  the broadcast serializer exactly — it omits empty strings and absent
  optionals, and injects a redundant `type` key that the typed form drops
  (every consumer keys off the envelope type).
- encode.rs: event_payload() parses the event `data` JSON into the typed
  oneof; pass-through events (settings, ping, tool_sandboxed, ...) return
  None and stay JSON-only. Replay events are typed too via the same path,
  so reconnect/replay decode matches live.
- decode.rs: event_data / event_data_json (+ projected/replay variants).
  Byte-stability first: during the migration window the original `data`
  string wins verbatim (GUI journal + NATS republish must not change);
  the typed reconstruction takes over only when `data` is absent.
- agent grpc/mod.rs: map_broadcast_event, the attach-replay tail, and the
  projection-snapshot builder all populate the typed payload.
- Parity fixtures cover all 14 kinds incl. agent_end sparse/full/incomplete
  shapes, tool_end exit-code/soft-fail/target-path semantics, usage with
  optional provider fields, both error variants, and the tool_args
  object-vs-JSON-string forms; a budget test pins text_chunk encode under
  5µs/event (measured well below 1µs).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(channels): adopt future-rpc for proto, decode and event parsing

Batch 8 of the typed-RPC milestone: the channel bridge becomes the first
client on the shared wire contract.

- grpc_client.rs consumes future_rpc::proto (re-exported under the
  historical module name); the checked-in channels/src/generated/proto.rs
  copy is deleted and build.rs no longer codegens future.proto (feishu_ws
  stays, so tonic-build drops out of the build-deps).
- call() decodes through future_rpc::decode::response_data — typed payload
  first, JSON `data` fallback — so every command reads identically against
  old and new agents.
- AgentClient::parse_event now delegates to future_rpc::events::
  parse_agent_event; the AgentEvent enum and its parser moved into the
  crate so every future client decodes events the same way. The parser is
  typed-first with the JSON fallback; tool_args keeps its wire semantics
  (string-form only) on both paths.
- expand_projection_snapshot carries the typed payload through, so
  reconnected/replayed events decode through the same path as live ones.
- Parse tests moved to the crate, where each case now runs as twins: the
  JSON-data event (old agent) and the typed-payload event (new agent).
  Channels keeps projection-expansion, SessionState and ImageInput tests,
  plus a delegation smoke test on both wire states.
- The (ignored, live-agent) integration test switches to future_rpc proto
  + decode instead of its private generated copy.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(gui): adopt future-rpc for agent wire decode

Batch 9 of the typed-RPC milestone: the GUI Tauri backend joins the
shared wire contract (largest consumer — boundary bridge strategy, not
per-site typed migration, so every deep read keeps its exact shape).

- agent_proto.rs re-exports future_rpc::proto under the historical paths;
  the checked-in src/generated/proto.rs and the build.rs codegen block are
  deleted (future-rpc is the single codegen owner; path dependency with
  aligned tonic/prost versions).
- All unary response parses (remote-bridge pass-throughs, get_state deep
  reads for crash reconcile/watchdog, prompt ack, sync_future_models,
  models/skills typed structs, session ensure/entries, import, approval
  reconcile, run control, observer probes) now go through
  future_rpc::decode::response_data — typed payload first, JSON `data`
  fallback — returning the same canonical dual-casing Value the deep reads
  already expect.
- Event pipeline (stream.rs persistence + fold, observer.rs forward/
  persist/NATS mirror, remote snapshot republish) routes through
  event_data_json / projected_event_data_json: byte-stable while the agent
  dual-writes `data` (the original string wins verbatim), typed
  reconstruction takes over automatically once `data` is retired.
- The observer's get_session_events_since reconstruction populates the
  typed payload so replayed session events decode like live ones.
- New wire_decode_tests pin the GUI-facing guarantees: typed/data parity,
  old-agent fallback, dual-write byte stability, and typed reconstruction
  without `data`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* build(proto): converge codegen on future-rpc in Makefile and CI

Batch 10 of the typed-RPC milestone: the codegen entry points match the
new single-owner layout.

- `make generate-proto` now regenerates future-rpc (future.proto — server
  + all clients) and channels (feishu_ws only) plus the TUI embedded proto;
  the retired agent / gui/src-tauri regeneration lines are gone.
- CI rust-quality gains a "proto codegen is fresh" gate: regenerate under
  REGENERATE_PROTO and `git diff --exit-code` the checked-in generated
  files, catching proto edits that skipped `make generate-proto`
  (deterministic for the pinned prost/tonic-build).

Verified: a clean-room regenerate of future-rpc + channels is byte-identical
(no diff). The TUI/CLI embedded proto syncs when the TS clients adopt the
shared package (next batches).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(rpc): scaffold @future-os/rpc shared TS wire-contract package

Batch 11 of the typed-RPC milestone: the TypeScript half of the shared
contract, mirroring the Rust future-rpc crate. Standalone and additive —
no client consumes it yet (adoption is the next batches).

- shared/future-rpc: proto.ts (EMBEDDED_PROTO + a loader configured
  exactly as the TUI/CLI have always loaded it: camelCase, int64→String,
  enums→String, defaults, oneofs), decode.ts (responseData /
  streamEventData — JSON `data` first for migration-window shape parity,
  typed `payload` oneof as the post-`data` fallback), types.ts (merged
  superset of the duplicated tui/cli payload types), index.ts.
- scripts/generate-proto.ts embeds proto/future.proto into EMBEDDED_PROTO;
  `make generate-proto` now refreshes it alongside the Rust codegen.
- decode unit tests cover data-parse, type-key stripping, and the typed
  oneof fallback. .gitignore covers shared dist/node_modules.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(rpc): harden shared-package proto embedding + add grpc loader helper

Follow-up to the @future-os/rpc scaffold:
- generate-proto.ts now anchors on an explicit __EMBEDDED_PROTO_END__
  marker instead of a bare backtick-semicolon; future.proto comments
  legitimately contain backticks and a "`;" sequence, which truncated the
  EMBEDDED_PROTO template literal on regeneration.
- proto.ts: marker-anchored EMBEDDED_PROTO plus loadGrpcAgentProto(), the
  drop-in grpc.loadPackageDefinition(...).proto replacement the TUI/CLI
  will adopt.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* build(npm): make shared/future-rpc, tui, cli an npm workspace

Prepares TUI/CLI to consume the @future-os/rpc wire-contract package.
A single root package-lock.json replaces the per-package lockfiles (gui and
mobile keep their own installs — separate toolchains). Node modules hoist to
the repo root; @future-os/rpc resolves via workspace symlink.

Baseline verified: tui and cli typecheck clean under the new install model.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* build(npm): workspace-aware Makefile + CI for shared package

Makefile: a node-workspace target installs the root npm workspace and builds
shared/future-rpc; build/test/lint for tui+cli depend on it (gui/mobile keep
their per-directory installs).

CI: tui/cli jobs run a single root `npm ci`, build shared/future-rpc before
typecheck, and cache the root package-lock.json. The changes filter now also
triggers tui/cli on shared/future-rpc/** and root manifest edits.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(tui): adopt @future-os/rpc for proto loading and wire decode

Batch 12 of the typed-RPC milestone. The TUI's grpc-client drops its
~770-line EMBEDDED_PROTO copy and the local proto-loader/resolveProtoPath
plumbing in favour of the shared wire-contract package:

- proto comes from loadGrpcAgentProto() (@future-os/rpc), the single source
  of truth for the schema and its loader options.
- unary responses decode through responseData(); stream events through
  streamEventData() — both read the typed payload oneof when present and
  fall back to the JSON `data` string during the migration window.
- tui/scripts/generate-proto.ts now only refreshes the CLI's embedded proto
  (deleted once the CLI adopts the package in batch 13). The TUI's embedded
  proto is regenerated via shared/future-rpc/scripts/generate-proto.ts.

Verified: tui tsc clean, 162 bun tests pass, `bun build --compile` bundles
the workspace package (148 modules), and the standalone binary loads the
proto and reaches the gRPC connect step at runtime. Also re-syncs the CLI's
embedded proto with the payload-extended schema.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(cli): adopt @future-os/rpc; drop embedded proto from both TS clients

Batch 13 of the typed-RPC milestone. The CLI's grpc-client drops its
~770-line EMBEDDED_PROTO copy and local proto-loader/resolveProtoPath
plumbing in favour of the shared wire-contract package, completing the TS
consolidation:

- proto comes from loadGrpcAgentProto() (@future-os/rpc); unary responses
  decode through responseData(), streamed events through streamEventData()
  (typed oneof first, JSON `data` fallback during the migration window).
- tui/scripts/generate-proto.ts is deleted — no TS client embeds the proto
  anymore; the single EMBEDDED_PROTO lives in shared/future-rpc/src/proto.ts
  and is refreshed via its own generate-proto (wired into `make
  generate-proto`). tui's build no longer runs a proto-embed step.

Verified: tui+cli tsc clean, 162+108 bun tests pass, both standalone
binaries \`bun build --compile\` (bundle the workspace package) and load the
proto at runtime; \`make generate-proto\` regenerates Rust + TS code
idempotently.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(rpc): document the typed-RPC wire contract and dual-write policy

Batch 14 (final) of the typed-RPC milestone:

- future-rpc/README.md: full contract reference — single codegen ownership,
  the typed payload oneofs at field 20, the dual-write migration policy,
  encode/decode module map, and the field-number/optional/null-semantics
  rules.
- CLAUDE.md: corrects the stale per-crate codegen note and adds the
  wire-contract conventions (future-rpc ownership, dual-write, decode
  fallback, field-number stability) for future contributors.

Full gate green: root cargo fmt/clippy/test, GUI backend fmt/clippy/test,
tui (162) + cli (108) + shared (10) bun tests, and both standalone binaries
compile and load the shared proto at runtime.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(rpc): complete TS type adoption; end duplicated rpc types

Review fix for the "shared types.ts is dead code" finding: the TUI and CLI
local rpc/types.ts are now thin re-exports of @future-os/rpc, making the
shared package the single source of truth for TS RPC payload types and
removing ~425 lines of duplicated definitions.

- shared types.ts gains PermissionLevel (CLI needs it) and legacy
  snake_case aliases on SessionSummary / RecentTerminalAck. The agent
  emits both canonical camelCase and legacy snake_case during the migration
  window, and client code reads a mix, so the shared types model both.
  Fields read as required (updated_at, run_id) are typed required to match
  existing call sites.
- tui/src/rpc/types.ts and cli/src/rpc/types.ts become
  `export type * from "@future-os/rpc"`; all existing `from "./types.js"`
  imports keep working. The unused promptCmd helper is dropped.

Verified: tui+cli tsc clean, 162+108 bun tests pass, both standalone
binaries build.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(rpc): address third-party review of the typed-RPC wire contract

Fixes from the external review of the typed-RPC milestone:

P1 — TS typed fallback never fired: proto-loader with defaults:true
materializes an absent `data` as "" (not undefined), and decode only
checked `!= null`, so the typed `payload` fallback could never fire once
the agent stops dual-writing. responseData/streamEventData now treat an
empty string as absent. Adds real-loader-behavior tests (typed fallback
fires on "" for both unary and stream). The shape-normalization layer
(camelCase/int64/inflate parity with the legacy JSON) is deferred to a
follow-up.

P1 — CI path filters missed future-rpc: rust_workspace and gui_tauri now
include future-rpc/** (and proto/** for the GUI path-dep), so edits to the
shared crate revalidate the Rust workspace and GUI backend.

P2 — build.rs rerun-if-changed: future-rpc and channels build.rs now declare
rerun-if-changed on the proto source, so `make generate-proto` after a proto
edit is not skipped by Cargo's build-script cache.

P2 — stale standalone proto temp file: resolveProtoPath now derives the temp
filename from a content hash, so a binary whose embedded proto changed never
reads a stale temp file left by an older build.

Deferred (flagged, separate work): release pipelines must build
shared/future-rpc before the CLI/TUI; Makefile node-workspace staleness.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* build: build shared @future-os/rpc before CLI/TUI in release pipelines

Remaining build-chain fixes from the third-party review:

P1 — release pipelines did not build shared/future-rpc/dist: package.json
exports point at dist/, which is gitignored, so a fresh runner's `npm ci`
left the CLI's `@future-os/rpc` import unresolvable. build.yml,
build-macos-signed.yml, build-windows-signed.yml and the local
macOS/Windows packaging scripts now install the npm workspace at the root
(shared/future-rpc + tui + cli) and run `npm run build` in
shared/future-rpc before compiling the CLI.

P2 — Makefile node-workspace staleness: the rebuild condition only compared
proto.ts, so edits to decode.ts/types.ts/index.ts reused a stale dist. It now
rebuilds when any shared/future-rpc/src/**/*.ts is newer than dist. `make
clean` also removes the root node_modules and shared/future-rpc/dist.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(rpc): consolidate proto + rust crate + ts package under future-rpc/

Merge the three wire-contract homes into one directory: proto/future.proto
moves to future-rpc/proto/, the future-rpc Rust crate moves to
future-rpc/rust/, and the shared/future-rpc TS package moves to
future-rpc/ts/. Update every caller: root/agent/channels/gui Cargo.toml
workspace members and path deps, loop build.rs proto path, npm workspace +
package-lock, Makefile, CI path filters and proto-freshness gate, packaging
scripts (dmg + both Windows), .gitignore, and comments/docs.

Verified: cargo check --workspace + gui lib, proto regeneration is
diff-clean for both Rust and TS, npm build succeeds.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs(rpc): clarify TS JSON-first strategy; fix make run targets and CI lockfile refs

Address third-party review of the typed-RPC migration: document that TS
clients stay JSON-first until replaced by Rust (no typed normalization
planned), so the JSON dual-write is not retired prematurely. Fix `make
run-tui`/`run-cli` to depend on node-workspace (fresh checkouts otherwise
miss the @future-os/rpc dist build), build the rpc package before the CLI in
the GUI test scripts, and point the release workflows' npm cache at the root
package-lock.json (cli/package-lock.json was removed). Also align stale
`proto/future.proto` path references to `future-rpc/proto/` across comments
and docs, and fix resolveProtoPath's dev-checkout candidate range.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* ci(rpc): trigger TS checks on proto changes and verify embedded proto freshness

Editing future.proto now revalidates the CLI/TUI jobs (added
future-rpc/proto/** to their path filters) and the proto codegen freshness
gate regenerates the TS embedded proto and includes future-rpc/ts/src/proto.ts
in its git diff --exit-code, so a proto edit can no longer land with stale TS
generated code while CI stays green.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* ci(rpc): add Node 24 to rust-quality for TS proto freshness step

The proto codegen freshness gate regenerates the TS embedded proto with
`node scripts/generate-proto.ts`, which relies on Node 24's native type
stripping. The rust-quality job had no Setup Node step, so the runner's
preinstalled node (20/22) would fail to parse the TypeScript and the gate
could never pass. Add actions/setup-node@v6 pinned to Node 24.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Apply remaining changes

Co-authored-by: tallcode <[email protected]>

* style(gui): rustfmt the sidecar placeholder helper added by copilot

The if/else ext assignment did not match rustfmt 1.97 output, failing
`cargo fmt --check` in CI.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: tallcode <[email protected]>
huichen added a commit that referenced this pull request Sep 22, 2026
)

* feat(tui): bring the terminal UI up to the desktop feature surface

The TUI had fallen behind the desktop app: no provider or model editing, no
skills browser or install path, no sandbox or permission controls, and menus
that could only list a flat set of choices. This lands the interaction surface
the desktop already had, plus the defects that surfaced while verifying it.

Interaction surfaces
- A popup-menu framework (incremental search, groups, multi-select, reload) now
  backs /providers, /models, /tools, /sessions, /tree and the scoped-model
  picker, replacing the flat lists.
- Provider and model configuration: add and edit providers, keys, endpoints and
  models from the panel. /provider-key captures a key and does what its prompt
  promises — empty input clears the stored key.
- Skills: a browser that merges the agent's own skills with the installable
  catalogue, with search, groups, a detail preview and use. Install, uninstall
  (a two-press confirmation that any other key disarms) and upgrade run through
  the `future` binary, then refresh the panel so it shows the new state.
- Sandbox and permission: /sandbox shows the tier, its reason and how platforms
  differ, and surfaces the agent's silent sandbox-to-manual fallback instead of
  hiding it; /permission persists the level.
- Diff rendering for edit, write and patch output, with per-file stats,
  collapsing and syntax colouring.
- A full-screen pager (/transcript) with search, copy and a status row, whose
  live search claims the first escape.
- Clipboard (/copy) with a tmux, native, OSC 52 ladder and an honest notice when
  a write cannot be confirmed.
- Desktop notifications and the terminal title (OSC 9 and OSC 0), respecting the
  terminal's own settings.
- External editor drafts for /editor, and a theme catalog behind /theme that
  repaints every chrome widget.
- /worktree picks or creates a git worktree and moves the session into it,
  reusing the existing set_cwd RPC; destructive git subcommands are refused.
- /keymap lists every binding by group and rebinds one, with conflict detection
  and persistence to `~/.future/tui/keybindings.json`.
- Finished transcript rows are inserted into the terminal's own scrollback, so a
  conversation can be scrolled back to and selected with the terminal's copy
  mode after the TUI exits. Rows are handed over once (a watermark), re-wrapped
  at the terminal width, and sanitised so a tool result cannot replay an escape
  into the terminal a second time.
- /history results now show why each hit matched and when it was said: the query
  is highlighted inside the snippet (display-width aware, so CJK and emoji are
  not cut), the timestamp is printed, and the opaque entry id is demoted.
- Long pastes fold. A paste longer than 200 characters never enters the box as
  text: it is kept aside and replaced by a `[Pasted Content N chars]` marker
  (numbered `#2`, `#3` … for repeats, reusing a number a deleted marker frees),
  and expanded back to the pasted bytes on submit. The threshold is the box's own
  height in characters — three lines at 80 columns, so roughly 240 characters are
  visible — because a paste that overflows the box while still being shown as
  text is what the marker exists to prevent. The count is characters, not bytes,
  so CJK is not three times as long as it looks.
- Pasting an image *path* attaches the file instead of inserting the text: an
  `[Image #N]` marker in the box, the number of waiting images beside it, and the
  path on the wire as an attachment. Dragging a file into the terminal pastes its
  path, so this is how that gesture becomes an attachment. The path is normalised
  (quotes, `file://`, backslash-escaped spaces) and the file is checked by its
  magic bytes — a text file named `notes.png` is not an image, so it stays text.
- Ctrl+V takes an image off the system clipboard (a screenshot), or its text when
  it holds no image. `super+v` is bound to the same path: upstream of a
  Kitty-protocol terminal a Command press is reported that way, and where the
  terminal keeps Command for its own Paste menu the key never arrives at all —
  which is why Ctrl+V remains what that case sends. Deleting a marker drops its
  attachment and the survivors are renumbered, so what is shown is what is sent.
- A paste burst is detected when the terminal does not send bracketed paste (some
  Windows hosts): characters that arrive faster than typing are buffered as one
  paste, so an `Enter` inside it is a newline rather than a submit and a `?` in it
  does not toggle anything. Only the bracketed-paste-less path uses it, so the
  recorded screens are unchanged.

Slash commands added to the dispatch surface
/shell /delete /title /metrics /snapshot /context /export (now a real
implementation rather than a stub) /agent /history /tool-output /autocompact
/autoretry /scoped-models /fork /keymap /worktree and /theme <id>.

Shortcuts
ctrl+v pastes the clipboard (image or text) and is listed in `/help` with the
other keys — pasting an image has no slash command to be discovered through.
ctrl+x copies the last answer, as before.

Commands removed
- /append-prompt and /system-prompt were silent no-ops: the agent composes a
  run's system prompt from project context, skills, workspace memory and the
  tool list and never reads the list field those commands wrote, so the value was
  overwritten at every run boundary. Their RPCs stay (the CLI builds them
  directly for its own flags) but nothing here sends them any more.
- /ephemeral, /rule, /quit-agent and /stats were removed by choice. /stats was
  not dropped: its counters are now the tail of /status, so the session report
  and the usage ledger have one home instead of two panels printing the same
  numbers.
- Unknown slash commands still fall through to a prompt, so one typed from
  muscle memory is sent as text rather than rejected. That is the existing,
  test-pinned behaviour that also lets `/usr/bin/foo` be sent as a message.

Fixes
- The skills child's pipes are drained while it waits, so a catalogue larger
  than the 64 KiB pipe buffer no longer deadlocks into a timeout.
- An overlay owns its whole row instead of splicing over the rows beneath it, so
  chat text can no longer bleed into a panel's leading columns.
- /help scrolls (the commands above were unreachable at 80x36), /permission
  opens focused on the permission half of its shared card, and truncated hints
  end in an ellipsis.
- A panel's live search claims escape before the overlay closes, matching what
  the components already did when tested in isolation.
- The pager accepts the key ids a real terminal sends (pageDown, not pagedown).
- The mock agent carries `state` on agent_end, without which the completion
  notification path was unreachable in the harness.
- A test restores the panic hook it installed instead of removing it, so a
  leaked hook can no longer swallow another test's panic or append to the
  developer's real crash log.
- Cumulative token totals are labelled as resent-per-call and joined by an
  average per query, so they cannot be read as the current context size.
- markdown follows the active palette: under the light theme, headings, links
  and code were painted with the dark constants' xterm indices (1.4-2.3:1 on
  white) while the palette's own md_* roles went unread.
- /history snippets were byte slices of concatenated UTF-8, so a window edge
  could land inside a multi-byte character and lossy decoding rendered the half
  as U+FFFD — the box users saw with CJK text. The partial character is dropped
  on each edge instead of substituted for; the SQL and `byteOffset` are
  unchanged.

Verification
- 2020 TUI unit tests, 8 CLI smoke tests and 5 bug-hunt regressions pass, plus
  1822 agent tests; rustfmt and clippy are clean at the pinned 1.97.0 toolchain.
- A tmux harness drives the real TUI against a deterministic mock agent and
  compares recorded screens byte for byte, waiting on content instead of fixed
  sleeps. It covers every panel listed above plus the applied state (tier set,
  permission applied, theme switched, tool expanded, search, paging) and the
  paste surfaces (folding, an image path, attachment numbering, renumbering
  after a delete): 51 checks pass, 0 warnings.
- Pasting was checked end to end on a real pane, not through doubles. A 250
  character paste folds, and the whole text still reaches the agent while the
  marker never does (the mock echoes the prompt, so the pane is the wire). A
  pasted image path and a Ctrl+V from the clipboard both attach, and the
  attachment's path, kind and name arrive on the prompt.
- The clipboard probe was run on macOS both ways: with a real PNG on the
  clipboard it writes the file, and with text on it the tool fails without
  leaving a partial file behind — which is the fallback to a text paste.
- The scrollback path was checked against a real pane, not a double: the exit
  status and the conversation are readable through `capture-pane -S` after the
  TUI leaves, the oldest rows sit above the viewport (so scrolling is required to
  reach them), and one exchange produces exactly one copy of each row.
- New-on-branch coverage is complete: three independent oracles (two blame-based,
  one difflib) agree on zero uncovered lines, sanity-checked against a report
  with 57059 records of which 96.9% are covered.

Not verified here
- Windows and Linux are covered by CI only; this machine cannot cross-compile
  the agent's `ring` dependency. The clipboard probe's PowerShell and Wayland /
  X11 command lines are held by unit tests, not by a real clipboard on a host
  that has them.
- Command+V cannot be shown to work on a terminal that does not speak the Kitty
  keyboard protocol (Terminal.app, for one): the key never arrives there. That is
  a property of the terminal, not something the TUI can fix — Ctrl+V is what that
  case sends, and both spellings are bound.
- The keymap panel's capture/rebind flow was driven by unit tests and the
  keybindings.json round trip, not end to end in a real pane.
- ctrl+p (cycle model) cannot be exercised in the harness: the real agent
  implements `cycle_model`, the mock does not.

* fix(tui): make the clipboard, skills and sandbox tests host-independent

Twelve tests passed on macOS and failed on Linux CI, each for the same shape of
reason: a test asserted one host's behaviour while the code under test read the
host it happened to be running on.

- Clipboard paste: four tests drove `ctrl+v`/`super+v` and asserted the macOS
  probe names (`osascript`/`pbpaste`), while `paste_clipboard` read
  `std::env::consts::OS` — on Linux the probes are `wl-paste`/`xclip`. The OS is
  now a parameter (`paste_clipboard_for_os`), as the sandbox panel already does
  for its platform, and the tests pin macOS.
- Sandbox/permission panels: three tests asserted `current: Sandboxed` and the
  marked tier row, which is the macOS platform default; on Linux the default is
  `Manual` and Bubblewrap adds its own caveat. The app now reads one
  `host_sandbox_platform()`, pinned to macOS in the test build, so the whole
  panel lifecycle (open, probe, policy answer) agrees.
- Copy: `recording_clipboard` inherited the host's resolved candidate list. On
  macOS `pbcopy` was found and the recording runner was reached; a Linux runner
  without X11/Wayland resolved to no candidates, so `copy()` took the OSC 52
  fallback and recorded nothing. The helper now carries one synthetic candidate,
  the same on every host — `copy()` keeps using the clipboard's own list, so
  only the fixture changes, and the real OSC 52 fallback keeps its own test.
- Skills: `skills_cli_for_host` returned `None` when no `future` binary was
  resolvable, so on a CI runner (none next to the test executable, none on
  `PATH`) the panel showed the no-binary notice and two tests waited for
  behaviour that needs an installer. The test build now always offers the
  refusing installer; a test that wants the missing-binary state sets
  `skills_cli = None`, as one already did.

Verified: 2020 tui unit tests pass, rustfmt clean, clippy clean at the pinned
1.97.0 toolchain. Each of the twelve is host-independent by construction rather
than by a host check — the test build cannot read the host for the platform, the
OS arrives as an argument, and the candidate list is synthetic — so the run on
this Mac is the run CI will do, not a second behaviour to be reconciled later.
huichen added a commit that referenced this pull request Oct 27, 2026
A code block's layout is its meaning. Folding a line onto the next one
shifts every column after the fold, so box-drawing art, an aligned table
and a paste of a TUI screen all come out scrambled: on a phone the
launchpad capture `│ |> [Image #1][Image #2] … │` lost its right border
onto a second line and the frame below it no longer closed.

The block now sits in a horizontal ScrollView with the gutter on its
scrolling content, and the virtual rows of a long block stack in a column
(a horizontal ScrollView's content is a row, which would have put them
side by side). A sideways pan is not contended for by the surrounding
message list — the tables in the same file already rely on that — while
the nested *vertical* viewport the old comment warned about stays gone;
the expand toggle is still what makes a long block's tail reachable.

This also matches the desktop, whose `<pre>` scrolls sideways instead of
wrapping (`desktop/src/features/markdown/renderers/CodeBlock.tsx`), so the
same reply now reads the same on both.

Measured in the mobile harness (390×844, headless Chrome, a fenced box-art
capture appended to the demo reply): the painted height divided by its
line height is 5 for a 5-line source — no line folded — and the scroller
carries 81 CSS px of horizontal overflow (scrollWidth 431 vs clientWidth
350) inside a 350 px column. Jest: 150 suites / 2889 tests pass.
huichen added a commit that referenced this pull request Oct 27, 2026
A code block's layout is its meaning. Folding a line onto the next one
shifts every column after the fold, so box-drawing art, an aligned table
and a paste of a TUI screen all come out scrambled: on a phone the
launchpad capture `│ |> [Image #1][Image #2] … │` lost its right border
onto a second line and the frame below it no longer closed.

The block now sits in a horizontal ScrollView with the gutter on its
scrolling content, and the virtual rows of a long block stack in a column
(a horizontal ScrollView's content is a row, which would have put them
side by side). A sideways pan is not contended for by the surrounding
message list — the tables in the same file already rely on that — while
the nested *vertical* viewport the old comment warned about stays gone;
the expand toggle is still what makes a long block's tail reachable.

This also matches the desktop, whose `<pre>` scrolls sideways instead of
wrapping (`desktop/src/features/markdown/renderers/CodeBlock.tsx`), so the
same reply now reads the same on both.

Measured in the mobile harness (390×844, headless Chrome, a fenced box-art
capture appended to the demo reply): the painted height divided by its
line height is 5 for a 5-line source — no line folded — and the scroller
carries 81 CSS px of horizontal overflow (scrollWidth 431 vs clientWidth
350) inside a 350 px column. Jest: 150 suites / 2889 tests pass.
huichen added a commit that referenced this pull request Oct 27, 2026
A prompt used to be one full row of grey: the background started at the
transcript's left edge and ran to its right edge, so the reader's own words
looked like a highlight rather than a message, and two prompts in a row read
as one striped block.

The prompt is now a bubble, the same shape the desktop draws: a rounded frame
in the palette's accent, `user_bg` filling only what the box covers, one column
of padding either side, right-aligned with a column of margin. It hugs its own
text (`hi there` gets a 12-column box, not a 120-column bar) and stops at 64
columns, which is the desktop's `max-w-2xl` inside `max-w-3xl` proportion.

The run state (`queued (#2)`, `cancelled`, `merged into the previous run`) moves
inside the bubble as its last row — it describes that prompt, and the box now
holds everything about the message and nothing else. A column too narrow to
frame (under 13 columns of bubble content) keeps the old band, because two
borders and two padding columns there would leave almost nothing for the words.

Tests: the transcript-row helpers now read *through* the frame (a body row
gives back its words, the border rows drop), since fold/seam/spacer assertions
are not about the box; three new tests pin the box itself — geometry and right
alignment, the width cap with a wrapping prompt, and the narrow-column
fallback.
huichen added a commit that referenced this pull request Oct 27, 2026
Reverts the framed bubble (`cd8cd659a`) and its follow-up (`d380ca766`), which
had taken the frame off but kept the hug and the right alignment. What the
reader's own words want here is the plainest thing the surface can do: the
prompt on the transcript's left edge, its background running the full width of
the column, nothing drawn around it.

So `render_user_message` is one loop again — each markdown line as ` line`
filled to the column width — and the run state (`queued (#2)`, `cancelled`,
`merged into the previous run`) is a full-width dim row under it rather than a
row inside a box. The bubble's constants, its row painter, its width cap and
the geometry tests that pinned them go with it.
huichen added a commit that referenced this pull request Oct 27, 2026
…ash-safe journals (#1384)

* fix(mobile): stop folding code blocks — a long line pans instead

A code block's layout is its meaning. Folding a line onto the next one
shifts every column after the fold, so box-drawing art, an aligned table
and a paste of a TUI screen all come out scrambled: on a phone the
launchpad capture `│ |> [Image #1][Image #2] … │` lost its right border
onto a second line and the frame below it no longer closed.

The block now sits in a horizontal ScrollView with the gutter on its
scrolling content, and the virtual rows of a long block stack in a column
(a horizontal ScrollView's content is a row, which would have put them
side by side). A sideways pan is not contended for by the surrounding
message list — the tables in the same file already rely on that — while
the nested *vertical* viewport the old comment warned about stays gone;
the expand toggle is still what makes a long block's tail reachable.

This also matches the desktop, whose `<pre>` scrolls sideways instead of
wrapping (`desktop/src/features/markdown/renderers/CodeBlock.tsx`), so the
same reply now reads the same on both.

Measured in the mobile harness (390×844, headless Chrome, a fenced box-art
capture appended to the demo reply): the painted height divided by its
line height is 5 for a 5-line source — no line folded — and the scroller
carries 81 CSS px of horizontal overflow (scrollWidth 431 vs clientWidth
350) inside a 350 px column. Jest: 150 suites / 2889 tests pass.

* fix(tui): apply the model row that was picked when two providers share its id

The model picker keyed its rows by the bare model id, and `enter` sent that
id straight to `set_model`. With two providers offering one id — `future`'s
`deepseek-flash` and a `models.json` `westlakehpc/deepseek-flash` — the row
picked and the model set were decided by the agent's own resolution order
(user-defined models before the built-in catalogue), so choosing the `future`
row left the session on `westlakehpc/deepseek-flash`.

Rows now carry the `provider/id` reference the desktop and phone clients
already send, which is also the canonical spelling the agent persists. The
launchpad's model chip and the model lookups behind the thinking-level ring
resolve a reference (exact match first, bare id/tail only as a fallback) and
cycle over references, so a staged choice names the same model the row did.

* fix(rpc): give the journal report the maintenance deadline

The run-journal report scans the table it reports on: it sums the
payload length of every run_events row, so its cost follows the one
table that grows without bound. Measured on a real 4.4 GiB store:
23.8 s for the first, cold, report, and an earlier cold run hit the
30 s STORAGE_TIMEOUT and printed 'Timeout expired' — the diagnostic
failing on the database it exists to diagnose.

Class it with the reclamation next to it (60 s) instead, and pin the
invariant in a policy test. The cheap indexed reads must not follow it
there, which the same test asserts.

Also pin the sweep's own red line in a store test: entries and
message_blocks are byte-identical across a reclamation.

* docs(guide): measure run-journal cost and the reclamation procedure

A 4.4 GiB agent.db was 76% run_events plus its uniqueness index, and
the reads around it were not slow at all: session list, get_state and
transcript measured the same at 4.4 GiB and 1.3 GiB. What was unbounded
is the journal itself — only a completion notification folds it, and
135 of 1,166 settled runs still held their raw stream.

Record the measurement, what the sanctioned sweep does and does not
touch, the one-off VACUUM (5.4 s, 4.22 -> 1.30 GiB) with its lock and
disk requirements, the backup/restore path, and the leftovers: 50
journals that never got an agent_end, 179 MiB, kept by design.

* fix(tui): the rail opens to 60 columns, not 48

The divider stopped at 48 whatever the terminal width, so a file or a
session row read in the rail was clipped to a column count the reader
could not widen. The ceiling is now 60, which still leaves the
conversation more than its 20-column floor at the narrowest frame that
shows a rail (88 - 60 - 1 = 27).

* feat(cli,agent): add --message-file for verbatim programmatic dispatch

`future run` had one way to carry a message from a file: `@<file>`, which
wraps the content in a `<file name="…">` block. That shape is right for a
human attaching a file in a terminal, and the agent guideline told every
programmatic dispatch (agent → agent, sub-session hand-off) to use it for
long or non-ASCII payloads — so a dispatched child's first user turn was a
file attachment rather than the instruction, and the title derived from that
turn started at the wrapper. `host/src/agent_bridge/import.rs` already
carries a patch for exactly that symptom.

- `--message-file <path>`: the file's bytes ARE the message — no wrapper, no
  joining, nothing trimmed. Mutually exclusive with a message argument and
  `@files` (a usage error, not a silent winner). Empty/whitespace-only,
  unreadable, non-UTF-8 and NUL-bearing (binary) files each fail with their
  own message instead of sending nothing or truncating.
- `@<file>` is untouched, byte for byte: same wrapper, same semantics.
- The agent guideline now points programmatic dispatch at `--message-file`
  and says why `@<file>` is the wrong shape for it; the docs (wiki CLI in
  both languages, and the self-inspection guide's dispatch section) say the
  same.
- The generic "No prompt provided" line no longer stacks on top of a failed
  read, so the reported reason is the only one printed.

Verified live: a child session dispatched with `--message-file` stored the
file's text verbatim (207 bytes, byte-identical) with no `<file` in its first
user entry, and a session created that way was titled from the instruction's
first line.

* fix(agent): map thinking levels onto each model's declared effort vocabulary

`westlakehpc/deepseek-flash` answers `reasoning_effort: "medium"` with
HTTP 400 ("DeepSeek V4.1 reasoning_effort must be low, high, xhigh, max,
or an integer within [1, 100] in chat_template_kwargs"), because the level
was sent verbatim: `thinkingLevels` named the picker's levels, not the
values that access path accepts. Any model at `medium` failed 100% of the
time, and `medium` is one of the shipped levels.

Which values a model accepts is now data. A model (or its provider) can
declare `compat.reasoningEffort`:

  { "values": ["low", "high", "xhigh", "max"],
    "integer": {"min": 1, "max": 100},
    "param": "chat_template_kwargs.reasoning_effort" }

and each thinking level is mapped onto it, monotone and without dropping a
level: a listed spelling travels as itself; an unlisted level travels as
the integer at its own point of the provider's range (`medium` -> 50 for
1..=100, the midpoint, because the provider accepts a number but no such
spelling); with no integer range it snaps to the closest spelling, ties
going shallower (never more effort than the user chose). `param` exists
because this gateway accepts the spellings at the top level but a number
only under `chat_template_kwargs` (a top-level integer is a 500). A
malformed declaration fails model resolution, and a level the vocabulary
cannot express is named in a deduped warning when the model is resolved,
instead of surfacing as a provider 400 after the user waited a request.

Without `compat.reasoningEffort` every model keeps the previous contract
(levels are wire values, sent verbatim), so the built-in catalogue is
unchanged. `default` still sends nothing and `off` still sends the
protocol's disable spelling; neither is used to paper over a refusal.

Tests cover the failure shape end to end, every chat format plus the
Responses API, the mapping rules and parse errors, and a sweep over every
registered model at every level it offers, asserting the value on the wire
is one the model declares it accepts.

* feat(desktop): step through a folder's images in the preview, and read them at 1:1

Opening a picture from the right-hand Files panel showed one image at a time,
so comparing a folder of figures meant closing the overlay and finding the next
row by hand. The control bar also reported a percentage relative to "fit", which
said 100% for a screenshot that was really being drawn at a third of its pixels —
the number could not tell you whether you were looking at the real thing.

- The bar now leads with <-/-> and a "2 / 5" readout that walk the images of the
  directory the row was opened from, in the tree's own order; the arrows disable
  at the ends, and Left/Right do the same from the keyboard. The list comes from
  the listing the row was drawn from, so no extra read. A folder with one image,
  or a preview that is not a picture, shows no stepping at all.
- The percentage is now the picture's real scale against its own pixels, and a
  1:1 button jumps to it (double-click still toggles fit <-> actual size). "Fit to
  window" replaces "Reset zoom", which no longer describes what that button does
  now that 1:1 sits beside it.
- MAX_SCALE rises from 6x to 12x of fit so 1:1 stays reachable for very large
  images, whose fit is a small fraction (an 8000px screenshot in a 1200px window
  fits at 0.15).
- The picture carries a hover hint — scroll/double-click to zoom, drag to pan
  once zoomed — because dragging at fit cannot move anything (the whole picture
  is already on screen) and that reads as "drag is broken".

* fix(tui): the rail's arrows switch tabs in 文件 too

A focused rail answers ←/→ with its neighbour tab, and its own hint row says
so (`… · ←→ 页签`) — except on 文件, where the arrows had been given to the
tree. There they did nothing at all on a file or on a closed top-level
directory, and `→` on a file dropped a preview over the whole screen, so the
third tab read as a dead end: the only ways out were `ctrl+1`…`ctrl+3` or the
pointer.

←/→ are the strip's on all three tabs again. The tree keeps the keys that are
its own: ↑↓ walk, `enter` opens a directory or previews a file, and `⌫` closes
a directory or walks up to the one holding the row — the "up one" every file
browser has. 文件's hint row names that key (`↑↓ · ⏎ 打开 · ⌫ 收起 · ←→ 页签`),
which is the only place it can be discovered, and the other two tabs never
claim it.

Tests: ←/→ return `SwitchPanel` from four different tree rows (a file, a closed
directory, an open one, a picture); `⌫` closes an open directory and climbs out
of a nested row; the footer names `⌫` only on 文件.

* feat(tui): reasoning starts collapsed, like the desktop

The transcript printed the model's reasoning text in full by default, so a
streamed reply spent the screen on its own thinking and pushed the answer it
had just written off the bottom. The desktop and the phone both start a
`Thinking` block collapsed; the terminal was the one client that did not.

Reasoning now keeps one `▸ thinking` row at the default level — with the count
in the compact view, and the ellipsis only while the reasoning itself is still
arriving — and the text lives at the full-process level, so `ctrl+e` alone
answers "what did it think?". `render_all_detailed` (the `/transcript` record)
reveals it too. The old placeholder hint said `ctrl+o`, which in the workbench
opens Preferences, so it is gone with the placeholder.

A settled reply already folded to the answer it ends on; that path is
unchanged, and the streaming/folding tests now pin the collapsed reasoning
alongside it.

* feat(tui): a framed user bubble instead of a full-width band

A prompt used to be one full row of grey: the background started at the
transcript's left edge and ran to its right edge, so the reader's own words
looked like a highlight rather than a message, and two prompts in a row read
as one striped block.

The prompt is now a bubble, the same shape the desktop draws: a rounded frame
in the palette's accent, `user_bg` filling only what the box covers, one column
of padding either side, right-aligned with a column of margin. It hugs its own
text (`hi there` gets a 12-column box, not a 120-column bar) and stops at 64
columns, which is the desktop's `max-w-2xl` inside `max-w-3xl` proportion.

The run state (`queued (#2)`, `cancelled`, `merged into the previous run`) moves
inside the bubble as its last row — it describes that prompt, and the box now
holds everything about the message and nothing else. A column too narrow to
frame (under 13 columns of bubble content) keeps the old band, because two
borders and two padding columns there would leave almost nothing for the words.

Tests: the transcript-row helpers now read *through* the frame (a body row
gives back its words, the border rows drop), since fold/seam/spacer assertions
are not about the box; three new tests pin the box itself — geometry and right
alignment, the width cap with a wrapping prompt, and the narrow-column
fallback.

* fix(tui): the activity row follows the session, and counts a call once

The footer's `思考 · 1071s · 53 工具` belonged to whichever conversation this
client last narrated, not to the one on screen: `Live`'s run state (kind,
clock, tool tally, rate) is the client's own and nothing dropped it when the
reader clicked another row in the rail, so the conversation they had left kept
counting there for as long as the TUI stayed open.

- `switch`, a fork and `/new` now forget the run this client was narrating
  (`Live::forget_run`), and the newly attached session takes the row back:
  `get_state`'s `isStreaming` says whether its run is still in flight, which is
  what makes a conversation started by the desktop (or by a queued run) show
  the spinner instead of `idle` until its next event.
- `53 工具` was also twice the truth. The agent announces one call twice
  (`phase: "input"` while its arguments stream, `phase: "execution"` when it
  runs) and `add_tool_start` dedupes the row, but the counter incremented per
  event — 26 calls read as 52, and `tool_end` only took one phantom back. The
  tally is now a set of call ids, and it is a tally for the run (what the row
  and the demo's `2 tool calls` both say) rather than a count of the calls still
  open, which would read `0` while the model thinks.

`docs/guide/tui.md` says what the row means, since that ambiguity is what let
both of these sit: the row describes the conversation on screen, counts one
call per call, and starts over at a switch.

* docs(screenshots): a sheet for the user bubble's hairline, with and without

The user's own messages in a conversation are drawn as a filled bubble with a
1px accent hairline around it. Whether that hairline earns its place is a
judgement about a soft edge, so it wants two panels of the same frame rather
than an argument: `user-bubble-border-variants` renders the first user message
with the border and with the border's colour taken out, injecting a stylesheet
so a re-render cannot put the hairline back, and rejecting the capture if the
bubble is not fully on screen — a sheet framed on the wrong element would
otherwise look plausible.

The window is 900 wide and the frame is scrolled last: two 1280 panels halve a
2x capture, and the fixture's approval card settles after boot, which moved the
bubble under an earlier scroll.

* feat(tui): the rail's 最近 splits into 活跃 and 更早, with a spinner

The desktop's recent view files a conversation whose run is still in flight
above the ones that have gone quiet, and marks the running row with a
spinner. The rail had one flat list, so a run started from another client (or
a `/future-goal` worker on the same agent) was invisible here.

最近 now leads with an 活跃 stretch and follows with 更早, each captioned with
how many conversations it holds — the desktop's caption in the rail's shape.
The two headings are only drawn while both stretches are non-empty: with
nothing running the whole list *is* 更早, and a heading saying so would spend
one of the rail's twenty rows on nothing. A running row draws the activity
row's spinner in its state slot (`SessionRow::streaming`, from the agent's own
`isStreaming`); the conversation on screen keeps its `▸` while it is quiet and
yields the slot while it runs, because its title is already the accent one.

Two things had to follow the flag. The rail's list is re-read every five
seconds while the rail is on screen: the agent pushes events for the attached
session only, so another client's run reaches this surface no other way, and
without it the spinner would freeze mid-turn and 活跃 would never empty. And
the tick clock now animates for the rail as well as the activity row, each
gated on its band being laid out.

Verified on a real pty against the demo agent: the frame shows
`活跃 1` / `更早 2` with the spinner on the running row, and the spinner turns
through all ten frames at the designed two a second (an earlier `paint |= …`
kept a frame owed on every tick, which measured as eight).

* fix(tui): the conversation starts under the header's rule, with no gap row

The tall layout put the conversation one row below the header
(`body_y = header_h + 1`), leaving a row no band paints: title, hairline, a
blank line, then the transcript. It cost the conversation a row on every
frame, and the frame diagram in `docs/guide/tui.md` draws the transcript
directly beneath the hairline, so that gap was the one band nobody could name.

The body now starts on `header_h`. Every frame row belongs to a band, and
`the_bands_tile_the_frame_without_overlap_or_holes` says so outright
(`blank == 0`) instead of allowing one. The rail moves up with it — its tab
strip is row 2, not row 3 — so
`the_rail_button_collapses_and_reopens_from_the_edge` is pinned to the frame's
new shape.

* fix(tui): the composer's box is as tall as its draft, not as tall as the cursor

A draft typed with ctrl+j lost its closing rule as soon as the reader moved
back up a line: the band grew by the cursor's row while the box painted every
row of the draft, so the box was taller than the band and its *last* row — the
closing rule — was what got cut off.

The height now comes from the box itself (widgets::input_content_rows, sharing
one window calculation with input_box), measured at the width the box paints
at, and the composer passes that room back in so a draft taller than the window
scrolls inside the box instead of overflowing it. The hardware cursor follows
the row the box reports instead of assuming the draft's last line, and the key
handler's line width is the box's own (-4, not -6): one definition of the
draft's width for painting, moving and measuring.

* feat(tui): delete a conversation, with a chord and a confirm box

`future tui` had no way to remove a conversation: the rail only opened rows,
`ctrl+r` only switched, and the palette had no verb for it — the agent's
`delete_session`, the desktop's thread menu and the client's own
`GrpcClient::delete_session` had no surface here.

`ctrl+d` is now a rebindable action (`deleteSession`, listed in the shortcut
editor and the help overlay), `/delete` is the palette's door to it, and
`delete` in a focused rail opens the same box for the row under the cursor.
None of them deletes: the box names the conversation and where it lives, and
its `enter` is what asks the agent.

Deleting the conversation on screen opens the row that took its place, so the
transcript never stays on a session the agent no longer has; the last one
detaches to the launchpad. A refusal (the agent keeps a session a compaction
holds) leaves everything as it was and says why on the notice row.

* refactor(tui): drop linear reading

Nobody used it, so the option and the native-scrollback reader behind it are
gone: `alt+l`, the preferences row, the rebindable `linearReading` action and
the settings key it persisted. The workbench now always owns the alternate
screen, which removes the mode-switch plumbing in the driver (`sync_mode`, the
deferred overlay output, the single-line prompt redraw) and the second terminal
start path.

`system_theme_id` — the `COLORFGBG` light/dark hint, the one piece of the old
`accessibility` module that had nothing to do with reading mode — moves next to
the palette it selects.

* feat(tui): colour a previewed file by its language

The preview box showed every file as one colour of text: a `.rs` file read
as a wall of body-coloured lines, with its comments, strings and numbers
indistinguishable from its identifiers.

`syntax.rs` classifies a preview's lines into keywords, types, called
names, strings, numbers, comments, attributes and keys. It names tokens,
never colours — `theme::Palette::token` maps them, so highlighted code
follows the theme in force instead of arriving in a dark highlighter's
palette on a light canvas, which is the one thing a 256-colour theme kit
cannot afford to break.

It is deliberately not a parser: each line is walked once and only
"inside a block comment" or "inside a multi-line string" crosses lines.
That covers Rust's raw strings and lifetimes, Python's docstrings and
decorators, JavaScript's template literals, JSON/TOML/YAML keys, CSS
properties and HTML tags; an unrecognised extension is painted exactly as
it came. Classification happens once, when the file is read, and the
lines travel as an `Arc<[Line]>` because the adapter rebuilds the frame's
data once per event.

Tabs are expanded to four spaces on the way in: a literal `\t` in a painted
row moves the cursor to the terminal's own tab stop, which is how a
tab-indented file tore the frame's columns before.

Measured: a 55 KB file classifies in 4 ms in a debug build, 0.4 ms in
release; the preview box keeps its exact-rows-of-exact-columns invariant
at every size, in both themes (a new render test asserts the keyword
colour, the string colour, the muted comment, and that a called name is
not a keyword).

* feat(mobile): preview any picture in the conversation, and send pictures as pictures

On the phone an image in a reply was only reachable through the file-preview
flow (download, then the reader), an image linked from elsewhere was not
tappable at all, and a picture the user had sent showed up as a paperclip and a
file name — so there was nothing to look at, and nothing to tap.

- A new full-screen viewer (pinch to zoom, drag to pan, close in the header)
  is mounted by the chat screen and reached from every picture on it. A reply's
  image opens it on its already-loaded bytes instead of routing through the
  file-preview transfer; an image the agent linked with an http(s) URL is now
  tappable too; a picture inside a previewed document opens it as well. A linked
  picture still opens its link, and a surface with no viewer mounted keeps the
  old target rather than growing a button with nowhere to go.
- A sent picture is drawn as itself: a bubble that was just sent reads this
  phone's own copy immediately, durable history reads the desktop copy through
  the same preview transfer the reply images use, and a refused transfer falls
  back to the old chip — which is still the way to the file preview and its
  download/share actions.
- The harness could not prove any of this: the mobile mock pointed at port 7392
  while `scenarios.json` served assets on 7391, and 7391 belongs to the desktop
  harness's terminal server, so `serve_assets` "reused" a server that answers
  404 and every demo picture was a broken image while the capture reported
  success. The assets port is 7392 again, `serve_assets` refuses a port held by
  anything that does not serve the demo figures, and the existing `image` /
  `image-zoom` scenarios capture again. A new `image-attachment` scenario
  asserts the bubble draws a thumbnail and that tapping it opens the viewer.

* refactor(tui): drop the density preference, always draw the two-row header

`ctrl+o` no longer offers 界面密度. The two-row context header it already
defaulted to is now the only header: the comfortable five-row identity block,
its block-font wordmark and the `density` key in `settings.json` are gone, so
a saved `"density": "comfortable"` is simply ignored.

Removes the `Density` enum, `PreferenceRow::Density`, `effective_density`,
`widgets::wordmark_rows`/`wordmark_width`, and renames
`layout_with_preferences` to `layout_with_position` since rail position is the
only layout preference left.

* feat(tui): a rail that repeats neither its title nor a band of its own

The rail's first row restated what the tab strip above it already said —
`最近  308 个会话`, `工作区  3 个工作区`, `文件  12 项` — at the cost of one
row of every list, so it is gone from all three tabs. The blank row under the
tabs stays, and that is the whole heading now.

The rows also painted `panel` (235) behind them, which was the only explicit
background in the surface: the chat, the composer and the tab strip all keep
the terminal's own canvas. On a terminal whose palette is not ours that read
as a black rectangle dropped beside the conversation. The rail now keeps the
canvas like everything else — the divider column already says where it starts
— and `panel` is what fills a menu, a picker or an overlay box, whose frames
paint it themselves.

* fix(tui): shift+←→ walks the rail's three tabs, shift+↑↓ the conversations

The focused rail's footer named `↑↓ 选择 · ⏎ 打开 · ←→ 页签`, which reads as if
`↑↓` changed the conversation and `⏎` were the way to switch it. `↑↓` only moves
the list cursor (the switch is `enter`, or a key that steps the transcript), and
`←→` stop being the tab keys on 文件, where they walk the tree.

So the two chords are now the shift pair, in one row at the foot of the rail:

  shift+←→ 页签 · shift+↑↓ 切换会话

`shift+←`/`shift+→` become a rebindable `PanelPrev`/`PanelNext` (the same intent
as `ctrl+1`…`ctrl+3`, one tab at a time): they show a hidden rail, take the keys,
and wrap through 最近 → 工作区 → 文件 — including on 文件, where the plain arrows
belong to the tree. `shift+↑`/`shift+↓` take over the previous/next session
step, and the preview box keeps all four chords so a picture cannot switch the
conversation underneath it.

* feat(tui): a git panel for the workbench

`/git` (or `alt+g`) is a read-only, tig-shaped browser with four tabs: commits
(`git log --graph`, 200 commits, decorations), refs (local/remote branches and
tags with upstream tracking), changes (the working tree, the same porcelain read
`/diff` uses) and stashes. The selected row's detail loads on its own: a
commit's stat and patch, a ref's upstream and tip, a file's patch, a stash's
diff.

Keys inside the panel: `1`-`4` switch tabs, `tab` moves the keys between the
list and the detail (a wide box shows both), `enter` opens what is under the
cursor (a ref filters the log to it, a changed file opens in the preview box, a
commit hands the keys to its patch), `y` copies the sha/ref name/path,
`backspace` clears the filter, `r` re-reads and `esc` closes. Rows the log's
graph only draws are painted but never selected, and the pointer is held to the
same rule.

Nothing here stages, commits, checks out, resets or drops a stash: the panel is
a reader, like `/diff` and `/worktree`. Every query is argv-only, bounded (one
page of log, a capped patch) and has a deadline, so a `git` waiting on another
session's rebase lock cannot freeze the frame that asked for it.

* feat(tui): a user bubble that is only its background

The prompt is drawn right-aligned with a fill of `user_bg`, and it had a
rounded accent frame on top of that: two rule rows, two side bars, and a colour
that appears nowhere else in the transcript. The frame drew the eye to the box
rather than to the words in it, so it is gone — the bubble is its background,
one column of padding either side, nothing else. What is left is the same hug
around the widest row and the same one-column margin off the transcript's edge,
so a prompt still reads as its own block rather than a full-width band.

The narrow-column fallback keeps its meaning with two fewer columns of chrome
(the plain band now starts below 11 columns, not 13), and the transcript
helpers that used to strip the frame no longer have one to strip.

* fix(agent): a settled run's journal is foldable when its stream was cut off

`agent_end` answered the wrong question. Whether a run is over is what
`runs` says — every attempt re-reads it and again under the publish lock —
while `agent_end` only says whether the *stream* is complete. The old gate
used the second as the first, so it refused exactly the journals a crash
leaves behind: truncated streams that will never grow a terminal. Measured
on a real store, that was 50 runs / 762k events / 179 MiB kept forever, and
they were the ones that most needed reclaiming.

Now a truncated stream folds too, once its run has been settled for a minute
(the `run_terminal` entry settles `runs` *before* the final event broadcast,
so inside that window a producer may still be appending; a minute later it
either finished or died). A run with no settle time — a legacy import — has
no age to read and keeps its journal. The decision is made from the source
read that already ran, so a refusal costs one indexed read instead of a full
fold, and the source equality that fences publication now includes the tail's
event type.

Nothing diagnostic is lost by folding a truncated stream: `DeltaFolder` keeps
every non-delta event verbatim — `error`, an unfinished `tool_start`, the
partial arguments of a cancelled call — and only merges delta runs, which is
what it already did for complete streams. The published snapshot carries
exactly the events that were there. `journal.truncated_publishes` counts them
durably and the report prints it as `Truncated`.

`a_concurrent_append_never_produces_an_inconsistent_snapshot` asserted a
gapless index sequence for *both* replay representations, which a folded
snapshot cannot satisfy: merging a run of deltas moves the segment's index to
the last one it absorbed. It now asserts no duplicate/ordering for both and
gaplessness only for a raw journal, which is what those words mean.

* feat(agent): a bounded startup catch-up folds what a crash left behind

A completion notification only covers a run whose process is still alive when
it ends. Everything else — a crash, a stop, an older build, a fold that failed —
stayed a raw journal until somebody remembered to run `future session journal
--reclaim`. That is how a real store reached 4.4 GiB with 135 of 1,166 settled
runs still holding their streams, and the structure that produced it was still
there for the next time.

The compactor thread now takes one bounded catch-up pass, queued first at
start: at most 16 runs and at most 10 s of folding, whichever ends first, with
the budget starting after the candidate plan is read (at startup that job waits
behind the storage worker's own migration, and billing that wait spent the whole
budget before the first fold — measured on a 4.77 GiB store: 33 s of queueing).
The plan itself is index-driven, not the sweep's whole-journal GROUP BY, because
this runs at startup. Not interrupted mid-fold, so one very large run can exceed
the time bound; `has_more` says the next start continues.

It is not a timer and not on a request path, and it logs one line either way:
folded/examined counts, events, snapshot bytes, truncated, errors, the refusal
reasons and the elapsed time. Before this, "the store is quiet" and "the store
has no idea" looked identical in a file that stopped shrinking.

Measured on a 4.77 GiB copy with 148 settled runs holding raw journals: the
first start after the upgrade folded 10 runs (162,544 events, 8 of them
truncated) in 10.05 s and reported has_more; the explicit sweep took the
remaining 138 (8,162,910 events) and left 0 reclaimable. Every one of the 363
session transcripts was byte-identical at each step.

* docs(guide): the fold admission rule, the catch-up, and the second measurement

The run-journal page said truncated streams are kept forever. They are not
any more, so the page now states what actually decides a fold — `runs` for the
run being over, `agent_end` for the stream being complete, the 60 s grace for
the producer being gone — with a table of every state and its durable refusal
reason, and the two cases that genuinely stay: no settle time to age, and
provider deltas that cannot be proven duplicates.

Adds the startup catch-up as its own section: the bounds, the fact that it is
one pass on the compactor thread rather than a timer or a request path, the
exact log line, and how to read it. Records the second measurement on a
4.77 GiB copy — 148 settled runs holding journals, 47 sessions with a crash-cut
run, 138 runs / 8.16 M events reclaimed, 0 reclaimable after, 77.6 % off the
file, and 0 transcript differences across all 363 sessions at every step.

* feat(tui): the files panel moves out of the rail into its own surface

The rail listed three things, two of which are true for the whole agent
(the conversation list, filed two ways) and one of which is true for the
conversation on screen (its workspace). A tree that belongs to a session
does not belong in a tab strip of agent-wide lists.

文件 is now its own panel, the way /git is: `ctrl+3` (the chord the third
tab answered to), the header's `[ctrl+3] 文件` button, or `/files` opens a
box over the frame holding the session's workspace tree. The keys are the
tree's own — `↑`/`↓` walk, `⏎`/`→` open, `⌫`/`←` go up a level, `r`
re-reads, `esc`/`q` close — and a click on a row is the same verb as
`⏎` on it.

The rail keeps two tabs: `←`/`→`, `shift+←`/`→`, `ctrl+1`, `ctrl+2` and
`/panel`-style verbs walk 最近 and 工作区 only. `PanelId::TABS` is the one
list they read, so 文件 cannot be stepped onto by accident.

The panel is scoped to the session, like the git browser: opening it
re-reads the directory, and `Live::refresh_local` re-scans the tree when
the conversation moves to another workspace, so switching conversations
never leaves yesterday's tree on screen.

The header paints its first pointer button — the app's `[key] label`
shape, dropped whole when the row is too narrow to keep the title beside
it — and the rows the box paints register their own hit regions, so the
same model serves the rail, the narrow-terminal panel and the box.

* feat(tui): the prompt is a full-width band again, not a bubble

Reverts the framed bubble (`cd8cd659a`) and its follow-up (`d380ca766`), which
had taken the frame off but kept the hug and the right alignment. What the
reader's own words want here is the plainest thing the surface can do: the
prompt on the transcript's left edge, its background running the full width of
the column, nothing drawn around it.

So `render_user_message` is one loop again — each markdown line as ` line`
filled to the column width — and the run state (`queued (#2)`, `cancelled`,
`merged into the previous run`) is a full-width dim row under it rather than a
row inside a box. The bubble's constants, its row painter, its width cap and
the geometry tests that pinned them go with it.

* feat(tui): buttons and drag in the picture preview, and sharp zoom

The preview box was keyboard-only: a reader with a mouse could zoom with the
wheel and nothing else, a picture could not be dragged, and stepping to the
next figure meant closing the box and finding the next row in the panel. And
the picture itself was decoded to 1024 px, so zooming past 2x showed an upscaled
guess rather than detail.

- The box opens with a control row: `[缩小] 2x [放大] [适应]` and
  `[上一张] 2/5 [下一张]`. Every control is a key the box already answered
  (`+`/`-`/`0`, `[`/`]`), routed through the same handler — the row exists so a
  pointer does not need the chords, not as a second implementation. A segment
  that would do nothing (the ends of the folder, the terminals that cannot place
  a bitmap) is drawn dim, so nothing looks live that is not.
- `[` and `]` step through the pictures of the folder the row was opened from,
  in the panel's own order; the list is read once when the box opens
  (`files::image_siblings`), and a folder with one picture offers no steps.
- Dragging the picture pans it, one cell per cell, clamped by the paint to the
  picture's own edge. The delta comes from the press cell, so a drop and re-grab
  never drifts.
- A preview is decoded to 2048 px now, which is what a zoom actually shows, while
  the bitmap transmitted to the terminal is downsampled to ten pixels per cell
  (`run::transmit_bitmap`): a 2048px photograph across a hundred cells does not
  ship fifteen megabytes over the pty to be scaled away on arrival.

Images in the conversation are not part of this change: the transcript renders
Markdown images as nothing today, so they need the message model, the shared
renderer and the transcript's hit map to carry a picture's path before a click
or `enter` can open it. That is the next step, not a flag away.

* fix(tasks): give a run with no answer a reason instead of `completed`

An hourly task run that produced no output left `status=completed` and an
empty summary, and a `session_retention=delete` task had already thrown the
conversation away — nothing said why, so the run could not be attributed at
all. The 2026-10-27 sweep lost a whole turn that way (dev was 24 commits
ahead of main with no open PR, and the ledger read "completed").

Two defects stacked up:

- `agent_bridge::stream` read `cancelled` and `interrupted_by_restart` as
  clean terminals. The Agent labels a run it cut off exactly that way, so a
  run the Agent host restarted under was recorded as a finished one. A
  terminal carrying an `error` was ignored too.
- `run_prepared_prompt_inner` marked the local run failed and then returned
  `Ok(())`, so the task executor saw success and read an empty answer out of
  the journal.

Now the fold maps every non-finishing state to its own termination kind,
headless callers are told about the failure, and the ledger records
`finish_reason` (`answer` / `empty_answer` / `cancelled` / `interrupted` /
`timeout` / `provider_error` / `error`) plus a one-line `finish_note` saying
how far the run got (answer size, last tool call). A blank answer is a
failure with `[EMPTY_ANSWER]`, not a completion with an empty string.
`future task runs --json` (and the phone's ledger view) expose both fields.

`future session wait` had the same silent success for delegated sub-sessions:
it printed nothing and exited 0 whether the child answered or was cut off.
It now names the run's ending and fails on anything but an answer.

Goal workers already read the Agent's raw terminal state and never claimed a
`completed` run it had not finished; their remaining gap (a completed-but-
empty turn counts as success for todos with no evidence contract) is left
alone here.

* feat(tui): one prefix for the shortcuts — ctrl only, no tmux collisions

Every default was either `ctrl+…` or `alt+…` depending on when it was added —
`ctrl+m` model beside `alt+m` mouse, `ctrl+r` sessions beside `alt+r` refresh —
and five of them were chords the terminal owns: `ctrl+m` is Enter without
modifier reporting, `ctrl+1/2/3` are not ctrl chords at all in a legacy
terminal, `ctrl+b` is tmux's prefix, `ctrl+v` is some terminals' paste, and
`alt` composes a character on macOS unless Option is set to Meta, which is the
terminal this surface is developed against.

Now every default is a `ctrl` chord (or an arrow with shift), and the map is the
fifteen letters that actually arrive: `ctrl+c` quit, `ctrl+n` new chat,
`ctrl+r` sessions, `ctrl+d` delete, `ctrl+x` stop, `ctrl+q` queue, `ctrl+e`
fold/unfold the process, `ctrl+p` commands, `ctrl+o` model, `ctrl+t` effort,
`ctrl+l` language, `ctrl+g` git, `ctrl+s` the rail, `ctrl+f` refresh, `ctrl+v`
paste.

The rest have no chord and keep a typed door instead: approval `/mode`,
workspaces `/workspace`, copy `/copy`, mouse capture `/mouse`, preferences
`/preferences`, the newest attachment `/preview` (new command), the files panel
`/files`, the rail's three panels (a click, or `shift+←`/`shift+→`), reduced
motion (the preferences row). The help overlay prints `—` in the key column for
those, the shortcut editor round-trips "no chord" as an empty override, and
moving a chord onto such an action takes it from its owner instead of
duplicating it.

Letters are excluded for stated reasons, documented on `default_key`: a terminal
sends Backspace/Tab/`\n`/Enter for `ctrl+h`/`i`/`j`/`m`; `ctrl+a` and `ctrl+b`
are the `screen` and `tmux` prefixes; `ctrl+z` is suspend; and
`ctrl+u`/`k`/`w`/`y` are the composer's own readline set, which a global chord
would shadow.

* feat(tui): the desktop's palette family in /theme

The TUI had six palettes while the desktop ships fourteen; the reader who
picks `tokyo-night` there had nothing comparable here. `/theme` now offers
22: the six the workbench already shipped, unchanged and still first, plus
the desktop's own family — `ayu`, `catppuccin`, `everforest`, `gruvbox`,
`kanagawa`, `nightfox`, `nord`, `rose-pine`, `solarized`, `tokyo-night`,
`vesper` — and `-light` renditions of catppuccin, everforest, gruvbox, rose
pine and solarized, because a TUI theme is one rendition and a light
terminal deserves more than two choices.

Each new palette exists twice, as the file layout requires: a 29-field
inline `Theme` (`tui/src/themes.rs`) and a workbench `Palette`
(`tui/src/workbench/theme.rs`), same id, same order, both next to the
existing six. Hues are nearest-match 256-colour approximations of
`desktop/src/theme/palettes.json` (the comments carry the source hex), so
the two apps read as one product; backgrounds are the desktop canvas stepped
one index for `panel`, `tool_*_bg` and the selection band, which is what a
full-screen surface needs and an inline one does not.

The tests that pin the catalogue move with it: the frozen id list, the
picker's window at 22 rows (a short terminal must still reach the last
entry), and a new frame test that renders every palette end to end — a
palette is data, and one that broke a row would otherwise only show up on
the reader's screen. The i18n guard gains the seven new multi-word names as
proper-noun exemptions (BUDGET 34 → 41).

Docs: the user guide, the workbench spec's theme item (the frozen colour
table stays as the contract for the original six) and the dsh parity table.

* docs(tui): the files panel's entry, in the words the ctrl-only map uses

The keymap redesign (`ctrl` only, `ctrl+1/2/3` retired) landed while the
files panel was being built, so a few sentences still described the old
entry: the spec promised `ctrl+3`, and its Chinese half promised `alt+t` —
a chord this branch had picked and the redesign ruled out. Neither is
back: the files panel keeps the doors it actually has, `/files` and the
header's 文件 button, and the shortcut editor still lists the action so a
reader who wants a chord can bind one. With every `ctrl` letter either
taken (15) or unusable (11: Backspace/Tab/newline/Enter, the screen and
tmux prefixes, suspend, and the composer's readline set) there is no
letter left to give it.

Its help row now says what it opens — "打开本会话的文件面板" — instead of a
bare 文件 sitting in a column of descriptions, which is the `HelpKeyFiles`
row the table already carried.

Also in this pass: the Chinese spec's Keyboard section is brought in line
with the English one the redesign rewrote (it still named `ctrl+b`,
`ctrl+m` and `alt+z`), the duplicated `shift+←`/`shift+→` row in the zh
key table is dropped, and the layout note over `layout_preferences` names
`ctrl+s`.

Tests: the help table and the shortcut editor print `—` for the chordless
rows and never `ctrl+1`/`ctrl+2`/`ctrl+3`.

* fix(tui): put the git panel's copy in the table and pin the preview box's protocol

The `tui-cli` job failed two ways on the same branch, both for real.

`i18n_guard` caught five hardcoded English sentences in `workbench/git_panel.rs`
— the panel is new and never reached `workbench/i18n.rs`. Three of them are the
panel's own words: a `git` that failed without a message, the empty-repository
case (reusing the existing "not a git repository" row), and the ref header's
`ahead N · behind N`. They are now `GitNoMessage`, `GitNoRepo` and
`GitAheadBehind`, drawn with `t` / `render` in the reader's language. The
`git show --format=` template behind a ref's tip is `GitTipFormat`: its
`Author:` / `Date:` labels are drawn, so it belongs to the table too. Only the
`does not have any commits` comparison — matched against git's own stderr and
never painted — is exempt, with an `// i18n:` marker and one BUDGET step
(34 → 35).

The two preview tests (`the_preview_box_controls_step_through_the_folder`,
`dragging_the_picture_pans_it`) asserted that a box drawn for a terminal with
the kitty protocol has zoom controls and a drag surface, but never said which
terminal that was: they read the process-global capability cache, which
`terminal_image`'s own tests leave at whatever they last set —
`render_image_iterm2` leaves Iterm2, `render_image_none_capabilities_returns_null`
leaves None — and which `the_preview_box_paints_the_picture_and_stays_in_the_frame`
overwrites twice mid-run. Outside a kitty/ghostty terminal (CI) detection
answers None by itself, so the pair fails every run there; inside one it fails
only when a sibling wins the race. `terminal_image::CapabilitiesGuard` gives
each such test an exclusive hold that installs its protocol and restores the
previous value on drop, and every test that touches the cache now goes through
it.

Measured: `cargo test -p future-tui --lib` with no kitty/ghostty in the
environment failed both tests before (2 of 2 runs), passes 1382 tests twice with
the guard; green in the developer's Ghostty env and with KITTY_WINDOW_ID=1 too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant