Skip to content

fix(agent): persist a skipped tool result, and stop a user stop from fencing the session - #1337

Merged
huichen merged 7 commits into
mainfrom
fix/recovery-abort-persist
Oct 24, 2026
Merged

huichen merged 7 commits into
mainfrom
fix/recovery-abort-persist

Conversation

@huichen

@huichen huichen commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator

#1333 让「用户按停止」不再锁死整个会话,但它只覆盖了结果已经写下的那一类。这批补上剩下的两个口子。

1. 未执行的调用没有落盘,重载后被当成崩溃

agent/src/agent/mod.rs 里「因中断而跳过」的合成结果 [Tool execution cancelled — … was skipped due to user interrupt] 只 push 进内存消息列表,没有走 on_tool_result(已执行的调用在 :395 有)。而命名这些调用的 assistant 条目已经落盘,于是 transcript 上留下「调用有、结果没有」——recovery_safety 无法把它和「进程死在调用中途」区分开,照样围栏整会话。

修法就是补一次 on_tool_result,与已执行调用一致。落盘后 result_state 把它归到 NotExecuted:既围栏,也不算「可能已经跑过」。

2. 存量会话:无结果 + 该 run 是用户停止的

load() 里新增 user_stopped(该 run 的终态是 RUN_STATE_CANCELLED)。完全没有任何结果且 user_stopped 时,归 Aborted 而不是 unresolved——写结果的进程是被用户停下的,这和第 1 条是同一个问题,不是这个围栏存在理由的那个「没人在场」。

为了让三条判据只在一处,把内联的 if/else 链改成显式的 Doubt { Settled, Aborted, Unknown }:先定「这条调用有多可疑」,再让只读豁免 / write_is_applied / 定点警告 / 围栏去消费它。行为与 #1333 逐条对应,没有改动任何判定内容。

3. 收回 #1333 引入的两个退步

  • 中止的只读 shell(git status 之类)不再进 aborted,恢复原来的静默豁免——只读命令不可能改坏东西,没有要核对的东西,也就没有理由警告。
  • 中止的 write 若文件内容已经和要写的一致,先走 write_is_applied 按已验证处理(写 recovery_verified),不再要求模型自己去核对。

边界(没有放宽的那几条)

  • interrupted_by_restart / incomplete / error 的悬空调用仍然围栏(missing_result_after_a_restart_still_fences_the_session 三态逐个验)。
  • timed_out / execution_failed 仍然围栏,即使同一 run 里用户后来也按了停止(timed_out_result_still_fences_even_in_a_user_stopped_run)——超时是没人做的决定,副作用确实可能只做了一半。
  • [Tool execution lost …] 仍然围栏。
  • command_is_read_only(含 cd 任意位置的放宽)与 write_is_applied 的判定本身一行未改。

删掉一条旧用例

missing_result_still_fences_even_in_a_cancelled_run 构造的正是「无结果 + 用户按停止」并断言围栏,与本批第 2 条逻辑上不可共存。它把「用户主动停止」写成了「崩溃」,记录的是本批要改掉的旧契约,所以整条删除、原位置留了一段注释说明来由。替代覆盖更强:用户中止一态 + 重启/未完成/错误三态两条用例。其余既有断言一条未动。

验证

cargo fmt --check                                            exit=0
cargo clippy -p future-agent --all-targets -- -D warnings     exit=0
cargo test -p future-agent --lib recovery_safety              23 passed; 0 failed
cargo test -p future-agent --lib agent::                     138 passed; 0 failed
cargo test -p future-agent --lib rpc::                       779 passed; 1 failed

最后那 1 个失败是 grpc::tests::the_public_serve_wrappers_bind_serve_and_report_bind_failures,在未改动的 dev-huichen 上同样失败,与本批无关、没有触碰。

新增用例 7 条(recovery_safety 6 条 + run_loop 1 条实证「跳过的结果确实进了 journal」),删除 1 条。

The assistant entry naming a turn's tool calls reaches the journal as soon as
the turn ends. Results for calls that actually ran are persisted too, but the
`[Tool execution cancelled — … was skipped due to user interrupt]` results this
loop synthesizes for the calls the interrupt cut off were only pushed into the
in-memory messages.

On disk that left a call with no result at all, which is indistinguishable from
"the process died between the call and its result" — so the next recovery pass
fenced the whole session for a stop the user asked for. Measured on a real
transcript: one run with two shell calls, the user stopped it, one result
landed, and every later tool in that session was refused.

The skip placeholder now goes through the same result callback as an executed
call, so it lands in the journal as `[Tool execution cancelled …]` and recovery
classifies it as provably not executed.
…ed operation

A call with no result at all was always the crash case: nobody can say whether
it ran, so the session fences. That is right for a kill, an OOM or a system
shutdown, and those all land on `interrupted_by_restart` or leave the run
unterminated. It is not right for the run the user ended themselves: the only
process that could have written that result was stopped on purpose.

A missing result in a run whose terminal state is `cancelled` is now classified
as an aborted operation instead, so it is questioned once by `before_tool`
rather than fencing the session. This is also what heals transcripts an earlier
build already wrote: the shape "two calls in flight, stop pressed, one result
recorded" exists on disk today and keeps those sessions locked.

The two questions an abort raises are now answered before the abort branch, so
the previous classification does not skip them:

* a provably read-only shell command is exempt again — it cannot have changed
  anything, so there is nothing to warn about;
* a `write` whose target already holds the requested content is verified and
  persisted as `recovery_verified` again, instead of asking the model to go and
  check something the journal can answer.

Unchanged: a missing result after a restart, a kill or a shutdown still fences
the session; a `timed_out` or `execution_failed` result still fences it even
when the user also pressed stop; `[Tool execution lost` still fences; and
`not_started`/`launch_failed` still count as not executed.
`missing_result_still_fences_even_in_a_cancelled_run` built "no result at all"
with a `RUN_STATE_CANCELLED` terminal and asserted that the session fences.
That asserted the very behaviour this branch removes: a cancelled run is the
user pressing stop, not an unsupervised crash.

It was written in the previous change, where the contract still was "a missing
result always fences", so it records the old contract rather than an
independent expectation. Keeping it under another name would also collide with
the two tests that now state the current contract, so it is deleted with a
comment where it stood. Coverage is strictly wider: a missing result after a
crash is still fenced for `interrupted_by_restart`, `incomplete` and `error`,
and a missing result after a user stop is questioned once instead of fencing.
@huichen
huichen merged commit efe7c4a into main Oct 24, 2026
25 checks passed
huichen added a commit that referenced this pull request Oct 25, 2026
… needed

The mechanism was a pair, introduced together in #1313: on startup the Agent
continued every run a restart had cut off, and to make that safe it fenced the
whole session when a tool call's outcome was unknown. The fence had no release
path, so a restart that happened to land on a running shell left that session
refusing every mutating tool forever — only `read` got through. #1333/#1337
narrowed it for user-aborted calls; the restart case was left because
auto-continuation depended on it.

Per the user's decision, the pair goes together. Without an automatic
re-issue there is nothing to replay, so the fence guards a call that cannot
happen while its own cost — a conversation turned read-only until a human runs
a CLI — is real.

Removed:
- The startup pass and its plumbing: `agent/src/rpc/resume.rs`, the hook in
  `service/startup.rs`, `resumeInterruptedOnStart` (agent settings and the
  host's write-through), and the whole "continue a run without a user message"
  path: `continue_interrupted_run`, `Continuation`, `ResumeContext`,
  `close_outstanding_tool_calls`, `append_run_continuation`,
  `run_started_continuation`, `auto_resume_of`.
- The fence and its release valve: `agent/src/rpc/recovery_safety.rs`,
  `acknowledge_recovery`, `future session unblock`, the `custom`
  `recovery_acknowledged` entry, and their docs.

What remains is the informational half, which was designed for this:
`repair_dangling_tool_calls` still answers a call whose result never landed with
"[Tool execution lost — … so whether it ran is unknown. Check whether it took
effect before running it again]", and a crashed run keeps its open
`run_started` — the state clients already render as `interruptedRun`. The next
run starts from a prompt somebody sent (the user, a client, or a supervising
conversation) and closes the crashed run through `append_run_start` like any
other boundary, so the journal never carries two open runs.

The fence's tests were removed with the file they lived in; the property they
encoded is now carried by `append_run_start_closes_an_unterminated_run` (a new
prompt closes the crashed run) and the placeholder tests under
`session/manager/tests/`. `docs/architecture/agent-supervision.md` §9.1 gains a
reversal note and its D8/D9/D10 rows are marked reversed rather than rewritten,
so the design history stays readable.

Verified on a copy of the session this was reported against
(20261025-215423): with the fence gone its `shell` runs again, a kill mid-tool
followed by a restart submits nothing, and the next prompt still tells the model
that the earlier call's outcome is unknown.
huichen added a commit that referenced this pull request Oct 25, 2026
… retired; recovery named (#1355)

* fix(remote): replace a refused relay grant instead of ending recovery

A bridge whose relay grant was refused stayed dead until the process
restarted. `desktop.log` from 2026-10-25 shows the shape twice: a relay
`draining` event, then fifteen minutes later `User Authentication
Expired` on the live socket, then `authorization violation` on every
reconnect and nothing else for the rest of the run. `future remote
status` kept reporting the machine as serving.

Two independent dead ends produced it, and both had the same cause: a
credential verdict taken as the end of *recovery* rather than the end of
*that generation*.

- `watch_generation` returned as soon as `NatsHealth::is_terminal()` was
  set, so a rejected credential — including one the relay only refused
  because its authorization cache had not caught up — was never replaced.
  The generation is disposable by design: `recovery_plan` rebuilds it with
  `host.refresh`, i.e. a new mint, which is a different thing from
  rotating the refused grant. It is now treated as one more unhealthy
  generation, under the existing budget (three rebuilds per ten minutes,
  then a cool-down that keeps trying instead of stopping).
- `spawn_runtime_reconnect` spent exactly one attempt. When the rebuild
  failed — or answered a status `retryable_start_status` does not call
  transient, which is what a refused credential does — nothing was
  scheduled again, because the watch that asked for it had already
  returned. A failed rebuild now re-arms that watch, so the budget, and
  not a single attempt, decides when to stop trying.

Two supporting changes keep those from being reached for the wrong
reason:

- `Event::Draining`/`LameDuckMode` ask for a replacement generation. The
  drain usually arrives just after a rotation, so the grant in hand is the
  one the retiring node stopped honouring; waiting for the close costs
  whatever lifetime the credential had left.
- The refresh loop no longer connects with a credential that has already
  expired (a mint that crossed its own expiry, a clock that moved): it
  records `credential_expired` and asks for another, instead of earning a
  refusal that ends a generation over a credential dead on arrival.

The grant's deadline is now in the status (`credentialExpiresAt`, also a
line of the prose report), because "when does it renew" is the question
that separates "between rotations" from "lapsed while nobody renewed it"
— and it previously had no answer outside the socket log.

Tests: two end-to-end regressions in `remote::tests::runtime_tests`
(a refused grant is replaced without a restart; a failed rebuild is
retried), both failing before this change; the health unit tests now
assert that a drain asks for a rebuild and that a successful migration
withdraws it. The fixture keeps `automatic_recovery` off, so the two new
tests raise a `RuntimeHooks` switch for the duration they need it.

Verified: cargo fmt clean; clippy `-D warnings` clean for
future-remote-server and future-host on the pinned 1.97 toolchain;
172 + 273 + 123 tests green in the touched modules.

* fix(agent): release a restart-recovery fence explicitly instead of deadlocking

A restart that cut a tool call off left its effect unknown, and
`RecoverySafety` then refused every mutating tool in that session forever:
`unresolved` was recomputed from the transcript on every load, and "unknown
effect" never becomes a result there. Only `read` passed, so any restart that
happened to land on a running shell permanently ended the conversation.

The fence stays the default — nothing is replayed, and a model assertion still
cannot release it — but it now has one explicit, recorded way out:

- `acknowledge_recovery` (CLI: `future session unblock <id> [--why <text>]`)
  appends one `custom`/`recovery_acknowledged` entry naming the exact
  `(run_id, call_id)` pairs, the time, the caller and an optional reason.
  Repeating it is a no-op.
- `RecoverySafety::load` moves those calls from `unresolved` to the `aborted`
  tier: that operation is still questioned once per run (the model is told to
  verify it read-only first) and every other tool works again. It is not marked
  verified, because a human decision is not that fact.
- `pause_reason` now says this is a session-wide fence, tells the model not to
  retry, and names `future session unblock <id>` — and it keeps the call id.

`custom` (with a `name`) rather than a new entry type: every projection,
fork/clone and export path already skips unknown types, so the record stays
journal-only and never becomes model-visible context.

Tests pin the un-released behaviour unchanged, the released behaviour (same
call warned once, other tools allowed), idempotency, and that a release for an
unrelated call releases nothing. Docs: guide/session-recovery{,.zh-CN}.md.

* feat(i18n): let the desktop language picker follow the system

The picker only offered 中文/English, so a user who chose once could never go
back to tracking the OS. Add a "follow system" preference (the default while
nothing is stored), keep it as a stored value rather than a first-run fallback,
and resolve it to a bundle whenever it is applied.

* docs: describe the desktop language picker's follow-system default

* feat(tui): a bilingual surface that follows the reader's language

`future tui` drew its chrome in Chinese only, so an English reader met Chinese
tabs, pickers and key hints in an otherwise English terminal. The chrome now
ships both languages side by side in `workbench/i18n.rs` — one key per line with
its 中文 and English spelling, so a half-translated key does not compile — and
the surface picks one at start: `LC_ALL`, `LC_MESSAGES`, `LANG` (Windows: the
user UI language when none is set), else English.

`/lang` opens a picker with the same three rows the desktop and the phone use
(system / 中文 / English); the choice is persisted as `language` in
`~/.future/tui/settings.json` and applied to the frame, the adapter's own
sentences and the panels' local facts at once. Content — a conversation, a
session title, a path — is never translated.

`workbench_demo --lang en` prints either language, and the screenshot capture
pins `zh` through that settings file so a baseline does not depend on the
machine's locale.

* fix(mobile): hold the reader's row when the conversation list re-ranks

The list stays mounted under an open conversation (`App.tsx`), so its pixel
offset survives a visit — but the rows do not. Both the recency page and the
two tree pages redraw whenever the catalogue moves: a message appended anywhere
re-ranks the row it belongs to, a run that ends leaves "Active", a peer
machine's list is re-read after an action on it. A reader who scrolled to a
conversation and came back found the same offset over different conversations,
which is the "it was not where I left it" report.

The FlatList now carries a native anchor (`maintainVisibleContentPosition`), the
same one the transcript uses (`useChatScroll`): when the rows above the first
visible one change, the view moves its offset to keep that row in place. Within
zero of the top it stays at the top instead, because at the head of a page
ranked by recency the newest row belongs on screen rather than pushed above it.

Verified in the harness (web build, `?recent=1&recentMany=1`): scrolling to a
conversation, opening it and coming back leaves `scrollTop` untouched at 902
and the same scroll node, i.e. nothing in JS resets the list — the movement the
report describes is the rows, not the offset. tsc, eslint and `jest src/screens`
(17 suites, 309 tests) clean.

* refactor(agent): remove restart auto-resume and the recovery fence it needed

The mechanism was a pair, introduced together in #1313: on startup the Agent
continued every run a restart had cut off, and to make that safe it fenced the
whole session when a tool call's outcome was unknown. The fence had no release
path, so a restart that happened to land on a running shell left that session
refusing every mutating tool forever — only `read` got through. #1333/#1337
narrowed it for user-aborted calls; the restart case was left because
auto-continuation depended on it.

Per the user's decision, the pair goes together. Without an automatic
re-issue there is nothing to replay, so the fence guards a call that cannot
happen while its own cost — a conversation turned read-only until a human runs
a CLI — is real.

Removed:
- The startup pass and its plumbing: `agent/src/rpc/resume.rs`, the hook in
  `service/startup.rs`, `resumeInterruptedOnStart` (agent settings and the
  host's write-through), and the whole "continue a run without a user message"
  path: `continue_interrupted_run`, `Continuation`, `ResumeContext`,
  `close_outstanding_tool_calls`, `append_run_continuation`,
  `run_started_continuation`, `auto_resume_of`.
- The fence and its release valve: `agent/src/rpc/recovery_safety.rs`,
  `acknowledge_recovery`, `future session unblock`, the `custom`
  `recovery_acknowledged` entry, and their docs.

What remains is the informational half, which was designed for this:
`repair_dangling_tool_calls` still answers a call whose result never landed with
"[Tool execution lost — … so whether it ran is unknown. Check whether it took
effect before running it again]", and a crashed run keeps its open
`run_started` — the state clients already render as `interruptedRun`. The next
run starts from a prompt somebody sent (the user, a client, or a supervising
conversation) and closes the crashed run through `append_run_start` like any
other boundary, so the journal never carries two open runs.

The fence's tests were removed with the file they lived in; the property they
encoded is now carried by `append_run_start_closes_an_unterminated_run` (a new
prompt closes the crashed run) and the placeholder tests under
`session/manager/tests/`. `docs/architecture/agent-supervision.md` §9.1 gains a
reversal note and its D8/D9/D10 rows are marked reversed rather than rewritten,
so the design history stays readable.

Verified on a copy of the session this was reported against
(20261025-215423): with the fence gone its `shell` runs again, a kill mid-tool
followed by a restart submits nothing, and the next prompt still tells the model
that the earlier call's outcome is unknown.

* test(tui): fail when the workbench draws chrome it did not take from the table

`i18n.rs` makes a half-translated key uncompilable. It says nothing about a
string that never went through the table, and that is how the bilingual surface
drifts back to one language: every branch that adds a panel adds its own labels,
and a hardcoded literal compiles and looks finished in whichever language its
author happened to write. The three branches waiting to merge are exactly that
case.

`tui/tests/i18n_guard/` is the check, run by `cargo test -p future-tui` with no
new CI job. It reads the sources and reports `file:line: literal` for two
shapes:

- Anything with a CJK character under `tui/src/` — chrome is authored in Chinese
  here, so a Chinese literal is chrome that skipped the table. Content is
  untouched: a conversation, a title or a path is runtime data.
- An English sentence drawn by the surface (`workbench/` plus the modules it
  pulls display text out of). Two words of three or more letters, in a literal
  that is not a path, an identifier, an escape sequence or a format skeleton.

Test modules are not read (they draw no frame) and `workbench/demo.rs` is exempt
as a file (its strings are the content a session carries). The rest is a
30-row allowlist with a reason per row or a same-line `// i18n: <reason>`
marker, and `BUDGET` pins the number of exemptions so a new one cannot be added
quietly — the test fails until the number a reviewer reads moves too. Stale
rows fail as well.

On `dev-huichen` the guard is green: 52 files, 2299 literals outside tests, 60
chrome candidates, all exempted. 27 of those exemptions are pre-existing
English-only chrome (the notice row, the approval-mode chip, the compaction
marker, the folded-output footer) — frozen rather than translated, because
translating them would change what a reader sees and belongs in its own change.

`docs/tui/i18n-homeless-strings.md` (and its zh-CN pair) documents the rules,
the blind spots, the frozen gaps, and the port list for `feat/workbench-ui`,
`feat/wb-mentions` and `fix/workbench-degrade`, measured by pointing the same
check at each branch's tree and diffing it against the commit where it left
`dev-huichen`: 167/120/47 added literals, of which 84/6/41 are new chrome and
the rest are already table rows, demo data, or known gaps. It also calls out the
strings hardcoded in several places at once so the merge fixes them once.

The only change to a drawing path is a comment: the two invariant messages the
guard exempts in place carry their `// i18n:` marker. No wording, no behaviour,
and no row of the existing 102 keys moved.

* feat(agent): name the shutdown sub-step a slow drain is stuck in

A timeout report prints the stage the drain was in when its budget ran out.
The admission phase had exactly one name, so "during admission" could not say
whether the time went on the session-map snapshot or on one session's lock -
"the service is wedged" and "one busy session is wedged" need different
answers, and the last three timeouts were all reported as this one name.

Split it into "admission: session snapshot" and "admission: interrupting
sessions", both set BEFORE the step that may block: a drain stuck past its
deadline never reaches its own completion line, and the deadline watcher reads
only this name. The initial "admission" stays as the value a report shows when
the drain never got as far as either step.

Also time both steps and warn past 250 ms, naming the sub-step and the session
whose lock was held (with whether it had an active run, read from the guard
once it is finally ours). Measurement only: no try_read, no skipped session, no
change to `wait` or to the five-second budget, and a timeout still fails
exactly as before.

Tests drive `drain` on the test thread so a thread-local subscriber sees the
warning: a held session write lock produces a warning naming the sub-step and
that session and not the uncontended snapshot, and a drain with free locks
stays quiet (the threshold must filter, or it would bury the one that matters).

* test(cli): assert the endpoint of a terminal credential verdict, not the race

`a_freshly_refreshed_credential_rejected_on_a_live_link_is_terminal`
asserted that a refused-but-fresh grant arms no rebuild, and the loaded CI
runner printed `[RT001] … rebuilding generation (1/3)` before the entry's
status poll noticed the verdict — red on Linux/macOS/Windows `tui-cli`
(run 40207454243), green when the case ran alone.

The assertion is stale, not the code: `d99a2546d` made a refused grant end
only *that generation*, so `watch_generation` now treats the terminal health
as one more unhealthy generation and rebuilds it from a new mint. Two
components react to the same verdict on independent clocks — the watcher's
one-second tick and the entry's one-second status poll — so which line lands
first is not a property of the product.

What the terminal verdict buys is the endpoint, and that is what the test now
asserts: the run must end by itself, it must fail, the reason must be
`ServiceAuthorization`, and the last phase the entry reports must be
`Failed` — a rebuild may report the replacement live for as long as this
broker takes to refuse it, but it must not turn the stop into continued
service. `ChildRun` grows `wait_for_exit` and `settled_text` for that; the
docstrings and the TAU-D26 index bullet now name the `d99a2546d` contract
instead of the arm it replaced.

Verified: 14/14 green in five consecutive full runs of the binary on 1.97
(70-72 s each) plus twice standalone; the inverted phase assertion was
checked once to fail against the real transcript.

* fix(desktop): remove the auto-resume switch that no longer does anything

`9c83f6115` removed restart auto-resume and the recovery fence it needed, so the
agent no longer reads `resumeInterruptedOnStart`. The desktop kept the switch:
toggling it stored a value nothing acted on, which is worse than having no
switch, because it read as a guarantee about restart behaviour.

Removed: the GeneralPage row and its props/type, the SettingsDialog wiring, the
`AppSettings` / `DEFAULT_APP_SETTINGS` / `updateAppSettings` fields, the
settings.rs test literal, the en/zh copy, the screenshot fixture, and the CLI
surface (`future desktop settings` listed it as settable and wrote it).

Kept deliberately: `AppSettings::auto_resume_interrupted` and its stored key
read back unchanged, so existing app.db rows and older clients see the same
document, with no writer and no UI behind it. `SETTINGS` and the round-trip
test's field list are the two places told about that one exception.

Verified: desktop vitest 5291 passed, tsc / eslint / vite build clean; cargo
test -p future-cli 1398 passed (one PATH-race flake that passes 3/3 alone),
future-app-settings 20 passed, host settings + session modules 54 passed;
clippy -D warnings on future-cli / future-host / futureos; fmt clean; make
check-docs clean.
huichen added a commit that referenced this pull request Oct 25, 2026
…w the reader (#1356)

* fix(screenshots): model the cursor, wrapping and terminal queries a real TUI uses

Capturing a second TUI (dsh-tui 0.17.0) as a style reference exposed four places
where the renderer only understood how *our* UI draws. Each is a real terminal
behaviour, not a special case for that app.

- **Relative cursor movement.** dsh-tui skips with `CSI nC` and descends with
  `CSI nB` instead of writing spaces and newlines (445 `26C`, 1299 `1B` in one
  launch). Unknown sequences were consumed, so every glyph landed at the left
  margin — a picture that looks like the *application* rendered badly.
  CUB/CUF/CUU/CUD/CNL/CPL/CHA/VPA/HVP now move the cursor.

- **Movement clamps to the screen.** A cursor cannot leave the grid. Without the
  clamp the column ran past the last one, and the next glyph then looked like an
  overflow, so an app that skips to the right edge tore its own frame apart.

- **Wrapping and scrolling.** A terminal wraps at the right edge and scrolls when
  written past the bottom; both were silently dropped (444 wrapping writes and 89
  scrolls in one dsh-tui launch). Dropping them left the banner in torn fragments
  and everything after the overflow in the wrong rows.

- **Terminal interrogation.** A real terminal answers: DA1, DA2, XTVERSION, the
  OSC 10/11 colour queries, DECRQM for synchronized output, and device status.
  Our pty said nothing, so an app that asks stalled on a degraded first frame —
  measured: the same dsh-tui run drew a torn, left-aligned splash in the pty and
  a clean centred wordmark under tmux, which answers. `tui_capture` now replies.

- The caret is exempt from the alignment check: it is an overlay on the cell the
  app parked the cursor at, and a translucent block over the background reads as
  a fully inked cell, which made a correct frame fail its own check.

Verification, in order of strength:

- every added behaviour has a self-test, and each was re-run with the behaviour
  removed to confirm the test fails;
- `future tui`'s frame is cell-identical to **pyte**'s (0 of 38 rows differ);
- dsh-tui's frame is row-identical to **tmux**'s for 37 of 38 rows, the remaining
  row being the workspace path (different cwd in the two runs).

* docs(testing): record the doubao thinking-level live verification

Verified the fix on the wire against the live Future platform with two
isolated agents built from the same recipe (FUTURE_VERSION pinned), one at
9b13e09 (pre-fix) and one at ab3dcc5:

- new code: medium goes out as reasoning_effort "high", off goes out as
  thinking {"type":"enabled"} with no depth hint; medium/off/high all
  returned a normal reply;
- deepseek-flash is byte-identical to the pre-fix request body at the same
  level, so the new compat flag did not spill over;
- the committed 400 from 20:09 did NOT reproduce: six pre-fix calls with
  reasoning_effort "medium" (and one sending thinking disabled) all
  returned 200. The platform catalogue is field-identical to the 11:59
  cache apart from the proxy BaseURL, so this is a server-side difference,
  not a client-side one. The record says so instead of claiming a
  reproduction.

Also records that the platform catalogue still does not declare
reasoning_effort_values for doubao, which is the alternative fix that
needs a platform-side decision.

* docs(testing): say that the doubao verification worktrees are gone

The record's reproduction steps pointed at two scratch worktrees that were
removed after the merge; a reader following them would look for paths that
no longer exist.

* fix(cli): report why the host stopped even when cleanup fails

The foreground host `?`-ed the Agent shutdown before reading the serving
loop's own result, so a cleanup that ran out of its budget replaced the whole
report. Measured on a loaded host: the only line left was "Agent failed to
stop: ... during admitted commands", with nothing saying what had stopped the
entry in the first place - the run had quit because the Agent stopped
answering, and that fact was dropped on the floor.

Combine the two halves in `exit_outcome` instead: both are reported when both
failed, cause first and the cleanup failure named as an additional
complication; a single failure on its own stays exactly the message it was, so
no ordinary exit gains a sentence about a shutdown problem it did not have.

Exit status is unchanged: failure in either half is still a failure, and only
a run where both succeeded is Ok. `until_shutdown`, `StopCause`, the signal
handling and every shutdown timeout/budget are untouched.

Tests: loop failure plus cleanup failure puts both reasons in the final
message; a clean shutdown leaves the loop's reason alone; a failed cleanup on
an ordinary exit is still a failure; both succeeding is success.

* fix(screenshots): read streams without newline translation; honour ED modes

The dsh-tui comparison I published was torn, and the cause was not the app: my
tooling read its capture with a text-mode reader.

`Path.read_text()` (like `open()` in text mode) applies universal newlines and
turns every `\r` into `\n`. In a terminal stream those are different keys. dsh-tui
writes bare CR to return to column 0 and steps rows with `CSI nB` itself, so the
translation turned each "column 0, same row" into "next row": the banner came out
in diagonal fragments and the whole frame looked scrambled. Measured on the same
bytes: read as bytes -> 38/38 rows identical to tmux; read with read_text -> torn.

- `read_stream(path)` reads bytes and decodes them, and the CLI entry uses it.
  `capture.py tui` already decoded bytes, so the harness path was sound; the
  damage was in scripts (and the render CLI) that went through `read_text`.
- ED now honours its parameter. `CSI 3J` clears the scrollback and leaves the
  screen alone; wiping on it (as before) discards the frame just painted. A real
  terminal also does not move the cursor for any ED form, and 0/1 erase only the
  region around the cursor. Found while investigating the tearing; it is not what
  caused it, since dsh-tui follows `3J` with `2J` and a full redraw.

Self-tests pin both: a bare CR survives `read_stream`, and `3J` keeps the screen
while `2J` clears and `0J` clears from the cursor.

Verification, this time printing both sides instead of a count:

- replay of tmux's own `pipe-pane` bytes vs `capture-pane`: 38/38 rows;
- our pty capture vs tmux at the same 30s: 38/38 rows, wordmark centred at rows
  10-14 and 16-20 with nothing above them;
- pyte agrees on both frames: 38/38 for dsh-tui and 38/38 for `future tui`.

* fix(remote): replace a refused relay grant instead of ending recovery

A bridge whose relay grant was refused stayed dead until the process
restarted. `desktop.log` from 2026-10-25 shows the shape twice: a relay
`draining` event, then fifteen minutes later `User Authentication
Expired` on the live socket, then `authorization violation` on every
reconnect and nothing else for the rest of the run. `future remote
status` kept reporting the machine as serving.

Two independent dead ends produced it, and both had the same cause: a
credential verdict taken as the end of *recovery* rather than the end of
*that generation*.

- `watch_generation` returned as soon as `NatsHealth::is_terminal()` was
  set, so a rejected credential — including one the relay only refused
  because its authorization cache had not caught up — was never replaced.
  The generation is disposable by design: `recovery_plan` rebuilds it with
  `host.refresh`, i.e. a new mint, which is a different thing from
  rotating the refused grant. It is now treated as one more unhealthy
  generation, under the existing budget (three rebuilds per ten minutes,
  then a cool-down that keeps trying instead of stopping).
- `spawn_runtime_reconnect` spent exactly one attempt. When the rebuild
  failed — or answered a status `retryable_start_status` does not call
  transient, which is what a refused credential does — nothing was
  scheduled again, because the watch that asked for it had already
  returned. A failed rebuild now re-arms that watch, so the budget, and
  not a single attempt, decides when to stop trying.

Two supporting changes keep those from being reached for the wrong
reason:

- `Event::Draining`/`LameDuckMode` ask for a replacement generation. The
  drain usually arrives just after a rotation, so the grant in hand is the
  one the retiring node stopped honouring; waiting for the close costs
  whatever lifetime the credential had left.
- The refresh loop no longer connects with a credential that has already
  expired (a mint that crossed its own expiry, a clock that moved): it
  records `credential_expired` and asks for another, instead of earning a
  refusal that ends a generation over a credential dead on arrival.

The grant's deadline is now in the status (`credentialExpiresAt`, also a
line of the prose report), because "when does it renew" is the question
that separates "between rotations" from "lapsed while nobody renewed it"
— and it previously had no answer outside the socket log.

Tests: two end-to-end regressions in `remote::tests::runtime_tests`
(a refused grant is replaced without a restart; a failed rebuild is
retried), both failing before this change; the health unit tests now
assert that a drain asks for a rebuild and that a successful migration
withdraws it. The fixture keeps `automatic_recovery` off, so the two new
tests raise a `RuntimeHooks` switch for the duration they need it.

Verified: cargo fmt clean; clippy `-D warnings` clean for
future-remote-server and future-host on the pinned 1.97 toolchain;
172 + 273 + 123 tests green in the touched modules.

* fix(agent): release a restart-recovery fence explicitly instead of deadlocking

A restart that cut a tool call off left its effect unknown, and
`RecoverySafety` then refused every mutating tool in that session forever:
`unresolved` was recomputed from the transcript on every load, and "unknown
effect" never becomes a result there. Only `read` passed, so any restart that
happened to land on a running shell permanently ended the conversation.

The fence stays the default — nothing is replayed, and a model assertion still
cannot release it — but it now has one explicit, recorded way out:

- `acknowledge_recovery` (CLI: `future session unblock <id> [--why <text>]`)
  appends one `custom`/`recovery_acknowledged` entry naming the exact
  `(run_id, call_id)` pairs, the time, the caller and an optional reason.
  Repeating it is a no-op.
- `RecoverySafety::load` moves those calls from `unresolved` to the `aborted`
  tier: that operation is still questioned once per run (the model is told to
  verify it read-only first) and every other tool works again. It is not marked
  verified, because a human decision is not that fact.
- `pause_reason` now says this is a session-wide fence, tells the model not to
  retry, and names `future session unblock <id>` — and it keeps the call id.

`custom` (with a `name`) rather than a new entry type: every projection,
fork/clone and export path already skips unknown types, so the record stays
journal-only and never becomes model-visible context.

Tests pin the un-released behaviour unchanged, the released behaviour (same
call warned once, other tools allowed), idempotency, and that a release for an
unrelated call releases nothing. Docs: guide/session-recovery{,.zh-CN}.md.

* feat(i18n): let the desktop language picker follow the system

The picker only offered 中文/English, so a user who chose once could never go
back to tracking the OS. Add a "follow system" preference (the default while
nothing is stored), keep it as a stored value rather than a first-run fallback,
and resolve it to a bundle whenever it is applied.

* docs: describe the desktop language picker's follow-system default

* feat(tui): a bilingual surface that follows the reader's language

`future tui` drew its chrome in Chinese only, so an English reader met Chinese
tabs, pickers and key hints in an otherwise English terminal. The chrome now
ships both languages side by side in `workbench/i18n.rs` — one key per line with
its 中文 and English spelling, so a half-translated key does not compile — and
the surface picks one at start: `LC_ALL`, `LC_MESSAGES`, `LANG` (Windows: the
user UI language when none is set), else English.

`/lang` opens a picker with the same three rows the desktop and the phone use
(system / 中文 / English); the choice is persisted as `language` in
`~/.future/tui/settings.json` and applied to the frame, the adapter's own
sentences and the panels' local facts at once. Content — a conversation, a
session title, a path — is never translated.

`workbench_demo --lang en` prints either language, and the screenshot capture
pins `zh` through that settings file so a baseline does not depend on the
machine's locale.

* fix(mobile): hold the reader's row when the conversation list re-ranks

The list stays mounted under an open conversation (`App.tsx`), so its pixel
offset survives a visit — but the rows do not. Both the recency page and the
two tree pages redraw whenever the catalogue moves: a message appended anywhere
re-ranks the row it belongs to, a run that ends leaves "Active", a peer
machine's list is re-read after an action on it. A reader who scrolled to a
conversation and came back found the same offset over different conversations,
which is the "it was not where I left it" report.

The FlatList now carries a native anchor (`maintainVisibleContentPosition`), the
same one the transcript uses (`useChatScroll`): when the rows above the first
visible one change, the view moves its offset to keep that row in place. Within
zero of the top it stays at the top instead, because at the head of a page
ranked by recency the newest row belongs on screen rather than pushed above it.

Verified in the harness (web build, `?recent=1&recentMany=1`): scrolling to a
conversation, opening it and coming back leaves `scrollTop` untouched at 902
and the same scroll node, i.e. nothing in JS resets the list — the movement the
report describes is the rows, not the offset. tsc, eslint and `jest src/screens`
(17 suites, 309 tests) clean.

* refactor(agent): remove restart auto-resume and the recovery fence it needed

The mechanism was a pair, introduced together in #1313: on startup the Agent
continued every run a restart had cut off, and to make that safe it fenced the
whole session when a tool call's outcome was unknown. The fence had no release
path, so a restart that happened to land on a running shell left that session
refusing every mutating tool forever — only `read` got through. #1333/#1337
narrowed it for user-aborted calls; the restart case was left because
auto-continuation depended on it.

Per the user's decision, the pair goes together. Without an automatic
re-issue there is nothing to replay, so the fence guards a call that cannot
happen while its own cost — a conversation turned read-only until a human runs
a CLI — is real.

Removed:
- The startup pass and its plumbing: `agent/src/rpc/resume.rs`, the hook in
  `service/startup.rs`, `resumeInterruptedOnStart` (agent settings and the
  host's write-through), and the whole "continue a run without a user message"
  path: `continue_interrupted_run`, `Continuation`, `ResumeContext`,
  `close_outstanding_tool_calls`, `append_run_continuation`,
  `run_started_continuation`, `auto_resume_of`.
- The fence and its release valve: `agent/src/rpc/recovery_safety.rs`,
  `acknowledge_recovery`, `future session unblock`, the `custom`
  `recovery_acknowledged` entry, and their docs.

What remains is the informational half, which was designed for this:
`repair_dangling_tool_calls` still answers a call whose result never landed with
"[Tool execution lost — … so whether it ran is unknown. Check whether it took
effect before running it again]", and a crashed run keeps its open
`run_started` — the state clients already render as `interruptedRun`. The next
run starts from a prompt somebody sent (the user, a client, or a supervising
conversation) and closes the crashed run through `append_run_start` like any
other boundary, so the journal never carries two open runs.

The fence's tests were removed with the file they lived in; the property they
encoded is now carried by `append_run_start_closes_an_unterminated_run` (a new
prompt closes the crashed run) and the placeholder tests under
`session/manager/tests/`. `docs/architecture/agent-supervision.md` §9.1 gains a
reversal note and its D8/D9/D10 rows are marked reversed rather than rewritten,
so the design history stays readable.

Verified on a copy of the session this was reported against
(20261025-215423): with the fence gone its `shell` runs again, a kill mid-tool
followed by a restart submits nothing, and the next prompt still tells the model
that the earlier call's outcome is unknown.

* test(tui): fail when the workbench draws chrome it did not take from the table

`i18n.rs` makes a half-translated key uncompilable. It says nothing about a
string that never went through the table, and that is how the bilingual surface
drifts back to one language: every branch that adds a panel adds its own labels,
and a hardcoded literal compiles and looks finished in whichever language its
author happened to write. The three branches waiting to merge are exactly that
case.

`tui/tests/i18n_guard/` is the check, run by `cargo test -p future-tui` with no
new CI job. It reads the sources and reports `file:line: literal` for two
shapes:

- Anything with a CJK character under `tui/src/` — chrome is authored in Chinese
  here, so a Chinese literal is chrome that skipped the table. Content is
  untouched: a conversation, a title or a path is runtime data.
- An English sentence drawn by the surface (`workbench/` plus the modules it
  pulls display text out of). Two words of three or more letters, in a literal
  that is not a path, an identifier, an escape sequence or a format skeleton.

Test modules are not read (they draw no frame) and `workbench/demo.rs` is exempt
as a file (its strings are the content a session carries). The rest is a
30-row allowlist with a reason per row or a same-line `// i18n: <reason>`
marker, and `BUDGET` pins the number of exemptions so a new one cannot be added
quietly — the test fails until the number a reviewer reads moves too. Stale
rows fail as well.

On `dev-huichen` the guard is green: 52 files, 2299 literals outside tests, 60
chrome candidates, all exempted. 27 of those exemptions are pre-existing
English-only chrome (the notice row, the approval-mode chip, the compaction
marker, the folded-output footer) — frozen rather than translated, because
translating them would change what a reader sees and belongs in its own change.

`docs/tui/i18n-homeless-strings.md` (and its zh-CN pair) documents the rules,
the blind spots, the frozen gaps, and the port list for `feat/workbench-ui`,
`feat/wb-mentions` and `fix/workbench-degrade`, measured by pointing the same
check at each branch's tree and diffing it against the commit where it left
`dev-huichen`: 167/120/47 added literals, of which 84/6/41 are new chrome and
the rest are already table rows, demo data, or known gaps. It also calls out the
strings hardcoded in several places at once so the merge fixes them once.

The only change to a drawing path is a comment: the two invariant messages the
guard exempts in place carry their `// i18n:` marker. No wording, no behaviour,
and no row of the existing 102 keys moved.

* feat(agent): name the shutdown sub-step a slow drain is stuck in

A timeout report prints the stage the drain was in when its budget ran out.
The admission phase had exactly one name, so "during admission" could not say
whether the time went on the session-map snapshot or on one session's lock -
"the service is wedged" and "one busy session is wedged" need different
answers, and the last three timeouts were all reported as this one name.

Split it into "admission: session snapshot" and "admission: interrupting
sessions", both set BEFORE the step that may block: a drain stuck past its
deadline never reaches its own completion line, and the deadline watcher reads
only this name. The initial "admission" stays as the value a report shows when
the drain never got as far as either step.

Also time both steps and warn past 250 ms, naming the sub-step and the session
whose lock was held (with whether it had an active run, read from the guard
once it is finally ours). Measurement only: no try_read, no skipped session, no
change to `wait` or to the five-second budget, and a timeout still fails
exactly as before.

Tests drive `drain` on the test thread so a thread-local subscriber sees the
warning: a held session write lock produces a warning naming the sub-step and
that session and not the uncontended snapshot, and a drain with free locks
stays quiet (the threshold must filter, or it would bury the one that matters).

* test(cli): assert the endpoint of a terminal credential verdict, not the race

`a_freshly_refreshed_credential_rejected_on_a_live_link_is_terminal`
asserted that a refused-but-fresh grant arms no rebuild, and the loaded CI
runner printed `[RT001] … rebuilding generation (1/3)` before the entry's
status poll noticed the verdict — red on Linux/macOS/Windows `tui-cli`
(run 40207454243), green when the case ran alone.

The assertion is stale, not the code: `d99a2546d` made a refused grant end
only *that generation*, so `watch_generation` now treats the terminal health
as one more unhealthy generation and rebuilds it from a new mint. Two
components react to the same verdict on independent clocks — the watcher's
one-second tick and the entry's one-second status poll — so which line lands
first is not a property of the product.

What the terminal verdict buys is the endpoint, and that is what the test now
asserts: the run must end by itself, it must fail, the reason must be
`ServiceAuthorization`, and the last phase the entry reports must be
`Failed` — a rebuild may report the replacement live for as long as this
broker takes to refuse it, but it must not turn the stop into continued
service. `ChildRun` grows `wait_for_exit` and `settled_text` for that; the
docstrings and the TAU-D26 index bullet now name the `d99a2546d` contract
instead of the arm it replaced.

Verified: 14/14 green in five consecutive full runs of the binary on 1.97
(70-72 s each) plus twice standalone; the inverted phase assertion was
checked once to fail against the real transcript.

* fix(desktop): remove the auto-resume switch that no longer does anything

`9c83f6115` removed restart auto-resume and the recovery fence it needed, so the
agent no longer reads `resumeInterruptedOnStart`. The desktop kept the switch:
toggling it stored a value nothing acted on, which is worse than having no
switch, because it read as a guarantee about restart behaviour.

Removed: the GeneralPage row and its props/type, the SettingsDialog wiring, the
`AppSettings` / `DEFAULT_APP_SETTINGS` / `updateAppSettings` fields, the
settings.rs test literal, the en/zh copy, the screenshot fixture, and the CLI
surface (`future desktop settings` listed it as settable and wrote it).

Kept deliberately: `AppSettings::auto_resume_interrupted` and its stored key
read back unchanged, so existing app.db rows and older clients see the same
document, with no writer and no UI behind it. `SETTINGS` and the round-trip
test's field list are the two places told about that one exception.

Verified: desktop vitest 5291 passed, tsc / eslint / vite build clean; cargo
test -p future-cli 1398 passed (one PATH-race flake that passes 3/3 alone),
future-app-settings 20 passed, host settings + session modules 54 passed;
clippy -D warnings on future-cli / future-host / futureos; fmt clean; make
check-docs clean.

* feat(tui): make the workbench adaptable to the reader

* perf(remote): pipeline indexed NATS downloads

* perf(tui): one frame metric per iteration, and an idle ticker that paints nothing

The driver loop had two independent ways to re-lay-out the whole
conversation for nothing:

* The event path asked the adapter for a whole frame at width `1`
  (`live.data(1)`) to read one field. `ChatArea` caches its rendered rows
  per width, so every keystroke and every streamed token threw the cache
  away twice and re-wrapped + re-parsed the whole transcript.
* The ticker arm was empty, so the loop could not tell "nothing changed"
  from "nothing happened" and recomposed the frame eight times a second —
  including the `WorkbenchData` clone of every rendered row.

`layout::Frame` now carries the frame's own metrics (size, the bands, and
the conversation's text width) and one is computed per iteration and
handed to both halves of it, so the width the transcript wraps to is the
width it is drawn at. `Live::activity_kind()` / `activity_animating()`
answer the two fields the loop reads without building a frame.
`chat_padding()` / `chat_inner()` are the single definition of the
conversation width, which also settles a sub-8-column disagreement between
the driver's wrap width and the compositor's padding.

Agent events that are already queued are now applied in one layer
(`drain`, capped at `COALESCE_LIMIT = 4096` so a producer that outruns the
surface cannot starve the keyboard), and a `TickClock` answers whether a
120 ms tick owes a frame at all: the spinner's drawn frame while a run is
in flight (4 ticks, two frames a second), and the sidebar's session ages
once a minute otherwise. With nothing on screen that reads the clock, an
idle tick paints nothing.

Measured (macOS, pinned 1.97.0 toolchain, release probe; see
docs/testing/tui-event-loop-cost-2026-10-26.md): one streamed delta in a
200-turn conversation 33.5 ms -> 0.45 ms, with 2 -> 0 full transcript
rebuilds per event; a 20-delta batch 666 ms -> 0.4 ms; at 30 tokens/s that
is ~100 % of a core -> ~1.3 %. An idle debug build over a 600-turn
session: 18.6 % -> 0.3 % of one core (4.2 % -> 0.3 % with no tty), and an
idle 3 s sample no longer reaches `render_all`, `Live::data` or `compose`
at all. Frames stay byte-identical at every terminal size of 8 columns and
wider (30 frames / 638 rows compared against origin/dev-huichen with a
temporary dump harness).

* fix(remote): report a non-numeric pull index as a chunk-index error

fcb516f (perf(remote): pipeline indexed NATS downloads) moved numeric
pulls into a pipelined path but dropped the parse-failure arm, so a pull
whose index is not a number fell through to the catch-all and answered
"Unsupported transfer operation." instead of the chunk-index error the
pre-pipeline loop, the host transfer-loop test and clients expect.

Restore that message through one constant shared by the "chunk" arm and
the pull fall-through.
@huichen
huichen deleted the fix/recovery-abort-persist branch October 26, 2026 07:45
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