Skip to content

refactor(packages,tui,host,agent): share config io and the TLS provider; name the writer - #1415

Merged
huichen merged 5 commits into
mainfrom
pr/huichen
Oct 29, 2026
Merged

huichen merged 5 commits into
mainfrom
pr/huichen

Conversation

@huichen

@huichen huichen commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

What and why

The TUI depended on future-host for three calls and on future-tasks for nothing at all, so cargo test -p future-tui linked the whole application backend — Agent, the remote stack, bundled SQLite — to reach one TLS install and two config-file helpers (cargo tree -p future-tui: 318 crates → 180). This branch extracts that shared plumbing into two small packages and, on top of it, stops the session database's fence reads from waiting on whoever holds the writer.

Commits

  • refactor(packages,tui,host,agent): share config io and the TLS provider
  • fix(agent,host): name what holds the writer, and take the fence reads off it
  • chore(agent): drop a scratch file that rode along with the commit

Verification

Run locally at 3d8706b62 (and at 00ed828b5 for the refactor commit) with rustc/clippy 1.99.1 and ulimit -n 8192:

  • cargo fmt --all -- --check → clean
  • cargo clippy -p future-config -p future-http -p future-host -p future-agent -p future-tui --all-targets -- -D warnings → clean
  • cargo test -p future-tui --lib → 1510 passed / 3 ignored
  • cargo test -p future-config → 7 passed; cargo test -p future-http → tests/http_client.rs 1 passed
  • cargo test -p future-agent --lib → 2740 passed, 1 failed: session::persistence::tests::recovery_is_ordered_after_already_accepted_appends (Result::unwrap() on Timeout, agent/src/session/persistence.rs:1577). That file is not in this diff, the same test has failed under parallel load on earlier branches, and it passes alone at this tip in 0.33 s — a parallel-load flake, not a regression.
  • cargo test -p future-agent --lib -- session::database session::content presence → 58 passed / 1 ignored
  • cargo test -p future-host --lib -- agent_bridge → 391 passed; -- config_io → 4 passed
  • The full future-host --lib suite was not run locally (its remote-peer tests run for many minutes); CI covers it.

Notes

  • Two new workspace members: packages/config (future-config, strict read + atomic write for the hand-editable JSON under ~/.future/) and packages/http (future-http, the HTTP entry points and the process-wide TLS provider decision). make test-config / test-http are added and wired into make test.
  • future_agent::http re-exports the new entry points, so existing callers keep their import paths and Ring is still chosen in one place.
  • The TUI drops its future-host and future-tasks dependencies and reaches ~/.future/tui/settings.json through the shared primitives.
  • docs/architecture/packages.md (and the Chinese copy) list both packages.

The TUI depended on `future-host` for three calls and on `future-tasks` for
nothing at all, so `cargo test -p future-tui` linked the whole application
backend — Agent, remote stack, bundled SQLite — to reach one TLS install and
two config-file helpers. `cargo tree -p future-tui`: 318 crates → 180.

- `packages/config` (`future-config`) owns the strict-read + atomic-write
  primitives. The host keeps its `Error` boundary and the lenient-read /
  snapshot / rollback helpers it alone uses; the TUI reads and writes
  `~/.future/tui/settings.json` through the shared primitives.
- `packages/http` (`future-http`) owns the HTTP entry points and the
  process-wide TLS provider decision. `future_agent::http` re-exports them, so
  every existing caller keeps its path and Ring is chosen in one place.
- The TUI drops `future-host` and `future-tasks`, plus the stale comment that
  claimed `install_rustls_provider` was its only use of the host.
… off it

A remote command that times out says only that the *caller* waited. The lane
that made it wait had no record at all, so "agent slow" could not be closed:
a job that ran for 38 s, a process that was descheduled, and a lock held by the
checkpoint all looked identical from the desktop log.

1. Name the job. Every writer job may now declare itself (`call_as`), and a job
   that holds the ordered writer for >=1 s writes one row:

     storage job slow: job=commit elapsed=38120ms queued=0ms

   `elapsed` and `queued` are deliberately both present: a long `elapsed` names
   a job that must be split, a long `queued` with a short `elapsed` names a
   process that was not running (sleep, app-nap, paging) or a lane held by an
   earlier job. The cut is the same 1 s the command-side diagnostics use
   (`SLOW_COMMAND_MS`), so the two files can be read against each other. The
   idle reclaim slice and the checkpoint are timed the same way, which is what
   separates them from a writer job: the checkpoint has its own thread and
   never joins the writer's queue.

2. Shrink what holds it, without touching an atomicity contract. The compaction
   pass read its source row and each event page on the writer; those are pure
   reads, so they moved to the read lane and the writer now only publishes and
   retires. The remaining long jobs were already bounded by construction
   (reclaim slices stop at 10 ms, `content::reclaim` works in LIMIT 16/64
   steps, compaction pages by COMPACTION_PAGE_EVENT_LIMIT, legacy import commits
   per session). `delete_many` and `prune_events` are single transactions on
   purpose — splitting them would change what a failed delete leaves behind —
   so they stay as they are and the new row will say so.

3. Take the fence off the writer. `session_presence` is the first RPC of every
   remote content command, and it was read on the ordered writer because that
   was the only connection when it was written (2026-10-18, #1186): measured on
   2026-10-29, four commands released together after 18–21 s because one writer
   job was running, and two had already hit their 30 s deadline. It now runs on
   its own fence connection — not the writer, not the two-worker read pool, so
   neither a long write nor a large history page can delay it. The connection is
   opened on first use, so a process that never fences carries no extra fd.

   The trade is ordering, not freshness: a fence sees every committed write but
   not one still queued. That is why the desktop now asks once more (150 ms)
   before treating `missing` as fact — `deleted` and `import_failed` are
   verdicts and are never re-asked. Identity stays read live; it is two indexed
   rows, and a cache would only be another thing to invalidate.

4. The rest of the read-only queries that were still queued on the writer:
   `typed_events` (+ its paged sibling), `import_records`, and the compaction
   scans above. `queued_receipt`/`has_queued_receipt_run` deliberately stay:
   they are the admission check that a prompt was not already queued, so they
   must not read behind an accepted write. `load_metadata` stays for the same
   reason in the other direction — its read may repair the history index, which
   is a write.

Tests: the row's cut and field shape; a fence read answering while a writer job
holds the lane, plus the mirrored assertion that the writer lane still waits for
the job in front of it; `get_session_presence` answering under the same hold
through the RPC dispatcher; and the desktop's recheck — `missing` asked twice
(`deleted` and `present` once). `agent/src/session` (625), `agent rpc` (786),
`agent_bridge` (391) and `application` (109) are green, clippy `-D warnings` and
`make check-docs` clean on 1.99.1.
The commit message was staged by the same `git add -A` as the work; the
message text is in the commit body, not the tree.
@huichen
huichen enabled auto-merge (squash) October 29, 2026 01:32
@huichen
huichen merged commit 1bd9b23 into main Oct 29, 2026
63 of 66 checks passed
@huichen
huichen deleted the pr/huichen branch October 29, 2026 02:37
huichen added a commit that referenced this pull request Oct 29, 2026
…budget room

Two required checks were red on #1415 (2026-10-29), and both still fail on the
same tests today:

- Rust macOS test / host-remote: `remote_peer::runtime_tests::
  a_burst_of_events_reaches_the_emitter_in_order` — "the burst never fully
  arrived".
- Rust Windows test / agent: `service::approval_tests::
  shutdown_releases_a_blocking_tool_approval` — "Agent shutdown deadline
  exceeded during journal compactor and SQLite".

The burst is a lost-publish race, not a slow stream. `connect_with_emitter`
returns once the `SUB` has left the client, not once the broker has applied it:
async-nats' `Client::flush()` only flushes the write buffer and awaits no
acknowledgement (0.50 has no ping/pong call, contrary to the comment that sat in
`session::subscribe` and said an "ordered PONG" was waited for). A publish from
the host's *other* connection that reaches the fake broker first is then lost,
and NATS Core has no replay — the emitter legitimately never sees it. Held open
as a hypothesis only until it was made to fail on purpose: registering the events
`SUB` 300 ms late in the fake broker reproduces the CI message verbatim, and
`FakeNats::wait_for_sub` in the test turns it green. Two sibling tests in the
same file published the same way with the same exposure, so all three now wait
for the lane the way the rest of the file already did. The misleading comment in
`remote-client/src/session.rs` now says what `flush` does and what it does not
buy (production is unchanged: a gap across a reconnect is still healed by
`get_events_since`).

The shutdown test's 3 s budget was a bound on the Windows runner, not on the
drain: its assertions are all final state (approval released, caller joined,
`Stopped`), and the slow-lane measurement that landed with #1415 has one writer
job holding storage for 18-30 s. The budget moves to 30 s, matching
`cli_prompt_and_follow_up_use_real_run_finalization_without_dequeuing_on_shutdown`.

No production behaviour changes.
huichen added a commit that referenced this pull request Oct 29, 2026
…budget room

Two required checks were red on #1415 (2026-10-29), and both still fail on the
same tests today:

- Rust macOS test / host-remote: `remote_peer::runtime_tests::
  a_burst_of_events_reaches_the_emitter_in_order` — "the burst never fully
  arrived".
- Rust Windows test / agent: `service::approval_tests::
  shutdown_releases_a_blocking_tool_approval` — "Agent shutdown deadline
  exceeded during journal compactor and SQLite".

The burst is a lost-publish race, not a slow stream. `connect_with_emitter`
returns once the `SUB` has left the client, not once the broker has applied it:
async-nats' `Client::flush()` only flushes the write buffer and awaits no
acknowledgement (0.50 has no ping/pong call, contrary to the comment that sat in
`session::subscribe` and said an "ordered PONG" was waited for). A publish from
the host's *other* connection that reaches the fake broker first is then lost,
and NATS Core has no replay — the emitter legitimately never sees it. Held open
as a hypothesis only until it was made to fail on purpose: registering the events
`SUB` 300 ms late in the fake broker reproduces the CI message verbatim, and
`FakeNats::wait_for_sub` in the test turns it green. Two sibling tests in the
same file published the same way with the same exposure, so all three now wait
for the lane the way the rest of the file already did. The misleading comment in
`remote-client/src/session.rs` now says what `flush` does and what it does not
buy (production is unchanged: a gap across a reconnect is still healed by
`get_events_since`).

The shutdown test's 3 s budget was a bound on the Windows runner, not on the
drain: its assertions are all final state (approval released, caller joined,
`Stopped`), and the slow-lane measurement that landed with #1415 has one writer
job holding storage for 18-30 s. The budget moves to 30 s, matching
`cli_prompt_and_follow_up_use_real_run_finalization_without_dequeuing_on_shutdown`.

No production behaviour changes.
huichen added a commit that referenced this pull request Oct 29, 2026
… search line (#1417)

* test(agent): assert the fence lag a negative answer has to survive

The fence lane is worth its one open connection only because the cost is
bounded and compensated: a read that does not queue behind the ordered writer
cannot see a write that is still queued, so a session whose placeholder commit
is waiting reads missing. This asserts that lag directly — the fence answers
while the writer is held, the queued create is not visible yet, and the same
question answers present once it commits — so a later change that puts the
fence back on the writer lane, or a caller that trusts missing without
confirming it, has a test to fail.

The desktop half of that contract is covered by
agent_bridge::tests::presence_fence_tests (missing asked twice, deleted and
present once).

* test(agent): give the ordered-recovery wait room for a loaded disk

recovery_is_ordered_after_already_accepted_appends asserts the order of two
entries, not the latency of the commit between them, but it waited only 5 s for
that commit to land. Every writer commits with `synchronous = FULL`, so a suite
running 32 databases at once can spend longer than that in fsync alone: the full
`cargo test -p future-agent` at 32 threads failed here with `Timeout` on
2026-10-29 while the same suite at 8 threads (CI-like) was green twice.

The wait stays bounded — a real deadlock still fails — but at 60 s it measures
scheduling rather than the disk. No assertion changed.

* test(agent): key the reset race hook by session instead of one slot

Four tests register a reset-race hook, and the registry held exactly one. Under
parallel execution the last registration replaced the others, so a reset found no
hook for its own id and succeeded where the test expected `history_changed` — the
id gate was there, the storage was not. Measured 2026-10-29: the full
`cargo test -p future-agent` failed here with 32 test threads and passed with 8.

The registry is now a map keyed by session id, and the hook is removed before it
runs: it writes through the same manager, so holding the registry across that
work would serialize every other test's reset. Test-only (`#[cfg(test)]`); no
production path changes.

* fix(tui): typing, pasting and `esc` take the keys back from the rail

A focused rail kept the keys while printable characters, pastes and the
clipboard chord still reached the draft, so the `enter` that followed one
of them opened the rail's selected conversation instead of sending the
prompt. On the launchpad that read as "the first message was never sent —
the screen jumped to somebody else's streaming session".

Editing chords and a second `escape` now blur the rail too, so the keys
land where the typing did. The search line keeps its own `escape`: the
first one clears the filter, the next one leaves the rail.

* fix(tui): leave the rail's tabs to shift+left/right only

A focused rail answered the plain left/right arrows by switching between
最近 and 工作区. The rail can hold the keys while the prompt is still on
screen — a click on a tab, a conversation opened from a row, `ctrl+d` —
and a reader standing in the draft reads those two keys as the caret's,
so the rail moved under a caret that never did.

The tabs are now `shift+left`/`shift+right` alone (`Action::PanelPrev` /
`PanelNext`), which already worked from anywhere. Inside a focused rail
the plain arrows are swallowed rather than handed to the editor: that
caret is not the reader's, and moving one they cannot see is the same
surprise one layer down.

* fix(agent): keep the exchanges a backward history page asked for

`get_session_entries` counts a backward `limit` in user exchanges, but the
canonical branch of `read_display_page` capped the row range at 64 on top of
that window. One busy run is far more than 64 display rows on its own (an
assistant step and a tool entry per call), so a ten-exchange tail page came
back as whatever fitted, the client's missing-user-prefix fetch pulled that
run's question in, and the transcript opened on the newest exchange alone —
everything above it looked like it had been lost, with no page of it loaded
and no sign that any existed.

A backward read now takes the window it named. The row ceiling stays on the
forward branch, where `limit` counts rows and `nextOffset` resumes them. The
canonical page is still bounded: its rows carry no bodies, so the bound moves
to the materializer that reads them — the same eight-megabyte budget every
other page has, which happens to be exactly what the compatibility branch was
already using for its inline bodies.

Measured on a real 784-row session: a `limit: 10` tail read returned 64 rows
(one exchange) before and 783 rows across all ten exchanges after.

* test(host,agent): publish after the event lane exists; give the stop budget room

Two required checks were red on #1415 (2026-10-29), and both still fail on the
same tests today:

- Rust macOS test / host-remote: `remote_peer::runtime_tests::
  a_burst_of_events_reaches_the_emitter_in_order` — "the burst never fully
  arrived".
- Rust Windows test / agent: `service::approval_tests::
  shutdown_releases_a_blocking_tool_approval` — "Agent shutdown deadline
  exceeded during journal compactor and SQLite".

The burst is a lost-publish race, not a slow stream. `connect_with_emitter`
returns once the `SUB` has left the client, not once the broker has applied it:
async-nats' `Client::flush()` only flushes the write buffer and awaits no
acknowledgement (0.50 has no ping/pong call, contrary to the comment that sat in
`session::subscribe` and said an "ordered PONG" was waited for). A publish from
the host's *other* connection that reaches the fake broker first is then lost,
and NATS Core has no replay — the emitter legitimately never sees it. Held open
as a hypothesis only until it was made to fail on purpose: registering the events
`SUB` 300 ms late in the fake broker reproduces the CI message verbatim, and
`FakeNats::wait_for_sub` in the test turns it green. Two sibling tests in the
same file published the same way with the same exposure, so all three now wait
for the lane the way the rest of the file already did. The misleading comment in
`remote-client/src/session.rs` now says what `flush` does and what it does not
buy (production is unchanged: a gap across a reconnect is still healed by
`get_events_since`).

The shutdown test's 3 s budget was a bound on the Windows runner, not on the
drain: its assertions are all final state (approval released, caller joined,
`Stopped`), and the slow-lane measurement that landed with #1415 has one writer
job holding storage for 18-30 s. The budget moves to 30 s, matching
`cli_prompt_and_follow_up_use_real_run_finalization_without_dequeuing_on_shutdown`.

No production behaviour changes.

* fix(tui): keep the mention menu out of a pasted image marker

Pasting an image writes `[Image #1]` into the draft. Its `#1]` is the
marker's own text, but the mention reader takes the token after the last
space and only checks that it starts with a sigil, so the paste opened the
conversation list with `1]` as the query — and the reader had to dismiss it
before sending.

A sigil inside a paste-written span (an `[Image #N]` marker or a
`[Pasted Content … chars #N]` placeholder) is now part of that token
instead of the start of a mention. A `#` typed after the marker still
opens the list.

* fix(tui): keep a running reply's newest step on its own row

The transcript is bottom-anchored: its window is the last rows, so a row that
disappears at the tail pulls every line above it down, and the next event pushes
them back up. The live fold did that once per step — the `▸ thinking…` marker
became a count the moment reasoning ended, and each finished call folded into
the burst above it — so a turn of eighteen calls jittered the whole conversation
36 times (measured: 8→6→7→8→6… rows per event; the screenshot's 思考… row was
the row being removed).

A running reply now keeps its newest step — the call in flight or just finished,
the reasoning slice being written — on its own row until the next step takes it
over, so the transcript only ever grows while a reply streams. Prose keeps the
old shape: the summary moves onto the answer, in the row the step vacated. A
reasoning slice also shows its marker as soon as it starts, not on its first
token.

Also rebuild the transcript when a fold's counts move with its structure
unchanged (a prose slice's reasoning joining the counts above it) — heads alone
said nothing moved, leaving the old numbers and a marker the counts had taken
over on screen.

* test(host,agent): publish after the event lane exists; give the stop budget room

Two required checks were red on #1415 (2026-10-29), and both still fail on the
same tests today:

- Rust macOS test / host-remote: `remote_peer::runtime_tests::
  a_burst_of_events_reaches_the_emitter_in_order` — "the burst never fully
  arrived".
- Rust Windows test / agent: `service::approval_tests::
  shutdown_releases_a_blocking_tool_approval` — "Agent shutdown deadline
  exceeded during journal compactor and SQLite".

The burst is a lost-publish race, not a slow stream. `connect_with_emitter`
returns once the `SUB` has left the client, not once the broker has applied it:
async-nats' `Client::flush()` only flushes the write buffer and awaits no
acknowledgement (0.50 has no ping/pong call, contrary to the comment that sat in
`session::subscribe` and said an "ordered PONG" was waited for). A publish from
the host's *other* connection that reaches the fake broker first is then lost,
and NATS Core has no replay — the emitter legitimately never sees it. Held open
as a hypothesis only until it was made to fail on purpose: registering the events
`SUB` 300 ms late in the fake broker reproduces the CI message verbatim, and
`FakeNats::wait_for_sub` in the test turns it green. Two sibling tests in the
same file published the same way with the same exposure, so all three now wait
for the lane the way the rest of the file already did. The misleading comment in
`remote-client/src/session.rs` now says what `flush` does and what it does not
buy (production is unchanged: a gap across a reconnect is still healed by
`get_events_since`).

The shutdown test's 3 s budget was a bound on the Windows runner, not on the
drain: its assertions are all final state (approval released, caller joined,
`Stopped`), and the slow-lane measurement that landed with #1415 has one writer
job holding storage for 18-30 s. The budget moves to 30 s, matching
`cli_prompt_and_follow_up_use_real_run_finalization_without_dequeuing_on_shutdown`.

No production behaviour changes.

* fix(tui): keep the mention menu out of a pasted image marker

Pasting an image writes `[Image #1]` into the draft. Its `#1]` is the
marker's own text, but the mention reader takes the token after the last
space and only checks that it starts with a sigil, so the paste opened the
conversation list with `1]` as the query — and the reader had to dismiss it
before sending.

A sigil inside a paste-written span (an `[Image #N]` marker or a
`[Pasted Content … chars #N]` placeholder) is now part of that token
instead of the start of a mention. A `#` typed after the marker still
opens the list.

* fix(tui): break Chinese lines at the width, not at a stray space

`wrap_text_with_ansi` retreated to the last space whenever a line
overflowed. Chinese may break between any two characters, so a draft with
one space inside an otherwise unspaced run of Chinese (an IME habit, not a
word separator) broke there and sent the rest of the line down: a pasted
paragraph in the composer wrapped into half-empty rows and the box grew a
row for each one.

A break between two wide glyphs now uses the width itself. Closing
punctuation never opens a line (禁则): when the break lands on `,。、`, the
glyph before it comes down with it. ASCII word wrapping and the ASCII fast
path are unchanged.

* fix(tui): keep a running reply's newest step on its own row

The transcript is bottom-anchored: its window is the last rows, so a row that
disappears at the tail pulls every line above it down, and the next event pushes
them back up. The live fold did that once per step — the `▸ thinking…` marker
became a count the moment reasoning ended, and each finished call folded into
the burst above it — so a turn of eighteen calls jittered the whole conversation
36 times (measured: 8→6→7→8→6… rows per event; the screenshot's 思考… row was
the row being removed).

A running reply now keeps its newest step — the call in flight or just finished,
the reasoning slice being written — on its own row until the next step takes it
over, so the transcript only ever grows while a reply streams. Prose keeps the
old shape: the summary moves onto the answer, in the row the step vacated. A
reasoning slice also shows its marker as soon as it starts, not on its first
token.

Also rebuild the transcript when a fold's counts move with its structure
unchanged (a prose slice's reasoning joining the counts above it) — heads alone
said nothing moved, leaving the old numbers and a marker the counts had taken
over on screen.

* fix(tui): read the cache rate off the prompt, not the prompt plus the reads

`cache_percent` divided the cached reads by `cache_read_tokens +
input_tokens`, treating `inputTokens` as the uncached remainder. It is
not: the agent accumulates the provider's `prompt_tokens` there, and the
cached bytes are part of that prompt (`Usage::cached_tokens_exceed_prompt`
exists to reject a block where they are not). Adding the reads a second
time pins every heavily cached session at a 50% ceiling — measured on
this machine's runs, sessions reading 99.5% showed 49.9%, and the
footer's "缓存 50%" was that ceiling rather than a rate.

Divide by the prompt alone, which is the denominator
`models::cache_hit_rate` already uses, and clamp a self-contradicting
provider to 100%.

* refactor(tui): drop the rail's search line

The rail painted a search row in the blank line under its tabs
(`/ 搜索会话`, and `❯ 搜索会话▏` while it took keys), and `/` on a
focused rail opened it instead of the palette. That row is chrome the
reader pays for on every frame, and searching sessions already has a
door: `ctrl+r` opens the history picker with its own filter line, which
matches the same three fields (title, workspace, id) as the rail did.

So the row goes, and with it the second search implementation:

- `panels::Filter` collapses back into `Folded` — the rail's only view
  state is which workspaces are shut, and `rows_with`/`render_with` take
  it directly; the query/open fields, the needle matching, the
  count-and-heading overrides and the "no matching sessions" empty state
  go with it.
- `/` on a focused rail is the palette's key, exactly as it is from the
  prompt; the full-screen panel (`ctrl+d` on a narrow terminal) keeps
  `esc`/`q`/`↑`/`↓` and nothing else.
- `RailSearch`/`RailSearchHint`/`PanelEmptySearch` leave the copy
  bundles, and the rail footer names only its own chords.

Folds are untouched: `enter` on a workspace heading still folds, and
`foldedWorkspaces` still survives a restart.
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