Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): gate configuration behind runtime (#1684)
Call Whiteadea98b367d8
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex ff29a61e6..d16bdeb92 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -358,6 +358,8 @@ class EngineAdapter(Protocol):async def start(self) -> EngineStatus: ...+ async def stop_runtime(self) -> EngineStatus: ...+async def stop(self) -> None: ...async def status(self) -> EngineStatus: ...diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex a002b859f..15c37fe8c 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -132,4 +132,6 @@ async def dispatch_model_hub_rpc(return await service.runtime_install()if operation == "runtime_start":return await service.runtime_start()+ if operation == "runtime_stop":+ return await service.runtime_stop()raise ModelHubError("source_not_found", status=404)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 5e780327e..f4116c9ee 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -209,6 +209,9 @@ class UnavailableEngineAdapter:async def start(self) -> EngineStatus:raise EngineUnavailableError+ async def stop_runtime(self) -> EngineStatus:+ return await self.status()+async def stop(self) -> None:return None@@ -4524,6 +4527,29 @@ class ModelHubService:status = await self._engine_call(self.adapter.start())return _runtime_payload(status)+ async def runtime_stop(self) -> dict:+ await self.reconcile_runtime_installation()+ async with self._mutation_lock:+ config = self.store.load()+ hub_backends = sorted(+ backend+ for backend, agent in config.agents.items()+ if agent.mode == "hub"+ )+ if hub_backends:+ raise ModelHubError(+ "runtime_in_use",+ status=409,+ data={"backends": hub_backends},+ )+ stop_runtime = getattr(self.adapter, "stop_runtime", None)+ if not callable(stop_runtime):+ raise ModelHubError("engine_down", status=503)+ status = await self._engine_call(stop_runtime())+ if status.health is EngineHealth.INSTALLING:+ raise ModelHubError("runtime_busy", status=409)+ return _runtime_payload(status)+def migration_scan(self) -> dict:config = self.store.load()return {diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex ff29a61e6..d16bdeb92 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -358,6 +358,8 @@ class EngineAdapter(Protocol):async def start(self) -> EngineStatus: ...+ async def stop_runtime(self) -> EngineStatus: ...+async def stop(self) -> None: ...async def status(self) -> EngineStatus: ...diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex a0f1889eb..092399696 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -36,7 +36,8 @@{"method": "GET", "path": "/api/models/turns/<turn_id>/provenance", "response_schema": "ProvenanceResponse", "exercise": {"path": "/api/models/turns/turn_contract01/provenance", "status": 200}},{"method": "GET", "path": "/api/models/runtime/status", "response_schema": "RuntimeResponse", "exercise": {"path": "/api/models/runtime/status", "status": 200}},{"method": "POST", "path": "/api/models/runtime/install", "response_schema": "RuntimeResponse", "exercise": {"path": "/api/models/runtime/install", "status": 200}},- {"method": "POST", "path": "/api/models/runtime/start", "response_schema": "RuntimeResponse", "exercise": {"path": "/api/models/runtime/start", "status": 200}}+ {"method": "POST", "path": "/api/models/runtime/start", "response_schema": "RuntimeResponse", "exercise": {"path": "/api/models/runtime/start", "status": 200}},+ {"method": "POST", "path": "/api/models/runtime/stop", "response_schema": "RuntimeResponse", "exercise": {"path": "/api/models/runtime/stop", "status": 200}}],"definitions": {"SourceApi": {diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 0bf860548..2f402f470 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -56,6 +56,7 @@ compatibility path.| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 6; `not_started` is installed lazy-start idleness, not an alarm. || POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. || POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Explicitly starts the managed engine. Uses the existing mutation authentication and CSRF guards; status reads never start it. |+| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |The removed global route `PUT /api/models/priority` has no replacement. Backend Sourceorder is explicit configuration through the sources route; exact per-model order isdiff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex a9325ad2e..34e383de2 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -33,12 +33,13 @@ a reviewer can open the exact frame.| 11 | `cyaYh` | 模型网关 11 — 编辑来源 / 移除来源 || 12 | `qQvkP` | 模型网关 12 — needs_action 来源卡片 || 13 | `Q9q5lF` | 模型网关 13 — 添加订阅厂商菜单 |+| 14 | `IM4c2` | 模型网关 14 — 运行时关闭 |There is no 07: it was removed during the design pass and the remaining frameswere deliberately **not** renumbered, so that every existing reference to "08"keeps pointing at the same picture.-**All thirteen frame exports are covered and specified.** Frame 02's drawing remains the+**All fourteen frame exports are covered and specified.** Frame 02's drawing remains thevisual authority; §1.2 now registers the interaction facts a drawing cannot carry: theroute-replacement draft, save and guard sequence, complete success-envelope consumption,lost-response reconciliation, failure copy and keyboard path. G-32 remains in §0.5 only@@ -797,25 +798,25 @@ state exit; held intent never bypasses the evidence column.| Authoritative phase evidence | held `install_and_start` | held `install_start_switch` | no held sequence || --- | --- | --- | --- || Status reads `installing`, including after reload | Installing; retain the sequence and keep the 2s read owner | Installing; retain the sequence and keep the 2s read owner | Installing and keep the same 2s read owner; there is no continuation promise |-| Status reads `not_started` | Send runtime start, enter Starting and retain the sequence | Send runtime start, enter Starting and retain the sequence | Not started; do not infer either sequence |-| Status reads `down` | Send runtime start, enter Starting and retain the sequence | Send runtime start, enter Starting and retain the sequence | Unreachable; do not infer either sequence |+| Status reads `not_started` | Send runtime start, enter Starting and retain the sequence | Send runtime start, enter Starting and retain the sequence | Closed; do not infer either sequence; the page-level switch is the only activation |+| Status reads `down` | Send runtime start, enter Starting and retain the sequence | Send runtime start, enter Starting and retain the sequence | Closed with failed-start copy; do not infer either sequence; the page-level switch is the only activation || Status reads `not_installed` | The owning F state retains the sequence; Retry resumes install | The owning §1.9 Failed state retains the sequence; Retry resumes install | Dispatch `error_key` and manifest support through Install failed / Not installed / Unsupported host || Status reads runtime live (`ok` or `degraded`) | Perform the ordinary full live-page dispatch, then release the sequence | Send the mode `PATCH` and enter §1.9 Committing; retain the sequence until M5 accepts the committed AgentSupply evidence, then let M5 own its Source read | Perform the ordinary full live-page dispatch || Any owned request or read fails | The owning F state retains this exact sequence; Retry resumes its first unproved phase | The owning F state retains this exact sequence; Retry resumes its first unproved phase | The owning F state has no sequence to reconstruct || Frame | State | Entry condition | Failure / pending | Copy keys | Exit || --- | --- | --- | --- | --- | --- |-| §1.0 | Loading | Route entered, first payload outstanding | → Unreachable / Sources unread / Partial | — | What the payload says decides where it lands, not the fact that it arrived. In the order the page reads it: `health` first — `down` → Unreachable (engine down); `installing` → Installing; `not_installed` + non-null `error_key` → Install failed; `not_installed` + null `error_key` → Not installed or Unsupported host by the manifest; `not_started` → Not started; `degraded` → Impaired. Of those readings only `degraded` leaves the dispatch running, because it is the one reading under which the page's own two reads still answer (D-34) — the two are then dispatched underneath an Impaired pill at region grain, one of them failing → Sources unread or Partial in the region it owns; then `sources == []` → Empty (no sources); and a payload that trips none of them → Ready |+| §1.0 | Loading | Route entered, first payload outstanding | → Closed / Sources unread / Partial | — | What the payload says decides where it lands, not the fact that it arrived. In the order the page reads it: `health` first — `down` or `not_started` → Closed; `installing` → Installing; `not_installed` + non-null `error_key` → Install failed; `not_installed` + null `error_key` → Not installed or Unsupported host by the manifest; `degraded` → Impaired. Only `ok` / `degraded` expose the internal configuration. Under `degraded`, the page's two reads are dispatched beneath the Impaired pill at region grain; one failing → Sources unread or Partial in the region it owns. Then `sources == []` → Empty (no sources), and a payload that trips none of them → Ready || §1.0 | Ready | `health` reads `ok`, both page reads answered, and at least one source `[contract]` | F5 | `shell.running` | Any mutation re-renders in place `[derived]` || §1.0 | Empty (no sources) | `sources == []` | F5 | `upstream.empty` | 添加订阅 → 13, then a vendor row → 04; 添加 API Key → 05; first source → Ready || §1.0 | Not installed | `health: not_installed`, `error_key: null`, and an exact asset exists for server-derived `host_platform` `[contract]` | F5 | `shell.notInstalled`, `install.title` … `install.cancel` | Confirm holds initiating sequence `install_and_start` → Installing || §1.0 | Unsupported host | `health: not_installed`, `error_key: null`, and no `manifest.assets[].platform` exactly equals server-derived `host_platform` `[contract]` | F5 | `shell.unsupported` | Not from this page — 直连 (§1.8) is the documented escape hatch || §1.0 | Installing | `health: installing` from `POST /api/models/runtime/install`, a later status read or G-10's reload read `[contract]` | F2 — the installing-state read owner keeps the last progress state and read cause across a failed tick; the next 2s tick retries `[derived]` | `install.progress` | The observed state, not intent, owns the read loop. H1 dispatches every later RuntimeDependency: `installing` continues it; `not_started` or `down` starts runtime only for a held sequence; failed `not_installed` enters its F state; `ok` / `degraded` takes the held sequence's live row or ordinary page dispatch. Unmount stops polling; reload reconstructs no sequence || §1.0 | Install failed | `health: not_installed` with `error_key: settings.models.install.fail.detail` `[contract]` | F1 lands here | `install.fail.title`, `settings.models.install.fail.detail`, `install.retry` | 重试 sends the idempotent install route → Installing; dismiss leaves the persisted failed projection, and a later successful install clears it before entering Installing |-| §1.0 | Not started | `health` reads `not_started` `[contract]` | F5 | `shell.notStarted` | Run pill → Starting |+| §1.0 | Closed | `health` reads `not_started` or `down` `[contract]` | F5 | `shell.notStarted` or `shell.stopped`; `shell.closed.*` | Hide the tabs, Sources, Agent gateway models, route controls, supply lines and configuration dialogs. The off switch sends Start and enters Starting || §1.0 | Starting | Start accepted — `POST /api/models/runtime/start` | → Unreachable; H1 retains any initiating sequence | `shell.starting` | H1 owns a live payload before ordinary page dispatch: held `install_and_start` → perform Loading's full live dispatch, then release; held `install_start_switch` → send the mode `PATCH`, enter §1.9 Committing and release only after M5 accepts commit evidence; no held sequence → Loading's ordinary dispatch. No runtime reading may infer either intent || §1.0 | Impaired | `health` reads `degraded` `[contract]` | F2 at shell grain, over whatever the page already drew — on a first paint that is nothing, and the region whose read failed carries its own F1 beneath this pill (D-34) | `shell.degraded` | The next payload decides, read the way Loading reads one (D-33): `health` back to `ok` with both page reads answered and at least one source → Ready, `sources == []` → Empty (no sources), a page read still failing → Sources unread or Partial, another `health` value → whichever state that value names |-| §1.0 | Unreachable (engine down) | Status request fails, or `health` reads `down` `[contract]` | F2; H1 retains any initiating sequence | `shell.stopped` | Every recovered RuntimeDependency enters H1: only `ok` / `degraded` may advance held `install_start_switch` to its mode `PATCH`; `not_started` / `down` resumes runtime start for either held sequence; `installing` resumes the installing-state read owner; `not_installed` enters its registered failure/support state. With no held sequence H1 performs the ordinary health dispatch, and no recovery reading creates intent |+| §1.0 | Status unread | Status request fails with no retained live snapshot | F2; H1 retains any initiating sequence | `shell.unread`, `shell.closed.unread.*` | Internal configuration remains hidden until a live `ok` / `degraded` snapshot is available. A retained live snapshot may remain visible under F2, but the switch is disabled because the read is not authoritative || §1.0 | Partial | Sources load, per-backend supply does not | F1 on a first paint, in the region the group rollups would have filled; F2 on any later read, which keeps the rollups already drawn | `gateway.supply.unread`, `gateway.retry` on a first paint; `—` on a later one, which states nothing new because nothing it was showing changed `[derived]` | 重试 → the supply read runs again and what comes back decides, read against the source list this page is already holding (D-33): a reading with at least one source → Ready, or whichever rollup §1.1 names for it; a reading while `sources == []` → Empty (no sources), which a first-paint retry reaches whenever the list that succeeded beside it was the empty one; another failure → back here || §1.0 | Sources unread | The mirror: `GET /api/models/sources` fails while `health` and per-backend supply both answer `[derived]` | F1, in the region the list would have filled | `upstream.unread`, `upstream.retry` | The list decides, not the fact that one arrived: 重试 answers with at least one source → Ready, and with `sources == []` → Empty (no sources); a later payload carrying the list is read the same two ways || §1.1 | Ready | Sources + per-backend supply both loaded — the two page-level payloads every group-level element is drawn from. The per-model 当前 line is a third read, owned by Chain unresolved below, and this state neither waits on it nor fails with it | F5 | `gateway.group.subtitle.direct`, `gateway.group.subtitle.gateway`, `gateway.group.mode.direct`, `gateway.group.mode.gateway`, `gateway.group.status.ok` | Card → 06; 来源顺序 → 03; model row → 02; 切换到网关 → 10; 切换到直连 → Leaving the gateway; collapse row → Group expanded |@@ -1123,25 +1124,26 @@ destination and gets its own key, which is the case this rule is the complement**States** — §0.8, rows marked §1.0. Every other frame inherits them, and the rowsthat belong to a frame alone are marked with that frame instead.-Every state above except Ready is **not drawn** `[derived]`. Required behaviour:+Ready and Runtime off are drawn. Every other state above is **not drawn** `[derived]`.+Required behaviour:- Empty: upstream module keeps its head and footer and shows one line —「还没有来源。先添加一个订阅或 API Key。」 The gateway module shows its backendgroups with 「没有可用来源」 per group rather than vanishing; a backend thatexists is a fact independent of whether anything can supply it.-- **Not installed**: the pill reads `shell.notInstalled` and **is** an activation- target — for installation, not for start `[derived]`. It carries the same idle styling+- **Not installed**: the pill reads `shell.notInstalled`; the adjacent off switch is the+ activation target — for installation, not for start `[derived]`. The pill carries the same idle stylingas Not started, for the same reason: a missing optional component is not a fault. Itmust never offer 点击启动, because starting is not the action that resolves it. Theruntime contract enumerates `not_installed` alongside `not_started`(`runtime-dependency.schema.json`, `health`) `[contract]`, so a UI that collapses thetwo renders a start button that cannot succeed and reports the failure as if the- engine had crashed. Activating the pill opens an install confirm that names the+ engine had crashed. Activating the switch opens an install confirm that names thecomponent and its rough duration before anything is downloaded, exactly as D-26requires — but it is the **non-switching variant**, and the difference is notcosmetic `[derived]`.- | | From a backend's 切换到网关 (D-26) | From the run pill |+ | | From a backend's 切换到网关 (D-26) | From the runtime switch || --- | --- | --- || Title | 把 {{backend}} 切换到网关 | 安装网关组件 || What it promises | install, start, and move that one backend to the gateway | install and start the component; **no backend changes mode** |@@ -1149,16 +1151,16 @@ Every state above except Ready is **not drawn** `[derived]`. Required behaviour:| Primary | 安装并切换 | 安装并启动 || Where it lands | that backend on the gateway | the same page, run pill in Starting then healthy |- Reusing D-26's confirm here would be underspecified and then wrong: the run pill is a+ Reusing D-26's confirm here would be underspecified and then wrong: the runtime switch is apage-level control with **no backend in hand**, so an implementation would have toinvent one to fill `{{backend}}` in the title and the four `effects.*` bullets, andwhichever it picked would silently switch a backend the user never named. The user- pressed 点击安装; the confirm may promise installation and nothing else. Both variants+ turned the gateway on; the confirm may promise installation and nothing else. Both variantsshare the component name, the duration and the download-nothing-before-consent rule —which is the part D-26 exists to keep from diverging — and differ on exactly theconsequence each entry point actually has.- **The initiating sequence, not the frame, owns post-install continuation** `[derived]`.- Before the install request, the non-switching run-pill confirm holds+ Before the install request, the non-switching runtime-switch confirm holds`install_and_start`; §1.9's three-step confirm holds `install_start_switch`. These arelocal operation intents, never a wire field or a second runtime state. H1 is their onecontinuation register: while either sequence remains held, a status read settling at@@ -1208,21 +1210,23 @@ Every state above except Ready is **not drawn** `[derived]`. Required behaviour:`manifest.assets[].platform`. A browser platform is a different subject and is never afallback. Unsupported `not_installed` therefore renders the inert escape immediately,while a supported host renders the install affordance.-- **Not started**: the pill reads `shell.notStarted` and is the page's start- affordance. It is styled as an *idle* pill — `$--muted` label on `#FFFFFF0A`,+- **Not started**: the pill reads `shell.notStarted`; the adjacent off switch is the+ page's start affordance. The pill is styled as an *idle* pill — `$--muted` label on `#FFFFFF0A`,**not** the error treatment `[derived]`. The runtime contract classes`not_started` as lazy-start idleness rather than an alarm `[contract]`, and apage that paints idleness red teaches users to ignore the colour that matters.- Derived columns render `—` exactly as in Unreachable; supply that has never been- arbitrated is unknown, not empty.+ The closed page-level gate replaces every internal column; no `—` placeholder is+ rendered for configuration that is intentionally unavailable while the runtime is off.- **Starting**: the pill reads `shell.starting` with the `loader-circle` spinner and- stops accepting activation, so a second click cannot queue a second start+ the switch stops accepting activation, so a second click cannot queue a second start`[derived]`.-- Unreachable: the run pill flips to `shell.stopped` — the error treatment, because an- engine that *was* running and stopped answering is a fault — and every derived- column (current source, chain, takeover) renders `—`, **not** a stale last-known- value. See D-3: a surface that cannot prove a fact must say so.- Recovery offers the same start action as Not started.+- **Down**: the run pill flips to `shell.stopped` with the error treatment, because an+ engine that *was* running and stopped answering is a fault. The closed page-level gate+ replaces the internal configuration and its body explains that the previous start did+ not become ready. Recovery offers the same switch action as Not started.+- **Status unread**: a first-paint status transport failure uses `shell.unread`, hides the+ internal configuration and disables the switch. A retained live F2 snapshot may remain+ visible, but its switch is disabled until the next authoritative status read.- **Impaired**: the pill reads `shell.degraded` with the error treatment and **no**activation target `[derived]`. The engine is answering, so the page keeps the data ithas and no column falls back to `—`; on a first paint the data it has may be none, and@@ -1238,40 +1242,48 @@ Every state above except Ready is **not drawn** `[derived]`. Required behaviour:paint, not only from a loaded page**, and saying so is the whole of this clause: the twopage-level payloads are separate requests, so the supply read can fail on the very firstone while the source list succeeds — the exact condition this row defines — and a- first-paint dispatch offering only Unreachable resolves it to 网关未运行 with a Start- button, for an engine that answered. It also discards the inventory that did load, so+ first-paint dispatch offering only Closed would replace the whole internal surface with+ a runtime switch, for an engine that answered. It also discards the inventory that did load, sothe repair costs the user a fetch that already succeeded. A partial payload is partialwhether it is the first or the fiftieth.- **Sources unread**: the mirror of Partial, and it needs its own row for the reason- Partial does. A failed source list used to arrive at Unreachable, which is the sentence- for an engine that stopped answering: it renders 网关未运行, it offers Start, and it- blanks every derived column. None of that is true here — the status read answered, the+ Partial does. A failed source list used to arrive at Closed, which is the sentence+ for an engine that is not running: it renders the closed gate and offers the runtime+ switch. None of that is true here — the status read answered, thesupply read answered, and one list did not — so the pill keeps whatever `health` said,no other region degrades, and the repair is to ask for the list again. Reading anoutage off the failure of one read is the same mistake in the other direction asreading health off a stale value: both state a fact the payload did not carry.-**The run pill is a total rendering of `health`, and the states above are how it gets-there** `[contract]`. Every value `runtime-dependency.schema.json` admits for it is-rendered, and no pill is drawn for anything else. One value splits, on a second field —-the same shape frame 06's bar has when it splits `active` on adoption:+**The runtime control is a total rendering of `health`, and the states above are how it+gets there** `[contract]`. The pill names the state; the adjacent switch owns activation.+Every value `runtime-dependency.schema.json` admits is rendered, and no state is inferred+from an empty relationship array. One value splits on a second field — the same shape+frame 06's bar has when it splits `active` on adoption:| `RuntimeDependency.status.health` `[contract]` | State | Pill | Treatment | Activation || --- | --- | --- | --- | --- |-| `ok` | Ready | `shell.running` | idle | none |-| `degraded` | Impaired | `shell.degraded` | error | none |-| `down` | Unreachable | `shell.stopped` | error | start (`POST /api/models/runtime/start` `[contract]`) |-| `not_started` | Not started | `shell.notStarted` | idle | start |+| `ok` | Ready | `shell.running` | idle | on switch; stop only when every Agent backend is Direct (`POST /api/models/runtime/stop` `[contract]`) |+| `degraded` | Impaired | `shell.degraded` | error | on switch; same guarded stop rule |+| `down` | Closed | `shell.stopped` | error | off switch; start (`POST /api/models/runtime/start` `[contract]`) |+| `not_started` | Closed | `shell.notStarted` | idle | off switch; start || `installing` | Installing | `install.progress` | idle / busy | none; status reads own progress || `not_installed`, `error_key` non-null `[contract]` | Install failed | `install.fail.title` / `settings.models.install.fail.detail` | error | retry `POST /api/models/runtime/install` || `not_installed`, `error_key: null`, exact asset for `host_platform` `[contract]` | Not installed | `shell.notInstalled` | idle | the non-switching install confirm — **never** the start route || `not_installed`, `error_key: null`, no exact asset for `host_platform` `[contract]` | Unsupported host | `shell.unsupported` | idle | none — 直连 (§1.8) is the escape hatch |+The runtime is a page-level gate. Only `ok` and `degraded` expose the tabs, Sources,+Agent gateway-model rows, route controls, supply graph and internal dialogs. Every other+authoritative health renders a closed/setup surface instead. Turning the gateway off is+not a bulk routing mutation: while any backend remains in Hub mode, the switch is disabled+and names those backends; the server independently rejects the same race with+`runtime_in_use`. Configuration is preserved while hidden and reappears unchanged after a+successful start.+Starting is the one pill with no `health` behind it: it is the client's own optimisticstate between accepting the press and the next payload. A transport failure — the status-request not returning at all — renders as Unreachable, which is the one pill two inputs-share, because from the page's side an engine that says `down` and an engine that says-nothing afford the same action. And `degraded` here is the *engine* speaking about+request not returning at all — renders Status unread and disables the switch because the+page has no authoritative action basis. And `degraded` here is the *engine* speaking aboutitself, unrelated to `supply_status: degraded` above, which is a backend speaking aboutits arbitration; the two hold independently and D-24's rule applies to both words.@@ -1358,14 +1370,35 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa| --- | --- | --- || `shell.title` | 模型 | Models || `shell.running` | 网关运行中 | Gateway running |-| `shell.stopped` `[derived]` | 网关未运行 | Gateway not running |+| `shell.stopped` `[derived]` | 网关已关闭 | Gateway off || `shell.degraded` `[derived]` | 网关降级运行 | Gateway running degraded |-| `shell.notStarted` `[derived]` | 网关未启动 · 点击启动 | Gateway not started · click to start |-| `shell.notInstalled` `[derived]` | 网关组件未安装 · 点击安装 | Gateway component not installed · click to install |+| `shell.notStarted` `[derived]` | 网关已关闭 | Gateway off |+| `shell.notInstalled` `[derived]` | 网关组件未安装 | Gateway component not installed || `shell.allDirect_one` `[frame]` | {{count}} 个后端都在直连 | The only backend is direct || `shell.allDirect_other` `[frame]` | {{count}} 个后端都在直连 | All {{count}} backends are direct || `shell.starting` `[derived]` | 正在启动… | Starting… |+| `shell.stopping` `[derived]` | 正在关闭… | Stopping… || `shell.unsupported` `[derived]` | 这个平台还没有网关组件 | No gateway component for this platform yet |+| `shell.toggle.turnOn` `[derived]` | 开启模型网关 | Turn model gateway on |+| `shell.toggle.turnOff` `[derived]` | 关闭模型网关 | Turn model gateway off |+| `shell.toggle.stopBlocked` `[derived]` | 请先将 {{names}} 切换为直连,再关闭模型网关 | Switch {{names}} to Direct before turning the model gateway off |+| `shell.toggle.stopUnavailable` `[derived]` | 暂时无法读取 Agent 路由状态,当前不能关闭模型网关 | Agent routing status is unavailable; the model gateway cannot be turned off yet |+| `shell.closed.off.title` `[frame]` | 模型网关已关闭 | Model gateway is off |+| `shell.closed.off.body` `[frame]` | 开启后才会显示和编辑来源、路由与网关模型。 | Turn it on to view and edit sources, routes, and gateway models. |+| `shell.closed.down.title` `[derived]` | 模型网关已关闭 | Model gateway is off |+| `shell.closed.down.body` `[derived]` | 上一次启动没有就绪。开启网关即可重试。 | The previous start did not become ready. Turn it on to try again. |+| `shell.closed.notInstalled.title` `[derived]` | 模型网关尚未安装 | Model gateway is not installed |+| `shell.closed.notInstalled.body` `[derived]` | 开启后会安装由 Avibe 管理的网关组件。 | Turn it on to install the managed gateway component. |+| `shell.closed.unsupported.title` `[derived]` | 模型网关不可用 | Model gateway is unavailable |+| `shell.closed.unsupported.body` `[derived]` | 当前平台没有兼容的托管网关组件。 | This platform does not have a compatible managed gateway component. |+| `shell.closed.installing.title` `[derived]` | 正在安装模型网关 | Installing model gateway |+| `shell.closed.installing.body` `[derived]` | 安装并启动完成后才会显示来源与路由。 | Sources and routing will appear after installation and startup complete. |+| `shell.closed.starting.title` `[derived]` | 正在启动模型网关 | Starting model gateway |+| `shell.closed.starting.body` `[derived]` | 网关就绪后才会显示来源与路由。 | Sources and routing will appear when the gateway is ready. |+| `shell.closed.stopping.title` `[derived]` | 正在关闭模型网关 | Turning model gateway off |+| `shell.closed.stopping.body` `[derived]` | 运行时停止期间会隐藏网关配置。 | Gateway configuration is hidden while the runtime stops. |+| `shell.closed.unread.title` `[derived]` | 暂时无法读取网关状态 | Model gateway status unavailable |+| `shell.closed.unread.body` `[derived]` | 确认运行状态前不会显示网关配置。 | Configuration stays hidden until the runtime state can be confirmed. || `shell.gatewayInfo.label` `[derived]` | 什么是网关 | What the gateway is || `shell.gatewayInfo.body` `[derived]` | 网关是本机的一层调度:它持有你添加的来源,按你配置的顺序供给各个 Agent。 | The gateway is a dispatch layer on this machine: it holds the sources you add and supplies them to your Agents in the order you configure. || `install.title` `[derived]` | 安装网关组件 | Install the gateway component |@@ -1749,13 +1782,12 @@ current-text slot immediately renders a page-owned statement: `chain_length: 0`selects server-owned `models.launch.route_unconfigured`, while a nonempty chain selects`legend.unavailable` in `$--gold`. The page has already proved which of those two factsholds even though it cannot yet name a current hop or detailed cause. This reuses the-row's measured 10.5px text slot and adds no geometry. The unresolved rendering otherwise-matches the one §1.0 gives those same columns when the engine is unreachable, for the same reason (D-3-— a surface that cannot prove a fact must say so). **The rendering is shared; the state-is not** — 「Chain unresolved」 is a row-grain state of its own precisely so that this-one cannot be written as a transition into §1.0 Unreachable, which would stop the run-pill, offer 启动引擎 and clear every derived column on the page over a request about one-model. A stale last-known hop is specifically excluded. AC-30 makes takeover a projection of the chain the surface+ row's measured 10.5px text slot and adds no geometry. The unresolved rendering follows+ D-3 — a surface that cannot prove a fact must say so. 「Chain unresolved」 is a row-grain+ state of its own precisely so that this one cannot be written as a transition into §1.0+ Closed, which would replace the entire internal surface with the runtime gate over a+ request about one model. A stale last-known hop is specifically excluded. AC-30 makes+ takeover a projection of the chain the surfacedisplays, so a takeover badge drawn from a chain no longer in hand is a projection ofnothing — the one failure that rule exists to prevent. And a failed chain read degradesthose columns and nothing else, which is §1.0's Partial rule read at row grain: only the@@ -5293,6 +5325,36 @@ value in `title` `[derived]`.---+### 1.13 Frame 14 `IM4c2` — Runtime off++**The question it answers:** *what remains when the managed gateway is not running?*+The page shell, runtime state pill and unchecked switch remain. The tab strip, Sources,+Agent gateway models, route controls, supply graph and every internal configuration+dialog are absent. Configuration is preserved; it is hidden rather than deleted.++**Element inventory** `[frame]`++| Element | Displays | Interactive | On activate |+| --- | --- | --- | --- |+| Runtime pill | `shell.notStarted` or `shell.stopped` | no | none |+| Runtime switch | Unchecked `Switch/Unchecked` | yes when start/install is available | Start the runtime, or open the managed-install confirmation |+| Closed-state icon | Neutral power glyph in a 44×44 bordered tile | no | none |+| Closed-state title | `shell.closed.off.title` | no | none |+| Closed-state body | `shell.closed.off.body` | no | none |++**Geometry** `[frame]` — the frame is 1440×1100 Dark and reuses Frame 01's shell.+The internal area is a fill-width 854px vertical band with only top/bottom borders;+content is centered, with a 44×44 radius-8 icon tile, 17px title and 12.5px body.+The runtime switch sits beside the state pill in the page header. No hidden internal+surface consumes layout space.++`down` uses the same positive inventory with failed-start body copy; `not_installed`,+`installing`, `starting`, `stopping`, unsupported and unread states replace only the+center title/body and busy glyph. A retained live F2 snapshot may keep the prior internal+surface visible, but its switch is disabled until an authoritative status read lands.++---+## 2. Interaction decisions, and whyEach rule is one line, with one line of why. The why is not commentary: when twodiff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 54616b485..05cc890c3 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -143,6 +143,7 @@ class FakeAdapter:self.orphan_cleanup_succeeds = Falseself.cancel_disposition = RetainedMaterialDisposition.NONEself.start_calls = 0+ self.stop_runtime_calls = 0self.install_calls = 0self.credential_count = 0self.observation: SourceObservation | None = None@@ -165,6 +166,17 @@ class FakeAdapter:self.start_calls += 1return await self.status()+ async def stop_runtime(self):+ self.stop_runtime_calls += 1+ return EngineStatus(+ health=EngineHealth.NOT_STARTED,+ installed_version="v7.2.95",+ verified=True,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso="2026-07-23T03:40:00+00:00",+ )+async def stop(self):return None@@ -716,6 +728,9 @@ def test_every_model_hub_endpoint_returns_its_contract_response(monkeypatch.setenv("XDG_CONFIG_HOME", str(isolated_home / ".config"))save_config(isolated_home)service = _seed_response_conformance_service(tmp_path)+ if endpoint == "POST /api/models/runtime/stop":+ for agent in service.store.config.agents.values():+ agent.mode = "direct"monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))client = app.test_client()base_url = "http://127.0.0.1:15131"@@ -842,6 +857,30 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):_assert_valid("runtime-dependency.schema.json", runtime)+def test_runtime_stop_requires_every_backend_to_be_direct(tmp_path):+ service, _store, adapter = _service(tmp_path)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.runtime_stop())++ assert exc_info.value.code == "runtime_in_use"+ assert exc_info.value.status == 409+ assert exc_info.value.data == {"backends": ["claude", "codex", "opencode"]}+ assert adapter.stop_runtime_calls == 0+++def test_runtime_stop_returns_explicit_not_started_state(tmp_path):+ service, store, adapter = _service(tmp_path)+ for agent in store.config.agents.values():+ agent.mode = "direct"++ runtime = asyncio.run(service.runtime_stop())++ assert adapter.stop_runtime_calls == 1+ assert runtime["status"]["health"] == "not_started"+ _assert_valid("runtime-dependency.schema.json", runtime)++def test_runtime_start_syncs_sources_before_starting_once(tmp_path):class OrderedAdapter(FakeAdapter):def __init__(self):@@ -1017,6 +1056,23 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):assert calls == [("runtime_start", None)]+def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):+ from vibe import model_hub_client++ calls = []++ async def rpc(operation, payload=None):+ calls.append((operation, payload))+ return {"contract_version": 6, "status": {"health": "not_started"}}++ monkeypatch.setattr(model_hub_client, "_rpc", rpc)++ runtime = asyncio.run(ModelHubRemoteService().runtime_stop())++ assert runtime["status"]["health"] == "not_started"+ assert calls == [("runtime_stop", None)]++def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):from vibe import model_hub_client@@ -1045,6 +1101,19 @@ def test_runtime_start_is_allowlisted_by_controller_rpc(tmp_path):assert adapter.start_calls == 1+def test_runtime_stop_is_allowlisted_by_controller_rpc(tmp_path):+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc++ service, store, adapter = _service(tmp_path)+ for agent in store.config.agents.values():+ agent.mode = "direct"++ runtime = asyncio.run(dispatch_model_hub_rpc(service, "runtime_stop", {}))++ assert runtime["status"]["health"] == "not_started"+ assert adapter.stop_runtime_calls == 1++def test_runtime_install_is_allowlisted_by_controller_rpc(tmp_path):from core.handlers.model_hub.rpc import dispatch_model_hub_rpc@@ -5280,6 +5349,32 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t_assert_valid("runtime-dependency.schema.json", runtime)+def test_runtime_stop_route_requires_csrf_before_stopping_engine(monkeypatch, tmp_path):+ service, store, adapter = _service(tmp_path)+ for agent in store.config.agents.values():+ agent.mode = "direct"+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"++ rejected = client.post("/api/models/runtime/stop", base_url=base_url)++ assert rejected.status_code == 403+ assert adapter.stop_runtime_calls == 0++ accepted = client.post(+ "/api/models/runtime/stop",+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert accepted.status_code == 200+ runtime = accepted.get_json()["runtime"]+ assert adapter.stop_runtime_calls == 1+ assert runtime["status"]["health"] == "not_started"+ _assert_valid("runtime-dependency.schema.json", runtime)++def test_runtime_install_route_is_reachable_and_persists_installing(monkeypatch,tmp_path,diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 644fa275f..52507e0e6 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1929,6 +1929,18 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(supervisor.stop()+def test_supervisor_disable_restores_explicit_off_state(tmp_path: Path) -> None:+ supervisor, _store = _fixture_supervisor(tmp_path)+ supervisor.ensure_running()++ supervisor.disable()++ assert supervisor.status()["status"]["health"] == "not_started"+ supervisor.ensure_running()+ assert supervisor.status()["status"]["health"] == "ok"+ supervisor.stop()++def _assert_supervisor_owned_startup_log(message: str,*,diff --git a/ui/src/components/settings/SettingsPrimitives.tsx b/ui/src/components/settings/SettingsPrimitives.tsxindex 34738be8a..24a3cea81 100644--- a/ui/src/components/settings/SettingsPrimitives.tsx+++ b/ui/src/components/settings/SettingsPrimitives.tsx@@ -119,15 +119,17 @@ export const SearchField: React.FC<SearchFieldProps> = ({// fill --mint, blur 8 #5BFFA055 glow, 38×22 with knob inset 3.// Off state mirrors fcMl6 (Switch/Unchecked): fill + stroke = --border-strong// (14% white dark / 14% black light) for sufficient contrast against bg-background.-export const ToggleSwitch: React.FC<{ enabled: boolean; onClick: () => void; disabled?: boolean }> = ({+export const ToggleSwitch: React.FC<{ enabled: boolean; onClick: () => void; disabled?: boolean; label?: string }> = ({enabled,onClick,disabled,+ label,}) => (<buttontype="button"role="switch"aria-checked={enabled}+ aria-label={label}disabled={disabled}onClick={onClick}className={clsx(diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex b7a689b6d..f6396598d 100644--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -50,8 +50,6 @@ const renderPill = (? unreadRegion(): readyRegion(runtime(health, options.withAsset, options.hostPlatform))}starting={options.starting ?? false}- onStart={vi.fn()}- onInstall={vi.fn()}/></I18nextProvider>,);@@ -75,22 +73,22 @@ describe('Model Hub runtime pill', () => {expect(freshRuntimeProjection(retained)).toBeNull();});- it('maps every runtime health to its registered shell copy and activation', () => {+ it('maps every runtime health to its registered shell copy without owning activation', () => {expect(renderPill('ok')).toContain(zh.settings.models.shell.running);expect(renderPill('ok')).not.toContain('<button');expect(renderPill('degraded')).toContain(zh.settings.models.shell.degraded);expect(renderPill('degraded')).not.toContain('<button');expect(renderPill('down')).toContain(zh.settings.models.shell.stopped);- expect(renderPill('down')).toContain('<button');+ expect(renderPill('down')).not.toContain('<button');expect(renderPill('not_started')).toContain(zh.settings.models.shell.notStarted);- expect(renderPill('not_started')).toContain('<button');+ expect(renderPill('not_started')).not.toContain('<button');});it('uses the server manifest resolution without re-deriving host support', () => {expect(renderPill('not_installed', { withAsset: true })).toContain(zh.settings.models.shell.notInstalled);- expect(renderPill('not_installed', { withAsset: true })).toContain('<button');+ expect(renderPill('not_installed', { withAsset: true })).not.toContain('<button');expect(renderPill('not_installed')).toContain(zh.settings.models.shell.notInstalled);- expect(renderPill('not_installed')).toContain('<button');+ expect(renderPill('not_installed')).not.toContain('<button');expect(renderPill('not_installed', { withAsset: true, hostPlatform: 'linux-amd64' })).toContain(zh.settings.models.shell.unsupported);expect(renderPill('not_installed', { withAsset: true, hostPlatform: 'linux-amd64' })).not.toContain('<button');});@@ -106,8 +104,6 @@ describe('Model Hub runtime pill', () => {<RuntimePillread={failRegionRead(readyRegion(runtime('ok')))}starting={false}- onStart={vi.fn()}- onInstall={vi.fn()}/></I18nextProvider>,);diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex ad559a729..ebfd7d2f4 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -242,7 +242,7 @@ describe('SettingsModelsPage surface branches', () => {expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();});- it('keeps the stopped runtime action visible on the direct-only surface', async () => {+ it('gates all internal configuration behind the stopped runtime switch', async () => {const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([@@ -251,6 +251,7 @@ describe('SettingsModelsPage surface branches', () => {directAgent('opencode'),]);vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(stopped);+ const start = vi.spyOn(modelsApi, 'startRuntime').mockResolvedValue(runtime);vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);render(@@ -261,8 +262,52 @@ describe('SettingsModelsPage surface branches', () => {</ToastProvider>,);- expect(await screen.findByRole('button', { name: /Gateway stopped|网关已停止/i })).toBeTruthy();+ const toggle = await screen.findByRole('switch', { name: /Turn model gateway on|开启模型网关/i });+ expect(toggle.getAttribute('aria-checked')).toBe('false');+ expect(await screen.findByText(/^Model gateway is off$|^模型网关已关闭$/i)).toBeTruthy();+ expect(screen.queryAllByRole('tab')).toHaveLength(0);expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();++ await userEvent.click(toggle);++ await waitFor(() => expect(start).toHaveBeenCalledOnce());+ expect(await screen.findAllByRole('tab')).toHaveLength(3);+ });++ it('stops an unused running gateway and hides its retained configuration', async () => {+ renderPage([retainedSource]);+ const stopped = { ...runtime, status: { ...runtime.status, health: 'not_started' as const } };+ const stop = vi.spyOn(modelsApi, 'stopRuntime').mockResolvedValue(stopped);++ await screen.findByText('Retained source');+ await userEvent.click(screen.getByRole('switch', { name: /Turn model gateway off|关闭模型网关/i }));++ await waitFor(() => expect(stop).toHaveBeenCalledOnce());+ expect(await screen.findByText(/^Model gateway is off$|^模型网关已关闭$/i)).toBeTruthy();+ expect(screen.queryByText('Retained source')).toBeNull();+ expect(screen.queryAllByRole('tab')).toHaveLength(0);+ });++ it('does not turn the runtime off while a backend still uses the gateway', async () => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([takeoverAgent]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ const stop = vi.spyOn(modelsApi, 'stopRuntime').mockResolvedValue(runtime);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ const toggle = await screen.findByRole('switch', { name: /Switch codex to Direct|请先将 codex 切换为直连/i });+ expect((toggle as HTMLButtonElement).disabled).toBe(true);+ await userEvent.click(toggle);+ expect(stop).not.toHaveBeenCalled();+ expect(await screen.findByText('Retained source')).toBeTruthy();});it('renders Frame 01 with tabs when retained sources remain under all-direct backends', async () => {diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex d48825ed9..ffc422cf3 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,5 +1,5 @@import * as React from 'react';-import { ArrowLeft, Gauge, LoaderCircle, Route, ScrollText } from 'lucide-react';+import { ArrowLeft, Gauge, LoaderCircle, Power, Route, ScrollText } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';+import { ToggleSwitch } from '../SettingsPrimitives';import { AddApiKeyDialog } from './AddApiKeyDialog';import { OAuthConnectDialog } from './OAuthConnectDialog';import { EnableGatewayDialog } from './EnableGatewayDialog';@@ -57,7 +58,7 @@ import {unreadRegion,type RegionRead,} from './regionRead';-import { freshRuntimeProjection, pollRuntimeStatus, runtimeCanAttemptInstall, startRuntimeWithStatusRefresh } from './runtimeLifecycle';+import { freshRuntimeProjection, pollRuntimeStatus, runtimeCanAttemptInstall, runtimeIsRunning, startRuntimeWithStatusRefresh } from './runtimeLifecycle';import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';import { useSourceMutationReport } from './useSourceMutationReport';import { backendVisual } from './vendorMeta';@@ -148,10 +149,9 @@ type AuthorizedSurfaceLanding = {export const RuntimePill: React.FC<{read: RegionRead<RuntimeDependency>;starting: boolean;- onStart: () => void;- onInstall: () => void;+ stopping?: boolean;directCount?: number;-}> = ({ read, starting, onStart, onInstall, directCount }) => {+}> = ({ read, starting, stopping = false, directCount }) => {const { t } = useTranslation();const projection = foldRegionRead<RuntimeDependency, { runtime: RuntimeDependency; authoritative: boolean } | null>(read, {loading: () => null,@@ -167,9 +167,11 @@ export const RuntimePill: React.FC<{const health = runtime.status.health;const unread = read.kind === 'degraded' && read.cause === 'read_failed';const canInstall = health === 'not_installed' && runtimeCanAttemptInstall(runtime);- const allDirect = authoritative && !starting && health === 'ok' && directCount !== undefined && directCount > 0;+ const allDirect = authoritative && !starting && !stopping && health === 'ok' && directCount !== undefined && directCount > 0;const key = unread? 'unread'+ : stopping+ ? 'stopping': starting? 'starting': health === 'installing'@@ -185,20 +187,47 @@ export const RuntimePill: React.FC<{: canInstall? 'notInstalled': 'unsupported';- const action = authoritative && !starting && health !== 'installing' && (health === 'down' || health === 'not_started')- ? onStart- : authoritative && !starting && canInstall- ? onInstall- : null;const className = cn('model-hub-runtime-pill',(health === 'down' || health === 'degraded' || unread) && 'model-hub-runtime-pill--error',allDirect && 'model-hub-runtime-pill--direct',);- const content = <><span className="model-hub-runtime-dot" />{(starting || health === 'installing') && <LoaderCircle className="animate-spin" />}{t(`settings.models.shell.${key}`, allDirect ? { count: directCount } : undefined)}</>;- return action- ? <button type="button" className={className} onClick={action}>{content}</button>- : <span className={className}>{content}</span>;+ return <span className={className}><span className="model-hub-runtime-dot" />{(starting || stopping || health === 'installing') && <LoaderCircle className="animate-spin" />}{t(`settings.models.shell.${key}`, allDirect ? { count: directCount } : undefined)}</span>;+};++const RuntimeClosedState: React.FC<{+ read: RegionRead<RuntimeDependency>;+ runtime: RuntimeDependency | null;+ starting: boolean;+ stopping: boolean;+}> = ({ read, runtime, starting, stopping }) => {+ const { t } = useTranslation();+ const health = runtime?.status.health ?? null;+ const key = stopping+ ? 'stopping'+ : starting+ ? 'starting'+ : read.kind === 'unread'+ ? 'unread'+ : health === 'installing'+ ? 'installing'+ : health === 'not_installed' && runtime?.manifest.resolution === 'unsupported'+ ? 'unsupported'+ : health === 'not_installed'+ ? 'notInstalled'+ : health === 'down'+ ? 'down'+ : 'off';+ const busy = starting || stopping || health === 'installing';+ return (+ <section className="model-hub-runtime-closed" aria-live="polite">+ <span className="model-hub-runtime-closed-icon" aria-hidden="true">+ {busy ? <LoaderCircle className="animate-spin" /> : <Power />}+ </span>+ <h2>{t(`settings.models.shell.closed.${key}.title`)}</h2>+ <p>{t(`settings.models.shell.closed.${key}.body`)}</p>+ </section>+ );};const ModelHubShell: React.FC<{ actions?: React.ReactNode; detailBack?: () => void; children: React.ReactNode; rootRef?: React.Ref<HTMLDivElement> }> = ({ actions, detailBack, children, rootRef }) => {@@ -299,6 +328,7 @@ export const SettingsModelsPage: React.FC = () => {const [usageRead, setUsageRead] = React.useState<RegionRead<UsageSummary>>(loadingRegion);const [usageWindow, setUsageWindow] = React.useState<UsageWindowOption>(USAGE_DEFAULT_WINDOW_DAYS);const [startingRuntime, setStartingRuntime] = React.useState(false);+ const [stoppingRuntime, setStoppingRuntime] = React.useState(false);const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);const [installOpen, setInstallOpen] = React.useState(false);const [apiKeyOpen, setApiKeyOpen] = React.useState(false);@@ -395,6 +425,10 @@ export const SettingsModelsPage: React.FC = () => {degraded: (staleData) => staleData,});const runtimeHealth = retainedRuntime?.status.health ?? null;+ const runtimeSurfaceEnabled = retainedRuntime !== null+ && runtimeIsRunning(retainedRuntime)+ && runtimeRead.kind !== 'unread';+ const runtimeConfigurationVisible = runtimeSurfaceEnabled && !stoppingRuntime;React.useEffect(() => {const runtimeCanRecover = runtimeRead.kind === 'unread'|| (runtimeRead.kind === 'degraded' && runtimeRead.cause === 'read_failed')@@ -757,7 +791,7 @@ export const SettingsModelsPage: React.FC = () => {}}, [feed, showToast, t]);const startRuntime = async () => {- if (startingRuntime) return;+ if (startingRuntime || stoppingRuntime) return;setStartingRuntime(true);try {const result = await startRuntimeWithStatusRefresh(modelsApi);@@ -770,11 +804,55 @@ export const SettingsModelsPage: React.FC = () => {setStartingRuntime(false);}};+ const stopRuntime = async () => {+ if (startingRuntime || stoppingRuntime) return;+ setStoppingRuntime(true);+ try {+ const stopped = await modelsApi.stopRuntime();+ setRuntimeRead(readyRegion(stopped));+ setRuntimeRecoveryPending(false);+ setSelectedSourceId(null);+ setTab('sources');+ } catch {+ const observed = await modelsApi.getRuntimeStatus().catch(() => null);+ setRuntimeRead((previous) => observed ? readyRegion(observed) : failRegionRead(previous));+ showToast(t('settings.models.errors.stopFailed') as string, 'error');+ } finally {+ setStoppingRuntime(false);+ }+ };const landingLoading = sourcesRead.kind === 'loading'&& supplyRead.kind === 'loading'&& runtimeRead.kind === 'loading';const directEmpty = modelsSurfaceKindFromReads(supplyRead, sourcesRead) === 'direct_empty';const installedAgents = agents.filter((agent) => agent.cli_present);+ const hubBackends = agents.filter((agent) => agent.mode === 'hub').map((agent) => agent.backend);+ const stopBlocked = runtimeSurfaceEnabled && (supplyRead.kind !== 'ready' || hubBackends.length > 0);+ const runtimeSwitchUnsupported = runtimeHealth === 'not_installed'+ && retainedRuntime?.manifest.resolution === 'unsupported';+ const runtimeSwitchDisabled = startingRuntime+ || stoppingRuntime+ || runtimeRead.kind !== 'ready'+ || runtimeHealth === 'installing'+ || runtimeSwitchUnsupported+ || stopBlocked;+ const runtimeSwitchLabel = stopBlocked+ ? supplyRead.kind === 'ready'+ ? t('settings.models.shell.toggle.stopBlocked', { names: hubBackends.join(', ') })+ : t('settings.models.shell.toggle.stopUnavailable')+ : runtimeSurfaceEnabled+ ? t('settings.models.shell.toggle.turnOff')+ : t('settings.models.shell.toggle.turnOn');+ const toggleRuntime = () => {+ if (runtimeSwitchDisabled) return;+ if (runtimeSurfaceEnabled) {+ void stopRuntime();+ } else if (runtimeHealth === 'not_installed') {+ setInstallOpen(true);+ } else {+ void startRuntime();+ }+ };const installedSupplyRead = foldRegionRead<AgentSupply[], RegionRead<AgentSupply[]>>(supplyRead, {loading: () => loadingRegion(),ready: () => readyRegion(installedAgents),@@ -1036,23 +1114,30 @@ export const SettingsModelsPage: React.FC = () => {return (<ModelHubShellrootRef={pageRef}- detailBack={selectedSourceId ? () => selectSource(null) : undefined}+ detailBack={runtimeConfigurationVisible && selectedSourceId ? () => selectSource(null) : undefined}actions={!landingLoading- ? directEmpty && installedAgents.length === 0- ? undefined- : <span className="flex items-center gap-2">+ ? <span className="flex items-center gap-2"><RuntimePillread={runtimeRead}starting={startingRuntime}- onStart={() => void startRuntime()}- onInstall={() => setInstallOpen(true)}+ stopping={stoppingRuntime}directCount={directEmpty ? installedAgents.length : undefined}/>- {!directEmpty && <TakeoverPill count={takeoverCount} />}+ {runtimeConfigurationVisible && !directEmpty && <TakeoverPill count={takeoverCount} />}+ <span title={runtimeSwitchLabel}>+ <ToggleSwitch+ enabled={runtimeSurfaceEnabled}+ disabled={runtimeSwitchDisabled}+ label={runtimeSwitchLabel}+ onClick={toggleRuntime}+ />+ </span></span>: undefined}>{landingLoading ? <div className="text-[13px] text-muted">{t('common.loading')}</div>+ : !runtimeConfigurationVisible+ ? <RuntimeClosedState read={runtimeRead} runtime={retainedRuntime} starting={startingRuntime} stopping={stoppingRuntime} />: selectedSourceId? selectedSource? <SourceDetailPanel@@ -1169,6 +1254,7 @@ export const SettingsModelsPage: React.FC = () => {</div></div>}</div>}+ {runtimeConfigurationVisible && <><SourceMutationReportreport={sourceMutationReport.report}onComplete={() => { void sourceMutationReport.complete(); }}@@ -1257,6 +1343,7 @@ export const SettingsModelsPage: React.FC = () => {trackWrite={(work) => agentWriteRegistry.track(adoptAgent.backend, work)}/>)}+ </>}{installOpen && retainedRuntime && (<InstallGatewayDialogruntime={retainedRuntime}diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex e922ce0a4..e36a397f5 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -268,6 +268,51 @@background: currentColor;}+.model-hub-runtime-closed {+ display: flex;+ min-height: 360px;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ border-block: 1px solid var(--border);+ padding: 56px 24px;+ text-align: center;+}++.model-hub-runtime-closed-icon {+ display: grid;+ width: 44px;+ height: 44px;+ margin-bottom: 16px;+ place-items: center;+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ background: var(--model-hub-wash-05);+ color: var(--muted);+}++.model-hub-runtime-closed-icon > svg {+ width: 18px;+ height: 18px;+}++.model-hub-runtime-closed h2 {+ color: var(--foreground);+ font-size: 17px;+ font-weight: 650;+ letter-spacing: 0;+ line-height: 1.35;+}++.model-hub-runtime-closed p {+ max-width: 440px;+ margin-top: 7px;+ color: var(--muted);+ font-size: 12.5px;+ letter-spacing: 0;+ line-height: 1.65;+}+.model-hub-takeover-pill {display: inline-flex;width: fit-content;diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex b431accf1..5f3efd284 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -137,6 +137,7 @@ export type ModelsApi = {/** Start the contract-owned client installation transaction. */installRuntime(): Promise<RuntimeDependency>;startRuntime(): Promise<RuntimeDependency>;+ stopRuntime(): Promise<RuntimeDependency>;startOAuth(vendor: string, channel: SupplyChannel, clientNonce?: string): Promise<OAuthFlow>;getOAuthStatus(flowId: string): Promise<OAuthResult>;submitOAuth(flowId: string, value: string): Promise<OAuthResult>;@@ -468,6 +469,7 @@ export const modelsApi: ModelsApi = {getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),+ stopRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/stop', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),startOAuth: (vendor, channel, clientNonce) =>call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/start',diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex ca9606544..3413f026f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -666,15 +666,56 @@"shell": {"title": "Models","running": "Gateway running",- "stopped": "Gateway stopped · click to start",+ "stopped": "Gateway off","degraded": "Gateway running degraded","unread": "Gateway status unavailable",- "notStarted": "Gateway not started · click to start",- "notInstalled": "Gateway component not installed · click to install",+ "notStarted": "Gateway off",+ "notInstalled": "Gateway component not installed","allDirect_one": "The only backend is direct","allDirect_other": "All {{count}} backends are direct","starting": "Starting…",+ "stopping": "Stopping…","unsupported": "No gateway component for this platform yet",+ "toggle": {+ "turnOn": "Turn model gateway on",+ "turnOff": "Turn model gateway off",+ "stopBlocked": "Switch {{names}} to Direct before turning the model gateway off",+ "stopUnavailable": "Agent routing status is unavailable; the model gateway cannot be turned off yet"+ },+ "closed": {+ "off": {+ "title": "Model gateway is off",+ "body": "Turn it on to view and edit sources, routes, and gateway models."+ },+ "down": {+ "title": "Model gateway is off",+ "body": "The previous start did not become ready. Turn it on to try again."+ },+ "notInstalled": {+ "title": "Model gateway is not installed",+ "body": "Turn it on to install the managed gateway component."+ },+ "unsupported": {+ "title": "Model gateway is unavailable",+ "body": "This platform does not have a compatible managed gateway component."+ },+ "installing": {+ "title": "Installing model gateway",+ "body": "Sources and routing will appear after installation and startup complete."+ },+ "starting": {+ "title": "Starting model gateway",+ "body": "Sources and routing will appear when the gateway is ready."+ },+ "stopping": {+ "title": "Turning model gateway off",+ "body": "Gateway configuration is hidden while the runtime stops."+ },+ "unread": {+ "title": "Model gateway status unavailable",+ "body": "Configuration stays hidden until the runtime state can be confirmed."+ }+ },"gatewayInfo": {"label": "What the gateway is","body": "The gateway is a dispatch layer on this machine: it holds the sources you add and supplies them to your Agents in the order you configure."@@ -1024,7 +1065,8 @@},"errors": {"engineDown": "Model engine is not ready yet; try again shortly",- "startFailed": "Model engine could not be started"+ "startFailed": "Model engine could not be started",+ "stopFailed": "Model gateway could not be turned off"},"runtime": {"notStarted": "Not started · starts automatically on first use",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 86ce1e1d1..58e320d38 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -666,15 +666,56 @@"shell": {"title": "模型","running": "网关运行中",- "stopped": "网关已停止 · 点击启动",+ "stopped": "网关已关闭","degraded": "网关降级运行","unread": "网关状态未读到",- "notStarted": "网关未启动 · 点击启动",- "notInstalled": "网关组件未安装 · 点击安装",+ "notStarted": "网关已关闭",+ "notInstalled": "网关组件未安装","allDirect_one": "{{count}} 个后端都在直连","allDirect_other": "{{count}} 个后端都在直连","starting": "正在启动…",+ "stopping": "正在关闭…","unsupported": "这个平台还没有网关组件",+ "toggle": {+ "turnOn": "开启模型网关",+ "turnOff": "关闭模型网关",+ "stopBlocked": "请先将 {{names}} 切换为直连,再关闭模型网关",+ "stopUnavailable": "暂时无法读取 Agent 路由状态,当前不能关闭模型网关"+ },+ "closed": {+ "off": {+ "title": "模型网关已关闭",+ "body": "开启后才会显示和编辑来源、路由与网关模型。"+ },+ "down": {+ "title": "模型网关已关闭",+ "body": "上一次启动没有就绪。开启网关即可重试。"+ },+ "notInstalled": {+ "title": "模型网关尚未安装",+ "body": "开启后会安装由 Avibe 管理的网关组件。"+ },+ "unsupported": {+ "title": "模型网关不可用",+ "body": "当前平台没有兼容的托管网关组件。"+ },+ "installing": {+ "title": "正在安装模型网关",+ "body": "安装并启动完成后才会显示来源与路由。"+ },+ "starting": {+ "title": "正在启动模型网关",+ "body": "网关就绪后才会显示来源与路由。"+ },+ "stopping": {+ "title": "正在关闭模型网关",+ "body": "运行时停止期间会隐藏网关配置。"+ },+ "unread": {+ "title": "暂时无法读取网关状态",+ "body": "确认运行状态前不会显示网关配置。"+ }+ },"gatewayInfo": {"label": "什么是网关","body": "网关是本机的一层调度:它持有你添加的来源,按你配置的顺序供给各个 Agent。"@@ -1024,7 +1065,8 @@},"errors": {"engineDown": "模型引擎未就绪,请稍后重试",- "startFailed": "模型引擎启动失败"+ "startFailed": "模型引擎启动失败",+ "stopFailed": "模型网关关闭失败"},"runtime": {"notStarted": "未启动 · 首次使用时自动启动",diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex b56123113..87471debe 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -258,3 +258,6 @@ class ModelHubRemoteService:async def runtime_start(self) -> dict:return await _rpc("runtime_start")++ async def runtime_stop(self) -> dict:+ return await _rpc("runtime_stop")diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex b6edbec7b..323a67129 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -861,6 +861,14 @@ class CLIProxyEngineAdapter:await asyncio.to_thread(self.supervisor.ensure_running)return await self.status()+ async def stop_runtime(self) -> EngineStatus:+ async with self._installation_lock:+ status = await self.status()+ if status.health is EngineHealth.INSTALLING:+ return status+ await asyncio.to_thread(self.supervisor.disable)+ return await self.status()+async def stop(self) -> None:async with self._installation_lock:self._installation_stopping = Truediff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.pyindex 423705a9c..d798a3911 100644--- a/vibe/model_hub_runtime/supervisor.py+++ b/vibe/model_hub_runtime/supervisor.py@@ -72,6 +72,12 @@ class EngineSupervisor:with self._lock:self._stop_locked()+ def disable(self) -> None:+ """Stop the managed engine and restore explicit lazy-start idleness."""+ with self._lock:+ self._stop_locked()+ self._start_attempted = False+def restart_if_running(self) -> None:with self._lock:if not self._is_running_locked():diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 172a1ae8c..6f615be1f 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4969,6 +4969,16 @@ async def model_hub_runtime_start():return _model_hub_error(exc)[email protected]("/api/models/runtime/stop", methods=["POST"])+async def model_hub_runtime_stop():+ from core.handlers.model_hub import ModelHubError++ try:+ return _model_hub_success(runtime=await _model_hub_service().runtime_stop())+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/platforms", methods=["GET"])def platforms_get():from vibe import api