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): interrupt both switch directions and tell users why work stopped (#2299)
Call White0a4ace368774
diff --git a/core/backend_failure.py b/core/backend_failure.pyindex 967e00b0b..24ae2b279 100644--- a/core/backend_failure.py+++ b/core/backend_failure.py@@ -39,7 +39,7 @@ def _terminal_output(request: Any, output: MessageOutput | None) -> MessageOutpureturn terminal_turn_output()-def _harness_run_identity(context: Any, request: Any) -> str:+def harness_run_identity(context: Any, request: Any) -> str:"""The Run id proving that this Turn was entered through Harness, if any."""for source in (getattr(request, "context", None), context):@@ -90,7 +90,7 @@ def _failure_identity(## Non-harness contexts have no run to align to, so a backend's explicit id# still wins there and that path is unchanged.- harness_identity = _harness_run_identity(context, request)+ harness_identity = harness_run_identity(context, request)if harness_identity:return _turn_failure_identity(context, request) or harness_identity@@ -236,7 +236,7 @@ def terminal_backend_failure_output("""terminal = _terminal_output(request, output)- if not (_turn_failure_identity(context, request) or _harness_run_identity(context, request)):+ if not (_turn_failure_identity(context, request) or harness_run_identity(context, request)):return terminalmetadata = dict(terminal.metadata)@@ -395,7 +395,7 @@ async def emit_backend_failure(terminal = replace(terminal, metadata={**terminal.metadata, "local_error_detail": hub_failure[1]},)- harness_run_id = _harness_run_identity(context, request)+ harness_run_id = harness_run_identity(context, request)owns_failure_contract = bool(_turn_failure_identity(context, request) or harness_run_id)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 165c6804d..a03767b64 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -4839,53 +4839,47 @@ class ModelHubService:async def set_agent_mode(self, backend: str, mode: object) -> dict:if mode not in {"hub", "direct"}:raise ModelHubError("mode_switch_blocked")- if mode == "hub":- from core.backend_restart import NativeMigrationBlockedError+ from core.backend_restart import NativeMigrationBlockedError- # Serialize with takeover and retire the managed runtime so the- # next launch goes through the Hub. Mode-only consent never imports- # a login: native auth stays native beside the Hub, where the- # migration dialog can still take it over later.- async with self._migration_lock:- async with self._mutation_lock:- current = self.store.load()- 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.+ # Either direction serializes with takeover and retires the managed+ # runtime under the shared guard, which interrupts running work: a+ # turn left running would keep using the mode it started in, and the+ # Hub refuses a backend that has left it. Mode-only consent never+ # imports a login: native auth stays native beside the Hub, where the+ # migration dialog can still take it over later.+ async with self._migration_lock:+ async with self._mutation_lock:+ current = self.store.load()+ agent = self._agent(current, backend)+ if agent.mode == mode:+ return self._agent_payload(current, agent)+ if mode == "hub":+ # Refuse a switch that would be refused anyway before the+ # guard destroys any work.try:blocked = await self._native_config_blocks_launch(current, backend)except (TakeoverStateError, OSError):raise ModelHubError("mode_switch_blocked", status=409) from Noneif 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()- 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"- await self._commit_synced(previous, config)- committed = self.store.load()- return self._agent_payload(committed, self._agent(committed, backend))- except NativeMigrationBlockedError as error:- _log_native_refusal("Model Hub mode switch", error)- raise ModelHubError("mode_switch_blocked", status=409) from None- except (TakeoverStateError, OSError):- raise ModelHubError("mode_switch_blocked", status=409) from None- async with self._mutation_lock:- previous = self.store.load()- config = self._clone_config(previous)- agent = self._agent(config, backend)- agent.mode = mode- await self._commit_synced(previous, config)- committed = self.store.load()- return self._agent_payload(committed, self._agent(committed, backend))+ 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()+ if mode == "hub" and 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 = mode+ await self._commit_synced(previous, config)+ committed = self.store.load()+ return self._agent_payload(committed, self._agent(committed, backend))+ except NativeMigrationBlockedError as error:+ _log_native_refusal("Model Hub mode switch", error)+ raise ModelHubError("mode_switch_blocked", status=409) from None+ except (TakeoverStateError, OSError):+ raise ModelHubError("mode_switch_blocked", status=409) from Noneasync def reorder_agent_chains(self,diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 7991b2500..03eb4b74b 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -3023,6 +3023,8 @@ class TaskExecutionStore:*,terminal_status: Optional[str] = None,error: Optional[str] = None,+ interrupt_reason: Optional[str] = None,+ cancellation_error: Optional[str] = None,) -> bool:if self._sqlite is None:return False@@ -3030,6 +3032,8 @@ class TaskExecutionStore:run_id,terminal_status=terminal_status,error=error,+ interrupt_reason=interrupt_reason,+ cancellation_error=cancellation_error,)def record_skip_reason(self, run_id: str, *, reason: str) -> bool:@@ -7484,14 +7488,24 @@ class ScheduledTaskService:return "\n".join(lines)def settle_activity_runs(self, activity: Any) -> list[str]:- """Settle deferred Runs when a failed/stopped owned Activity is last."""+ """Settle deferred Runs when a failed/stopped owned Activity is last.++ An Activity whose metadata names an ``interrupt_reason`` was ended by+ the service itself, as a forced runtime refresh does. Its Runs then+ settle as that interruption, which owes the user a notice, instead of a+ silent ``canceled``.+ """activity_status = str(getattr(activity, "status", "") or "").strip().lower()if activity_status == "completed":# A completed Claude task may still produce a user-visible follow-up;# that Message owns Run settlement so output and callback stay aligned.return []- terminal_status = "failed" if activity_status == "failed" else "canceled"+ interrupt_reason = str((getattr(activity, "metadata", None) or {}).get("interrupt_reason") or "") or None+ if interrupt_reason:+ terminal_status = SETTLEMENT_TERMINAL_STATUS.get(interrupt_reason, "failed")+ else:+ terminal_status = "failed" if activity_status == "failed" else "canceled"metadata = getattr(activity, "metadata", None) or {}run_ids: list[str] = []primary = str(getattr(activity, "run_id", "") or "").strip()@@ -7508,19 +7522,40 @@ class ScheduledTaskService:has_blocker = getattr(registry, "has_blocking_run_activity", None)has_pending_output = getattr(registry, "has_pending_run_output", None)settled: list[str] = []+ # An Activity that failed on its own is the Run's cause even when a+ # sibling still blocks settlement; a later interruption must not+ # replace it.+ own_failure = (+ f"Background Activity {getattr(activity, 'id', '')} failed"+ if activity_status == "failed" and not interrupt_reason+ else None+ )for run_id in run_ids:self.request_store.defer_run_terminal(run_id,terminal_status=terminal_status,+ **({"error": own_failure} if own_failure else {}),)if callable(has_blocker) and has_blocker(run_id):continueif callable(has_pending_output) and has_pending_output(run_id):continue- error = f"Background Activity {getattr(activity, 'id', '')} {activity_status}"+ error = (+ self._t(SETTLEMENT_I18N_KEYS.get(interrupt_reason, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT]))+ if interrupt_reason+ else f"Background Activity {getattr(activity, 'id', '')} {activity_status}"+ )if self.request_store.settle_deferred_run(run_id,error=error,+ **(+ {+ "interrupt_reason": interrupt_reason,+ "cancellation_error": self._t(SETTLEMENT_I18N_KEYS[SETTLED_BY_STOPPED]),+ }+ if interrupt_reason+ else {}+ ),):settled.append(run_id)if settled:diff --git a/core/session_activities.py b/core/session_activities.pyindex b2dad9a2c..8c4855571 100644--- a/core/session_activities.py+++ b/core/session_activities.py@@ -2293,8 +2293,18 @@ class SessionActivityRegistry:or any(key[0] == identity for key in self._terminal_snapshots))- def end_backend(self, backend: str, *, status: str = "killed") -> list[SessionActivity]:- """Settle every Activity owned by a force-terminated backend runtime."""+ def end_backend(+ self,+ backend: str,+ *,+ status: str = "killed",+ metadata: dict[str, Any] | None = None,+ ) -> list[SessionActivity]:+ """Settle every Activity owned by a force-terminated backend runtime.++ ``metadata`` is recorded on each Activity this call ends, so a cause the+ caller names survives a settlement retried after restart.+ """identity = str(backend)with self._lock:@@ -2332,6 +2342,7 @@ class SessionActivityRegistry:status=status,retain_terminal_snapshots=True,force=True,+ metadata=metadata,))now = _now_iso()@@ -2353,6 +2364,7 @@ class SessionActivityRegistry:replace(activity,status=status if status in TERMINAL_ACTIVITY_STATUSES else "killed",+ metadata={**activity.metadata, **(metadata or {})},updated_at=now,completed_at=now,)@@ -2403,6 +2415,7 @@ class SessionActivityRegistry:retain_terminal_snapshots: bool = False,activation_identity: RuntimeActivationIdentity | None = None,force: bool = False,+ metadata: dict[str, Any] | None = None,) -> list[SessionActivity]:key = (str(backend), str(runtime_key))if (@@ -2462,7 +2475,7 @@ class SessionActivityRegistry:if status in TERMINAL_ACTIVITY_STATUSESelse "disconnected"),- metadata=None,+ metadata=metadata,expects_output=False,retain_terminal_snapshot=retain_terminal_snapshots,activation_identity=activation_identity,diff --git a/core/session_turns.py b/core/session_turns.pyindex bfefd6093..18663e4c9 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -31,7 +31,7 @@ from sqlalchemy.engine import Connection, Enginefrom core.delivery_target import normalize_message_kindfrom core.agent_input import AgentInputMetadata-from core.backend_failure import backend_failure_notification_output+from core.backend_failure import backend_failure_notification_output, harness_run_identityfrom core.message_context import (resolve_turn_sink_key,)@@ -645,8 +645,10 @@ class SessionTurnManager:str, _SessionLifecycleState] = weakref.WeakValueDictionary()# Interruption reports owed to turns whose platform was not connected yet- # when recovery ran, keyed by platform. See ``_report_lost_im_turn``.- self._pending_lost_turn_reports: dict[str, list[tuple[str, str, str, str]]] = {}+ # when recovery ran, keyed by platform. See ``_report_interrupted_turn``.+ # Entries are ``(session_id, origin_native_message_id, turn_id, backend,+ # message_key)``: the key keeps each held notice's own explanation.+ self._pending_lost_turn_reports: dict[str, list[tuple[str, str, str, str, str]]] = {}# One in-flight retry task per platform for the reports above.self._lost_turn_retry_tasks: dict[str, asyncio.Task[None]] = {}# The live turn sink per TURN SINK KEY. Each is@@ -6288,14 +6290,22 @@ class SessionTurnManager:return language_getter()return getattr(getattr(self.controller, "config", None), "language", "en")- async def _report_lost_im_turn(+ async def _report_interrupted_turn(self,session_id: str,origin_native_message_id: str,turn_id: str,backend: str,+ *,+ message_key: str = "turn.interrupted.serviceRestart",+ context: "MessageContext | None" = None,) -> None:- """Tell an IM turn's author that its runtime died with the service.+ """Tell a turn's author that its runtime died under it.++ The service restarting and a forced runtime refresh both end a Turn that+ has no Run to carry the news; ``message_key`` names which one, and a held+ notice keeps it. A live Turn passes its own ``context``; recovery and+ retries rebuild it from the Session.An IM turn owns no ``agent_runs`` row, so the Harness interruption lane isstructurally unreachable for it: notices are stamped on runs, and@@ -6320,22 +6330,23 @@ class SessionTurnManager:if self.controller is None:return- try:- context = self._delivery_context(session_id)- except Exception:- logger.debug(- "lost turn report: no delivery context for session=%s",- session_id,- exc_info=True,- )- return+ if context is None:+ try:+ context = self._delivery_context(session_id)+ except Exception:+ logger.debug(+ "lost turn report: no delivery context for session=%s",+ session_id,+ exc_info=True,+ )+ returnplatform = str(getattr(context, "platform", "") or "")- if self._transport_can_deliver(platform) and await self._emit_lost_turn_report(- context, session_id, origin_native_message_id, turn_id, backend+ if self._transport_can_deliver(platform) and await self._emit_turn_interruption_notice(+ context, session_id, origin_native_message_id, turn_id, backend, message_key=message_key):returnself._pending_lost_turn_reports.setdefault(platform, []).append(- (session_id, str(origin_native_message_id or ""), turn_id, backend)+ (session_id, str(origin_native_message_id or ""), turn_id, backend, message_key))logger.info("lost turn report held until %s transport can deliver (session=%s)",@@ -6379,8 +6390,8 @@ class SessionTurnManager:if not pending or self.controller is None:return 0reported = 0- unsent: list[tuple[str, str, str, str]] = []- for session_id, origin_native_message_id, turn_id, backend in pending:+ unsent: list[tuple[str, str, str, str, str]] = []+ for session_id, origin_native_message_id, turn_id, backend, message_key in pending:try:context = self._delivery_context(session_id)except Exception:@@ -6390,8 +6401,8 @@ class SessionTurnManager:exc_info=True,)continue- if await self._emit_lost_turn_report(- context, session_id, origin_native_message_id, turn_id, backend+ if await self._emit_turn_interruption_notice(+ context, session_id, origin_native_message_id, turn_id, backend, message_key=message_key):reported += 1else:@@ -6399,7 +6410,9 @@ class SessionTurnManager:# transient API error still loses the notice. Popping happened# first, so an unsent report has to be put BACK or the only# record of the interruption is gone for the process's lifetime.- unsent.append((session_id, str(origin_native_message_id or ""), turn_id, backend))+ unsent.append(+ (session_id, str(origin_native_message_id or ""), turn_id, backend, message_key)+ )if unsent:self._pending_lost_turn_reports.setdefault(platform, []).extend(unsent)logger.info(@@ -6461,13 +6474,15 @@ class SessionTurnManager:if self._lost_turn_retry_tasks.get(platform) is asyncio.current_task():self._lost_turn_retry_tasks.pop(platform, None)- async def _emit_lost_turn_report(+ async def _emit_turn_interruption_notice(self,context: "MessageContext",session_id: str,origin_native_message_id: str,turn_id: str,backend: str,+ *,+ message_key: str = "turn.interrupted.serviceRestart",) -> bool:"""Emit one interruption notice. ``False`` means it did NOT reach the user.@@ -6482,28 +6497,29 @@ class SessionTurnManager:delivered = await self.controller.emit_agent_message(context,"notify",- i18n_t("turn.interrupted.serviceRestart", self._controller_language()),+ i18n_t(message_key, self._controller_language()),# Recovery already settled this Turn. Carry its exact identity# through delayed sends without granting another settlement or# guessing the target from the Session's current Turn.output=backend_failure_notification_output(context,backend,- output=MessageOutput(metadata={"turn_id": turn_id, "replayed": True}),- failure_id=f"turn:{turn_id}",- failure_id_authoritative=True,+ output=MessageOutput(metadata={"turn_id": turn_id or None, "replayed": True}),+ # A legacy Turn has no durable id; its context token names it.+ failure_id=f"turn:{turn_id}" if turn_id else None,+ failure_id_authoritative=bool(turn_id),),)except Exception:logger.warning(- "lost turn report: failed to notify session=%s",+ "turn interruption notice: failed to notify session=%s",session_id,exc_info=True,)return Falseif not delivered:logger.warning(- "lost turn report: notify produced no delivery for session=%s",+ "turn interruption notice: notify produced no delivery for session=%s",session_id,)return False@@ -6518,7 +6534,7 @@ class SessionTurnManager:await stamp(context, native_message_id, INTERRUPTED_REACTION_EMOJI)except Exception:logger.debug(- "lost turn report: terminal reaction failed for session=%s",+ "turn interruption notice: terminal reaction failed for session=%s",session_id,exc_info=True,)@@ -6712,7 +6728,7 @@ class SessionTurnManager:continuerecovered.append(target_session)if not owning_run_ids:- await self._report_lost_im_turn(target_session, origin_message_id, turn_id, backend)+ await self._report_interrupted_turn(target_session, origin_message_id, turn_id, backend)successor_turn_id = str(terminal.get("successor_turn_id") or "")if successor_turn_id:await self._start_persisted_turn(successor_turn_id)@@ -8082,6 +8098,9 @@ class SessionTurnManager:legacy_projection_sessions: set[str] = set()tasks_to_settle: list[asyncio.Task] = []restored_owners: list[dict[str, Any]] = []+ # Harness Runs report their own interruption; a conversation turn has+ # nothing else to tell the user why it stopped.+ interrupted_turns: list[tuple[str, Turn]] = []if self._durable_schema_available():with self._sqlite_engine().connect() as conn:# Refresh owns exactly the generation that existed when draining@@ -8108,9 +8127,19 @@ class SessionTurnManager:# Record the cause BEFORE cancelling: this is a runtime refresh, not a# user Stop, so a scheduled run this turn owns must not settle as# ``canceled`` with the user-stop explanation (Codex P1). ``_run`` reads- # it off the Turn when it pops it.- turn.cancel_settled_by = SETTLED_BY_BACKEND_REFRESH+ # it off the Turn when it pops it. An outcome already decided, by a+ # Stop in flight or a result already delivered, keeps its own cause+ # and needs no refresh notice.+ refresh_owns_outcome = not self._turn_outcome_decided(turn)+ if refresh_owns_outcome:+ turn.cancel_settled_by = SETTLED_BY_BACKEND_REFRESHturn.cancel_defers_queue_resume = True+ # The same cause for the Run this Turn's dispatch waits on: a backend+ # whose cancellation cleanup releases the waiter itself would+ # otherwise report it as a Turn that produced no result.+ mark_complete = getattr(self.controller, "mark_turn_complete", None)+ if refresh_owns_outcome and callable(mark_complete) and not turn.task.done():+ mark_complete(turn.context, settled_by=SETTLED_BY_BACKEND_REFRESH)if turn.task.done():self.in_flight.pop(session_id, None)from core.inbox_events import bus@@ -8122,6 +8151,8 @@ class SessionTurnManager:else:turn.task.cancel()tasks_to_settle.append(turn.task)+ if refresh_owns_outcome and not harness_run_identity(turn.context, None):+ interrupted_turns.append((session_id, turn))if backend in self._draining_backends:self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)released_sessions.add(session_id)@@ -8132,9 +8163,18 @@ class SessionTurnManager:if self.controller is not None:for session_id in legacy_projection_sessions:self.controller.set_agent_status(session_id, "idle")+ for session_id, turn in interrupted_turns:+ self._notify_backend_refresh(+ session_id, "", turn.logical_turn_id or "", backend, context=turn.context+ )released_restored: set[str] = set()for owner in restored_owners:owner_id = str(owner["id"])+ # A restored owner has no live context, so read what the notice needs+ # before terminalizing retires the deliveries it is derived from, as+ # the service-restart report does.+ owned_by_run = bool(self.accepted_agent_run_ids_for_turn(owner_id))+ origin_message_id = self._turn_origin_native_message_id(owner_id)if owner["state"] == "starting":terminal = self._terminalize_durable_turn(owner_id,@@ -8162,6 +8202,9 @@ class SessionTurnManager:)if terminal.get("changed"):released_restored.add(str(owner["session_id"]))+ # Starting or active, the refresh retired this conversation's input.+ if not owned_by_run and self.controller is not None:+ self._notify_backend_refresh(str(owner["session_id"]), origin_message_id, owner_id, backend)for session_id in released_restored:if backend in self._draining_backends:self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)@@ -8175,6 +8218,51 @@ class SessionTurnManager:)return released+ def _turn_outcome_decided(self, turn: Turn) -> bool:+ """Whether a Stop or a delivered result already decided this live Turn.++ The runner can still be finishing cleanup after its result released the+ waiter, so the canceller's own cause is not the only record to consult.+ """++ if turn.cancel_settled_by is not None:+ return True+ get_sink = getattr(self.controller, "get_turn_sink", None)+ if callable(get_sink):+ sink = get_sink(resolve_turn_sink_key(self.controller, turn.context))+ if isinstance(sink, dict) and sink.get("settled_by"):+ return True+ if turn.logical_turn_id and self._durable_schema_available():+ with self._sqlite_engine().connect() as conn:+ row = delivery_store.get_turn(conn, turn.logical_turn_id)+ if row is not None and row.get("state") == "terminal":+ return True+ return False++ def _notify_backend_refresh(+ self,+ session_id: str,+ origin_native_message_id: str,+ turn_id: str,+ backend: str,+ *,+ context: "MessageContext | None" = None,+ ) -> None:+ # Off the teardown's path: a slow platform send must not hold the+ # runtime refresh that is waiting on this release. A send that fails is+ # held and retried like a service-restart report.+ asyncio.create_task(+ self._report_interrupted_turn(+ session_id,+ origin_native_message_id,+ turn_id,+ backend,+ message_key="turn.interrupted.backendRefresh",+ context=context,+ ),+ name=f"backend-refresh-notice:{session_id}",+ )+def fail_restored_backend_turn(self,turn_id: str,diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex b850cfb11..63253f5a1 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, 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. |+| 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 changes only the mode, but under the same guard: it interrupts running work on that backend and retires the managed runtime, so no turn keeps calling the Hub after the backend has left it, and a guard refusal returns `mode_switch_blocked`. || 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.mdindex af807f301..ab4d9dab1 100644--- a/docs/plans/model-hub-native-takeover.md+++ b/docs/plans/model-hub-native-takeover.md@@ -159,7 +159,11 @@ explicitly authorized acceptance check.terminated. The interruption runs as a forced backend restart, which keepsadmission closed until its teardown completes. The switch waits for it onlyfor 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+ timeout or cancellation, never cuts the teardown short. A mode switch in+ either direction enters it, since a turn left running keeps the mode it+ started in. Every interrupted conversation turn gets one visible notice, and+ a Harness Run, including one owned by a background Activity, settles as a+ backend-refresh interruption that owes its own notice. 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 existingdiff --git a/modules/agents/service.py b/modules/agents/service.pyindex 2f1ab5c55..712ea62c3 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -5,6 +5,7 @@ import uuidfrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Dict, Optional+from core.run_settlement import SETTLED_BY_BACKEND_REFRESHfrom core.session_activities import SessionActivityRegistryfrom core.message_output import (HARNESS_PROMPT_ECHO_SPEC_KEY,@@ -191,7 +192,14 @@ class AgentService:return Truedef force_end_backend_activities(self, backend: str) -> list[Any]:- completed = self.activities.end_backend(backend, status="killed")+ """End every Activity of a runtime the service is tearing down itself."""+ # The cause rides on each Activity it ends, so a settlement retried+ # after a transient failure or a restart still reports the refresh.+ completed = self.activities.end_backend(+ backend,+ status="killed",+ metadata={"interrupt_reason": SETTLED_BY_BACKEND_REFRESH},+ )for activity in completed:self.on_activity_terminal(activity)return completeddiff --git a/storage/background.py b/storage/background.pyindex b3347dfba..0e8ce46c7 100644--- a/storage/background.py+++ b/storage/background.py@@ -6659,9 +6659,18 @@ class SQLiteBackgroundTaskStore:*,terminal_status: Optional[str] = None,error: Optional[str] = None,+ interrupt_reason: Optional[str] = None,+ cancellation_error: Optional[str] = None,updated_at: Optional[str] = None,) -> bool:- """Apply one stored terminal intent after owned Activities become terminal."""+ """Apply one stored terminal intent after owned Activities become terminal.++ ``interrupt_reason`` names the infrastructure event that ended the owning+ Activity. It is recorded only when ``error`` is the Run's explanation, so+ an earlier deferred failure keeps its own cause. A cancellation that wins+ the race settles the Run as the user's stop, with ``cancellation_error``,+ whatever was recorded before it.+ """now = updated_at or _utc_now_iso()row_to_publish = None@@ -6783,6 +6792,16 @@ class SQLiteBackgroundTaskStore:"result_payload_json": _json_dumps(result_payload),}effective_error = deferred_error if deferred_error is not None else error+ effective_reason = None+ if interrupt_reason:+ if status == "canceled":+ # The user's cancellation won: it is the Run's outcome+ # whatever failure was recorded before it.+ effective_reason = "stopped"+ if cancellation_error is not None:+ effective_error = cancellation_error+ elif deferred_error is None:+ effective_reason = interrupt_reasonif effective_error is not None:values["error"] = str(effective_error)if deferred_result_text is not None:@@ -6796,7 +6815,9 @@ class SQLiteBackgroundTaskStore:parent_run_id=row["parent_run_id"],row_metadata_json=row["metadata_json"],extra_metadata=(- notice_metadata+ {**(notice_metadata or {}), "interrupt_reason": effective_reason}+ if effective_reason+ else notice_metadata),now=now,)diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 38a2700f0..08c18bbfe 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -54,6 +54,7 @@ capabilities:- tests/test_model_hub_persisted_migration.py- tests/test_native_process_inventory.py- tests/test_native_takeover_lifecycle.py+ - tests/test_internal_server.py- tests/test_member_management_parity.py- tests/test_model_hub_provenance.py- tests/test_model_hub_retention.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 95a5a74f2..efc5bb308 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -56,6 +56,7 @@ capability:- tests/test_model_hub_persisted_migration.py- tests/test_native_process_inventory.py- tests/test_native_takeover_lifecycle.py+ - tests/test_internal_server.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@@ -1289,6 +1290,23 @@ scenarios:test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-MIG-010 reports a refused switch to the gateway on the direct-only screenrelated_tests:- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+ - id: MH-MIG-011+ name: Switching back to direct interrupts running gateway work instead of leaving it to fail on the Hub's refusal+ status: covered+ kind: migration+ layer: unit+ test: tests/test_model_hub_api.py::test_mode_switch_commits_only_inside_the_interrupting_guard+ - id: MH-MIG-012+ name: Work interrupted by a runtime refresh is reported to the user as that interruption on every backend+ status: covered+ kind: migration+ layer: unit+ test: tests/test_internal_server.py::test_release_for_backend_refresh_names_the_interruption+ related_tests:+ - tests/test_scheduled_tasks.py::test_terminal_owned_activity_settles_deferred_run_once+ - tests/test_scheduled_tasks.py::test_refresh_ending_the_last_activity_keeps_the_runs_first_cause+ - tests/test_session_delivery_fsm.py::test_forced_refresh_tells_a_restored_conversation_turn_why_it_stopped+ - tests/test_agent_service.py::test_force_end_backend_activities_settles_pending_runs- id: MH-TAKEOVER-001name: Recoverable failures walk the configured route and exhaust only at its endstatus: covereddiff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex b698f54d2..85f1b9ae6 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -649,9 +649,13 @@ def test_agent_service_restart_wait_releases_gate_when_backend_disappears() -> Ndef test_force_end_backend_activities_settles_pending_runs() -> None:+ """MH-MIG-012: the service ending an Activity itself names that cause, so+ its Runs settle as a runtime-refresh interruption rather than a silent kill."""settled = []controller = SimpleNamespace(- scheduled_task_service=SimpleNamespace(settle_activity_runs=settled.append),+ scheduled_task_service=SimpleNamespace(+ settle_activity_runs=lambda activity, **kwargs: settled.append((activity, kwargs)),+ ),)service = AgentService(controller=controller)service.activities.start(@@ -682,9 +686,9 @@ def test_force_end_backend_activities_settles_pending_runs() -> None:service.force_end_backend_activities("claude")- assert sorted((item.id, item.status) for item in settled) == [- ("task-active", "killed"),- ("task-pending", "killed"),+ assert sorted((item.id, item.status, item.metadata.get("interrupt_reason")) for item, _ in settled) == [+ ("task-active", "killed", "backend_refresh"),+ ("task-pending", "killed", "backend_refresh"),]assert service.activities.ack_recovered_terminal.call_count == 2diff --git a/tests/test_claude_output_recovery_ledger.py b/tests/test_claude_output_recovery_ledger.pyindex 3d766cb63..725c6a50d 100644--- a/tests/test_claude_output_recovery_ledger.py+++ b/tests/test_claude_output_recovery_ledger.py@@ -1110,10 +1110,42 @@ def test_classification_run_ack_does_not_remove_output_receipt_across_restart(acassert activity_store.list_activities() == []+def test_force_end_cause_survives_a_settlement_retried_after_restart(activity_store):+ """MH-MIG-012: when settlement fails while a forced refresh ends an Activity,+ the next start settles it again from the durable snapshot. The refresh cause+ is recorded on the Activity itself, so that retry still reports it."""++ def unavailable(_activity):+ raise RuntimeError("database is locked")++ service = AgentService(+ SimpleNamespace(scheduled_task_service=SimpleNamespace(settle_activity_runs=unavailable)),+ activities=SessionActivityRegistry(activity_store),+ )+ service.activities.start(+ backend="claude",+ runtime_key="runtime-1",+ session_id="ses-1",+ activity_id="task-1",+ kind="background_task",+ run_id="run-1",+ )+ service.force_end_backend_activities("claude")++ restored = SessionActivityRegistry(activity_store).drain_recovered_terminals()+ assert [(item.id, item.status, item.metadata.get("interrupt_reason")) for item in restored] == [+ ("task-1", "killed", "backend_refresh"),+ ]++def test_force_end_service_ack_removes_durable_terminal_once(activity_store):settled = []service = AgentService(- SimpleNamespace(scheduled_task_service=SimpleNamespace(settle_activity_runs=settled.append)),+ SimpleNamespace(+ scheduled_task_service=SimpleNamespace(+ settle_activity_runs=lambda activity, **_kwargs: settled.append(activity),+ ),+ ),activities=SessionActivityRegistry(activity_store),)for runtime in ("first", "second"):diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex fa7b16f55..f2c11d0c8 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -120,7 +120,7 @@ def _build_controller_double(handler=None):or "") or None- def _mark_turn_complete(ctx):+ def _mark_turn_complete(ctx, *, settled_by=None):manager = getattr(controller, "session_turns", None)if manager is not None:spec = getattr(ctx, "platform_specific", None) or {}@@ -135,6 +135,8 @@ def _build_controller_double(handler=None):runtime_turn_id=f"runtime-turn:{logical_turn_id}",)sink = sinks.get(resolve_turn_sink_key(controller, ctx))+ if sink and settled_by:+ sink.setdefault("settled_by", settled_by)if sink and sink.get("done_event") is not None:sink["done_event"].set()@@ -3143,6 +3145,76 @@ def test_release_for_backend_refresh_cancels_matching_turn_and_sets_idle():assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}+ ("harness", "decided_by"),+ [(False, None), (True, None), (False, "stop"), (False, "result")],+ ids=["conversation", "harness-run", "stop-in-flight", "result-already-delivered"],+)+def test_release_for_backend_refresh_names_the_interruption(harness, decided_by):+ """MH-MIG-012: a forced runtime refresh settles the turn it interrupts as a+ backend refresh even when the backend swallows the cancellation and reports+ a result-less turn, and a conversation turn tells the user why it stopped.+ A Harness run reports its own interruption, so it gets no second notice; an+ outcome already decided, by a Stop in flight or a result the runner delivered+ before finishing its cleanup, keeps its own cause and gets none either."""+ controller = _build_controller_double()+ manager = session_turns.SessionTurnManager(controller)+ controller.set_agent_status = lambda *_args: None+ notices = []++ async def _emit(context, kind, text, **_kwargs):+ notices.append((context.channel_id, kind, text))+ return "notice-1"++ controller.emit_agent_message = _emit++ async def _go():+ ctx = MessageContext(user_id="U", channel_id="ses_opencode", platform="avibe")+ ctx.platform_specific = {+ "agent_session_id": "ses_opencode",+ "agent_session_target": {"agent_backend": "opencode"},+ **({"task_execution_id": "run-1"} if harness else {}),+ }+ sink_key = resolve_turn_sink_key(controller, ctx)+ controller.register_turn_sink(sink_key, on_chunk=None, done_event=asyncio.Event())+ if decided_by == "result":+ controller.get_turn_sink(sink_key)["settled_by"] = "terminal_result"++ async def _swallows_cancellation():+ try:+ await asyncio.sleep(60)+ except asyncio.CancelledError:+ # Like the OpenCode adapter: release the waiter as result-less.+ controller.mark_turn_complete(ctx, settled_by="no_terminal_result")++ task = asyncio.create_task(_swallows_cancellation())+ await asyncio.sleep(0)+ turn = session_turns.Turn(task=task, context=ctx, logical_turn_id="turn-1")+ if decided_by == "stop":+ turn.cancel_settled_by = "stopped"+ manager.in_flight["ses_opencode"] = turn+ await manager.release_for_backend_refresh(backend="opencode", base_session_ids={"ses_opencode"})+ for _ in range(5):+ await asyncio.sleep(0)+ return controller.get_turn_sink(sink_key), turn++ sink, turn = asyncio.run(_go())++ if decided_by is not None:+ assert turn.cancel_settled_by == ("stopped" if decided_by == "stop" else None)+ assert sink["settled_by"] != "backend_refresh"+ assert notices == []+ return+ assert sink["settled_by"] == "backend_refresh"+ if harness:+ assert notices == []+ else:+ assert len(notices) == 1+ channel, kind, text = notices[0]+ assert (channel, kind) == ("ses_opencode", "notify")+ assert text.startswith("⚠️ This turn was interrupted — its Agent runtime was restarted")++def test_release_for_backend_refresh_leaves_other_backend_turn_running():controller = _build_controller_double()manager = session_turns.SessionTurnManager(controller)diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex a2afbd367..204505d51 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -1465,7 +1465,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):settled = []class _RequestStore:- def defer_run_terminal(self, run_id, *, terminal_status):+ def defer_run_terminal(self, run_id, *, terminal_status, error=None):deferred.append((run_id, terminal_status))def settle_deferred_run(self, run_id):@@ -2459,7 +2459,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):terminal_runs = set()class _RequestStore:- def defer_run_terminal(self, run_id, *, terminal_status):+ def defer_run_terminal(self, run_id, *, terminal_status, error=None):events.append(("defer", run_id, terminal_status))def settle_deferred_run(self, run_id, *, error):diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 9fa764339..5f6c39f0f 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -4714,6 +4714,7 @@ def test_hub_to_direct_fallback_does_not_require_engine_sync(tmp_path):"claude-opus-4-6",)adapter.fail_sync = True+ service.migration_guard = _idle_mode_guardswitched = asyncio.run(service.set_agent_mode("claude", "direct"))@@ -4722,6 +4723,45 @@ def test_hub_to_direct_fallback_does_not_require_engine_sync(tmp_path):assert adapter.synced == [][email protected](("start", "target"), [("direct", "hub"), ("hub", "direct")])+def test_mode_switch_commits_only_inside_the_interrupting_guard(tmp_path, start, target):+ """MH-MIG-011: either direction retires the managed runtime under the+ migration guard, which interrupts running work. Switching back to direct+ outside it left a running gateway turn to fail later on the Hub's refusal."""+ service, store, _adapter = _service(tmp_path)+ service.migration_home = tmp_path / "native-home"+ store.config.agents["claude"].mode = start+ observed = []++ @asynccontextmanager+ async def guard(backends, *, external_processes=True):+ observed.append(("enter", backends, external_processes, store.config.agents["claude"].mode))++ async def verify_idle():+ pass++ yield verify_idle+ observed.append(("exit", store.config.agents["claude"].mode))++ service.migration_guard = guard+ switched = asyncio.run(service.set_agent_mode("claude", target))++ assert switched["mode"] == target+ assert observed == [("enter", ("claude",), False, start), ("exit", target)]++ @asynccontextmanager+ async def refusing(backends, *, external_processes=True):+ raise NativeMigrationBlockedError("native_runtime_busy", backends)+ yield # pragma: no cover - required async context-manager shape++ service.migration_guard = refusing+ with pytest.raises(ModelHubError) as refusal:+ asyncio.run(service.set_agent_mode("claude", start))++ assert refusal.value.code == "mode_switch_blocked"+ assert store.config.agents["claude"].mode == target++async def _confirm_guard(call):try:return await call({})@@ -4943,6 +4983,8 @@ _PROJECTION_MUTATIONS = {@pytest.mark.parametrize("mutation", _PROJECTION_MUTATIONS)def test_public_mutations_sync_the_engine_only_when_bindings_change(tmp_path, mutation):service, store, adapter = _service(tmp_path)+ # A mode switch retires the runtime under the guard; nothing runs here.+ service.migration_guard = _idle_mode_guard_set_claude_route_fixture(store, ("src_first0001", "src_second001"), _PROJECTION_MODEL)service._engine_synced = Truecall, synced_projection = _PROJECTION_MUTATIONS[mutation]diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 5cba88f5f..157946f54 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -4,6 +4,7 @@ import asyncioimport copyimport jsonfrom collections import deque+from contextlib import asynccontextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Mapping@@ -326,6 +327,15 @@ def _config(sources: list[ModelHubSourceConfig], *, model: str = "claude-opus-4-return ModelHubConfig(sources=sources, agents=agents)+@asynccontextmanager+async def _idle_mode_guard(backends, *, external_processes=True):+ # A mode switch retires the runtime under the migration guard; these+ # fixtures have no running work for it to interrupt.+ async def verify_idle():+ pass+ yield verify_idle++def _service(tmp_path: Path, config: ModelHubConfig, adapter: FakeAdapter | None = None) -> tuple[ModelHubService, MemoryStore, FakeAdapter]:store = MemoryStore(config)adapter = adapter or FakeAdapter()@@ -1242,6 +1252,7 @@ def test_direct_mode_rejects_chain_write_before_config_mutation(tmp_path):source = _source("src_direct01", (menu_model,))config = _config([source], model=menu_model)service, store, _ = _service(tmp_path, config)+ service.migration_guard = _idle_mode_guardasyncio.run(service.set_agent_mode("claude", "direct"))before = store.load().to_payload()@@ -2328,6 +2339,7 @@ def test_guards_ignore_a_preexisting_unrelated_interruption(tmp_path, mutation):def test_direct_mode_refuses_chain_and_probe(tmp_path):config = ModelHubConfig()service, _, _ = _service(tmp_path, config)+ service.migration_guard = _idle_mode_guardasyncio.run(service.set_agent_mode("claude", "direct"))with pytest.raises(ModelHubError) as chain_error:service.agent_chain("claude", "claude-opus-4-6")diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex e7cfde137..17e750d91 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -8157,18 +8157,120 @@ def test_deferred_failure_preserves_error_through_later_output(@pytest.mark.parametrize(- ("activity_status", "expected_run_status"),+ ("prior", "expected_run_status", "expected_reason", "expected_error"),[- ("failed", "failed"),- ("stopped", "canceled"),- ("killed", "canceled"),+ ("failed_sibling", "failed", None, "Background Activity task-first failed"),+ ("deferred_failure_then_cancel", "canceled", "stopped", "[Avibe Harness] This run was stopped"),+ ],+)+def test_refresh_ending_the_last_activity_keeps_the_runs_first_cause(+ tmp_path: Path,+ monkeypatch,+ prior: str,+ expected_run_status: str,+ expected_reason: str | None,+ expected_error: str,+) -> None:+ """MH-MIG-012: the refresh that ends a Run's last Activity replaces neither an+ Activity that already failed while its sibling blocked settlement, nor a+ user cancellation that won over an earlier recorded failure."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store = TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="claude",+ )+ controller = _avibe_controller_double(+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),+ handle_scheduled_message=lambda *_args, **_kwargs: None,+ )+ registry = SessionActivityRegistry()+ controller.agent_service = SimpleNamespace(activities=registry)+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )+ assert request_store.claim(request.id) is not None+ for activity_id in ("task-first", "task-last"):+ registry.start(+ backend="claude",+ runtime_key="runtime-1",+ session_id="target-session",+ activity_id=activity_id,+ kind="background_task",+ run_id=request.id,+ )+ if prior == "failed_sibling":+ first = registry.complete(+ backend="claude",+ runtime_key="runtime-1",+ activity_id="task-first",+ status="failed",+ )+ assert first is not None+ # The sibling still runs, so the Run cannot settle yet.+ assert service.settle_activity_runs(first) == []+ else:+ assert request_store._sqlite.defer_run_terminal(+ request.id,+ terminal_status="failed",+ error="provider unavailable",+ ) is True+ registry.complete(+ backend="claude",+ runtime_key="runtime-1",+ activity_id="task-first",+ status="completed",+ )+ assert request_store.cancel_run(request.id)+ last = registry.complete(+ backend="claude",+ runtime_key="runtime-1",+ activity_id="task-last",+ status="killed",+ metadata={"interrupt_reason": "backend_refresh"},+ )+ assert last is not None++ assert service.settle_activity_runs(last) == [request.id]+ terminal = request_store.get_run(request.id)+ assert terminal is not None+ assert terminal["status"] == expected_run_status+ assert terminal["error"].startswith(expected_error)+ assert terminal["metadata"].get("interrupt_reason") == expected_reason+++ ("activity_status", "interrupt_reason", "user_cancel", "expected_run_status", "expected_reason", "expected_error"),+ [+ ("failed", None, False, "failed", None, "Background Activity task-failed failed"),+ ("stopped", None, False, "canceled", None, "Background Activity task-failed stopped"),+ ("killed", None, False, "canceled", None, "Background Activity task-failed killed"),+ # MH-MIG-012: the service ending the Activity itself is an interruption+ # the user is told about, not a silent kill.+ (+ "killed",+ "backend_refresh",+ False,+ "failed",+ "backend_refresh",+ "[Avibe Harness] This run was interrupted because its Agent runtime was refreshed",+ ),+ # A user's cancellation that wins the race is still the user's stop.+ ("killed", "backend_refresh", True, "canceled", "stopped", "[Avibe Harness] This run was stopped"),],)def test_terminal_owned_activity_settles_deferred_run_once(tmp_path: Path,monkeypatch,activity_status: str,+ interrupt_reason: str | None,+ user_cancel: bool,expected_run_status: str,+ expected_reason: str | None,+ expected_error: str,) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))request_store = TaskExecutionStore()@@ -8208,16 +8310,22 @@ def test_terminal_owned_activity_settles_deferred_run_once(runtime_key="runtime-1",activity_id="task-failed",status=activity_status,+ metadata={"interrupt_reason": interrupt_reason} if interrupt_reason else None,)assert activity is not None+ if user_cancel:+ assert request_store.cancel_run(request.id)assert service.settle_activity_runs(activity) == [request.id]terminal = request_store.get_run(request.id)assert terminal is not Nonecompleted_at = terminal["completed_at"]assert terminal["status"] == expected_run_status- assert terminal["error"] == f"Background Activity task-failed {activity_status}"+ assert terminal["error"].startswith(expected_error)assert "deferred_terminal_status" not in terminal["result_payload"]+ assert terminal["metadata"].get("interrupt_reason") == expected_reason+ notice = request_store.sqlite_backend.owed_failure_notice(request.id)+ assert (notice is not None) == (expected_run_status == "failed")assert service.settle_activity_runs(activity) == []assert request_store.get_run(request.id)["completed_at"] == completed_atdiff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 5e4ff94d5..664bcf5cd 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -4473,7 +4473,7 @@ def test_retained_lost_turn_report_is_retried_on_its_own_clock(managers) -> None_first, restarted, _engine, _engine_b, _starts = managersemitted, _stamped = _capture_lost_turn_report(restarted)restarted.LOST_TURN_RETRY_DELAYS = (0.0, 0.0)- restarted._pending_lost_turn_reports["slack"] = [("ses_fsm", "m-origin", "trn-origin", "codex")]+ restarted._pending_lost_turn_reports["slack"] = [("ses_fsm", "m-origin", "trn-origin", "codex", "turn.interrupted.serviceRestart")]failures = 1async def _emit(_context, kind, text, **_kwargs):@@ -4507,7 +4507,7 @@ def test_lost_turn_retry_gives_up_instead_of_spinning(managers) -> None:_first, restarted, _engine, _engine_b, _starts = managersemitted, _stamped = _capture_lost_turn_report(restarted)restarted.LOST_TURN_RETRY_DELAYS = (0.0, 0.0)- restarted._pending_lost_turn_reports["slack"] = [("ses_fsm", "m-origin", "trn-origin", "codex")]+ restarted._pending_lost_turn_reports["slack"] = [("ses_fsm", "m-origin", "trn-origin", "codex", "turn.interrupted.serviceRestart")]async def _emit(_context, kind, text, **_kwargs):emitted.append((kind, text))@@ -4524,7 +4524,7 @@ def test_lost_turn_retry_gives_up_instead_of_spinning(managers) -> None:# One initial attempt plus one per configured delay, then it stops.assert len(emitted) == 3- assert restarted._pending_lost_turn_reports["slack"] == [("ses_fsm", "m-origin", "trn-origin", "codex")]+ assert restarted._pending_lost_turn_reports["slack"] == [("ses_fsm", "m-origin", "trn-origin", "codex", "turn.interrupted.serviceRestart")]def test_lost_turn_owning_a_run_leaves_the_notice_to_the_harness_lane(managers) -> None:@@ -5396,6 +5396,76 @@ def test_definite_handler_prewrite_exception_requeues_through_terminal_boundary(assert turn["start_receipt_outcome"] == "not_written"[email protected]("first_send_delivers", [True, False], ids=["delivered", "held-then-retried"])+def test_forced_refresh_tells_a_restored_conversation_turn_why_it_stopped(managers, first_send_delivers) -> None:+ """MH-MIG-012: a Turn restored across a service restart has no in-flight task,+ yet a forced refresh still terminalizes it. Its conversation gets the same+ notice as a live Turn, on the message that started it; without one the+ thread simply stops. A send that fails is held and retried as that same+ refresh notice, since it is the only account the user will get."""+ first, restarted, engine, _engine_b, _starts = managers+ context = _context()+ admitted = asyncio.run(+ first.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="restored turn interrupted by a switch",+ native_message_id="m-origin",+ ),+ context=context,+ )+ )+ turn_id = str(admitted.turn_id)+ context.platform_specific["turn_token"] = turn_id+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"+ first._active_identity = lambda _backend, _session_id, logical_id: (+ logical_id,+ f"native-{logical_id}",+ )+ first.on_native_start(+ context,+ backend="codex",+ runtime_key=f"runtime-key-{turn_id}",+ runtime_turn_id=f"runtime-{turn_id}",+ )+ emitted, stamped = _capture_lost_turn_report(restarted)+ delivered = []++ async def _emit(_context, kind, text, **_kwargs):+ emitted.append((kind, text))+ if first_send_delivers or delivered:+ return "msg-1"+ delivered.append(False)+ return None++ restarted.controller.emit_agent_message = _emit+ restarted.begin_backend_drain("codex")++ async def _go() -> int:+ released = await restarted.release_for_backend_refresh(+ backend="codex",+ base_session_ids={"ses_fsm"},+ )+ for _ in range(5):+ await asyncio.sleep(0)+ return released++ assert asyncio.run(_go()) == 1+ with engine.connect() as conn:+ settled = delivery_store.get_turn(conn, turn_id)+ assert settled is not None and settled["terminal_evidence_kind"] == "backend_refresh"+ if not first_send_delivers:+ assert stamped == []+ assert asyncio.run(restarted.notify_transport_ready("avibe")) == 1+ assert [kind for kind, _text in emitted] == ["notify"] * (1 if first_send_delivers else 2)+ assert all(+ text.startswith("⚠️ This turn was interrupted — its Agent runtime was restarted")+ for _kind, text in emitted+ )+ assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]++def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(managers,) -> None:@@ -5429,16 +5499,24 @@ def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(dispatch_text="ambiguous during forced refresh",)manager.begin_backend_drain("codex")+ emitted, _stamped = _capture_lost_turn_report(manager)- released = asyncio.run(- manager.release_for_backend_refresh(+ async def _go() -> int:+ released = await manager.release_for_backend_refresh(backend="codex",base_session_ids={"ses_fsm"},)- )+ for _ in range(5):+ await asyncio.sleep(0)+ return released++ released = asyncio.run(_go())assert released == 1assert _row(engine, delivery_id)["state"] == "retired"+ # MH-MIG-012: the refresh retired this conversation's input, so it says so.+ assert [kind for kind, _text in emitted] == ["notify"]+ assert emitted[0][1].startswith("⚠️ This turn was interrupted — its Agent runtime was restarted")with engine.connect() as conn:turn = delivery_store.get_turn(conn, turn_id)status = conn.execute(diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 11b4f67fc..132196771 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1033,6 +1033,7 @@},"turn": {"interrupted": {+ "backendRefresh": "⚠️ This turn was interrupted — its Agent runtime was restarted while it was still running, for example after switching between the Model Hub and direct mode or saving Agent settings. Send the request again if the work still needs doing.","serviceRestart": "⚠️ This turn was interrupted — the Avibe service restarted while it was still running. Send the request again if the work still needs doing."}},diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex a7cf892f5..5c33d0545 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1033,6 +1033,7 @@},"turn": {"interrupted": {+ "backendRefresh": "⚠️ 本轮执行被中断——它运行期间 Agent 运行时被重启(例如在模型网关和直连之间切换,或保存了 Agent 设置)。如果这项工作仍然需要完成,请重新发送请求。","serviceRestart": "⚠️ 本轮执行被中断——Avibe 服务在它运行期间重启。如果这项工作仍然需要完成,请重新发送请求。"}},