Skip to content

feat(agent,cli,tui,host): supervise the Agent on all entry points;held locks, run continuation - #1286

Merged
huichen merged 16 commits into
mainfrom
pr/huichen
Oct 21, 2026
Merged

huichen merged 16 commits into
mainfrom
pr/huichen

Conversation

@huichen

@huichen huichen commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

以 feat(agent,cli,tui,host): supervise the Agent across all three entry points 为主体的集成分支批次,另带三项配套改动与两处桌面修复。

提交(非合并,6 条)

  • feat(agent,cli,tui,host): supervise the Agent across all three entry points — agent/tui/cli/host 三个入口共享同一套 Agent 监管(packages/rpc/supervision、host::agent_host、tui::agent_supervisor、cli/src/headless/agent.rs、agent/src/rpc/resume.rs),文档见 docs/architecture/agent-supervision*.md。
  • feat(scripts): a lab guard that makes an experiment's data root provably isolated — scripts/dev/lab-guard.sh + 17 条 shell 用例。
  • test(rpc): cap the jitter bound in the restart-delay assertion — 重启退避抖动上界的断言收紧。
  • fix(tui,cli): wait on events instead of the host's speed in three flaky tests — 三条时序 flaky 测试改为等事件。
  • fix(desktop): split KaTeX into its own chunk and drop a no-op dynamic import — 数学公式渲染改懒加载(lazyKatex.ts、MathBlock/MathInline),新增 MathLazyLoad.test.tsx。
  • fix(desktop): restore the base stylesheet the palette commit dropped — 恢复被调色板提交丢掉的 globals.css 基础样式,附 globals.test.ts。

本地已跑(全绿)

  • cargo fmt --all -- --check
  • cargo clippy -p future-rpc -p future-host -p future-tui -p future-cli -p future-agent --all-targets -- -D warnings
  • cargo clippy -p futureos --all-targets -- -D warnings
  • cargo test -p future-rpc -p future-agent -p future-tui --lib(2235 通过)
  • cargo test -p future-host --lib -- agent_client agent_host(30 通过;整包 lib 套件在本机约 8 分钟以上,本次按模块跑)
  • cargo test -p future-cli --lib -- headless、cargo test -p future-cli --test remote_start_refusal
  • desktop: npm run lint(eslint + tsc)、vitest run src/features/markdown src/features/remote-peer/RemoteComposer.test.tsx src/styles/globals.test.ts
  • bash scripts/dev/lab-guard.test.sh(17 例全过)

后续并入本 PR 的 4 条(2026-10-21 晚)

  • fix(agent,host,desktop): keep a held Agent lock a yield, not a cancellation — 启动期被别的进程持有的 Agent 锁不再被当作取消,agent/tests/service_startup.rs 的 StartupBlocked 断言与桌面 agent_supervisor 夹具随之转绿。
  • fix(agent,host,cli,rpc): continue interrupted runs in the Agent, and unbreak three tests
  • fix(tui): report a clipboard program's exit status, not the broken pipe
  • fix(desktop): say "add a conversation" in the Vibe panel's menu

分支上的合并提交均为把上述任务分支并入 dev-huichen,不改变内容归属。

… import

The install build reported two warnings, both pointing at real bundle work:

- `index` was 2,024 kB, over the 2,000 kB budget. Almost a quarter of it was
  KaTeX (458 kB of source), which only a conversation that shows a formula
  needs. It now loads through `lazyKatex` on the first formula and lands as a
  259 kB chunk; `index` is 1,766 kB and the build is warning-free. Until the
  chunk arrives a formula renders its own source, so the line keeps its height
  instead of popping in.
- The composer's `import("./remotePromptOutbox")` could never split anything:
  the composer and `AppShell` both import that module statically, so it only
  earned an INEFFECTIVE_DYNAMIC_IMPORT warning. It calls the module directly
  now; the `active` flag still guards a recovery that settles after unmount.

Tests: `MarkdownMath` / `MathFallback` wait for the engine before asserting its
markup, and `MathLazyLoad` covers the split itself (source first, formula once
the chunk lands). Desktop suite: 364 files / 5,000 tests green, plus `tsc`,
`eslint` and `npm run build`'s worker check.
…points

Three entry points can bring the Agent up for one data root, and each answered
"who starts it, who owns it and what happens when it dies" differently. Measured
before this change: a `kill -9` of the owning process left the survivors
reconnecting forever (40s, two cases), and a client that met a held instance lock
exited 1 instead of waiting for the owner to finish starting.

What the supervisor does now, in `future-rpc::supervision` so all entries share
one policy:

- **Yielding instead of failing.** `ConnectionError::InstanceBusy` and
  `host::Error::AgentBusy` give "another process owns this data root" a type of
  its own; `AgentHost` maps it to `Stopped`, never `Failed`, so the host stays
  restartable. Both gates apply before any wait: a genuine failure (a dead
  explicit endpoint, a version mismatch) is still reported immediately.
- **Bounded waiting.** A client that meets a held lock waits up to 180s (the same
  budget `AgentHost::START_TIMEOUT` uses, not stacked on top of it), says so
  after 30s with the holder's pid/host, and stops with a stated reason. Headless
  exits at the cap and leaves the retry to its supervisor; the TUI keeps a
  usable screen and a permanent status line.
- **Self-healing.** Headless, the TUI and the Desktop now watch the endpoint
  instead of the launch they performed once. When nothing answers and the lock
  is free, they start an Agent; when another process holds it, they wait.
  Measured: 3s (headless) and 1s (TUI) to a new Agent after the owner was killed.
- **A crash-loop breaker.** 3 starts in 300s opens a 60s cooldown that doubles to
  600s. The budget is cleared only once the Agent has stayed reachable for 60s:
  clearing it on "became ready" would let an Agent that the host kills on every
  run (OOM, a per-user quota) reset the breaker each lap, which is the case the
  breaker exists for.
- **Restart continuation in the Agent.** The instance lock makes this the one
  trigger, so two clients cannot both continue the same interrupted task. It
  resumes from the Agent's own journal, skips streaming sessions, sessions parked
  on an approval, sessions with no model, sub-sessions and anything older than
  seven days, and never does more than three per start. Off by default
  (`resumeInterruptedOnStart` in `~/.future/agent/settings.json`): continuing
  sends a prompt the user did not type and spends their credits with nobody
  watching. It logs what it checked even when it continues nothing.
- Not under `cfg(test)`: a unit test that does not redirect HOME would otherwise
  read the developer's real settings and, once the switch is on, send prompts
  into their real sessions.

Verified with a release binary in isolated homes and a local stub model endpoint
(no real credential spent): see §13 of `docs/architecture/agent-supervision`
for the before/after of each case, including the two continuations and the
switch-off default.

Also fixes a pre-existing `-D warnings` failure that blocked the workspace
clippy pass on this branch: `WebPortPin`/`pin_web_port` were gated on
`test-support`, which the desktop and CLI enable without compiling this crate's
`#[cfg(test)]` tests, making them dead code there.

Known pre-existing, not addressed here: `grpc::tests::the_public_serve_wrappers…`
fails in a worktree whose path makes `target/test-homes/.../.future/run/agent.sock`
longer than a unix `sun_path` (104 bytes on macOS). It passes from the shorter
main-worktree path and fails identically on this branch's base commit.
The base is capped at 30s, so attempt 5's lower bound is 24s, not 25.6s; the
assertion failed intermittently, depending on the process-seeded jitter.
…bly isolated

An experiment launch that forgot to export FUTURE_HOME still ran, and only the
desktop's own lock stopped it from opening the real ~/.future. Luck, not design.
`scripts/dev/lab-guard.sh` closes that, and every gate fails closed.

Home gate (whitelist, not blacklist):

- **Set and non-empty.** Unset or empty is the accident itself: the app falls back
  to ~/.future.
- **Absolute.** A relative or `~` value is *ignored* by the app (it requires an
  absolute root), so it silently falls back too.
- **Resolved before comparing.** `~` is expanded and symlinks are resolved
  (`os.path.realpath`), so a `/tmp` link into the real home is seen as the real
  home.
- **Under `/tmp`, `$TMPDIR` or `/private/var/folders`.** On macOS `$TMPDIR` lives
  in `/var/folders/…`, so a `/tmp`-only rule would reject valid labs. Every root
  is resolved the same way as the candidate, and the path must be *under* a root
  (the bare root is refused), with `/tmpfoo` not matching `/tmp`.

Cleanup (`pids` / `kill`) never trusts a column position:

- Candidates come from verified supervisors (command line names this guard and
  this exact lab root) plus their descendants plus a recursive `lsof +D` sweep,
  so a child that opens no file under the lab is still found.
- A pid is signalled only if its command line names the root, or its parentage
  does, **and** it holds nothing under the real data root. Anything skipped is
  printed with its reason.
- TERM first (so a supervisor's trap can forward it), KILL only survivors.

`run` also sets HOME/USERPROFILE to the lab root and clears
FUTURE_AGENT_GRPC_ADDR / FUTURE_AGENT_SOCKET: an inherited endpoint override
points a "lab" run at the real Agent, the same class of accident.

Not on any product entry point's path: nothing under agent/, host/, cli/, tui/,
desktop/ or packages/ references it, and `future headless --help` is unaffected.

`lab-guard.test.sh` pins 17 cases (unset, empty, real root, real home, relative,
`~`, three whitelisted roots, bare root, look-alike prefix, two symlink escapes,
the `.future`-as-root mistake, the exported environment, pid discovery, orphan
cleanup, and the real-root refusal). Weakening the guard was verified to fail
two of them, so the assertions are not vacuous.

Two defects were found by running it, not by reading it: `lsof <dir>` does not
recurse (so a child was invisible and killing the supervisor orphaned it), and
SIGKILL bypassed the supervisor's trap. Both are fixed above.
…ky tests

Three tests decided a state transition by waiting on something other than the
transition itself. Each failed on `main` and on #1283's head on 2026-10-21, and
each is fixed here at its own seam rather than by loosening an assertion.

**`rpc::grpc_client::tests::manager_loop_top_stop_with_idle_manager`**
(`test task did not reach its synchronization point: Elapsed(())` on Windows).
The stream manager's first act on an empty session is to reach the idle branch,
and the test arms a gate at the top of that branch — but `GrpcClient::new`
spawns the manager, so on a multi-thread runtime the task could reach the branch
before the gate was armed, take an empty slot, and park on a wakeup that never
came. Split construction: `new()` is now `build()` plus `start_tasks()`, and a
test that must arm a gate in between uses the test-only `new_dormant()`.
`session_poke_between_empty_read_and_wait_is_not_lost` and
`disconnect_between_idle_check_and_wait_releases_the_client` had the same
ordering and use the same seam.

**`rpc::grpc_client::tests::subscribe_failure_modes`** (`never connected:
Elapsed(())` on macOS). The fixture's connect-state bound was 10 s. Measured on
a loaded host, the same handshake took 0.91 s to 14.96 s across concurrent
copies, so the bound sat inside the spread. It is now `CONNECT_STATE_BOUND =
60 s` (4x the worst measured), which bounds the whole `wait_conn` family —
a genuine regression still reports, it just takes longer to say so.

**`index::tests::interactive_resize_during_and_after_startup`** (exit 1 with
`future-tui: interrupted during startup` on macOS). The fixture decided startup
was over from the mock's command log plus a grace of `unary_delay_ms + 400`, but
startup keeps issuing unary calls after its last handshake command
(`list_models` follows the session handshake), so at a 400 ms delay the grace and
the end of startup were a dead heat and the ctrl+c landed in the startup
interrupt arm. `run_interactive` now signals the transition itself through a
test-only gate, so the driver waits on the real edge and the host's speed drops
out of the assertion.

`cli/tests/remote_start_refusal.rs`: on Windows the interrupt helper asserted a
successful `AttachConsole`, which also fails when the child has already exited —
and the parent can only check liveness *before* spawning the helper, so a child
that shuts down on its own in that window made the helper red. Attach is now
retried briefly and treated as moot when the child is gone; a live child without
a console is still a failure.
#1283 (d4dc86c) replaced the palette section of `styles/globals.css` and, in
the same edit, deleted every rule that is not a color: the `:root` base block,
two hand-written animation utilities, the rail toolbar's container query and the
two `::highlight()` rules. Nothing failed: the stylesheet still compiles, every
class is still used, and the palette suites only look at `--color-*`.

What that cost, all of it app-wide rather than rail-only:

- `-webkit-font-smoothing: antialiased` (and the `-moz-` twin) went with it, so
  macOS painted subpixel-antialiased glyphs and every label read heavier --
  `text-sm font-medium` most visibly, which is the rail's row title.
- The font stack fell back to Tailwind's `ui-sans-serif, system-ui`, losing the
  CJK preferences (PingFang / Microsoft YaHei / Source Han).
- `--text-*` stopped multiplying `--app-font-scale`, so the Settings text-size
  choice reached only the `leading-*` overrides: sizes were dead.
- The light `--shadow-*` values vanished, leaving light-theme panels, dialogs
  and the floating rail flat (the dark ones still lived in `:root.dark`).
- `animate-pop-in` and `animate-skill-entry-pulse` lost their keyframes while
  three components kept the class; the selection toolbar lost its container
  query, so its labels stopped collapsing; `::highlight(thread-search-*)`
  stopped painting in-thread search hits.

Restored verbatim from d4dc86c^, with a comment on why the smoothing flags
matter, and placed in the same order as before (`:root.dark` then `:root` then
the palette blocks, which the specificity notes in `globals.css` require).

`globals.test.ts` gains a base-rendition suite so this cannot happen quietly
again: the type tokens must read `var(--app-font-scale)`, the font stack and
both smoothing flags must be declared, light shadows must differ from the dark
ones, the base block must sit between `:root.dark` and the palettes, and each
hand-written animation keyframe plus the container query and highlight names
must exist. Falsified by reverting only the stylesheet: 6 tests red, 20 green;
restored, 26 green. The full desktop suite passes (5006 tests), as do
`tsc --noEmit`, eslint on the suite and stylelint.

Rendered evidence, harness `rail-tree` at 1280x860 before/after: mean ink in the
288px rail column 13.33 -> 11.64, i.e. the rows' strokes are visibly lighter
again; the built stylesheet keeps every restored rule, and `.text-sm` still
resolves through `var(--text-sm)`, so the text-size setting scales it.
@huichen
huichen enabled auto-merge (squash) October 21, 2026 10:31
The panel menu's add row carried `t("menu.add")` and `t("menu.addHint")`, but
`vibe.json` only ever had those strings under `add.*` (`add.title`,
`add.footer`). Nothing caught it: the component type-checks, the panel's tests
assert the rows they need, and the menu rendered the key itself — measured in
the harness with the menu open, the row read `menu.addmenu.addHint`. The
empty-state button under the grid asked for the same key and showed `menu.add`.

Adds `menu.add` / `menu.addHint` to both locales, phrased the way the add sheet
already says it ("adding pins it: it appears here and in the sidebar's pinned
section"), and points the empty state's sentence at the label the button now
shows.

`i18n/localeKeys.test.ts` closes the class: every literal key a component asks
for — `ns:key` or the single-argument form matched against every namespace —
must exist in every locale, plural suffixes included. Falsified by reverting the
two catalogs: the suite then reports exactly the four missing entries
(2 keys x 2 languages) and nothing else; with them, 2 tests green. The desktop
suite passes (5008 tests), as do tsc, eslint and stylelint.
…lation

Commit 4886036 gave a held instance lock its own
`ConnectionError::InstanceBusy` / `host::Error::AgentBusy`, so supervision can
wait for the holder instead of reporting a fault. Two callers still assumed the
old `StartupBlocked`/`Failed` shape:

- `AgentHost` mapped `AgentBusy` to `Stopped` (correct: the host stays
  restartable) but then dropped the reason: `start` fell through the wait loop
  into "Agent startup was cancelled", and the Desktop status page substituted
  the endpoint's transport error. Both now carry the worker's own refusal:
  the reason is recorded beside `Stopped`, returned from `start` as
  `AgentBusy`, exposed as `yield_reason` and used by `agent_status`. The
  `Stopped`-without-a-reason path still reads as a cancellation, which is what
  the stop-during-startup fixtures assert.

- `agent/tests/service_startup.rs` (gated-lock) still asserted `StartupBlocked`.
  That is the stale half of the pair: the lock gate deliberately reports the
  yield variant now, as `packages/rpc/src/connection/tests.rs` already asserts.
  The test's other claims (metadata untouched, no storage created) are
  unchanged; nothing was loosened.

The host's `locked` fixture now also pins the typed error and the recorded
reason, so neither can silently regress to a cancellation again.

Verified: cargo fmt --all --check; clippy -p future-host/-p future-agent/
-p futureos --all-targets -D warnings; cargo test -p future-agent --test
service_startup (15), -p future-rpc --lib (216), -p future-host --lib --
agent_host (22), -p futureos --lib -- agent_supervisor (9), -p future-cli
--lib -- headless::agent::block_fixtures (3).
`run_native` piped the text into the program and returned immediately when
that write failed. A program that exits without reading its stdin — `false`,
`cmd /c exit 3`, or a clipboard helper rejecting its arguments — makes the
write fail with EPIPE, so the caller heard "failed to write: Broken pipe"
instead of the reason the copy did not happen, and the exit status and stderr
were dropped on the floor. Whether the small payload of a real copy loses that
race depends on the host: the macOS runner produced it in
`native_runner_reports_a_nonzero_exit_without_stderr` (tui/src/clipboard.rs),
i.e. a required check failing on a behaviour nobody intended.

Now the write error is held aside, stdin is closed so a program that stopped
reading still sees EOF, and the wait decides: a non-zero exit reports its
status (or stderr) — the pipe broke because the program had already left — and
only a *successful* exit with an undelivered payload is reported as
"failed to write", which is the case where the clipboard really does not hold
what the caller asked for. That keeps both existing contract tests
(`true` with a 1 MB payload still reports the write failure) and makes the
exit-status arm deterministic.

Added `run_native_prefers_the_exit_status_over_a_broken_stdin_write`: a
non-reading program that exits 3 with a 1 MB payload, which forces the broken
pipe instead of racing for it.

Verified: cargo fmt --all --check; clippy -p future-tui --all-targets
-D warnings; cargo test -p future-tui --lib -- clipboard (65 passed); the two
non-zero-exit tests 40 consecutive runs, 0 failures.
…unbreak three tests

Continuation belongs to the Agent, not the desktop.

The Agent owns the journal the decision reads, and the instance lock makes it the
single trigger. The desktop's one-shot pass sent the same conversation a second
continuation when it ran beside it, so it is retired: the call is gone, the
module (759 lines with its tests) is deleted, and the replacement is
`agent/src/rpc/resume.rs`, which already ran there. The switch moves with the
executor: `resumeInterruptedOnStart` in `~/.future/agent/settings.json` is now
**on by default**, matching the consent the desktop already recorded
(`autoResumeInterrupted`, also on by default), so moving the mechanism does not
silently drop a behaviour users rely on. The desktop's Settings toggle writes
through to that key, because a switch nothing reads is worse than no switch.

Verified end to end with a release binary in an isolated home and a local stub
model endpoint: with no settings file at all, `future agent` alone logs
`1 conversation(s) checked, 1 continued`, the stub receives one request whose
last user message is the continuation prompt ("上一轮运行在 Agent 重启时被中断了" —
the Agent's wording, not the retired pass's), and `interruptedRun` clears with
`queryCount` 1→2. With `resumeInterruptedOnStart: false` nothing is sent and the
run stays interrupted.

Three test failures, each with the mechanism identified rather than papered over:

- **`models::tests::registry_injects_future_models_from_disk_cache`** flaked in
  parallel (2 of 10 runs; 0 of 4 when the future-models tests were excluded,
  which pointed at their background refreshes). Several test modules build a
  `Registry` without a `TestHome`, so a refresh thread they spawn can publish a
  different catalog into the process-global memory cache between another test's
  reset and its assertion. Test builds now serialize reads, resets and publishes
  through one re-entrant `CACHE_ACCESS` lock (re-entrant so a build reached from
  inside a build cannot deadlock), and every refresh carries a generation number
  so one that spans a reset never publishes. 20 runs after the change: no
  failures. A first attempt inverted the lock order against the existing
  future-models test lock and deadlocked the suite; the order is stated in the
  test.
- **`grpc::tests::the_public_serve_wrappers…`** failed in a long-path worktree:
  `$HOME/.future/run/agent.sock` was 113 bytes against the 104-byte `sun_path`
  limit (78 in the main worktree, which is why it only broke in worktrees). This
  is a product bug, not just a test one: a deep home made the Agent fail to bind
  with a bare `Operation not permitted`. Endpoints past the budget now fall back
  to a short deterministic name in a per-user directory under the temp root,
  keyed by a hash of the path they wanted (still per-instance). The temp root
  itself cannot be the parent — the endpoint's lease step chmods its parent to
  0700 and macOS refuses that on `$TMPDIR`, which is how the first attempt failed.
  Short homes keep the documented layout.
- **`cli/tests/bin.rs::config_wizard_reports_the_missing_console…`** hung forever.
  With piped stdin the unix path still let `rpassword` open `/dev/tty`; on a
  machine where the process has a controlling terminal it blocks there
  indefinitely, so the "an interactive console is required" error the test
  asserts never appears. Windows had this guard; unix did not. Non-terminal
  stdin is now refused before the platform read, on both. `future config` with
  piped answers exits 1 with that message instead of hanging.

`make check-docs` (311 docs), workspace clippy `-D warnings`, host/desktop
clippy, and the agent (2479), host (1745), tui (2235), rpc (218) and cli suites
all pass.
@huichen huichen changed the title feat(agent,cli,tui,host): supervise the Agent on all entry points;scripts lab guard, KaTeX chunk feat(agent,cli,tui,host): supervise the Agent on all entry points;held locks, run continuation Oct 21, 2026
@huichen
huichen merged commit 254f4d9 into main Oct 21, 2026
29 checks passed
@huichen
huichen deleted the pr/huichen branch October 21, 2026 11:32
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