Skip to content

refactor(host): extract shared backend and unify headless in future CLI - #1259

Merged
tallcode merged 83 commits into
mainfrom
refactor/headless-unified
Oct 20, 2026
Merged

tallcode merged 83 commits into
mainfrom
refactor/headless-unified

Conversation

@tallcode

Copy link
Copy Markdown
Collaborator

Move the shared application backend out of Desktop into the ordinary, GUI-free future-host library. A separately installed future CLI now runs the full foreground host with future headless; the retired futureos-headless executable is no longer built, packaged, or launched.

The shared owner now contains storage/migrations, credentials and identity, Agent hosting and request ownership, application operations, Remote adapters, scheduling/observers and bounded shutdown. Desktop retains Tauri/window/IPC presentation; CLI owns arguments, terminal interaction, signals, exit codes and its runtime. Existing Future home paths, databases, pairing files, local control channel, Remote contracts and permission boundaries are preserved.

Build/release wiring uses the unified CLI for Desktop sidecars and CLI-only payloads. Existing headless make targets are compatibility aliases. Actual ELF/PE/Mach-O dependency and isolated startup probes are wired into packaging, with the old-Linux/static smoke retained. Shared real database/RPC/approval/sandbox/file/shutdown tests move to their owning library instead of duplicating the backend under Desktop.

Validation

  • Local pinned-toolchain cargo fmt --all --check and cargo clippy --workspace --all-targets --locked --offline -- -D warnings pass.
  • Desktop type-check and full TS/TSX ESLint pass; documentation checks pass for 297 documents with zero pending bilingual pairs. Python helper syntax and merged GUI/CLI dependency boundaries pass: no GUI closure in Host or CLI.
  • No local unit or NATS tests were run in this preparation pass. PR CI executes owner suites and real entry/process tests on native runners.
  • The preceding branch run 39389611663 passed Linux/macOS Host, Windows Host, GUI, CLI/TUI, Agent, Remote, Desktop/Mobile frontend and Windows installer fixtures. Its Windows native lifecycle failed: an incomplete HTTP request fixture and console QR encoding exception. This head fixes both without dropping suites/assertions; native revalidation is pending this PR's checks. The preceding run is not represented as an overall pass.
  • The user reported manual testing complete for the primary-workspace exploratory handoff a0d4d8402064dab1b82b0ad39bbd645837446236 and requested this PR. Per-case/platform evidence was not separately supplied; that report is not transferred to later commits.

Evidence and remaining acceptance

Development plan, original-test ownership inventory, PR preparation evidence, and manual record retain traceable phase/commit/run information. The immutable baseline tracks 2193 original declarations, with 1712 assigned to Host, 53 to CLI and 428 retaining entry ownership.

Actual release packaging/signing, real install/upgrade/uninstall, released-payload old-Linux/static checks, matched performance measurements and final same-candidate acceptance remain outstanding under the user's revised order. Optional matched observation tooling is provided but has not executed; no performance improvement is claimed. Opening/merging this PR does not mark the larger Goal complete.

# Conflicts:
#	docs/architecture/headless-package-development.md
#	docs/architecture/headless-package-development.zh-CN.md
@tallcode
tallcode enabled auto-merge (squash) October 20, 2026 08:16
@tallcode
tallcode merged commit a5f9175 into main Oct 20, 2026
20 checks passed
@tallcode
tallcode deleted the refactor/headless-unified branch October 20, 2026 10:48
huichen added a commit that referenced this pull request Oct 20, 2026
main extracted the shared backend into `host/` (#1259), so the control channel
and the status DTOs my `status` op landed in moved there, and the headless entry
moved into `cli`. Conflicts resolved by keeping both sides' intent:

- `desktop/src-tauri/src/remote/mod.rs` takes main's forwarding module; the
  switch helpers it used to hold now live in `host/src/remote/mod.rs`, where the
  control channel can reach them, and are `pub` so the Tauri command module can
  keep forwarding to the same functions instead of growing a second copy.
- `host/src/remote/control.rs`: the new ops survive; main's `AppError` ->
  `Error` rename applied to the arm beside them.
- `host/src/remote/types.rs`: `DeviceControl` is exported unconditionally, because
  the status projection (not only tests) reads it.
- `cli/src/headless/mod.rs`: the store moved with the backend, so the switch
  lookup reads `future_host::store`.
huichen added a commit that referenced this pull request Oct 20, 2026
…ocess (#1266)

`Supervisor::restart_slot` decides one of three things from the pairing book
alone: stop a device the book no longer holds, forget one whose credential cannot
be upgraded in place, refresh one it can. Each was covered only end to end,
through a child Desktop — the most expensive and least stable way to assert a
three-way match.

- `supervisor/start.rs`: the decision is split out as
  `recovery_plan(&[PairingCreds], &str) -> SlotRecovery`, a pure function with no
  broker, no platform and no child; `restart_slot` matches on it, and each arm
  keeps its own effect (`stop_slot`, `forget_slot`, the refresh round trip).
- `supervisor/reconnect_tests.rs`: the three decisions plus the file effect of
  `Forget` (the slot leaves the book, so a device that can never connect stops
  being retried on every start). No timing in any of them.

This ports the intent of `aeda36823` (which was written against the pre-#1259 tree
and could not be cherry-picked: `restart_slot` now lives in
`packages/remote-server/`, and its `desktop/`-side file is a 37-line forwarding
shell). The other half of that commit — gating the child tests 3 and 4
`macos`-only because their fixture raced the `Remote: Ready` printout — is
**deliberately not ported**: main already replaced that dependency, so both tests
now poll the broker's connect counter and the book file instead of a status line,
and gating them would drop Linux coverage for a race that no longer exists.

Verified: `cargo test -p future-remote-server --lib` 164 passed, 5 ignored;
`cargo clippy -p future-remote-server --all-targets -- -D warnings` clean;
`cargo check -p future-host` clean (the crate's only in-tree consumer of this
module); `cargo fmt --all --check` clean.
huichen added a commit that referenced this pull request Oct 21, 2026
…sting clippy, from #1259)

`DesktopExecutor::connection_options` built the value as
`let mut options = ConnectionOptions::default(); options.root_bundle = …`,
which `clippy::field_reassign_with_default` rejects. The lint never reached CI
because `host`'s `test-support` feature adds a private `loopback_fixture` field:
the feature is enabled for the whole graph in the workspace-wide pass (the `cli`
and `desktop` dev-dependencies enable it), and with it on the
`for_loopback_fixture` shadowing moves the value, which the lint does not look
through. With the feature off — `cargo clippy -p future-host --lib` — it fired.

Neither struct-literal form works for both configurations: with `test-support` a
private field makes the literal (and the `..Default::default()` update syntax)
unconstructible from another crate, and without it the same single-field literal
is `needless_update`. So `ConnectionOptions` gains `with_root_bundle`, symmetric
with the existing `for_loopback_fixture`, and the caller chains both.

Behaviour is unchanged: both feature configurations produce the same value, and
the fixture path still goes through `for_loopback_fixture()`.

Verified:
- `cargo clippy -p future-host --lib -- -D warnings` (feature off, the red case): green
- `cargo clippy -p future-host --lib --features test-support -- -D warnings`: green
- `cargo clippy --workspace --all-targets -- -D warnings`: green
- `cargo clippy -p future-remote-server --lib`, `-p future-remote-client --lib`: green
- `cargo fmt --all --check`: clean
- `cargo test -p future-host --lib remote`: 553 passed
huichen added a commit that referenced this pull request Oct 21, 2026
…rminal (#1288)

* fix(rpc): a deep FUTURE_HOME gets a short endpoint, and says so when it cannot

A `FUTURE_HOME` longer than 88 bytes (macOS; 92 on Linux) could not start an Agent
at all. The endpoint is `<home>/run/agent.sock`, and `sun_path` holds 104 bytes
there, so startup died at "binding the gRPC endpoint" with the message
`path must be shorter than SUN_LEN` — which names neither the setting nor a way
out. Measured with `UnixListener::bind` at 103/104/106 bytes: `InvalidInput`,
`raw_os_error=None` (std refuses before the kernel), so this is neither `EPERM`
nor `ENAMETOOLONG`. This is not a rare shape: the repo's own
`.worktrees/<name>/target/test-homes/...` reaches 106 bytes.

C — a short endpoint, only where the old one cannot exist:

- The path is computed as before; it is relocated only when it does not fit the
  103-byte limit. Every home that can bind keeps exactly the layout it had, byte
  for byte (`a_home_that_fits_keeps_the_layout_unchanged`).
- The fallback is `/tmp/future-<uid>/<hash16>.sock`, recomputable from
  `(uid, wanted)` with no randomness or timestamp, so two processes deriving it
  independently get the same string (`a_home_too_deep_gets_a_recomputable_short_endpoint`).
- `/tmp`, never `$TMPDIR`: on macOS `$TMPDIR` is per-session, so a launchd-hosted
  Agent and a terminal client could compute two different endpoints for one home.
  `/tmp` is spelled the same way by both (it is a symlink to `/private/tmp`;
  neither side resolves it). Measured: three different `TMPDIR` values all yield
  `unix:///tmp/future-501/3913bf89c6031845.sock`.
- An explicit `FUTURE_AGENT_SOCKET` is used verbatim and never relocated: silently
  moving a path somebody named by hand is worse than letting bind refuse it.
- Compatibility is structural rather than a probe: the homes that get relocated
  are exactly the ones the previous release could not bind, so no old Agent can be
  serving there. A home that fits keeps the old path, so an old Agent still
  serving it is found as before.

Anti-squatting, because `/tmp` is world-writable: `/tmp/future-<uid>` is checked
with `lstat` — not a symlink, a directory, owned by our uid, mode 0700 — and any
failure refuses startup with the reason instead of repairing it (`chmod`-ing
somebody else's directory is the attack, not the fix). Verified live: a
pre-created symlink and a 0755 directory are both refused with actionable text
("remove it…" / "run `chmod 700 …`"), and a normal 0700 directory still serves.
The check runs in `LocalEndpointReservation::acquire`, which is the path the Agent
actually takes — the first attempt put it only in `bind_local_at` and every case
passed, because that function was never reached.

E — the message: an endpoint that still cannot fit reports its byte count, the
limit, and two ways out (shorten `FUTURE_HOME`, or set `FUTURE_AGENT_SOCKET`).

Verified end to end with a 103-byte home (old endpoint 118 bytes, so the previous
build could not bind it): the Agent listens on
`unix:///tmp/future-501/3913bf89c6031845.sock`, `future session list` against that
home answers, and the directory is `drwx------`. Unit tests cover the limit
boundary, the unchanged short-home layout, the verbatim explicit override,
recomputability, per-home distinctness, and each squatting refusal; rpc 221 pass,
agent 2479 pass, fmt and clippy clean.

Reverting this means restoring the two lines in `local_socket_path_from`.
**Stop any Agent running on the new layout first**: an old binary looks only at
the in-home path, so it would find the lock held with no visible endpoint and
report a failure that looks like the revert itself broke something.

* feat(tui): host the Agent in-process, and stop it on exit

The TUI now runs the Agent in its own process, the way `future headless` and the
desktop do. The Agent is no longer a child of the terminal, which removes the
whole class of problems a child brought: a terminal signal killing the Agent, a
zombie holding the endpoint, pipes that had to be drained so a chatty child never
blocked, output that had to be quoted back in a failure report, and — the reason
this matters most — the Agent dying whenever the terminal window closed while
another client was relying on it.

What replaced the sidecar:

- `tui/src/agent_host.rs` installs this entry point's Agent driver, shaped like
  the headless entry's (a short-lived probe runtime, dropped before the service
  gets one of its own), and starts the service through `future_host`'s process
  global host.
- `agent_supervisor` keeps the policy and loses the process plumbing: attach,
  wait for whichever process holds the lock (bounded, and it says so), start in
  process, and rate-limit its own restarts. Every one of those decisions still
  comes from `future_rpc::supervision`, so the three entry points answer "who owns
  the Agent" identically.
- The exit path stops an Agent this TUI owns, within a bound, on all three ways
  out (interactive, print mode, `--list-models`). An owned Agent holds the
  instance lock and the data-directory database; leaving that to process teardown
  would make the next start report a lock it cannot explain.

`future-tui` standalone stays attach-only, and now says why in one place: the
Agent re-runs its own executable as the Linux sandbox helper
(`--linux-sandbox-helper`) and puts that executable's directory on `PATH` for
shell tools, and only the unified `future` binary dispatches that flag. Hosting
from the standalone binary would break sandboxed shell commands, so it refuses
with the reason and the way out instead.

Verified with a release build in isolated homes: a clean home starts the Agent
inside the TUI (log shows `embedded Agent ready`, `Agent host finished owned=true`),
the instance lock is held by the TUI process itself rather than a child, and the
lock is released after the TUI exits. The standalone `future-tui` on an empty home
refuses with the sandbox-helper explanation and creates no lock; with an Agent
already serving it attaches and answers (`--version`, print mode) while the lock
holder stays the same process.

Removed with the sidecar: `agent_sidecar_launch.rs` and `agent_sidecar_readiness.rs`
(they existed to make the child's failure reporting observable), and the comments
in two other tests that referred to that launch path. `future-tui` 2231 lib tests
and its integration targets pass; `cargo fmt --check` and clippy for the crate are
clean.

Not changed, and outside this commit: `host/src/remote/supervisor/state.rs` fails
`clippy -D warnings` (`field_reassign_with_default`) at this branch's base commit
`7590cbef5`, from PR #1283. It is not touched here, and it is the reason the
workspace-wide clippy pass is red independently of this work.

* fix(agent): continue every interrupted conversation, oldest first, with a real concurrency bound

The pass took the first three of `list_all`, which orders by `updated_at`
descending. That starved the tail rather than merely capping work: the three most
recently touched conversations are exactly the ones a user is working in, and so
the ones the next restart is most likely to cut off again. They took the whole
budget on every pass, and older interrupts waited until those three went quiet.
The log looked healthy every time — "checked N, continued 3" said nothing about
the debt.

Now every eligible conversation is taken, ordered by **oldest interruption
first**, so the queue drains on the first pass. What bounds the work is
concurrency, not a quota: at most `MAX_IN_FLIGHT` (3) submissions are in flight
and the rest queue behind them. That bound has to be ours — the Agent has no
cross-session limiter (`GlobalQueueBudget` caps queue depth and bytes, not running
sessions), so without it a restart after an outage would fire one model request
per interrupted conversation at once.

The log now reports the account instead of only the work:
`N checked, M interrupted and eligible, X continued (at most 3 at a time),
K skipped (older than 7 days, sub-session, streaming, awaiting approval, or no
model)`.

Tests (and what each would have missed):

- `candidates_are_taken_oldest_interruption_first` drives the shipped
  `candidates_in_order`. The first version re-sorted the fixture itself and passed
  even with the implementation inverted; reworked, it fails with
  `left: ["newest", …], right: ["oldest", …]` when the sort is turned back to
  newest-first.
- `at_most_max_in_flight_continuations_run_at_once` runs the same refill-on-free
  loop over 10 tasks and asserts the peak against a literal 3, not against the
  constant — comparing the peak with `MAX_IN_FLIGHT` would pass for any value,
  including one big enough to fire everything at once. Raising the bound to 10
  fails it with "saw 10".
- `every_eligible_conversation_is_taken_not_just_the_first_few` pins that all ten
  candidates are taken and that the bound is below the queue size, so the other
  two tests mean something.
- `only_fresh_top_level_sessions_are_candidates` covers the cheap filter (age,
  sub-session).

Both falsifications were run and then reverted. `MAX_AGE` and
`run_loop.rs`'s assistant-tail guard are untouched (the latter is the separate
D10 change). `future-agent` 2483 lib tests pass; clippy clean.

* fix(remote-server): build ConnectionOptions through a setter (pre-existing clippy, from #1259)

`DesktopExecutor::connection_options` built the value as
`let mut options = ConnectionOptions::default(); options.root_bundle = …`,
which `clippy::field_reassign_with_default` rejects. The lint never reached CI
because `host`'s `test-support` feature adds a private `loopback_fixture` field:
the feature is enabled for the whole graph in the workspace-wide pass (the `cli`
and `desktop` dev-dependencies enable it), and with it on the
`for_loopback_fixture` shadowing moves the value, which the lint does not look
through. With the feature off — `cargo clippy -p future-host --lib` — it fired.

Neither struct-literal form works for both configurations: with `test-support` a
private field makes the literal (and the `..Default::default()` update syntax)
unconstructible from another crate, and without it the same single-field literal
is `needless_update`. So `ConnectionOptions` gains `with_root_bundle`, symmetric
with the existing `for_loopback_fixture`, and the caller chains both.

Behaviour is unchanged: both feature configurations produce the same value, and
the fixture path still goes through `for_loopback_fixture()`.

Verified:
- `cargo clippy -p future-host --lib -- -D warnings` (feature off, the red case): green
- `cargo clippy -p future-host --lib --features test-support -- -D warnings`: green
- `cargo clippy --workspace --all-targets -- -D warnings`: green
- `cargo clippy -p future-remote-server --lib`, `-p future-remote-client --lib`: green
- `cargo fmt --all --check`: clean
- `cargo test -p future-host --lib remote`: 553 passed

* feat(cli): pair and manage remote desktops from the terminal

\uture remote peers\ is the client role, the mirror of \uture remote
devices\: the machines this one connects out to.

  future remote peers [list] [--json]
  future remote peers add <invitation> [--json]
  future remote peers connect|disconnect <id|#> [--json]
  future remote peers rename <id|#> <name|--clear> [--json]
  future remote peers remove <id|#> [--yes] [--json]

add runs in the CLI rather than in the Desktop: a pairing is a one-time claim
plus a Noise handshake and needs nothing local to be serving, so a machine can
be paired before its Desktop is opened. It stores the credential in
~/.future/remote_peers.json and connects once, so a pairing that does not work
is reported now.

list reads that book; connect, disconnect and remove ask the running Desktop
through the same request/reply channel \uture remote devices\ uses, because a
live connection and the user's own stopped mark live in that process and
nowhere on disk. The host side gained peer-state, peer-connect,
peer-disconnect and peer-remove (a peer is named by desktopId, not pairId) and
answers each with the list as it stands afterwards.

Docs: desktop-headless gains a client-role section (en + zh), and the
directory layout now lists remote_peers.json.

* feat(agent): continue an interrupted run without a user message

D10 step 1 of 3. Restart recovery used to continue an interrupted
conversation by submitting a prompt, which lands in the transcript as a
user message nobody typed. This adds an accepting path that continues the
run in place: the journal gets the new run's `run_started` marker (with
`auto_resume_of` naming the interrupted run), and the run goes through
accept-before-mutate, the run lease and the broadcaster like any other.
The model receives the explanation as request-only context that never
enters the transcript or the event stream — no `user_message` event, no
user entry, no bubble for a client to draw.

The journal is the permission: `continue_interrupted_run` re-reads
`unterminated_run_id` at the accepting call and refuses anything else, so
`ResumeContext` can only be set from a run the session's own journal still
shows as open.

This step covers the tail shape that needs no repair — a tool result, which
is already a valid request. The assistant-tail guard is untouched, and a
call whose result never arrived is not answered yet.

Both shapes coexist: when continuing in place is refused (a journal that
proves nothing, a provider that cannot take the tail), the pass logs why
and falls back to the prompt it used before.

* feat(agent): answer a crashed tool call before continuing the run

D10 step 2 of 3. A run that died between issuing a tool call and recording
its result leaves a transcript that ends on `tool_calls` with nothing
answering it, and every provider rejects that request with HTTP 400. The
continuation now pairs those calls with a placeholder result first, then
appends the directive, so the request is valid.

The placeholder says the outcome is *unknown*, not that the tool did not
run. The process died in between, so nobody knows; "not executed" is the
one guess that invites the model to repeat a side effect that may already
have landed. The load-time repair, which writes the same placeholder into
a loaded session, said "was not executed" — it now shares this wording, so
a model reads the same story whichever path assembled the request.

The guard has to distinguish this tail from the one it exists to catch: an
assistant turn carrying unanswered tool calls is repairable, a turn that
stops on assistant text is not. Only the resuming path is allowed the
former, and a plain assistant tail is still refused.

* feat(agent): accept an assistant tail when the journal proves the run is open

D10 step 3 of 3. A run that died while the model was writing its answer
leaves the transcript on an assistant turn, which the loop refused outright
— and that is the most common tail a crash leaves. The continuation now
accepts it, appends the request-only directive and continues.

The relaxation is not "an assistant tail is allowed". `ResumeContext` is
the only way in, and it is built by `continue_interrupted_run`, which
re-reads `unterminated_run_id` at the accepting call: an assistant tail the
session's own journal cannot prove is a still-open run is refused exactly
as before. `run_rejects_assistant_last_message` keeps that boundary, and
`a_continuation_is_refused_when_the_journal_proves_no_open_run` covers the
same edge from the accepting side.

The model's interrupted turn is never deleted from the transcript — it was
produced, it is history, and the continuation only adds to the tail.

* docs(agent): D10 is landed, in three steps

The design section said the plan was fixed but the implementation had not
started, and the decision table listed D10 as an adopted plan awaiting a
separate task. Both are now wrong in the other direction. Update them, and
record one thing the plan got wrong: a turn carrying unanswered tool calls
is itself an assistant tail, so the guard needed an intermediate shape
before the plain-assistant step, and the relaxation has to be conditioned
on the journal rather than on the tail's role.
huichen added a commit that referenced this pull request Nov 3, 2026
The remote sync measurement harness moved from Desktop into future-host in
#1259, where the Agent channel runtime and the app store became entry-owned.
A lib test is now the entry, so serve_real_snapshot answered every business
command with " Entry must configure the Agent channel runtime before starting
huichen added a commit that referenced this pull request Nov 3, 2026
… journal fixes (#1485)

* docs(macos): record the Intel PREFIX trap, bare-binary install and release artifacts

* docs(macos): mirror the macOS install notes on the English side

* fix(agent): close a reasoning display once, so a retry cannot poison the journal

A model stream that runs out before its terminal frame is closed by the
provider layer (`finish_stream` emits `ReasoningEnd`/`TextEnd`), and the
stream-retry path then closed the same reasoning display again. The duplicate
reached the durable journal as a *new* block at offset zero under an identity
that already holds the first attempt's bytes:

    {message}:thinking:{block_id}

with `block_id` a fixed per-stream name (`reasoning`), so the second close
sealed an empty body over durable content. The journal refuses that
contradiction, and because the refusal is not a per-event one it marked the
session's journal unhealthy — which makes `run_snapshot`, and therefore
`get_events_since`, fail for the rest of the process's life. On the phone that
is a conversation whose transcript never finishes syncing, retrying forever.

Measured on this machine (2026-11-03): four sessions went unhealthy, every one
of them immediately after "LLM stream disconnected; reconnecting", and the
desktop logged `get_events_since` failing on each for hours afterwards.

- The retry closes only displays still open, and records that it closed them.
- The broadcaster drops a repeated close for a block this message already
  sealed instead of opening an empty block over it, so a duplicate close from
  any other producer stays a no-op rather than a refused batch.

Tests: a scripted disconnect either side of the provider layer's close, and
the content-sequence duplicate-close case.

* fix(agent): drop a refused canonical event instead of wedging the session

A canonical batch whose content conflicts with what is already durable (a gap, a divergent retry, a seal whose digest disagrees with the bytes) fails identically on every retry. The writer classified it as a storage failure, so the poisoned batch was kept and every later batch queued behind it failed too: the run went persistence_degraded, every cancel was a no-op because the terminal it must commit goes through the same journal, and nothing short of an agent restart released it. Four conversations on this machine were wedged that way in one hour.

The journal already has the right contract for a refusal - name it, drop that one event, keep the session writable - but only the raw journal path ever produced one. The canonical writer now reports a non-storage failure as that permanent refusal, and the per-event retry goes back through the semantic writer it just used (a canonical conversation's raw append refuses everything, so the old retry would have dropped the whole batch). A durable event the journal refuses is no longer recorded as a session-wide outage either.

* feat(desktop): a message queued while a reply streams is the Agent's own

The composer used to hold a send during a streaming reply in an in-memory queue and flush it once the run settled, so the message only existed in the window that wrote it: closing the window or losing the renderer lost it, and no other client on the conversation could see it waiting. It now leaves immediately with busy_policy enqueue_coalescing, which the host forwards to the Agent's scheduler: the Agent holds the prompt in the session's own queue, a burst folds into one turn at the run boundary (the join the client used to do), and get_state's queuedRuns is where every client reads it from. A queued ack already returns as run_queued, which the send pipeline reads as 'accepted and alive'; the queued send deliberately runs outside the one-send-at-a-time lock, since the run it waits behind is the one holding it.

* feat(desktop): the waiting rows are the Agent's, and can be taken back

Sending while a reply streams now leaves the message with the Agent, so the panel that used to mirror a client-side queue has to read the queue back: useAgentQueue reads session_queue (get_state's queuedRuns) and polls only while a run is in flight or rows are waiting. Removing a row cancels it on the Agent by run id; editing cancels and sends the corrected text again (there is no update-in-place command); a row the Agent parked as stale gets the start-now control, which the client-side queues of a paired computer never show.

* feat(desktop): say so when a reply's live preview cannot read its events

The live reply is a projection of the run's journal, read once per pushed
update. When those reads stop succeeding the bubble keeps the last projection
it built and simply never grows again — on 2026-11-03 that was
`get_events_since` failing with a refused event batch for minutes while the
run kept streaming, and the reader was left looking at reasoning frozen on
"The" with nothing on screen to explain it. The only trace was a console
warning.

The note is presentation only: it never touches the reattach path, the retry
cadence or the event read itself, and it disappears on the first successful
read (the field is cleared where the projection is written).

- Sustained, not a blip: the streak is measured from the first failure after
  the last success and must span `PREVIEW_STALL_AFTER_MS` (5 s ≈ 50 of the
  100 ms coalesced live ticks). A single racy read recovers on the next tick,
  well inside that window, so a thread switch or a reattach stays silent.
  Anchoring on failures rather than a wall clock also keeps a legitimately
  quiet run (no pushes, nothing being attempted) out of it.
- `stage` and the raw reason ride the error from where they happened
  (`read` vs `projection`), so opening the note names the stage, the streak
  length and the diagnostic instead of "something went wrong".
- A preview that gave up rebuilding this run's log is covered too: those ticks
  return before reading anything, so without recording that verdict the
  frozen-forever case would stay the one case with no note.
- Never an error, never a popup, never interrupts input: one muted line in the
  reply's footer, collapsed by default, and only ever on a streaming reply.

Tests: the threshold (silent at 4 999 ms, speaking at 5 000 ms), a single
failed read staying silent, recovery withdrawing the note, the give-up path
naming `projection` without adding reads, a reset dropping an earlier note,
and a render test asserting the collapsed label, the expanded stage/reason,
its disappearance on recovery and on a settled reply.

* fix(host): wire the sync measurement probe's entry-owned runtimes

The remote sync measurement harness moved from Desktop into future-host in
#1259, where the Agent channel runtime and the app store became entry-owned.
A lib test is now the entry, so serve_real_snapshot answered every business
command with " Entry must configure the Agent channel runtime before starting

* fix(desktop): show the session's approval tier in the composer badge

The badge rendered the app-wide `approvalTier` default, but the gate that
decides whether a tool call stops for approval is the agent session's own
policy. A session another client created or drives (a CLI `future session set
--sandbox manual`, another agent) keeps that tier, so the composer advertised
完全访问 while every shell command still asked — the badge was describing a
different session than the one on screen.

Read the tier the agent already reports: `get_state`'s `sandboxTier` was in the
payload and never parsed, and `sandbox_policy_changed` was not forwarded to the
webview, so a change made anywhere never repainted it. Both are wired now.

When the session reports no tier (it never chose one, the agent is older, or the
first state read has not landed) the badge says 按会话 / Per session. It does not
fall back to the default: that fallback is the very claim this fixes.

Display only. No approval decision changes and no write to a session's policy; a
picker change still reaches sessions exactly the way it always did.

* feat(desktop): hold a remote conversation's send queue in its session

A send made while a paired computer's reply streams used to wait in this
window's memory (`remoteSendQueue`) and be flushed as one joined message when the
host reported the run over. That copy could only ever be a guess: it died with
the window, no other client of that conversation (the phone, the host's own
screen) could see it, and a `session_busy` refusal had to be ridden out by a
client-side retry loop.

The prompt command already carries what a send means while the session is busy,
so the queue moves to the side that runs it:

* `promptRemoteConversation` passes `busyPolicy` through, and `sendRemotePrompt`
  keeps it on the durable outbox entry so a delivery retried after a reconnect
  still means what the reader asked for.
* A draft sent behind a streaming reply now goes out immediately with
  `enqueue_coalescing`. The session holds the row on its own receipt and folds
  the consecutive ones into a single turn — exactly the "send the queue as one
  message" behaviour this client used to implement itself.
* The panel reads that session's queue (`get_queue`, via `useRemoteQueue`) and
  its controls are the host's commands: remove = `cancel_queued_run`,
  edit = cancel then re-send (the host has no "change this row"), and a parked
  row offers "send this one now" = `release_queued_run`. Nothing waits in this
  app's memory or localStorage.
* Queueing is still not interrupting: the menu keeps both answers, but the
  interrupt now happens *after* the message was handed over and only if the host
  took it, so a refused send keeps both the draft and the reply.

Removed with the client-side queue: `remote-peer/sendQueue.ts`,
`remote-peer/queueDelivery.ts` (the retry loop whose rules belonged to that
flush) and `lib/sendQueue.ts` with its test — its last consumer was the remote
store, because the local GUI path already queues in the Agent. The phone keeps
its own copy until that path is migrated.

* feat(mobile): a queued send is the session's, not this phone's

A message written while a reply streams is now handed to the desktop at once
with a busy policy (`enqueue_coalescing`) instead of being held in the phone's
memory and AsyncStorage. The session keeps it on a durable receipt and runs it
at the turn boundary, so the queue is the conversation's own list: the same rows
the desktop's window shows, still there after this app is gone, and visible to
every device on the conversation. A queue kept here could only ever be a guess
about a conversation that lives on a paired machine — and an uninstall took it
with it.

The panel therefore reads `get_queue` (the host's `session_queue_snapshot`) and
its verbs are the session's: delete cancels that run id, edit takes the row back
and sends the new words (a queued prompt has no editable text on the session),
and a row the session parked offers "send this one now" as a release. Acting on
a row re-reads the panel whatever the answer was, so a row leaves when the
session says it left. Rows are kept with the session they were read for, and the
panel polls only while a run can still fill it or rows are waiting.

Deleted with the client-side queue: `features/chat/sendQueue.ts`,
`sendQueuePersistence.ts` (AsyncStorage), `queueDelivery.ts` (the four delivery
rules the retry loop needed) and `lib/sendQueue.ts`, plus their tests. The
composer's send slot no longer refuses a running reply: it offers "hand it to
the session" or "interrupt and send", and keyboard submit sends the same way.
"Stop and send the queue" is gone — the session starts waiting rows itself.

A refused send is still told to the reader rather than dropped: the phone adds
the policy only when it reads the reply as streaming, so a stale `false` leaves
the desktop's own `session_busy` refusal, which the toast already maps to a
sentence.

* docs(desktop): every client queues on the session, not in itself

The remote view and the phone now hand a queued message to the session that runs it and read the waiting rows back from that host, so the product description no longer says those two keep their own copies (memory / local storage).

* fix(queue): say what became of a row that left the session's queue

Two review defects on the queue that moved from the clients into the session.

D1 — a queued row that never ran disappeared without a word. Both readers
(`desktop/src/features/remote-peer/remoteQueue.ts` and
`mobile/src/remote/sessionQueue.ts`) parsed only `get_state`'s `queued` and
dropped `recentTerminalAcks`, so a row folded into the turn ahead (`merged`),
taken back on another device (`cancelled`), replaced (`superseded`) or lost with
a deleted conversation (`session_deleted`) simply vanished, and the reader
believed the message had been sent.

Both now read the acks and say one sentence about the newest one, plus a count
when a burst left together. The sentence is drawn outside the panel, because it
matters most once the panel is empty; it is said once (an ack that stays inside
the host's window is not repeated on every poll), it does not greet the reader
with acks that predate the view, and it is not shown for a row this window
cancelled itself (`forget`). The same defect existed on the desktop's local path
(`agentQueue.ts`) and is fixed the same way.

D2 — editing a waiting row re-sends `attachments: []`, and the panel claimed
`attachmentCount: 0` for rows whose files it never saw. The queue wire carries a
message's text and acceptance time only (`QueuedRunState` has no attachment
field, and adding one is a proto + agent change this task does not span), so the
count is now reported as unreported rather than zero, and the editor states the
trade where it is made: saving sends the new text only, and the files that
message was sent with do not come back. A files-only row offers no edit at all —
there is nothing to correct, and an empty save is a removal the bin beside it
already performs.

If a re-send is refused after the cancel, the corrected words go back into the
composer (desktop remote and phone) instead of being lost along with the row;
the local desktop path keeps them in the failed bubble its send pipeline writes.

Targeted checks: desktop `tsc --noEmit`, `vitest run src/features/agent
src/features/remote-peer src/i18n`, `eslint` on the touched files; mobile
`npm run typecheck`, `jest src/features/chat src/remote src/i18n`, `eslint` on
the touched files.

* fix(agent): keep a dead storage worker a storage failure

The canonical writer classifies a failed batch by type: a `rusqlite` or `io`
error in the chain is a storage failure a retry can clear, anything else is the
journal's permanent refusal of that one event. A storage lane whose worker has
died reports its own message instead ("SQLite worker is unavailable"), which
matched neither, so a dead database was read as a bad batch: the writer dropped
a durable event and shutdown reported the journal as cleanly flushed next to
the storage stage's real failure.

The lane's own availability errors are now the typed `StorageUnavailable` and
`refusal_unless_storage` counts them as storage. Verified by removing only that
clause: `a_dead_storage_worker_stays_retryable` and the service-level
`a_dead_storage_worker_is_reported_by_the_journal_and_storage_stages` both go
red with the reported symptom, and green with it restored.

Also repairs two encoding accidents in `content/journal.rs` from 30673f1: a
UTF-8 BOM on the first line and a mangled em dash in the `persist` doc comment.

* perf(agent,host): page a run's replay by cursor instead of reading the whole run

Two reads answered a page by building the whole answer first.

The agent's replay read used ORDER BY epoch,idx over a unique index that orders
(session_id,run_id,idx,epoch), so SQLite applied the idx> range there and then
sorted every matching row: a 1001-event page of a 136k-event run cost 23 ms of
database work and touched all 136k rows. Adding the epoch-major index alone
changed nothing (EXPLAIN still planned the temp b-tree), and INDEXED BY would
have made a near-tail cursor 10x worse (16.8 ms vs 1.7 ms). So the read walks
epochs in ascending order instead: per-epoch idx > ? is a real index range,
which returns the same rows in the same order by construction. Measured 1.0 ms
against 20.4 ms for the same page, and 0.07 ms for a 20-event page.

The host only paged when offset was 0; every continuation page re-read the run
from since=-1 and then trimmed, so page 2 cost a full replay (16.2 s for 136k
events) whatever the offset was. A continuation page is now a cursor read from
offset-1, with the envelope's offset/nextOffset/total preserved so the client
still advances, and a fallback to the old read whenever the first event is not
the offset asked for.

A/B on one isolated 997k-event home, debug build, same requests: continuation
pages 16.2 s -> 127 ms (offset 1000), 13.4 s -> 121 ms (offset 5000),
16.0 s -> 5.7 ms (tail), 23.8 s -> 5.5 ms; 24/24 event replies byte-identical.
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