Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): interrupt running work when switching to the gateway (#2297)

Call White219c81d7967f
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 1eccd5653..3832d8b94 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -18,6 +18,9 @@ logger = logging.getLogger(__name__)
DEFAULT_DRAIN_TIMEOUT_SECONDS = 300.0
_POLL_INTERVAL_SECONDS = 0.1
+# After an interruption only teardown remains: native processes exiting and
+# requests to a stopped runtime failing. Work still live past this is a fault.
+_INTERRUPT_SETTLE_SECONDS = 10.0
_NATIVE_BACKENDS = frozenset({"claude", "codex", "opencode"})
_T = TypeVar("_T")
@@ -385,17 +388,22 @@ class BackendRestartCoordinator:
refresh: Callable[[str, bool], Awaitable[None]],
*,
drain_timeout: float | None = None,
+ settle_timeout: float = _INTERRUPT_SETTLE_SECONDS,
poll_interval: float = _POLL_INTERVAL_SECONDS,
process_inventory: Callable[[Mapping[str, str]], tuple[int, ...]] = native_cli_processes,
) -> None:
self.controller = controller
self._refresh = refresh
self._drain_timeout = _configured_drain_timeout() if drain_timeout is None else max(0.0, drain_timeout)
+ # Independent of the drain timeout, which only decides when a restart
+ # stops waiting and interrupts; an interrupting switch never drains.
+ self._settle_timeout = max(0.0, settle_timeout)
self._poll_interval = max(0.001, poll_interval)
self._tasks: dict[str, asyncio.Task[Any]] = {}
self._request_locks: dict[str, asyncio.Lock] = {}
self._outcomes: dict[str, dict[str, str]] = {}
self._migration_backends: set[str] = set()
+ self._handoffs: set[asyncio.Task[None]] = set()
self._migration_auth_owners: dict[str, tuple[asyncio.Task, NativeCredentialLease]] = {}
self._process_inventory = process_inventory
@@ -499,6 +507,9 @@ class BackendRestartCoordinator:
) -> AsyncIterator[Callable[[], Awaitable[None]]]:
"""Yield an idle recheck under the same lease and closed admissions.
+ Every caller applies an explicit user decision, so running work on a
+ target backend is interrupted rather than awaited: its turns settle and
+ its runtime is torn down before the strict retirement below.
Call the recheck immediately before native withdrawal and CPA activation:
external CLIs do not participate in Avibe's advisory ownership protocol.
No external process is ever terminated by the check. Authentication
@@ -510,6 +521,8 @@ class BackendRestartCoordinator:
"""
targets = self._migration_targets(backends)
closed: list[str] = []
+ restarts: dict[str, asyncio.Task[None]] = {}
+ unretired: set[str] = set()
async with AsyncExitStack() as locks:
for backend in targets:
await locks.enter_async_context(self._request_locks.setdefault(backend, asyncio.Lock()))
@@ -518,7 +531,6 @@ class BackendRestartCoordinator:
raise NativeMigrationBlockedError("backend_restart_in_progress", (backend,))
self._assert_no_native_login(targets)
lease = NativeCredentialLease(targets, state_dir=self._native_state_dir()).acquire(recovery=True)
- locks.callback(lease.release)
self._migration_backends.update(targets)
try:
for backend in targets:
@@ -527,10 +539,25 @@ class BackendRestartCoordinator:
closed.append(backend)
for backend in targets:
await self.controller.agent_service.prepare_backend_restart(backend)
- deadline = asyncio.get_running_loop().time() + self._drain_timeout
+ # A forced restart owns the interruption and teardown, and it
+ # reopens admission only after the teardown. The switch waits
+ # for it at most the settle window, and leaving early, by
+ # timeout or cancellation, never cuts the teardown short.
for backend in targets:
+ if await self._has_active_turns(backend):
+ restarts[backend] = self._start_restart(backend, drain_timeout=0)
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + self._settle_timeout
+ for backend in targets:
+ restart = restarts.get(backend)
+ if restart is not None:
+ await asyncio.wait({restart}, timeout=max(0.0, deadline - loop.time()))
+ if not restart.done():
+ raise NativeMigrationBlockedError("native_runtime_busy", (backend,))
+ if restart.cancelled() or restart.exception() is not None:
+ raise NativeMigrationBlockedError("native_retirement_failed", (backend,))
while await self._has_active_turns(backend):
- if asyncio.get_running_loop().time() >= deadline:
+ if loop.time() >= deadline:
raise NativeMigrationBlockedError("native_runtime_busy", (backend,))
await asyncio.sleep(self._poll_interval)
self._assert_no_native_login(targets)
@@ -546,7 +573,12 @@ class BackendRestartCoordinator:
try:
await finish_native_operation(retire())
except Exception:
+ unretired.add(backend)
raise NativeMigrationBlockedError("native_retirement_failed", (backend,)) from None
+ # The runtime is retired and relaunches on demand, so a failed
+ # earlier restart no longer describes it.
+ if self._outcomes.get(backend, {}).get("state") == "failed":
+ self._outcomes.pop(backend, None)
async def verify_idle() -> None:
for backend in targets:
lease.assert_owned(backend)
@@ -569,11 +601,21 @@ class BackendRestartCoordinator:
finally:
for backend in targets:
self._migration_auth_owners.pop(backend, None)
- self._migration_backends.difference_update(targets)
- for backend in closed:
- if backend not in self._blocked_backends():
- self.controller.agent_service.end_backend_drain(backend)
- await self.controller.session_turns.end_backend_drain(backend)
+ # A teardown still running keeps the guard's exclusions: its
+ # backends stay migrating and closed, and the lease stays held,
+ # until it settles. Retries meanwhile refuse as a restart in
+ # progress instead of waiting for it.
+ pending = {backend: task for backend, task in restarts.items() if not task.done()}
+ try:
+ self._migration_backends.difference_update(set(targets) - set(pending))
+ await self._reopen_after_guard(
+ [backend for backend in closed if backend not in pending], restarts, unretired
+ )
+ finally:
+ if pending:
+ self._hand_off_guard(pending, lease, restarts, unretired)
+ else:
+ lease.release()
async def request_restart(self, backend: str) -> str:
"""Begin or join a restart and return without waiting for a long drain."""
@@ -600,9 +642,7 @@ class BackendRestartCoordinator:
agent_service.end_backend_drain(backend)
await session_turns.end_backend_drain(backend, resume_deferred=False)
raise
- task = asyncio.create_task(self._run(backend), name=f"backend-restart:{backend}")
- self._tasks[backend] = task
- task.add_done_callback(lambda completed, name=backend: self._on_done(name, completed))
+ task = self._start_restart(backend)
# Idle refreshes remain synchronous so setup/config errors reach the
# runtime-command requester. Only genuinely active work makes the
@@ -742,6 +782,16 @@ class BackendRestartCoordinator:
return {"state": "unavailable"}
return {"state": "applied"}
+ async def _interrupt(self, backend: str) -> None:
+ """Settle every turn running on ``backend`` ahead of a forced refresh."""
+ session_ids = self.controller.session_turns.active_runtime_session_ids_for_backend(backend)
+ await self.controller.session_turns.release_for_backend_refresh(
+ backend=backend,
+ base_session_ids=session_ids,
+ )
+ await self.controller.agent_service.force_cancel_backend_turns(backend)
+ self.controller.agent_service.force_end_backend_activities(backend)
+
async def _has_active_turns(self, backend: str) -> bool:
service = self.controller.agent_service
if service.runtime_turn_tokens_for_backend(backend):
@@ -754,30 +804,78 @@ class BackendRestartCoordinator:
result = await result
return bool(result)
- async def _run(self, backend: str) -> None:
+ async def _reopen_after_guard(
+ self, backends: list[str], restarts: dict[str, asyncio.Task[None]], unretired: set[str]
+ ) -> None:
+ for backend in backends:
+ if backend in self._blocked_backends():
+ continue
+ restart = restarts.get(backend)
+ # Like the restart path, deferred turns resume only on a runtime
+ # that was refreshed and not left half retired.
+ refreshed = backend not in unretired and (
+ restart is None or (not restart.cancelled() and restart.exception() is None)
+ )
+ self.controller.agent_service.end_backend_drain(backend)
+ await self.controller.session_turns.end_backend_drain(backend, resume_deferred=refreshed)
+
+ def _hand_off_guard(
+ self,
+ pending: dict[str, asyncio.Task[None]],
+ lease: NativeCredentialLease,
+ restarts: dict[str, asyncio.Task[None]],
+ unretired: set[str],
+ ) -> None:
+ async def reopen(backends: list[str]) -> None:
+ self._migration_backends.difference_update(backends)
+ await self._reopen_after_guard(backends, restarts, unretired)
+
+ async def release() -> None:
+ waiting = dict(pending)
+ try:
+ # Each backend reopens when its own teardown settles; only the
+ # shared lease waits for all of them.
+ while waiting:
+ done, _ = await asyncio.wait(waiting.values(), return_when=asyncio.FIRST_COMPLETED)
+ settled = [backend for backend, task in waiting.items() if task in done]
+ for backend in settled:
+ del waiting[backend]
+ await reopen(settled)
+ finally:
+ try:
+ await reopen(list(waiting))
+ finally:
+ lease.release()
+
+ task = asyncio.create_task(release(), name="migration-guard-handoff")
+ self._handoffs.add(task)
+ task.add_done_callback(self._handoffs.discard)
+
+ def _start_restart(self, backend: str, *, drain_timeout: float | None = None) -> asyncio.Task[None]:
+ task = asyncio.create_task(self._run(backend, drain_timeout), name=f"backend-restart:{backend}")
+ self._tasks[backend] = task
+ task.add_done_callback(lambda completed, name=backend: self._on_done(name, completed))
+ return task
+
+ async def _run(self, backend: str, drain_timeout: float | None = None) -> None:
forced = False
refreshed = False
loop = asyncio.get_running_loop()
- deadline = loop.time() + self._drain_timeout
+ deadline = loop.time() + (self._drain_timeout if drain_timeout is None else drain_timeout)
try:
while await self._has_active_turns(backend):
if loop.time() >= deadline:
forced = True
- session_ids = self.controller.session_turns.active_runtime_session_ids_for_backend(backend)
- await self.controller.session_turns.release_for_backend_refresh(
- backend=backend,
- base_session_ids=session_ids,
- )
- await self.controller.agent_service.force_cancel_backend_turns(backend)
- self.controller.agent_service.force_end_backend_activities(backend)
+ await self._interrupt(backend)
break
await asyncio.sleep(self._poll_interval)
await self._refresh(backend, forced)
refreshed = True
finally:
# Runtime admission opens before durable queues are flushed. A flush
- # therefore always enters the refreshed generation.
- if backend not in self._blocked_backends():
+ # therefore always enters the refreshed generation. A migration
+ # guard, or the handoff it left, reopens a backend it still holds.
+ if backend not in self._blocked_backends() and backend not in self._migration_backends:
self.controller.agent_service.end_backend_drain(backend)
await self.controller.session_turns.end_backend_drain(backend, resume_deferred=refreshed)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 1de831ba2..165c6804d 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -4817,6 +4817,25 @@ class ModelHubService:
logger.warning("Model Hub CLI presence probe failed for %s", backend, exc_info=True)
return False
+ async def _native_config_blocks_launch(self, config: ModelHubConfig, backend: str) -> bool:
+ # Native auth stays beside the Hub, but a config the CLI cannot parse
+ # fails every launch.
+ completed = self.migration_journal.completed() or {}
+ available = await asyncio.to_thread(
+ scan_native_configs, config,
+ mask_credential=_mask_credential,
+ home=self.migration_home,
+ validate_base_url=_validated_base_url,
+ legacy_auth=(
+ self.store.native_auth_snapshot((backend,))
+ if isinstance(self.store, V2ModelHubConfigStore) else None
+ ),
+ project_roots=self.migration_project_roots(),
+ clean_native_stores=completed.get("clean_native_stores"),
+ retained_native_ids=completed.get("retained_native_ids"),
+ )
+ return any(item.backend == backend and item.config_blocker for item in available)
+
async def set_agent_mode(self, backend: str, mode: object) -> dict:
if mode not in {"hub", "direct"}:
raise ModelHubError("mode_switch_blocked")
@@ -4833,32 +4852,21 @@ class ModelHubService:
agent = self._agent(current, backend)
if agent.mode == "hub":
return self._agent_payload(current, agent)
+ # The guard interrupts running work, so refuse a switch
+ # that would be refused anyway before destroying any.
+ try:
+ blocked = await self._native_config_blocks_launch(current, backend)
+ except (TakeoverStateError, OSError):
+ raise ModelHubError("mode_switch_blocked", status=409) from None
+ if blocked:
+ raise ModelHubError("mode_switch_blocked", status=409)
try:
async with self.migration_guard((backend,), external_processes=False) as verify_idle:
async with self._mutation_lock:
# Recheck idleness after the last asynchronous drain.
await verify_idle()
previous = self.store.load()
- available = await asyncio.to_thread(
- scan_native_configs, previous,
- mask_credential=_mask_credential,
- home=self.migration_home,
- validate_base_url=_validated_base_url,
- legacy_auth=(
- self.store.native_auth_snapshot((backend,))
- if isinstance(self.store, V2ModelHubConfigStore) else None
- ),
- project_roots=self.migration_project_roots(),
- clean_native_stores=(
- self.migration_journal.completed() or {}
- ).get("clean_native_stores"),
- retained_native_ids=(
- self.migration_journal.completed() or {}
- ).get("retained_native_ids"),
- )
- # Native auth stays beside the Hub, but a config
- # the CLI cannot parse fails every launch.
- if any(item.backend == backend and item.config_blocker for item in available):
+ if await self._native_config_blocks_launch(previous, backend):
raise ModelHubError("mode_switch_blocked", status=409)
config = self._clone_config(previous)
self._agent(config, backend).mode = "hub"
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 438b13fb1..b850cfb11 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -48,7 +48,7 @@ remain readable; ephemeral envelopes use only the terminal version.
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
| PUT `/api/models/agents/<backend>/sources` | `{order: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Atomically replaces default membership/order, preserves manual overrides, and guards effective hop removal or protected-supply loss. Pure reordering needs no guard. |
| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Compatibility default-order entry point with the same guards as Sources PUT. Never reorders manual arrays. Without order, returns the current projection. New UI uses Sources PUT. |
-| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. Direct-to-Hub serializes with takeover under the shared migration guard, drains and retires the managed runtime, and returns `mode_switch_blocked` only for a native config the CLI cannot parse or a guard refusal. Native auth, including an importable login, stays native beside the Hub and remains a migration candidate; CLIs running outside Avibe do not block the switch because it changes no native credential. It does not auto-create or adopt a native Source; native custody takeover is the optional grouped migration transaction. Hub-to-Direct remains mode-only. |
+| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. Direct-to-Hub serializes with takeover under the shared migration guard, interrupts running work on that backend and retires the managed runtime, and returns `mode_switch_blocked` only for a native config the CLI cannot parse or a guard refusal. Native auth, including an importable login, stays native beside the Hub and remains a migration candidate; CLIs running outside Avibe do not block the switch because it changes no native credential. It does not auto-create or adopt a native Source; native custody takeover is the optional grouped migration transaction. Hub-to-Direct remains mode-only. |
| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data. Every OpenCode row carries required `native_protocol`; Claude and Codex rows omit it. |
| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. A `providers` candidate whose id names a cached models.dev model exactly also carries that match's `models_dev_id`, `context_window`, `max_output_tokens`, `input_modalities`, `output_modalities`, `supports_tools`, and `supports_reasoning` together; those seven are absent otherwise. |
| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list starts automatic without a route key. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |
diff --git a/docs/plans/model-hub-native-takeover.md b/docs/plans/model-hub-native-takeover.md
index b70a6a4e5..af807f301 100644
--- a/docs/plans/model-hub-native-takeover.md
+++ b/docs/plans/model-hub-native-takeover.md
@@ -151,9 +151,16 @@ explicitly authorized acceptance check.
access-token acceptance, not inference entitlement or future refresh success.
- `ModelHubService.migration_guard` is a callable taking
`tuple[BackendName, ...]` and returning an asynchronous context manager.
- Entering it closes managed native admission, waits for active work (without
- a forced cancellation), strictly retires credential-bearing idle processes,
- and checks for external CLI users. It is acquired before `_mutation_lock`.
+ Entering it closes managed native admission, interrupts active work on the
+ target backends (every caller applies an explicit user switch or migration,
+ so running turns settle as a backend refresh and the managed runtime is torn
+ down instead of being awaited), strictly retires credential-bearing processes
+ that are then idle, and checks for external CLI users, which are never
+ terminated. The interruption runs as a forced backend restart, which keeps
+ admission closed until its teardown completes. The switch waits for it only
+ for a short settle window and refuses as busy after that. Leaving early, by
+ timeout or cancellation, never cuts the teardown short. It is acquired before
+ `_mutation_lock`.
Production installs wire it from the Controller; no production no-op.
Configured CLI identity is independent of backend enablement: the existing
auth-service binary resolver supplies raw/compatibility paths and persisted
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index 202fbf974..b616dbfc2 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -4787,7 +4787,7 @@ difference is not an inconsistency: that frame's entry condition is *every backe
| `effects.1.opencode` `[derived]` | OpenCode 自己的模型配置原样保留,这次切换不改动它 | OpenCode's own model configuration is kept as it is; this switch does not change it |
| `effects.2.opencode` `[derived]` | 它的型号从此由这一页上的来源供给;还没有来源时,先添加一个 | Its models are supplied from the sources on this page; if there are none yet, add one first |
| `effects.3` | 型号菜单不变 | The model menu does not change |
-| `effects.4` | 正在进行的对话不受影响,下一次请求开始生效 | Conversations in progress are unaffected; the change applies from the next request |
+| `effects.4` | 正在运行的任务会被中断,下一次请求开始生效 | Tasks in progress are interrupted; the change applies from the next request |
| `section.undo` | 可以撤回 | You can undo this |
| `undo.1` | 随时可以切换回直连 | You can switch back to direct at any time |
| `undo.2` | 回退入口:这一页的 {{backend}} 卡片 → 切到直连 | Where to undo: the {{backend}} card on this page → Switch to direct |
@@ -4849,9 +4849,10 @@ the least convenient one, not the one it was drafted from. A rule that counts th
does not read what they say.
**Every bullet is a consequence the user can check afterwards** `[frame]`. 型号菜单不变
-and 正在进行的对话不受影响 are there because they are the two things a cautious user
-actually fears, and both are falsifiable — which is what makes stating them worth the
-space. Nothing here explains what a gateway *is*; that argument belongs to 09's benefit
+and 正在运行的任务会被中断 are there because they are the two things a cautious user
+needs to know before confirming, and both are falsifiable — which is what makes stating
+them worth the space. The second once promised the opposite; a switch now interrupts
+running work instead of waiting for it (MH-MIG-009), so the confirm states the cost. Nothing here explains what a gateway *is*; that argument belongs to 09's benefit
card, and repeating it in the confirm would turn a decision surface into a second pitch.
**States** — §0.8, rows marked §1.9.
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 321e51428..cb79ad0a9 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -764,6 +764,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
self._session_last_activity: Dict[str, float] = {}
self._steering_states: Dict[str, _OpenCodeSteerState] = {}
self._restored_poll_servers: Dict[asyncio.Task, _SteeringAwareOpenCodeServer] = {}
+ # Request tasks already settling, interrupted by a forced refresh or in
+ # their own cleanup. A forced refresh never cancels these again, and a
+ # restored poll it interrupted retires its own durable record.
+ self._settling_request_tasks: set[asyncio.Task] = set()
async def _get_server(self) -> OpenCodeServerManager:
current_task = asyncio.current_task()
@@ -1168,6 +1172,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
Settings writes take effect without terminating active serve
processes; fall back to restart for older OpenCode versions.
"""
+ if force:
+ await self._cancel_active_requests()
previous_server = await self._client_manager.reset_config(opencode_config)
if previous_server is None:
previous_server = await OpenCodeServerManager.get_instance_if_managed_server_exists(
@@ -1212,6 +1218,36 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
request_timeout_seconds=opencode_config.request_timeout_seconds,
)
+ async def _cancel_active_requests(self) -> None:
+ """Cancel every request task before a forced server teardown.
+
+ Turn owners cancel foreground requests first; restored polls have no
+ owner, so without this they would poll the stopped server until their
+ failure limit and report a transport error for an intended interrupt.
+ """
+ cancelled: list[asyncio.Task] = []
+ for base_session_id, task in list(self._active_requests.items()):
+ # Cancelling a task that is already settling could abort the
+ # retirement in its cleanup.
+ if task.done() or task in self._settling_request_tasks:
+ continue
+ state = self._steering_states.get(base_session_id)
+ if state is not None and state.task is task:
+ state.closing = True
+ self._settling_request_tasks.add(task)
+ task.add_done_callback(self._settling_request_tasks.discard)
+ # Cancel without the steering lock, which the task itself may hold
+ # across a native call, and without a native abort: the teardown
+ # that follows ends the native run.
+ task.cancel()
+ cancelled.append(task)
+ if cancelled:
+ # Bounded like force_cancel_backend_turns: a stuck cleanup must not
+ # hold the teardown, and retirement does not depend on this wait.
+ # A task still settling keeps its session, as /stop and a new
+ # request already wait for it, so no successor shares its record.
+ await asyncio.wait(cancelled, timeout=2.0)
+
async def handle_message(self, request: AgentRequest) -> None:
lock = self._session_manager.get_session_lock(request.base_session_id)
task: Optional[asyncio.Task] = None
@@ -3026,6 +3062,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
err,
)
finally:
+ interrupted = current_task in self._settling_request_tasks
+ if current_task is not None:
+ # Settling from here on, however the poll ended.
+ self._settling_request_tasks.add(current_task)
+ current_task.add_done_callback(self._settling_request_tasks.discard)
await self._stop_caller_context_binding_renewal(
caller_context_binding_renewal
)
@@ -3036,11 +3077,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
steer_state.closing = True
if self._steering_states.get(poll_info.base_session_id) is steer_state:
self._steering_states.pop(poll_info.base_session_id, None)
- if terminal_poll_cleanup and server is not None:
+ if (terminal_poll_cleanup or interrupted) and server is not None:
await self._retire_active_poll(
server,
poll_info.opencode_session_id,
)
+ elif interrupted:
+ # Interrupted before registering a run marker: only the durable
+ # record would bring the run back after a restart.
+ self.sessions.remove_active_poll(poll_info.opencode_session_id)
if caller_context_binding_token and not self._active_poll_is_persisted(
poll_info.opencode_session_id
):
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 81876fa23..38a2700f0 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -53,6 +53,7 @@ capabilities:
- tests/test_model_hub_legacy_opencode_migration.py
- tests/test_model_hub_persisted_migration.py
- tests/test_native_process_inventory.py
+ - tests/test_native_takeover_lifecycle.py
- tests/test_member_management_parity.py
- tests/test_model_hub_provenance.py
- tests/test_model_hub_retention.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 43a723d6e..95a5a74f2 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -55,6 +55,7 @@ capability:
- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
- tests/test_model_hub_persisted_migration.py
- tests/test_native_process_inventory.py
+ - tests/test_native_takeover_lifecycle.py
- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
- tests/scenarios/model_hub/test_model_hub_valuation_scenarios.py
- tests/e2e/test_model_hub_guards.py
@@ -1265,6 +1266,29 @@ scenarios:
- tests/test_native_takeover_lifecycle.py::test_same_user_setuid_program_does_not_block_inventory
- ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+ - id: MH-MIG-009
+ name: Switching to the gateway or migrating interrupts running work instead of waiting for it
+ status: covered
+ kind: migration
+ layer: unit
+ test: tests/test_native_takeover_lifecycle.py::test_busy_guard_interrupts_running_work_then_retires_and_yields
+ related_tests:
+ - tests/test_native_takeover_lifecycle.py::test_guard_fails_closed_when_interruption_does_not_settle
+ - tests/test_native_takeover_lifecycle.py::test_abandoned_switch_keeps_admission_closed_until_teardown_completes
+ - tests/test_native_takeover_lifecycle.py::test_handoff_reopens_each_backend_when_its_own_teardown_settles
+ - tests/test_native_takeover_lifecycle.py::test_successful_retry_supersedes_a_failed_forced_restart_receipt
+ - tests/test_model_hub_native_takeover.py::test_mode_only_adoption_refuses_a_native_config_the_cli_cannot_parse
+ - tests/test_model_hub_native_takeover.py::test_mode_switch_refuses_an_unreadable_completed_receipt_before_interrupting
+ - tests/test_opencode_restore_polls.py::test_forced_refresh_neither_waits_on_nor_strands_a_stuck_restored_poll
+ - tests/test_agent_auth_service.py::AgentAuthServiceTests::test_opencode_agent_force_refresh_restarts_after_global_config_change
+ - id: MH-MIG-010
+ name: A refused switch to the gateway is reported where it was made and retried in place
+ status: covered
+ kind: migration
+ layer: unit
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-MIG-010 reports a refused switch to the gateway on the direct-only screen
+ related_tests:
+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
- id: MH-TAKEOVER-001
name: Recoverable failures walk the configured route and exhaust only at its end
status: covered
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index 5f0e5dfb4..a22b64cf4 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -1921,21 +1921,33 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
port=4096,
request_timeout_seconds=60,
)
+ calls = []
previous_server = SimpleNamespace(
binary="/opencode",
port=4096,
request_timeout_seconds=60,
refresh_global_config=AsyncMock(return_value=True),
- detach_after_deferred_refresh=AsyncMock(),
+ detach_after_deferred_refresh=AsyncMock(side_effect=lambda **_kw: calls.append(("detach", restored_poll.done()))),
reload_runtime_config=AsyncMock(),
)
+ # A poll restored after a restart has no turn owner to cancel it; left
+ # running, it would poll the stopped server and surface a transport
+ # error for an interruption the user chose.
+ restored_poll = asyncio.create_task(asyncio.Event().wait())
agent = OpenCodeAgent.__new__(OpenCodeAgent)
agent.opencode_config = old_config
agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))
- agent._client_manager = SimpleNamespace(reset_config=AsyncMock(return_value=previous_server))
+ agent._client_manager = SimpleNamespace(
+ reset_config=AsyncMock(return_value=previous_server),
+ )
+ agent._active_requests = {"base-restored": restored_poll}
+ agent._steering_states = {}
+ agent._settling_request_tasks = set()
await agent.refresh_runtime_config(new_config, force=True)
+ self.assertTrue(restored_poll.cancelled())
+ self.assertEqual(calls, [("detach", True)])
previous_server.refresh_global_config.assert_not_awaited()
previous_server.detach_after_deferred_refresh.assert_awaited_once_with(force=True)
previous_server.reload_runtime_config.assert_awaited_once_with(
diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.py
index 9910f4cca..ac6b259b5 100644
--- a/tests/test_model_hub_native_takeover.py
+++ b/tests/test_model_hub_native_takeover.py
@@ -610,6 +610,34 @@ def test_rejected_grant_terminal_decision_recovers_after_crash(monkeypatch, tmp_
assert adapter.revoked == []
+def test_mode_switch_refuses_an_unreadable_completed_receipt_before_interrupting(monkeypatch, tmp_path):
+ """MH-MIG-009: the pre-guard blocker scan reads the completed receipt; a
+ receipt it cannot trust refuses the switch as mode_switch_blocked, the
+ documented 409, instead of escaping as a server error."""
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ service, store, _adapter = _service(tmp_path, migration_home=home)
+ store.config.agents["codex"].mode = "direct"
+ receipt = service.migration_journal.path.with_name("last-completed.json")
+ receipt.parent.mkdir(parents=True, exist_ok=True)
+ receipt.write_text("{not json")
+ entered = []
+
+ @asynccontextmanager
+ async def guard(backends, *, external_processes=True):
+ entered.append(backends)
+ async def verify():
+ return None
+ yield verify
+
+ service.migration_guard = guard
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.set_agent_mode("codex", "hub"))
+ assert failure.value.code == "mode_switch_blocked"
+ assert store.config.agents["codex"].mode == "direct"
+ assert entered == []
+
+
@pytest.mark.parametrize(("backend", "relative", "payload"), [
("claude", ".claude/settings.json", "{not json"),
("codex", ".codex/config.toml", "model_providers = ["),
@@ -626,8 +654,11 @@ def test_mode_only_adoption_refuses_a_native_config_the_cli_cannot_parse(
# Nothing is importable, yet the CLI would fail before any Hub override.
assert not any(item["proposed_action"] == "import" for item in service.migration_scan()["items"])
+ entered = []
+
@asynccontextmanager
async def guard(backends, *, external_processes=True):
+ entered.append(backends)
async def verify():
return None
yield verify
@@ -637,3 +668,6 @@ def test_mode_only_adoption_refuses_a_native_config_the_cli_cannot_parse(
asyncio.run(service.set_agent_mode(backend, "hub"))
assert failure.value.code == "mode_switch_blocked"
assert store.config.agents[backend].mode == "direct"
+ # MH-MIG-009: the guard interrupts running work, so a switch that is
+ # refused anyway must be refused before it is entered.
+ assert entered == []
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
index 957b824d5..967610ad1 100644
--- a/tests/test_native_takeover_lifecycle.py
+++ b/tests/test_native_takeover_lifecycle.py
@@ -43,6 +43,8 @@ def controller_fixture(*, backends=("claude", "codex", "opencode"), busy=False):
session_turns=SimpleNamespace(
begin_backend_drain=Mock(side_effect=turns.add),
end_backend_drain=AsyncMock(side_effect=lambda backend, **kw: turns.discard(backend)),
+ active_runtime_session_ids_for_backend=Mock(return_value=set()),
+ release_for_backend_refresh=AsyncMock(return_value=0),
),
model_hub_service=SimpleNamespace(
migration_blocked_backends=set(), events=SimpleNamespace(path=get_state_dir() / "events.jsonl")
@@ -50,7 +52,8 @@ def controller_fixture(*, backends=("claude", "codex", "opencode"), busy=False):
config=SimpleNamespace(),
)
coordinator = BackendRestartCoordinator(
- controller, AsyncMock(), process_inventory=Mock(return_value=()), drain_timeout=0.01, poll_interval=0.001,
+ controller, AsyncMock(), process_inventory=Mock(return_value=()), drain_timeout=0.01, settle_timeout=0.01,
+ poll_interval=0.001,
)
controller.backend_restart_coordinator = coordinator
return controller, coordinator, admissions, turns
@@ -172,33 +175,174 @@ async def test_guard_closes_both_admissions_before_retirement_and_retains_only_b
@pytest.mark.asyncio
-async def test_busy_guard_never_cancels_or_yields():
[email protected]("drain_timeout", [1, 0])
+async def test_busy_guard_interrupts_running_work_then_retires_and_yields(drain_timeout):
+ """MH-MIG-009: every caller applies an explicit user switch, so live work is
+ interrupted, not awaited; a guard that waits for idle leaves the switch spinning.
+ The settle window is independent of the drain timeout, which only decides when
+ a restart stops waiting: an immediate drain must not refuse a brief teardown."""
controller, coordinator, admissions, turns = controller_fixture(busy=True)
- with pytest.raises(NativeMigrationBlockedError, match="native_runtime_busy"):
+ service = controller.agent_service
+ coordinator._drain_timeout = drain_timeout
+ coordinator._settle_timeout = 1
+ controller.session_turns.active_runtime_session_ids_for_backend.return_value = {"session-1"}
+ order = []
+ service.force_cancel_backend_turns.side_effect = lambda backend: order.append(("cancel", backend))
+
+ async def teardown(backend, forced):
+ await asyncio.sleep(0.01)
+ order.append(("refresh", backend, forced))
+ service.backend_runtime_active.return_value = False
+
+ coordinator._refresh.side_effect = teardown
+ service.agents["codex"].retire_for_native_migration.side_effect = lambda: order.append("retire")
+ async with coordinator.migration_guard(("codex",)):
+ assert admissions == turns == {"codex"}
+ order.append("mutate")
+ assert order == [("cancel", "codex"), ("refresh", "codex", True), "retire", "mutate"]
+ controller.session_turns.release_for_backend_refresh.assert_awaited_once_with(
+ backend="codex", base_session_ids={"session-1"},
+ )
+ assert not admissions and not turns
+
+
[email protected]("leaves", ["cancelled", "settle_window"])
+async def test_abandoned_switch_keeps_admission_closed_until_teardown_completes(leaves):
+ """MH-MIG-009: an interruption that hangs, such as a turn owner stuck in its
+ cancellation cleanup, must not hold the switch past the settle window, and
+ a switch that leaves early must not reopen admission between releasing turn
+ owners and tearing down the runtime they ran on."""
+ controller, coordinator, admissions, turns = controller_fixture(busy=True)
+ releasing, released = asyncio.Event(), asyncio.Event()
+
+ async def release(**_kw):
+ releasing.set()
+ await released.wait()
+ return 0
+
+ controller.session_turns.release_for_backend_refresh.side_effect = release
+
+ async def switch():
async with coordinator.migration_guard(("codex",)):
- pytest.fail("Mutation admitted while busy")
+ pytest.fail("mutation admitted over an unfinished interruption")
+
+ task = asyncio.create_task(switch())
+ try:
+ await releasing.wait()
+ if leaves == "cancelled":
+ task.cancel()
+ done, _ = await asyncio.wait({task}, timeout=2)
+ assert done, "the switch is still waiting on the interruption"
+ if leaves == "cancelled":
+ assert task.cancelled()
+ else:
+ with pytest.raises(NativeMigrationBlockedError, match="native_runtime_busy"):
+ task.result()
+ assert admissions == turns == {"codex"}
+ # The credential lease stays with the teardown, so no native login or
+ # config writer starts beside it, and a retry refuses at once.
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ NativeCredentialLease(("codex",)).acquire()
+ with pytest.raises(NativeMigrationBlockedError, match="backend_restart_in_progress"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("a retry entered beside an unfinished teardown")
+ finally:
+ released.set()
+ await coordinator.wait("codex")
+ for _ in range(50):
+ if not admissions:
+ break
+ await asyncio.sleep(0)
+ controller.agent_service.force_cancel_backend_turns.assert_awaited_once_with("codex")
+ coordinator._refresh.assert_awaited_once_with("codex", True)
+ controller.agent_service.agents["codex"].retire_for_native_migration.assert_not_awaited()
assert admissions == turns == set()
- controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
[email protected]("failure,code", [
+ ("survives", "native_runtime_busy"),
+ ("teardown", "native_retirement_failed"),
+])
+async def test_guard_fails_closed_when_interruption_does_not_settle(failure, code):
+ controller, coordinator, admissions, turns = controller_fixture(busy=True)
+ if failure == "teardown":
+ coordinator._refresh.side_effect = RuntimeError("stop failed")
+ with pytest.raises(NativeMigrationBlockedError, match=code):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("mutation admitted over live work")
+ coordinator._refresh.assert_awaited_once_with("codex", True)
controller.agent_service.agents["codex"].retire_for_native_migration.assert_not_awaited()
+ assert admissions == turns == set()
+ # Deferred turns resume only on a runtime that was actually refreshed.
+ controller.session_turns.end_backend_drain.assert_awaited_once_with(
+ "codex", resume_deferred=failure != "teardown",
+ )
@pytest.mark.asyncio
-async def test_guard_drains_active_work_naturally():
+async def test_handoff_reopens_each_backend_when_its_own_teardown_settles():
+ """MH-MIG-009: after a grouped migration leaves early, a backend whose
+ teardown settled reopens at once rather than waiting on a sibling that is
+ stuck; the shared credential lease stays held until both have settled."""
controller, coordinator, admissions, turns = controller_fixture(busy=True)
- coordinator._drain_timeout = 1
- ready = asyncio.Event()
+ gates = {"claude": asyncio.Event(), "codex": asyncio.Event()}
- async def transaction():
- async with coordinator.migration_guard(("codex",)):
- ready.set()
- task = asyncio.create_task(transaction())
- while not admissions:
+ async def release(*, backend, **_kw):
+ await gates[backend].wait()
+ return 0
+
+ controller.session_turns.release_for_backend_refresh.side_effect = release
+ with pytest.raises(NativeMigrationBlockedError, match="native_runtime_busy"):
+ async with coordinator.migration_guard(("claude", "codex")):
+ pytest.fail("mutation admitted over unfinished interruptions")
+ assert admissions == turns == {"claude", "codex"}
+ try:
+ gates["claude"].set()
+ await coordinator.wait("claude")
+ for _ in range(50):
+ if "claude" not in admissions:
+ break
+ await asyncio.sleep(0)
+ assert admissions == turns == {"codex"}
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ NativeCredentialLease(("claude",)).acquire()
+ finally:
+ gates["codex"].set()
+ await coordinator.wait("codex")
+ for _ in range(50):
+ if not admissions:
+ break
await asyncio.sleep(0)
- assert not ready.is_set()
- controller.agent_service.backend_runtime_active.return_value = False
- await task
- assert ready.is_set()
- assert not admissions and not turns
+ assert admissions == turns == set()
+ with NativeCredentialLease(("claude", "codex")):
+ pass
+
+
+async def test_successful_retry_supersedes_a_failed_forced_restart_receipt():
+ """MH-MIG-009: a forced restart that fails after stopping the runtime leaves a
+ failed receipt. A retry that finds the backend idle and retires it must clear
+ that receipt, or the switched backend keeps reporting itself not ready."""
+ controller, coordinator, _, _ = controller_fixture(busy=True)
+
+ def teardown(backend, forced):
+ controller.agent_service.backend_runtime_active.return_value = False
+ raise RuntimeError("reload failed")
+
+ coordinator._refresh.side_effect = teardown
+ with pytest.raises(NativeMigrationBlockedError, match="native_retirement_failed"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("mutation admitted after a failed teardown")
+ assert coordinator.snapshot("codex")["state"] == "failed"
+
+ async with coordinator.migration_guard(("codex",)):
+ pass
+ assert coordinator.snapshot("codex") == {"state": "applied"}
+ coordinator._refresh.assert_awaited_once_with("codex", True)
@pytest.mark.asyncio
@@ -215,6 +359,11 @@ async def test_failed_retirement_or_external_process_never_yields(failure):
async with coordinator.migration_guard(("codex",)):
pytest.fail("unsafe migration admission")
assert not admissions and not turns
+ # MH-MIG-009: a strict retirement that failed part-way leaves no runtime
+ # that deferred turns could safely resume on.
+ controller.session_turns.end_backend_drain.assert_awaited_once_with(
+ "codex", resume_deferred=failure != "retire_failure",
+ )
with NativeCredentialLease(("codex",)):
pass
diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.py
index d80b8aeb2..3b80e84cb 100644
--- a/tests/test_opencode_restore_polls.py
+++ b/tests/test_opencode_restore_polls.py
@@ -142,6 +142,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "en
agent._user_stopped_sessions = set()
agent._steering_states = {}
agent._restored_poll_servers = {}
+ agent._settling_request_tasks = set()
server = _Server()
agent._client_manager = SimpleNamespace(_server_manager=server)
@@ -1109,6 +1110,75 @@ def test_restore_settles_incomplete_assistant_when_unknown_status_recovers_idle(
)
[email protected]("stall", ["cleanup", "steering_lock", "retiring"])
+def test_forced_refresh_neither_waits_on_nor_strands_a_stuck_restored_poll(stall) -> None:
+ """MH-MIG-009: switching to the gateway interrupts a restored poll. The
+ teardown must not wait on the poll, whether its cancellation cleanup hangs
+ or it holds its steering lock across a native call; and once the poll does
+ settle it must retire its durable record, or the next restart restores a
+ run the user chose to interrupt. A poll that finished on its own and is
+ already retiring must be left to finish that retirement."""
+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
+ if stall == "steering_lock":
+ poll.processing_indicator = {
+ "platform": "avibe",
+ "opencode_native_steering": {"target_session_id": "ses_wb", "logical_turn_id": "logical-restored"},
+ }
+ active_polls = {"oc-1": poll}
+ agent, _, removed, _ = _build_agent(active_polls)
+ polling, release = asyncio.Event(), asyncio.Event()
+ recancelled = []
+
+ if stall == "retiring":
+ async def slow_mark_run_inactive(session_id):
+ polling.set()
+ await release.wait()
+ agent._test_inactive_runs.append(session_id)
+
+ agent._test_server.mark_run_inactive = slow_mark_run_inactive
+
+ async def run_restored_poll_loop(poll_info):
+ if stall == "retiring":
+ return True
+ if stall == "steering_lock":
+ # A native call made through the steering-aware server holds the lock.
+ async with agent._steering_states["ses_wb"].lock:
+ polling.set()
+ await asyncio.Event().wait()
+ polling.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ try:
+ await release.wait()
+ except asyncio.CancelledError:
+ recancelled.append(True)
+ raise
+
+ agent._poll_loop.run_restored_poll_loop = run_restored_poll_loop
+
+ async def run() -> None:
+ assert await agent.restore_active_polls() == 1
+ await polling.wait()
+ tasks = list(agent._active_requests.values())
+ await asyncio.wait_for(agent._cancel_active_requests(), timeout=5)
+ if stall == "cleanup":
+ assert active_polls == {"oc-1": poll}
+ # A second forced refresh, such as a retried switch, must leave the
+ # task's cleanup alone rather than cancel it mid-retirement.
+ await asyncio.wait_for(agent._cancel_active_requests(), timeout=5)
+ release.set()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+ asyncio.run(run())
+ assert recancelled == []
+ assert agent._active_requests == {}
+ assert agent._settling_request_tasks == set()
+ assert agent._test_inactive_runs == ["oc-1"]
+ assert removed == ["oc-1"]
+ assert active_polls == {}
+
+
def test_restored_avibe_poll_marks_session_running():
poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")
agent, status_writes, _, _ = _build_agent({"oc-1": poll})
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index 471aa8fd4..11851d6de 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -311,6 +311,12 @@ const AgentModelCard: React.FC<{
</div>
</ResponsiveMenu>
)}
+ {agent.mode !== 'hub' && switchFailed && (
+ <span role="status" className="flex min-w-0 items-center gap-1.5 px-2.5 text-[11px] font-semibold text-destructive-ink">
+ <span className="size-[5px] shrink-0 rounded-full bg-destructive" />
+ <span className="truncate">{t('settings.models.gateway.fail.switchToGateway')}</span>
+ </span>
+ )}
</div>
<div className="model-hub-agent-head-controls flex min-w-0 items-center justify-between gap-2">
<Badge variant="secondary" className={cn('model-hub-pill model-hub-fill-0a min-w-0', hasTakeover && 'model-hub-takeover-chip')}>
@@ -323,7 +329,7 @@ const AgentModelCard: React.FC<{
<ManageModelsButton className="model-hub-agent-head-action" disabled={pending} onClick={() => onOpenModels(agent)} />
<Button variant="outline" size="xs" className="model-hub-agent-head-action rounded-md bg-background px-2.5 text-[11px] font-semibold shadow-sm" onClick={() => onOpenOrder(agent)} disabled={pending}><ArrowDownUp aria-hidden="true" />{t('settings.models.gateway.sourceOrder')}</Button>
</div>
- ) : <Button variant="default" size="xs" className="model-hub-agent-head-action shrink-0 rounded-md px-2.5 text-[11px] font-semibold" onClick={() => onConnectHub(agent)} disabled={connecting}><PlugZap aria-hidden="true" />{t('settings.models.gateway.switchToGateway')}</Button>}
+ ) : <Button variant="default" size="xs" className="model-hub-agent-head-action shrink-0 rounded-md px-2.5 text-[11px] font-semibold" onClick={() => onConnectHub(agent)} disabled={connecting}><PlugZap aria-hidden="true" />{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.gateway.switchToGateway')}</Button>}
</div>
</div>
{agent.mode === 'hub' && (models.length === 0 ? <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t('settings.models.gateway.group.emptyModels')}</p><ManageModelsButton disabled={pending} onClick={() => onOpenModels(agent)} /></div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} originHelpOpen={activeOriginHelp === modelChainKey(agent.backend, modelId)} onOriginHelpChange={onOriginHelpChange} onOpenRoute={onOpenRoute} />)}{(canCollapse || needsChainRepair) && <div className="flex h-6 w-full items-center">{canCollapse && <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 flex-1 items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse') : t('settings.models.gateway.moreModels', { count: collapsed.hidden.length })}</button>}{needsChainRepair && <button type="button" onClick={retryChains} className="model-hub-model-collapse model-hub-model-collapse--repair flex h-6 items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button>}</div>}</div>)}
diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsx
index 679c752ce..12c7bdad3 100644
--- a/ui/src/components/settings/models/MigrationDialog.test.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx
@@ -313,7 +313,7 @@ describe('MigrationDialog — the settings default', () => {
});
it.each([
- ['migration_native_busy', 'Quit the running CLI, including terminal sessions, IDE extensions and desktop apps, or let its tasks finish, then retry.'],
+ ['migration_native_busy', 'Something is still using these assistants. Retry in a moment; if it keeps failing, quit any CLI running outside Avibe, including terminal sessions, IDE extensions and desktop apps.'],
['migration_permission_needed', 'Allow credential access, then retry.'],
['migration_recovery_pending', 'Migration is unfinished. Retry to continue.'],
['migration_item_conflict', 'Migration could not verify the saved configuration or its credentials. Check the files and authentication before retrying, or add the source manually in Model Hub.'],
@@ -777,6 +777,7 @@ describe('MigrationDialog — the Settings surface the setup scope must not dist
'sk-…9f21 · Codex configuration',
'Also remove the API keys from the native CLI configuration',
'Includes shell startup files and each CLI’s config files. Left unchecked, those keys stay as they are; assistants launched through Model Hub don’t use them.',
+ 'Migrating interrupts any task the selected assistants are running in Avibe.',
'Later',
'Start migration',
'Close',
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
index 638b7e8be..77940dd28 100644
--- a/ui/src/components/settings/models/MigrationDialog.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -502,6 +502,7 @@ export const MigrationDialog: React.FC<{
</div>
</div>
)}
+ <p className="px-1 text-[12px] leading-relaxed text-muted">{t('settings.models.migration.interruptNotice')}</p>
</div>
)}
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 72ca8f7c2..b5a7c3195 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -349,6 +349,27 @@ describe('SettingsModelsPage surface branches', () => {
expect(screen.queryByRole('dialog')).toBeNull();
});
+ // A refused switch to the gateway used to leave the Direct row exactly as it
+ // was: the failure was recorded, then pruned by the next read because the
+ // backend was still Direct, and no Direct surface rendered it anyway.
+ it.each([
+ ['the direct-only screen', []],
+ ['a gateway card', [retainedSource]],
+ ] as const)('MH-MIG-010 reports a refused switch to the gateway on %s and retries in place', async (_, sources) => {
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [] });
+ const setMode = vi.spyOn(modelsApi, 'setAgentMode')
+ .mockRejectedValueOnce(new ApiCallError('mode_switch_blocked'))
+ .mockResolvedValueOnce({ ...directAgent('claude'), mode: 'hub' });
+ renderPage([...sources], [directAgent('claude')]);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Switch to gateway|切换到模型网关/i }));
+
+ expect(await screen.findByText(/^The switch to gateway did not go through$|^没能切换到模型网关$/)).toBeTruthy();
+ await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/ }));
+ await waitFor(() => expect(setMode).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.queryByText(/^The switch to gateway did not go through$|^没能切换到模型网关$/)).toBeNull());
+ });
+
it('opens the same migration dialog from an existing Hub user entry', async () => {
vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([]);
vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [migrationCandidate] });
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index bd402d517..b0b595667 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -72,7 +72,7 @@ import { groupMigrationCandidates } from './migrationGrouping';
import { SUBSCRIPTION_MENU_ROWS } from './subscriptionOptions';
import { VendorGlyph } from './vendorGlyph';
import { backendVisual } from './vendorMeta';
-import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';
+import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentMode, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';
const CHAIN_READ_CONCURRENCY = 6;
const EVENT_PAGE = 20;
@@ -344,7 +344,12 @@ const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ t
);
};
-const DirectHome: React.FC<{ agents: AgentSupply[]; onSwitch: (agent: AgentSupply) => void }> = ({ agents, onSwitch }) => {
+const DirectHome: React.FC<{
+ agents: AgentSupply[];
+ switchFailures: ReadonlySet<string>;
+ connectingBackend: string | null;
+ onSwitch: (agent: AgentSupply) => void;
+}> = ({ agents, switchFailures, connectingBackend, onSwitch }) => {
const { t } = useModelsTranslation();
if (agents.length === 0) {
return <section className="model-hub-direct-empty"><h2>{t('settings.models.direct.empty.title')}</h2><p>{t('settings.models.direct.empty.body')}</p><span>{t('settings.models.direct.empty.install')}</span></section>;
@@ -359,6 +364,7 @@ const DirectHome: React.FC<{ agents: AgentSupply[]; onSwitch: (agent: AgentSuppl
<div className="model-hub-direct-content flex flex-col">
{agents.map((agent) => {
const { Icon } = backendVisual(agent.backend);
+ const switchFailed = switchFailures.has(agent.backend);
return (
<div key={agent.backend} className="model-hub-direct-row model-hub-direct-row--backend flex flex-wrap items-center gap-2.5 bg-background px-3 sm:flex-nowrap">
<span className="model-hub-direct-tile flex size-[34px] shrink-0 items-center justify-center rounded-[9px]"><Icon className="size-[17px]" /></span>
@@ -367,9 +373,11 @@ const DirectHome: React.FC<{ agents: AgentSupply[]; onSwitch: (agent: AgentSuppl
<span className="model-hub-direct-backend-name truncate text-foreground">{t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend })}</span>
<span className="model-hub-pill model-hub-direct-kind-pill border">{t('settings.models.direct.pill.direct')}</span>
</span>
- <span className="model-hub-direct-backend-detail truncate" title={t(`settings.models.direct.backend.${agent.backend}.detail`) as string}>{t(`settings.models.direct.backend.${agent.backend}.detail`)}</span>
+ {switchFailed
+ ? <span role="status" className="truncate text-[11px] font-semibold leading-normal text-destructive-ink">{t('settings.models.gateway.fail.switchToGateway')}</span>
+ : <span className="model-hub-direct-backend-detail truncate" title={t(`settings.models.direct.backend.${agent.backend}.detail`) as string}>{t(`settings.models.direct.backend.${agent.backend}.detail`)}</span>}
</span>
- <Button variant="secondary" size="sm" className="model-hub-direct-switch h-auto rounded-lg px-3 py-[9px] text-[11.5px] font-bold" onClick={() => onSwitch(agent)}>{t('settings.models.direct.action.switchToGateway')}</Button>
+ <Button variant="secondary" size="sm" className="model-hub-direct-switch h-auto rounded-lg px-3 py-[9px] text-[11.5px] font-bold" onClick={() => onSwitch(agent)} disabled={connectingBackend === agent.backend}>{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.direct.action.switchToGateway')}</Button>
</div>
);
})}
@@ -494,7 +502,21 @@ export const SettingsModelsPage: React.FC = () => {
);
const [selectedSourceId, setSelectedSourceId] = React.useState<string | null>(null);
const [agentWrites, setAgentWrites] = React.useState<ReadonlySet<string>>(() => new Set());
- const [switchFailures, setSwitchFailures] = React.useState<ReadonlySet<string>>(() => new Set());
+ // A failed switch is kept with the mode it failed to leave: it stays visible
+ // while that mode holds and clears once the backend has moved on.
+ const [switchFailureModes, setSwitchFailureModes] = React.useState<ReadonlyMap<string, AgentMode>>(() => new Map());
+ const switchFailures = React.useMemo<ReadonlySet<string>>(() => new Set(switchFailureModes.keys()), [switchFailureModes]);
+ const markSwitchFailed = (backend: string, mode: AgentMode) => {
+ setSwitchFailureModes((previous) => new Map(previous).set(backend, mode));
+ };
+ const clearSwitchFailure = (backend: string) => {
+ setSwitchFailureModes((previous) => {
+ if (!previous.has(backend)) return previous;
+ const next = new Map(previous);
+ next.delete(backend);
+ return next;
+ });
+ };
const [agentWriteRegistry] = React.useState(() => createPendingWrites(setAgentWrites));
const [sourceIntentAuthority] = React.useState(createIntentAuthority);
const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));
@@ -660,8 +682,8 @@ export const SettingsModelsPage: React.FC = () => {
});
if (freshSupply) {
refreshAllAgentChains(freshSupply);
- setSwitchFailures((previous) => new Set(
- [...previous].filter((backend) => freshSupply.some((agent) => agent.backend === backend && agent.mode === 'hub')),
+ setSwitchFailureModes((previous) => new Map(
+ [...previous].filter(([backend, mode]) => freshSupply.some((agent) => agent.backend === backend && agent.mode === mode)),
));
}
}, [refreshAllAgentChains, supplyRead]);
@@ -973,19 +995,11 @@ export const SettingsModelsPage: React.FC = () => {
if (aliveRef.current) showToast(t('settings.models.gateway.catalog.saved') as string, 'success');
}, [agentSaved, showToast, t]);
const switchToDirect = (agent: AgentSupply) => {
- setSwitchFailures((previous) => {
- const next = new Set(previous);
- next.delete(agent.backend);
- return next;
- });
+ clearSwitchFailure(agent.backend);
void agentWriteRegistry.track(agent.backend, async () => {
try {
const echoed = await modelsApi.setAgentMode(agent.backend, 'direct');
- setSwitchFailures((previous) => {
- const next = new Set(previous);
- next.delete(agent.backend);
- return next;
- });
+ clearSwitchFailure(agent.backend);
setAdoptAgent(null);
await agentSaved(echoed);
} catch {
@@ -995,25 +1009,17 @@ export const SettingsModelsPage: React.FC = () => {
const authoritative = result.value;
setSupplyRead(readyRegion(authoritative));
const committed = authoritative.some((row) => row.backend === agent.backend && row.mode === 'direct');
- setSwitchFailures((previous) => {
- const next = new Set(previous);
- if (committed) next.delete(agent.backend);
- else next.add(agent.backend);
- return next;
- });
+ if (committed) clearSwitchFailure(agent.backend);
+ else markSwitchFailed(agent.backend, 'hub');
} catch {
- setSwitchFailures((previous) => new Set(previous).add(agent.backend));
+ markSwitchFailed(agent.backend, 'hub');
}
}
});
};
const enterGateway = async (backend: AgentBackend) => {
const echoed = await modelsApi.setAgentMode(backend, 'hub');
- setSwitchFailures((previous) => {
- const next = new Set(previous);
- next.delete(backend);
- return next;
- });
+ clearSwitchFailure(backend);
await agentSaved(echoed);
};
// Migration is optional: declining it still switches the backend it was
@@ -1023,24 +1029,20 @@ export const SettingsModelsPage: React.FC = () => {
try {
await enterGateway(backend);
} catch {
- setSwitchFailures((previous) => new Set(previous).add(backend));
+ markSwitchFailed(backend, 'direct');
}
});
};
const switchToGateway = (agent: AgentSupply) => {
if (agentWrites.has(agent.backend)) return;
setAdoptAgent(agent);
- setSwitchFailures((previous) => {
- const next = new Set(previous);
- next.delete(agent.backend);
- return next;
- });
+ clearSwitchFailure(agent.backend);
void agentWriteRegistry.track(agent.backend, async () => {
try {
const result = await resumeGatewayAdoption(modelsApi, agentCollectionReads, agent.backend);
if (result.runtime) setRuntimeRead(readyRegion(result.runtime));
if (!result.ok) {
- setSwitchFailures((previous) => new Set(previous).add(agent.backend));
+ markSwitchFailed(agent.backend, 'direct');
return;
}
if (result.candidates.length > 0) {
@@ -1050,7 +1052,7 @@ export const SettingsModelsPage: React.FC = () => {
}
await enterGateway(agent.backend);
} catch {
- setSwitchFailures((previous) => new Set(previous).add(agent.backend));
+ markSwitchFailed(agent.backend, 'direct');
} finally {
if (aliveRef.current) setAdoptAgent(null);
}
@@ -1590,7 +1592,7 @@ export const SettingsModelsPage: React.FC = () => {
/>
: tab === 'usage' ? <UsageTab usage={usageRead} windowKey={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
: tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
- : directEmpty ? <DirectHome agents={installedAgents} onSwitch={switchToGateway} />
+ : directEmpty ? <DirectHome agents={installedAgents} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onSwitch={switchToGateway} />
: <div className="model-hub-overview">
<div className="model-hub-overview-body">
<div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c8b814581..3b08e58eb 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -988,7 +988,8 @@
"directDescription": "Use {{backend}}'s own models and credentials; gateway routes and priority no longer apply"
},
"fail": {
- "switchToDirect": "The switch back to direct did not go through"
+ "switchToDirect": "The switch back to direct did not go through",
+ "switchToGateway": "The switch to gateway did not go through"
},
"modelCount_one": "{{count}} model",
"modelCount_other": "{{count}} models",
@@ -2044,8 +2045,9 @@
"fallback": "Can't be migrated. Add it manually."
},
"applying": "Migrating…",
+ "interruptNotice": "Migrating interrupts any task the selected assistants are running in Avibe.",
"errors": {
- "nativeBusy": "Quit the running CLI, including terminal sessions, IDE extensions and desktop apps, or let its tasks finish, then retry.",
+ "nativeBusy": "Something is still using these assistants. Retry in a moment; if it keeps failing, quit any CLI running outside Avibe, including terminal sessions, IDE extensions and desktop apps.",
"permissionNeeded": "Allow credential access, then retry.",
"recoveryPending": "Migration is unfinished. Retry to continue.",
"itemConflict": "Migration could not verify the saved configuration or its credentials. Check the files and authentication before retrying, or add the source manually in Model Hub.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1e184ebfc..c83a214e6 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -988,7 +988,8 @@
"directDescription": "改用 {{backend}} 自带的模型与凭据,路由与优先级不再生效"
},
"fail": {
- "switchToDirect": "没能切回直连"
+ "switchToDirect": "没能切回直连",
+ "switchToGateway": "没能切换到模型网关"
},
"modelCount_one": "{{count}} 个模型",
"modelCount_other": "{{count}} 个模型",
@@ -2044,8 +2045,9 @@
"fallback": "暂不支持迁移,请手动添加。"
},
"applying": "迁移中…",
+ "interruptNotice": "迁移会中断所选助手在 Avibe 中正在运行的任务。",
"errors": {
- "nativeBusy": "请先退出正在运行的 CLI(包括终端、IDE 插件和桌面应用),或等待任务完成,再重试。",
+ "nativeBusy": "这些助手仍在被占用。请稍后重试;如果仍然失败,请退出在 Avibe 之外运行的 CLI(包括终端、IDE 插件和桌面应用)。",
"permissionNeeded": "请允许访问凭据,再重试。",
"recoveryPending": "迁移尚未完成,请重试以继续。",
"itemConflict": "无法验证已保存的配置或凭据。请检查配置文件和认证是否有效后重试,或在模型网关中手动添加供应商。",