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): fail a turn on a removed model once and name its Agents before removal (#2320)
Call Whitefbf6f09335a4
diff --git a/core/backend_failure.py b/core/backend_failure.pyindex 24ae2b279..551ab98ab 100644--- a/core/backend_failure.py+++ b/core/backend_failure.py@@ -368,6 +368,7 @@ async def emit_backend_failure(output: MessageOutput | None = None,failure_id: str | None = None,delivery: DeliveryEvidence | None = None,+ cause: BaseException | None = None,) -> bool:"""Notify and settle one terminal backend failure.@@ -379,6 +380,10 @@ async def emit_backend_failure(Non-Harness callers retain immediate auth recovery. The return value is true whenauth recovery supplied that immediate notification.+ ``cause`` is the exception the failure reports, when the adapter has one. A+ Model Hub turn refusal names its own cause, so it never reaches the text+ auth heuristic, which would misread a model id that says ``oauth``.+``delivery``, when supplied, is filled in with what the notify attempt actuallyproved. A durable Turn or legacy Harness Run supplies an evidence objectautomatically so Runs attached after settlement inherit the same proof. A clean@@ -439,9 +444,11 @@ async def emit_backend_failure(# function at all; see ``emit_replayed_backend_failure``. A bypass argument here# was the previous shape, and it left the replay inside this lifecycle with its# live behaviours switched off one at a time.+ from core.handlers.model_hub.service import turn_refusal+auth_service = getattr(controller, "agent_auth_service", None)maybe_recover = getattr(auth_service, "maybe_emit_auth_recovery_message", None)- if not harness_run_id and callable(maybe_recover):+ if not harness_run_id and callable(maybe_recover) and turn_refusal(cause) is None:try:handled_auth = await maybe_recover(context,diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 6f520ba9d..c9b800742 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -194,6 +194,11 @@ TURN_OUTCOME_RENDERING_AUTHORITY: dict[str, TurnOutcomeRenderingRule] = {discriminator="route_unconfigured",copy_keys=(("interrupted", "modelHub.launch.route_unconfigured"),),),+ "turn.no_candidate.unlisted": TurnOutcomeRenderingRule(+ outcome="no_candidate",+ discriminator="model_unlisted",+ copy_keys=(("interrupted", "modelHub.launch.model_unlisted"),),+ ),"turn.no_candidate.blocked": TurnOutcomeRenderingRule(outcome="no_candidate",discriminator="blocked_supply_state",@@ -364,6 +369,37 @@ def produce_turn_outcome(return projection+def no_candidate_decision(+ config: ModelHubConfig,+ resolution: ModelHubTurnResolution,+) -> str:+ """Choose the matrix row for a turn that has no runnable hop.++ An id the backend's model list does not hold has an empty effective Route+ unless a manual Route row was retained for it, so an empty chain for such+ an id is the list's answer rather than a Route the user can configure.+ """++ if not resolution.route_unconfigured:+ return "turn.no_candidate.blocked"+ requested = resolution.requested_model+ if requested and all(+ model.id != requested for model in config.agents[resolution.backend].models+ ):+ return "turn.no_candidate.unlisted"+ return "turn.no_candidate.unconfigured"+++def is_unlisted_model_outcome(projection: TurnOutcomeProjectionInput | None) -> bool:+ """Whether a turn was refused because its backend's list does not hold its model."""++ rule = TURN_OUTCOME_RENDERING_AUTHORITY["turn.no_candidate.unlisted"]+ return projection is not None and (projection.outcome, projection.discriminator) == (+ rule.outcome,+ rule.discriminator,+ )++REQUEST_NONFALLBACK_TURN_OUTCOME = produce_turn_outcome("turn.request_nonfallback")@@ -520,6 +556,8 @@ def render_turn_outcome_copy(f"{blocker.source}: {label}" if blocker.source else label)params["blockers"] = ", ".join(rendered)+ if params.get("backend"):+ params["backend"] = i18n_t(f"modelHub.backends.{params['backend']}", language)return i18n_t(copy.key, language, **params)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 71f8c4b60..16ef286e9 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -136,6 +136,7 @@ from .provenance import (ExactHopBlocker,TurnOutcomeProjectionInput,exact_hop_blockers,+ no_candidate_decision,produce_turn_outcome,)from .request import ModelHubRequest@@ -376,6 +377,16 @@ class ModelHubError(Exception):self.local_error_detail = local_error_detail+def turn_refusal(error: BaseException | None) -> TurnOutcomeProjectionInput | None:+ """The turn outcome a Model Hub error refuses its turn with, if it is one.++ Such an error states its own cause, so text matching on its message can+ only misread it, for example a model id that happens to say ``oauth``.+ """++ return error.turn_outcome if isinstance(error, ModelHubError) else None++class CredentialCleanupUnsettledError(ModelHubError):def __init__(self):super().__init__("engine_down", status=503)@@ -3892,6 +3903,54 @@ class ModelHubService:add(model_id)return protected+ def _removed_agent_models(+ self,+ previous: ModelHubConfig,+ updated: ModelHubConfig,+ backend: BackendName,+ removed_model_ids: set[str],+ ) -> list[dict]:+ """The Agents a model-list removal stops, as supply gaps.++ An Agent is affected only when the row its selection names before the+ save is removed. If its selection then names no surviving row, the+ removal stops it whatever supply the row had, and the gap carries the+ removed row's id. An OpenCode selection can still name a surviving row+ (``openai/foo`` falls back to ``foo``); it is stopped only when that row+ has no runnable hop, and the gap carries the row it now runs on. Both+ lists are matched the way the turn path matches them.+ """++ before = previous.agents[backend]+ after = updated.agents[backend]+ if before.mode != "hub" or self.named_agents_override is None:+ return []+ unavailable_source_ids = self._unavailable_native_sources(updated, backend)+ live_recovery = self.recovery_annotations(updated)+ surviving_ids = {model.id for model in after.models}+ agents_by_model: dict[str, set[str]] = {}+ for name, selected in self.named_agents_override(backend):+ selected = str(selected or "").strip()+ if self._menu_model_for_selection(before, selected) not in removed_model_ids:+ continue+ model_id = self._menu_model_for_selection(after, selected)+ if model_id in surviving_ids and resolve_model_hub_turn(+ updated,+ backend,+ model_id,+ now=self.now(),+ unavailable_source_ids=unavailable_source_ids,+ live_recovery=live_recovery,+ ).candidates:+ continue+ if model_id not in surviving_ids:+ model_id = self._menu_model_for_selection(before, selected)+ agents_by_model.setdefault(model_id, set()).add(name)+ return [+ {"backend": backend, "model_id": model_id, "agents": sorted(names)}+ for model_id, names in sorted(agents_by_model.items())+ ]+def _would_interrupt(self,config: ModelHubConfig,@@ -5516,19 +5575,6 @@ class ModelHubService:if model.id not in removed_model_id_set]- interrupted = self._introduced_interruptions(- previous,- config,- )- self._require_guard_plan(- force=force,- confirmed_remove_hops=confirmed_remove_hops,- confirmed_interruptions=confirmed_interruptions,- would_remove_hops=removed_hops,- would_interrupt=interrupted,- error="backend_model_in_route",- )-for model_id, desired in desired_by_id.items():baseline_model = baseline_by_id.get(model_id)current = current_by_id.get(model_id)@@ -5603,6 +5649,24 @@ class ModelHubService:view=agent.menu.view if agent.menu else "featured",checked=list(ordered_ids),)+ # The guard plans against the complete staged catalog, including the+ # rows this same save adds, edits and reorders: a removed row's Agent+ # may run on one of them afterwards. A save that conflicts has+ # already refused above, so it never asks a confirmation for nothing.+ interrupted = self._removed_agent_models(+ previous,+ config,+ agent_backend,+ removed_model_id_set,+ )+ self._require_guard_plan(+ force=force,+ confirmed_remove_hops=confirmed_remove_hops,+ confirmed_interruptions=confirmed_interruptions,+ would_remove_hops=removed_hops,+ would_interrupt=interrupted,+ error="backend_model_in_route",+ )await self._commit_synced(previous, config)await self._refresh_backend_catalog(cast(BackendName, backend))committed = self.store.load()@@ -5612,7 +5676,7 @@ class ModelHubService:self._agent(committed, backend),)}- if removed_hops:+ if removed_hops or interrupted:result["removed_hops"] = removed_hopsresult["interrupted"] = interruptedreturn result@@ -7428,10 +7492,15 @@ class ModelHubService:*,backend: BackendName,model_id: str,+ config: ModelHubConfig | None = None,) -> tuple[ModelHubConfig, ModelHubTurnResolution]:- """Inspect the complete effective chain used by the next turn."""+ """Inspect the complete effective chain used by the next turn.- config = self.store.load()+ ``config`` is a view of the stored config, for a backend that can take+ only part of what is stored; by default the stored config is inspected.+ """++ config = config if config is not None else self.store.load()resolution = resolve_model_hub_turn(config,backend,@@ -7514,11 +7583,7 @@ class ModelHubService:resolution: ModelHubTurnResolution,) -> TurnOutcomeProjectionInput:return produce_turn_outcome(- (- "turn.no_candidate.unconfigured"- if resolution.route_unconfigured- else "turn.no_candidate.blocked"- ),+ no_candidate_decision(config, resolution),config=config,resolution=resolution,)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex ee68b6c43..3210873ba 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1338,6 +1338,7 @@ class SessionHandler(BaseHandler):"claude",launch_model or "",process_scope=cached_key or composite_key,+ context=context,)bind_launch(context, model_hub_launch)runtime_model = model_hub_launch.runtime_model or launch_model@@ -2744,6 +2745,16 @@ class SessionHandler(BaseHandler):),)return False+ from modules.agents.model_hub import launch_refusal_copy++ refusal = launch_refusal_copy(self.controller, error)+ if refusal is not None:+ # The Hub refused this launch before any Claude process existed.+ await self._get_im_client(context).send_message(+ context,+ self._get_formatter(context).format_error(refusal),+ )+ return Falseif client is None:client = self.claude_sessions.get(composite_key)diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex 9710fdfad..0daf55dcb 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -250,11 +250,15 @@"type": "object","required": ["ok", "contract_version", "agent", "removed_hops", "interrupted"],"additionalProperties": false,+ "anyOf": [+ {"properties": {"removed_hops": {"minItems": 1}}},+ {"properties": {"interrupted": {"minItems": 1}}}+ ],"properties": {"ok": {"const": true},"contract_version": {"const": 10},"agent": {"$ref": "#/definitions/AgentSupplyApi"},- "removed_hops": {"type": "array", "minItems": 1, "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},+ "removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}}},diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex e0274ac95..9fe4bbe66 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -51,7 +51,7 @@ remain readable; ephemeral envelopes use only the terminal version.| 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. |+| 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 removal whose row has a Route, or whose row an enabled Agent selects, uses the exact echoed-plan guard and then atomically removes that Route (see **Model-list save** under Supply guard). Its success carries `removed_hops` and `interrupted` whenever either is nonempty; any other removal is ordinary `{agent}` success. Supplier inventory remains unchanged. || GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, derive `native_protocol` from the model id's last path segment through the vendor map, cap results at 8, and never persist automatically. || GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. || GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |@@ -689,6 +689,30 @@ Explicit manual-hop invalidations, lost inventory matches, and newly introducedprotected-supply gaps still use the exact-plan guard. This exception does not applyto Source deletion, default-membership changes, or Restore.+**Model-list save.** For `PUT /api/models/agents/<backend>/models`, the producer+`ModelHubService.set_agent_models` reports in `would_interrupt` exactly the removed menu+rows that enabled named Vibe Agents on that backend select, one `SupplyGap` per row keyed+by the removed menu id. Each Agent's model is matched to a row against the list before the+save with the rule the turn path uses (`opencode_menu_model_candidates` /+`opencode_menu_model_id`: the whole selection first, then the model part of an OpenCode+`<provider>/<model>` selection), so an Agent on `openai/gpt-5.6-sol` names row+`gpt-5.6-sol`. A row is reported whatever its supply before the save, because removing it+stops those Agents either way; Direct mode reports none. An OpenCode selection that+still names a surviving row after the save (`openai/foo` falling back to row `foo`) is+not stopped by the removal: it is reported only when that row has no runnable hop,+under the surviving row's id. Per-Session model overrides are+not enumerated: a turn that asks for a model the list no longer holds fails once with+`turn.no_candidate.unlisted`. The consumer is the backend catalog dialog's guard, which+names those Agents through `GuardImpact`; a refusal with no route hops gets its own+subtitle. Confirmation is the ordinary exact echo of both arrays, and the forced+success reports the same two arrays even when only `interrupted` is nonempty.++A client's agreement covers exactly the Agent impacts it showed. It may resend a+moved plan forced only while every `SupplyGap` in it, and every Agent within one,+was in the plan the user confirmed; a refusal that names any other gap or Agent is+a new question, asked before anything commits. A confirmation given before the+server spoke showed none, so it covers hop movement alone.+Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the complete`guard-refusal.schema.json` shape. The first refusal is:@@ -711,7 +735,9 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the cThe lead error and its evidence array are inseparable: `source_in_route_chain` and`source_model_in_route_chain` require nonempty `would_remove_hops`, while`source_last_supplier` requires nonempty `would_interrupt`. The other array remains a-complete projection and may independently be empty or nonempty.+complete projection and may independently be empty or nonempty. `backend_model_in_route`+requires at least one nonempty array: route hops, Agents that select a removed row, or+both.The shared guard planner stages the complete post-mutation Source/Route result and itsordered guard-report arrays. On confirmation the client resends the same substantive@@ -1669,7 +1695,7 @@ JSON Schema draft-07 cannot express cross-document or live-state relations. Thecontract harness and API-boundary tests enforce:<!-- authority-consumer: credential.refresh_once credential.refresh_failed credential.refresh_rejected credential.static_unauthorized credential.account_classified credential.request_nonfallback -->-<!-- authority-consumer: turn.served turn.exhausted turn.request_nonfallback turn.engine_down turn.streamed_fallback turn.no_candidate.unconfigured turn.no_candidate.blocked turn.canceled -->+<!-- authority-consumer: turn.served turn.exhausted turn.request_nonfallback turn.engine_down turn.streamed_fallback turn.no_candidate.unconfigured turn.no_candidate.unlisted turn.no_candidate.blocked turn.canceled --><!-- authority-consumer: mutation.source_metadata mutation.credential_replace mutation.source_refresh mutation.model_create mutation.model_efforts mutation.model_delete mutation.source_delete mutation.route_replace mutation.route_restore mutation.default_sources --><!-- authority-consumer: import.keep_native import.copy_key import.reauth import.controlled --><!-- authority-consumer: protocol anthropic openai_responses openai_chat -->diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex 2108e4a1e..28ec82266 100644--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json@@ -33,8 +33,7 @@"error": {"enum": ["source_in_route_chain",- "source_model_in_route_chain",- "backend_model_in_route"+ "source_model_in_route_chain"]}},diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 773caaf33..b931809f2 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -1263,6 +1263,7 @@ switch, remedy, or message branch absent from it.| `turn.engine_down` | `failed_terminal` | local `engine_down` at any request phase, including after an upstream attempt or streamed output | no Source is blamed or mutated; no replay or next-hop walk occurs | `models.errors.engine_down`; after output began it also states that this turn's output may be incomplete || `turn.streamed_fallback` | `failed_terminal` | streamed fallback-class Source failure, plus `source_transition_persisted: boolean` recording whether its cooldown or `needs_action` transition was committed | replay is forbidden. When `source_transition_persisted=true`, render `models.launch.retry` only when live inspection of the same effective chain makes a different hop current for the next turn; otherwise no switch exists. When `false`, attempt history remains committed, no switch/current change is claimed, and the existing config-recovery warning owns remediation | persisted with a different current hop: “The next turn has switched Sources; retry.” Persisted with no runnable hop: use the same `waiting`/`interrupted` rendering selected for `exhausted`. Not persisted: `modelHub.errors.stream_interrupted`, with no route-change or new-remedy claim || `turn.no_candidate.unconfigured` | `no_candidate` | configured chain is empty | no Source was attempted because no hop is configured | `models.launch.route_unconfigured`, naming the requested model and pointing to Models |+| `turn.no_candidate.unlisted` | `no_candidate` | configured chain is empty because the requested model is not in the backend's model list and keeps no manual Route the backend can address (OpenCode addresses only listed rows) | no Source was attempted because the backend no longer offers this model; sending the same input again cannot succeed, so it waits for an explicit retry instead of automatic startup retries. The id is no model of this backend, so no `supply_interrupted` event is recorded | `models.launch.model_unlisted`, naming the requested model and the backend and asking the user to choose another model || `turn.no_candidate.blocked` | `no_candidate` | configured chain is nonempty and model `supply_state` is `waiting` or `interrupted` | no Source was attempted because every exact hop is currently blocked | derive copy from the exact blocker set and reuse `_launch_failure` remedies: reauthorize, replace the key, or top up; `waiting` uses `models.launch.waiting`, while `interrupted` uses `models.launch.interrupted` || `turn.canceled` | `canceled` | the turn FSM, never a transport inference, settled Stop/cancel | no Source failure or route switch is fabricated | no Model Hub supply copy; the existing turn-canceled surface owns the message |@@ -1387,7 +1388,7 @@ the other array remains a complete projection and may independently be empty or| --- | --- | --- | --- || `guard_error.source_in_route_chain` | `source_in_route_chain` | `would_remove_hops` | `would_interrupt` remains complete || `guard_error.source_model_in_route_chain` | `source_model_in_route_chain` | `would_remove_hops` | `would_interrupt` remains complete |-| `guard_error.backend_model_in_route` | `backend_model_in_route` | `would_remove_hops` | `would_interrupt` remains complete |+| `guard_error.backend_model_in_route` | `backend_model_in_route` | `would_remove_hops` or `would_interrupt` | each array remains complete; a model-list save whose only impact is removing rows enabled Agents select carries only `would_interrupt` || `guard_error.source_last_supplier` | `source_last_supplier` | `would_interrupt` | `would_remove_hops` remains complete |**Source-mutation envelope matrix (authoritative and exhaustive; owner rulingsdiff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 3b143dd8f..b3e5e1e42 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -439,6 +439,11 @@ class ClaudeAgent(BaseAgent):client=None,) -> str:"""Return the durable notify text for Claude terminal errors."""+ from modules.agents.model_hub import launch_refusal_copy++ refusal = launch_refusal_copy(self.controller, error)+ if refusal is not None:+ return f"❌ {refusal}"if isinstance(error, ClaudeInputNotSentError):return f"❌ {self._translate_error(error.message_key)}"if isinstance(error, ClaudeSessionNotFoundError):@@ -663,8 +668,11 @@ class ClaudeAgent(BaseAgent):raiseexcept Exception as e:logger.error(f"Error processing Claude message: {e}", exc_info=True)+ from modules.agents.model_hub import launch_refusal_copy+missing_session = isinstance(e, ClaudeSessionNotFoundError)input_not_sent = isinstance(e, ClaudeInputNotSentError)+ hub_refusal = launch_refusal_copy(self.controller, e) is not Nonestop_owned = bool(getattr(request, "_claude_stop_owned", False))if missing_session:mark_prewrite_recovery_required(context, "native_session_not_found")@@ -706,10 +714,10 @@ class ClaudeAgent(BaseAgent):runtime_session_key,)return- # A typed local resume failure takes precedence over incidental- # auth words in the working path or captured process diagnostic.+ # A typed local resume failure or Hub refusal takes precedence+ # over incidental auth words in a path, model id, or diagnostic.handled = False- if not missing_session and not input_not_sent:+ if not missing_session and not input_not_sent and not hub_refusal:handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(context,"claude",diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 9316f27c2..c7f125bd8 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -517,6 +517,7 @@ class CodexAgent(BaseAgent):"codex",requested_model or "",process_scope=request.working_path,+ context=request.context,)bind_launch(request.context, launch)await self._interrupt_active_turn_before_runtime_change(request, launch)@@ -536,11 +537,14 @@ class CodexAgent(BaseAgent):self._event_handler._release_stream_turn(request.context)returnexcept Exception as e:+ from modules.agents.model_hub import launch_refusal_copy+logger.error("Failed to start Codex transport: %s", e, exc_info=True)language = str(getattr(getattr(self.controller, "config", None), "language", "en")or "en")+ refusal = launch_refusal_copy(self.controller, e)if isinstance(e, CodexRuntimeChangeBlockedError):# Not a source failure: no Hub cooldown. Hold the unwritten# input for an explicit retry once the blocking turn ends.@@ -549,6 +553,9 @@ class CodexAgent(BaseAgent):elif isinstance(e, CodexModelHubCatalogUnavailableError):await self._record_model_hub_native_failure(request.context, str(e))display_text = f"❌ {i18n_t('modelHub.errors.codex_catalog_unavailable', language)}"+ elif refusal is not None:+ await self._record_model_hub_native_failure(request.context, str(e))+ display_text = f"❌ {refusal}"else:await self._record_model_hub_native_failure(request.context, str(e))display_text = f"❌ Failed to start Codex CLI: {e}"@@ -559,6 +566,7 @@ class CodexAgent(BaseAgent):str(e),display_text=display_text,request=request,+ cause=e,)await self._remove_ack_reaction(request)self._event_handler._release_stream_turn(request.context)diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex 78338c6c6..9f6c03b0d 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -29,7 +29,7 @@ from core.handlers.model_hub.provenance import (PreparedGatewayRoute,TurnOutcomeProjectionInput,exact_hop_blockers,- produce_turn_outcome,+ is_unlisted_model_outcome,render_turn_outcome_copy,supply_interruption_reason,)@@ -46,9 +46,11 @@ from core.handlers.model_hub.service import (ModelHubService,create_default_service,project_opencode_public_model,+ turn_refusal,)from core.services.settings import load_config_or_defaultfrom core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from core.native_dispatch_phase import mark_prewrite_recovery_requiredfrom vibe.codex_config import format_toml_basic_stringfrom vibe.opencode_config import managed_opencode_runtime_config_content@@ -59,6 +61,9 @@ TurnMode = Literal["direct", "hub"]_CONTEXT_LAUNCH_ATTR = "_vibe_model_hub_launch"_CONTEXT_MODE_ATTR = "_vibe_model_hub_turn_mode"_CONTEXT_FAILURE_RECORDED_ATTR = "_vibe_model_hub_failure_recorded"+# The durable hold's reason when a turn asks for a model its backend's list+# does not hold: the same input fails the same way until another model is chosen.+UNLISTED_MODEL_RETRY_REASON = "model_hub_model_unlisted"_NATIVE_QUOTA_RE = re.compile(r"(?:quota|usage|credit|billing).{0,32}(?:exhaust|exceed|limit|deplet|insufficient)|"r"(?:exhaust|exceed|limit|deplet|insufficient).{0,32}(?:quota|usage|credit|billing)|"@@ -240,6 +245,7 @@ async def resolve_model_hub_launch(requested_model: str,*,process_scope: Optional[str] = None,+ context: Any = None,) -> ModelHubLaunch:router = getattr(controller, "model_hub_runtime", None)resolver = getattr(router, "resolve", None)@@ -255,12 +261,14 @@ async def resolve_model_hub_launch(turn_id=turn_id,)except ModelHubError as exc:- raise _localized_launch_error(+ failure = _localized_launch_error(controller,backend,requested_model,exc,- ) from None+ )+ _hold_unrunnable_input(context, failure)+ raise failure from Nonereturn ModelHubLaunch(backend=backend,channel="direct",@@ -274,6 +282,8 @@ async def resolve_opencode_overlay_launch(controller: Any,requested_model: str,overlay: OpenCodeOverlay | None,+ *,+ context: Any = None,) -> ModelHubLaunch:router = getattr(controller, "model_hub_runtime", None)resolver = getattr(router, "resolve_opencode_overlay_launch", None)@@ -281,13 +291,49 @@ async def resolve_opencode_overlay_launch(try:return await resolver(overlay, requested_model)except ModelHubError as exc:- raise _localized_launch_error(+ failure = _localized_launch_error(controller,"opencode",requested_model,exc,- ) from None- return await resolve_model_hub_launch(controller, "opencode", requested_model)+ )+ _hold_unrunnable_input(context, failure)+ raise failure from None+ return await resolve_model_hub_launch(+ controller, "opencode", requested_model, context=context,+ )+++def launch_refusal_copy(controller: Any, error: BaseException) -> str | None:+ """The copy a turn shows when the Hub refused its launch, or ``None``.++ The refusal names its turn-outcome matrix row, so every backend shows that+ row's copy as it is, never an exception name, a raw key, or a startup+ label around it.+ """++ outcome = turn_refusal(error)+ if outcome is None:+ return None+ return render_turn_outcome_copy(outcome, _language(controller))+++def _hold_unrunnable_input(context: Any, error: ModelHubError) -> None:+ """Keep an input whose model the backend does not list for an explicit retry.++ Sending it again unchanged fails the same way, so it must not spend the+ automatic startup retries a transient failure gets.+ """++ if context is not None and is_unlisted_model_outcome(error.turn_outcome):+ mark_prewrite_recovery_required(context, UNLISTED_MODEL_RETRY_REASON)+++def _language(controller: Any) -> str:+ return str(+ getattr(getattr(controller, "config", None), "language", "en")+ or "en"+ )def _localized_launch_error(@@ -298,11 +344,7 @@ def _localized_launch_error() -> ModelHubError:if error.turn_outcome is None:return error- language = str(- getattr(getattr(controller, "config", None), "language", "en")- or "en"- )- detail = render_turn_outcome_copy(error.turn_outcome, language)+ detail = render_turn_outcome_copy(error.turn_outcome, _language(controller))if detail is None:return errorreturn ModelHubError(@@ -784,17 +826,20 @@ class ModelHubRuntimeRouter:requested_model: str,process_scope: Optional[str],turn_id: Optional[str],+ listed_only: bool = False,) -> ModelHubError:+ view = None+ if listed_only:+ # A backend that addresses only listed rows cannot take a manual+ # Route retained for an id its list does not hold.+ view = self.service._clone_config(self.service.store.load())+ view.agents[backend].routes.pop(requested_model, None)projection_config, projection_resolution = self.service._inspect_terminal_chain(backend=backend,model_id=requested_model,+ config=view,)- turn_outcome = produce_turn_outcome(- (- "turn.no_candidate.unconfigured"- if projection_resolution.route_unconfigured- else "turn.no_candidate.blocked"- ),+ turn_outcome = self.service._produce_no_candidate_terminal_outcome(config=projection_config,resolution=projection_resolution,)@@ -815,7 +860,9 @@ class ModelHubRuntimeRouter:supply_state=supply_state,blockers=exact_hop_blockers(projection_resolution),)- if (+ # An unlisted id is not a model of this backend, so it has no supply to+ # interrupt: the turn's own refusal is the whole report.+ if not is_unlisted_model_outcome(turn_outcome) and (not projection_resolution.matching_sourcesor projection_resolution.structural_blocker_reason is not None):@@ -1036,6 +1083,15 @@ class ModelHubRuntimeRouter:)if launch is None:config = self.service.store.load()+ if all(model.id != requested_model for model in config.agents["opencode"].models):+ # The overlay holds launches only for listed rows.+ raise self._no_candidate_error(+ backend="opencode",+ requested_model=requested_model,+ process_scope="opencode:shared-server",+ turn_id=None,+ listed_only=True,+ )config, resolution = await self._resolve_turn(config,"opencode",@@ -1245,10 +1301,9 @@ def opencode_requested_model_for_overlay(if not overlay.available_identifiers:raise ModelHubError("mapping_target_unavailable", status=409)return overlay.available_identifiers[0]- candidate = opencode_menu_model_id(candidate, overlay.checked_identifiers)- if candidate in overlay.checked_identifiers:- return candidate- raise ModelHubError("mapping_target_unavailable", status=409)+ # A selection no menu row names is still the turn's request: the launch+ # resolution refuses it with the copy that says why.+ return opencode_menu_model_id(candidate, overlay.checked_identifiers)def opencode_model_for_overlay(diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 18b756400..3cce4d671 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -70,6 +70,7 @@ from modules.agents.model_hub import (OpenCodeOverlay,bind_launch,bind_turn_mode,+ launch_refusal_copy,opencode_model_for_overlay,opencode_model_catalog_for_overlay,opencode_requested_model_for_overlay,@@ -1545,6 +1546,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):self.controller,requested_model_str,model_hub_overlay,+ context=request.context,)bind_launch(request.context, model_hub_launch)model_str = opencode_model_for_overlay(@@ -2006,14 +2008,22 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):start_attempt_id,)- message = f"OpenCode request failed: {error_text}"+ refusal = launch_refusal_copy(self.controller, e)+ if refusal is not None:+ display_text = f"❌ {refusal}"+ else:+ display_text = (+ f"OpenCode request failed: {error_text}"+ f"{self._resource_failure_suffix(resource_failure)}"+ )await emit_backend_failure(self.controller,request.context,self.name,error_text,- display_text=f"{message}{self._resource_failure_suffix(resource_failure)}",+ display_text=display_text,request=request,+ cause=e,)finally:await self._stop_caller_context_binding_renewal(diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.pyindex e493cc121..503354d24 100644--- a/tests/scenario_harness/model_hub.py+++ b/tests/scenario_harness/model_hub.py@@ -343,3 +343,34 @@ def service_for(def round_trip(config: ModelHubConfig) -> ModelHubConfig:return ModelHubConfig.from_payload(config.to_payload())+++#: A model no backend's Model Hub list holds, as a removed row leaves it. Its id+#: carries words the native auth heuristics match, which a refusal must not trip.+UNLISTED_MODEL = "oauth-authentication-retired-模型-9"+++def unlisted_model_runtime(tmp_path: Path, language: str = "en"):+ """A controller whose real Hub runtime refuses ``UNLISTED_MODEL`` on every backend."""++ from types import SimpleNamespace++ from modules.agents.model_hub import ModelHubRuntimeRouter++ store = MemoryModelHubStore(config_with_sources([]))+ service = service_for(tmp_path, store, ModelHubScenarioAdapter())+ router = ModelHubRuntimeRouter(service=service, overlay_path=tmp_path / "overlay.json")+ return SimpleNamespace(config=SimpleNamespace(language=language), model_hub_runtime=router)+++def unlisted_model_copy(backend: str, language: str = "en") -> str:+ """The one refusal every backend shows for a turn on ``UNLISTED_MODEL``."""++ from vibe.i18n import t++ return t(+ "modelHub.launch.model_unlisted",+ language,+ model=UNLISTED_MODEL,+ backend=t(f"modelHub.backends.{backend}", language),+ )diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 112b68227..e08b604cb 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -1224,6 +1224,32 @@ scenarios:kind: selectionlayer: unittest: tests/test_model_hub_injection.py::test_opencode_overlay_runs_a_provider_qualified_selection_on_its_menu_row+ - id: MH-UNLISTED-001+ name: A Hub turn on a model its backend's list no longer holds fails once with one localized reason on every backend+ status: covered+ kind: turn_lifecycle+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_unlisted_001_removed_model_fails_its_next_turn_with_one_clear_reason+ related_tests:+ - tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_only_an_unlisted_model_holds_its_input_for_an_explicit_retry+ - tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_opencode_refuses_an_unlisted_model_its_retained_route_cannot_address+ - tests/test_claude_cli_path.py::test_claude_launch_on_an_unlisted_model_holds_the_input+ - tests/test_claude_session_recovery.py::test_unlisted_hub_model_shows_the_shared_refusal_once+ - tests/test_codex_request_routing.py::test_codex_turn_on_an_unlisted_model_fails_once_with_the_shared_copy+ - tests/test_multi_platform_runtime.py::test_opencode_turn_on_an_unlisted_model_fails_once_with_the_shared_copy+ - id: MH-UNLISTED-002+ name: Removing a model-list row that enabled Agents select names those Agents under the removed menu id before it commits+ status: covered+ kind: guard+ layer: contract+ test: tests/test_model_hub_api.py::test_mh_unlisted_002_model_list_save_names_the_agents_a_removed_row_stops+ related_tests:+ - "ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx::MH-UNLISTED-002: names the Agents a removed row stops when the row has no route, then echoes that plan"+ - "ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx::MH-UNLISTED-002: shows the Agents a focused removal would stop on its first refusal before anything commits"+ - "ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx::MH-UNLISTED-002: shows the Agents a focused removal would stop after its plan moves before anything commits"+ - "ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx::MH-UNLISTED-002: asks again before a confirmed save stops an Agent the guard did not show"+ - "ui/src/components/settings/models/guardedWrite.test.ts::sendAgreed"+ - "ui/src/components/settings/models/SourceDetailPanel.test.tsx::forces a guarded source deletion that would stop an Agent, once that Agent is shown, echoing the server plan byte for byte"- id: MH-MIG-001name: Native migration takes over selected credentials and cleans replaced native authstatus: covereddiff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pyindex ea1033bac..fd9c664df 100644--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -41,6 +41,11 @@ from core.handlers.model_hub.service import (ModelHubService,)from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from core.native_dispatch_phase import (+ DISPATCH_PHASE_PREWRITE,+ prewrite_failure_evidence,+ set_dispatch_phase,+)from core.run_settlement import SETTLED_BY_TERMINAL_RESULTfrom modules.agents.model_hub import (ModelHubRuntimeRouter,@@ -49,7 +54,10 @@ from modules.agents.model_hub import (opencode_model_for_overlay,opencode_requested_model_for_overlay,persisted_launch_identity,+ resolve_model_hub_launch,+ resolve_opencode_overlay_launch,)+from vibe.i18n import t as i18n_tclass MemoryStore:@@ -462,14 +470,15 @@ def test_mh_switch_001_switching_to_gateway_keeps_agent_models_runnable(finally:await gateway.close()- # The row now runs an Agent, so removing it names that Agent.+ # The row now runs an Agent, so removing it names that Agent under the+ # row it runs on, not the Direct-era spelling of its selection.baseline = service.backend_catalog_models("opencode")with pytest.raises(ModelHubError) as refused:await service.set_agent_models("opencode", baseline, [row for row in baseline if row["id"] != "gpt-5.6-sol"],)assert refused.value.data["would_interrupt"] == [- {"backend": "opencode", "model_id": "openai/gpt-5.6-sol", "agents": ["opencode"]},+ {"backend": "opencode", "model_id": "gpt-5.6-sol", "agents": ["opencode"]},]# Leaving the Gateway keeps the catalog, and Direct runs each Agent's@@ -1345,3 +1354,177 @@ def test_mh_set_003_released_launch_identity_shape_restores_without_certifying_fawait gateway.close()asyncio.run(exercise())++[email protected]("backend", ("claude", "codex", "opencode"))[email protected]("language", ("en", "zh"))+def test_mh_unlisted_001_removed_model_fails_its_next_turn_with_one_clear_reason(+ tmp_path: Path,+ backend: str,+ language: str,+) -> None:+ """MH-UNLISTED-001: after the model-list save removes a model, the next+ Hub turn that asks for it is refused with the same localized copy on every+ backend, naming the model and the backend, never a raw key or class name."""++ async def exercise() -> None:+ store = MemoryStore(_config(_source("src_unlisted1")))+ model_id = _requested_model(backend)+ if backend == "opencode":+ # The list keeps another row, so only the removed id is unlisted.+ agent = store.config.agents["opencode"]+ agent.models.append(+ ModelHubBackendModelConfig(id="model-kept", native_protocol="anthropic")+ )+ assert agent.menu is not None+ agent.menu.checked.append("model-kept")+ service = _service(+ tmp_path, store, AdapterBoundaryFake([]),+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),+ )+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(+ service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json",+ )+ controller = SimpleNamespace(+ config=SimpleNamespace(language=language),+ model_hub_runtime=router,+ )++ async def next_turn():+ if backend != "opencode":+ return await resolve_model_hub_launch(+ controller, backend, model_id, process_scope=str(tmp_path),+ )+ overlay = await router.prepare_opencode_overlay()+ requested = opencode_requested_model_for_overlay(model_id, overlay)+ return await resolve_opencode_overlay_launch(controller, requested, overlay)++ try:+ assert (await next_turn()).source_id == "src_unlisted1"++ baseline = service.backend_catalog_models(backend)+ kept = [row for row in baseline if row["id"] != model_id]+ with pytest.raises(ModelHubError) as guarded:+ await service.set_agent_models(backend, baseline, kept)+ await service.set_agent_models(+ backend, baseline, kept, force=True,+ confirmed_remove_hops=guarded.value.data["would_remove_hops"],+ confirmed_interruptions=guarded.value.data["would_interrupt"],+ )++ with pytest.raises(ModelHubError) as refused:+ await next_turn()+ finally:+ await gateway.close()++ expected = i18n_t(+ "modelHub.launch.model_unlisted",+ language,+ model=model_id,+ backend=i18n_t(f"modelHub.backends.{backend}", language),+ )+ assert str(refused.value) == expected+ assert model_id in expected+ assert "modelHub." not in expected and "ModelHubError" not in expected++ asyncio.run(exercise())+++ ("case", "discriminator", "held", "event_reason"),+ (+ ("listed_without_route", "route_unconfigured", False, "route_unconfigured"),+ ("unlisted", "model_unlisted", True, None),+ ("unlisted_with_manual_route", "blocked_supply_state", False, "source_missing"),+ ),+)+def test_only_an_unlisted_model_holds_its_input_for_an_explicit_retry(+ tmp_path: Path,+ case: str,+ discriminator: str,+ held: bool,+ event_reason: str | None,+) -> None:+ """MH-UNLISTED-001: an empty chain is the list's answer only for an id the+ list does not hold; a listed row still asks for a Route, and a retained+ manual Route still reports its own blocker. Only the unlisted id is final,+ and, being no model of this backend, it interrupts no supply in the feed."""++ config = _config()+ model_id = _requested_model("claude") if case == "listed_without_route" else "claude-gone-9"+ if case == "unlisted_with_manual_route":+ config.agents["claude"].routes[model_id] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig("src_deleted01", model_id),)+ )+ service = _service(+ tmp_path, MemoryStore(config), AdapterBoundaryFake([]),+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),+ )+ controller = SimpleNamespace(+ config=SimpleNamespace(language="en"),+ model_hub_runtime=ModelHubRuntimeRouter(service=service),+ )+ context = SimpleNamespace(platform_specific={})+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)++ with pytest.raises(ModelHubError) as refused:+ asyncio.run(+ resolve_model_hub_launch(+ controller, "claude", model_id, process_scope=str(tmp_path), context=context,+ )+ )++ assert refused.value.turn_outcome is not None+ assert refused.value.turn_outcome.discriminator == discriminator+ assert prewrite_failure_evidence(context) == (+ {"reason": "model_hub_model_unlisted", "requires_explicit_retry": True}+ if held+ else {}+ )+ assert [+ event["reason"]+ for event in service.events.list(limit=10)+ if event["kind"] == "supply_interrupted" and event["model_id"] == model_id+ ] == ([event_reason] if event_reason else [])+++def test_opencode_refuses_an_unlisted_model_its_retained_route_cannot_address(+ tmp_path: Path,+) -> None:+ """MH-UNLISTED-001: OpenCode addresses only listed rows, so a runnable manual+ Route retained for an unlisted id is not one its turn can take: the turn+ gets the same one refusal and hold as any other unlisted model."""++ async def exercise() -> None:+ store = MemoryStore(_config(_source("src_retained1")))+ agent = store.config.agents["opencode"]+ model_id = "model-retained"+ agent.routes[model_id] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig("src_retained1", _source_model_id("opencode")),)+ )+ service = _service(+ tmp_path, store, AdapterBoundaryFake([]),+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),+ )+ router = ModelHubRuntimeRouter(service=service, overlay_path=tmp_path / "overlay.json")+ controller = SimpleNamespace(config=SimpleNamespace(language="en"), model_hub_runtime=router)+ context = SimpleNamespace(platform_specific={})+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)++ overlay = await router.prepare_opencode_overlay()+ requested = opencode_requested_model_for_overlay(model_id, overlay)+ with pytest.raises(ModelHubError) as refused:+ await resolve_opencode_overlay_launch(controller, requested, overlay, context=context)++ assert str(refused.value) == i18n_t(+ "modelHub.launch.model_unlisted",+ "en",+ model=model_id,+ backend=i18n_t("modelHub.backends.opencode", "en"),+ )+ assert prewrite_failure_evidence(context) == {+ "reason": "model_hub_model_unlisted", "requires_explicit_retry": True,+ }++ asyncio.run(exercise())diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 66afe4051..34177dd14 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -32,8 +32,19 @@ from core.agent_auth_service import AgentAuthServicefrom core.handlers.session_handler import SessionHandlerfrom core.runtime_activation import RuntimeActivationRegistryfrom core.runtime_ownership import RuntimeTargetOwnershipSnapshot, SessionRuntimeDisposition+from core.native_dispatch_phase import (+ DISPATCH_PHASE_PREWRITE,+ prewrite_failure_evidence,+ set_dispatch_phase,+)+from core.handlers.model_hub.service import ModelHubErrorfrom modules.claude_sdk_compat import CLAUDE_SDK_MAX_BUFFER_SIZEfrom modules.im import MessageContext+from tests.scenario_harness.model_hub import (+ UNLISTED_MODEL,+ unlisted_model_copy,+ unlisted_model_runtime,+)@dataclass@@ -3722,3 +3733,22 @@ def test_to_app_config_never_spawns_npm_on_async_request_paths(monkeypatch, tmp_assert compat.claude.cli_path == "avibe-absent-claude-cli"assert compat.codex is not None and compat.codex.binary == "avibe-absent-codex-cli"assert compat.opencode is not None and compat.opencode.binary == "avibe-absent-opencode-cli"+++def test_claude_launch_on_an_unlisted_model_holds_the_input(tmp_path) -> None:+ """MH-UNLISTED-001: the Claude launch reaches the shared refusal and hold."""+ controller = _Controller(tmp_path)+ controller.model_hub_runtime = unlisted_model_runtime(tmp_path).model_hub_runtime+ controller.settings_manager.get_channel_routing = lambda _key: RoutingSettings(model=UNLISTED_MODEL)+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)++ with pytest.raises(ModelHubError) as refused:+ _run_session(handler, context)++ assert str(refused.value) == unlisted_model_copy("claude")+ assert prewrite_failure_evidence(context) == {+ "reason": "model_hub_model_unlisted", "requires_explicit_retry": True,+ }+ assert controller.claude_sessions == {}diff --git a/tests/test_claude_session_recovery.py b/tests/test_claude_session_recovery.pyindex 6aee6c5e5..958aec911 100644--- a/tests/test_claude_session_recovery.py+++ b/tests/test_claude_session_recovery.py@@ -22,7 +22,13 @@ from modules.agents.base import AgentRequestfrom modules.agents.claude_agent import ClaudeAgentfrom storage import message_deliveries as deliveries, messages_servicefrom storage.models import agent_sessions, session_turns+from modules.agents.model_hub import resolve_model_hub_launchfrom tests.backend_failure_retry_helpers import reserve_failure_retry+from tests.scenario_harness.model_hub import (+ UNLISTED_MODEL,+ unlisted_model_copy,+ unlisted_model_runtime,+)from tests.test_claude_agent_sessions import _StubControllerfrom tests.test_session_delivery_fsm import _context, _fsm_schema_template, managers # noqa: F401from vibe.i18n import t@@ -114,6 +120,38 @@ async def test_missing_session_delivers_localized_notice_and_terminal_failure(assert binding["workdir"] == working_path[email protected]("language", ["en", "zh"])+async def test_unlisted_hub_model_shows_the_shared_refusal_once(+ managers, monkeypatch, tmp_path, language+):+ """MH-UNLISTED-001: Claude shows the shared refusal once, never a wrapped+ exception or an auth prompt matched from words in its path."""+ _manager, _restarted, engine, _other, _starts = managers+ working_path = str(tmp_path / "oauth-login" / "原目录")+ agent, controller = _agent_fixture(monkeypatch, engine, language=language, working_path=working_path)+ controller.agent_auth_service.maybe_emit_auth_recovery_message.return_value = False+ runtime = unlisted_model_runtime(tmp_path, language)++ async def launch(_context, **_kwargs):+ # The launch half, including the input hold, is the session handler's+ # own test; this one covers what the agent shows for its refusal.+ await resolve_model_hub_launch(runtime, "claude", UNLISTED_MODEL)++ controller.session_handler.get_or_create_claude_session = AsyncMock(side_effect=launch)+ context = _context()+ context.platform_specific["turn_token"] = "trn_unlisted"+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)++ await agent.handle_message(_request(context, "继续", working_path))++ expected = f"❌ {unlisted_model_copy('claude', language)}"+ controller.im_client.send_message.assert_awaited_once_with(context, expected)+ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()+ with engine.connect() as conn:+ notices = messages_service.list_session_messages(conn, session_id="ses_fsm")["messages"]+ assert [notice["text"] for notice in notices] == [expected]++@pytest.mark.parametrize("retry", ["failure_notice", "send_now", "still_missing"])async def test_missing_session_queue_waits_for_explicit_recovery(managers, monkeypatch, tmp_path, retrydiff --git a/tests/test_codex_request_routing.py b/tests/test_codex_request_routing.pyindex 303ce17d0..085d68e8f 100644--- a/tests/test_codex_request_routing.py+++ b/tests/test_codex_request_routing.py@@ -21,13 +21,21 @@ from core.handlers.model_hub.turn_gateway import ModelHubTurnGatewayfrom core.run_settlement import SETTLED_BY_TERMINAL_RESULTfrom modules.agents.codex.agent import CodexAgentfrom modules.agents.model_hub import ModelHubRuntimeRouter, bind_launch, resolve_model_hub_launch+from core.native_dispatch_phase import (+ DISPATCH_PHASE_PREWRITE,+ prewrite_failure_evidence,+ set_dispatch_phase,+)from tests.scenario_harness.model_hub import (+ UNLISTED_MODEL,MemoryModelHubStore,ModelHubScenarioAdapter,ScenarioCallResult,config_with_sources,service_for,source,+ unlisted_model_copy,+ unlisted_model_runtime,)@@ -324,3 +332,40 @@ async def test_codex_adapter_keeps_request_metadata_on_compatibility_retry(runtiassert call.args[0] == "turn/start"assert call.args[1]["responsesapiClientMetadata"] == launch.gateway_request_metadataassert call.args[1]["model"] == launch.runtime_model++[email protected]("language", ("en", "zh"))+async def test_codex_turn_on_an_unlisted_model_fails_once_with_the_shared_copy(tmp_path, language):+ """MH-UNLISTED-001: Codex shows the shared refusal, never a login prompt+ matched from words in the model id, and holds the input."""+ controller = unlisted_model_runtime(tmp_path, language)+ controller.emit_agent_message = AsyncMock()+ controller.agent_auth_service = SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=True),+ )+ context = SimpleNamespace(platform_specific={})+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ request = SimpleNamespace(+ base_session_id="session-1", working_path=str(tmp_path),+ context=context, session_key="settings-1", ack_message_id=None,+ )+ agent = object.__new__(CodexAgent)+ agent.controller = controller+ agent._session_locks = {}+ agent._session_mgr = SimpleNamespace(set_session_key=Mock(), set_cwd=Mock())+ agent.ensure_agent_session_id = Mock()+ agent._bind_runtime_agent_session_id = Mock()+ agent._resolve_codex_agent_settings = Mock(return_value=(None, UNLISTED_MODEL, None, None))+ agent._get_or_create_transport = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent._event_handler = SimpleNamespace(_release_stream_turn=Mock())++ await agent.handle_message(request)++ agent._get_or_create_transport.assert_not_awaited()+ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()+ notify = controller.emit_agent_message.await_args_list[0]+ assert notify.args[1:3] == ("notify", f"❌ {unlisted_model_copy('codex', language)}")+ assert prewrite_failure_evidence(context) == {+ "reason": "model_hub_model_unlisted", "requires_explicit_retry": True,+ }diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 36d9207cf..b0e325402 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -3829,6 +3829,199 @@ def test_backend_catalog_guarded_removal_excludes_removed_model_and_accepts_echo} == before_other_agents+ ("backend", "agent_model", "supplied", "mode"),+ (+ ("claude", None, False, "hub"),+ ("codex", None, False, "hub"),+ ("opencode", "openai/gpt-5.6-sol", False, "hub"),+ ("opencode", "openai/gpt-5.6-sol", True, "hub"),+ ("codex", None, False, "direct"),+ ),+)+def test_mh_unlisted_002_model_list_save_names_the_agents_a_removed_row_stops(+ monkeypatch,+ tmp_path,+ backend,+ agent_model,+ supplied,+ mode,+):+ """MH-UNLISTED-002: removing a row an enabled Agent selects names that Agent+ under the removed menu id, whatever the row's supply was before the save."""++ service, store, _adapter = _service(tmp_path)+ agent = store.config.agents[backend]+ agent.mode = mode+ if backend == "opencode":+ agent.models = [+ ModelHubBackendModelConfig(id=model_id, native_protocol="openai_responses")+ for model_id in ("gpt-5.6-sol", "gpt-kept")+ ]+ agent.menu.checked = ["gpt-5.6-sol", "gpt-kept"]+ model_id = agent.models[0].id+ if supplied:+ store.config.sources = [+ ModelHubSourceConfig(+ id="src_unlisted02",+ kind="api_key",+ vendor="openai",+ display_name="Unlisted source",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id=model_id, provenance="discovered")],+ credential_ref="cred_unlisted02",+ )+ ]+ agent.sources.order = ["src_unlisted02"]+ service.named_agents_override = lambda name: (+ [("写作助手", agent_model or model_id), ("pm", agent_model or model_id), ("other", "gpt-kept")]+ if name == backend+ else []+ )+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ headers = csrf_headers(client, base_url)+ endpoint = f"/api/models/agents/{backend}/models"+ baseline = next(item["catalog_models"] for item in service.list_agents() if item["backend"] == backend)+ request_body = {+ "baseline": baseline,+ "models": [row for row in baseline if row["id"] != model_id],+ }++ response = client.put(endpoint, json=request_body, headers=headers, base_url=base_url)++ if mode == "direct":+ assert response.status_code == 200+ assert model_id not in {model.id for model in store.config.agents[backend].models}+ return+ assert response.status_code == 409+ refusal = response.get_json()+ _assert_valid("guard-refusal.schema.json", refusal)+ assert refusal["error"] == "backend_model_in_route"+ assert refusal["would_interrupt"] == [+ {"backend": backend, "model_id": model_id, "agents": ["pm", "写作助手"]}+ ]+ assert [hop["menu_model"] for hop in refusal["would_remove_hops"]] == (+ [model_id] if supplied else []+ )+ assert model_id in {model.id for model in store.config.agents[backend].models}++ committed = client.put(+ endpoint,+ json={+ **request_body,+ "force": True,+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ headers=headers,+ base_url=base_url,+ )++ assert committed.status_code == 200+ result = committed.get_json()+ Draft7Validator(+ {"$ref": "model-hub/api-response.schema.json#/definitions/AgentModelsResponse"},+ registry=_api_response_registry(),+ format_checker=FormatChecker(),+ ).validate(result)+ # The success reports the Agents it stopped even when no route went with them.+ assert result["removed_hops"] == refusal["would_remove_hops"]+ assert result["interrupted"] == refusal["would_interrupt"]+ assert model_id not in {model.id for model in store.config.agents[backend].models}++[email protected]("fallback", ("kept", "added_in_same_save"))+ ("fallback_supplied", "expected_gaps"),+ (+ (True, []),+ (False, [{"backend": "opencode", "model_id": "kimi-k2", "agents": ["writer"]}]),+ ),+)+def test_mh_unlisted_002_opencode_fallback_row_keeps_an_agent_running(+ monkeypatch,+ tmp_path,+ fallback,+ fallback_supplied,+ expected_gaps,+):+ """MH-UNLISTED-002: an OpenCode selection that names a row of the saved+ catalog, kept or added by the same save, is stopped only when that row+ cannot run, and is then named under the row it now runs on. The plan is+ computed from the complete staged catalog, so the exact echo of the same+ request commits it."""++ service, store, _adapter = _service(tmp_path)+ agent = store.config.agents["opencode"]+ kept_ids = ("moonshotai/kimi-k2", "kimi-k2") if fallback == "kept" else ("moonshotai/kimi-k2",)+ agent.models = [+ ModelHubBackendModelConfig(id=model_id, native_protocol="openai_responses")+ for model_id in kept_ids+ ]+ agent.menu.checked = list(kept_ids)+ if fallback_supplied:+ store.config.sources = [+ ModelHubSourceConfig(+ id="src_fallback01",+ kind="api_key",+ vendor="openai",+ display_name="Fallback source",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="kimi-k2", provenance="discovered")],+ credential_ref="cred_fallback01",+ )+ ]+ agent.sources.order = ["src_fallback01"]+ service.named_agents_override = lambda name: (+ [("writer", "moonshotai/kimi-k2")] if name == "opencode" else []+ )+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ headers = csrf_headers(client, base_url)+ baseline = next(item["catalog_models"] for item in service.list_agents() if item["backend"] == "opencode")+ desired = [row for row in baseline if row["id"] != "moonshotai/kimi-k2"]+ if fallback == "added_in_same_save":+ desired.append({**baseline[0], "id": "kimi-k2", "origin": "manual"})+ request_body = {"baseline": baseline, "models": desired}+ endpoint = "/api/models/agents/opencode/models"++ response = client.put(endpoint, json=request_body, headers=headers, base_url=base_url)++ # A supplied fallback leaves only the removed row's passthrough hop to confirm.+ assert response.status_code == 409+ refusal = response.get_json()+ _assert_valid("guard-refusal.schema.json", refusal)+ assert refusal["would_interrupt"] == expected_gaps+ assert [hop["menu_model"] for hop in refusal["would_remove_hops"]] == (+ ["moonshotai/kimi-k2"] if fallback_supplied else []+ )++ committed = client.put(+ endpoint,+ json={+ **request_body,+ "force": True,+ "would_remove_hops": refusal["would_remove_hops"],+ "would_interrupt": refusal["would_interrupt"],+ },+ headers=headers,+ base_url=base_url,+ )++ assert committed.status_code == 200+ assert committed.get_json()["interrupted"] == expected_gaps+ assert [model.id for model in store.config.agents["opencode"].models] == ["kimi-k2"]++def test_backend_catalog_removes_model_with_empty_route(tmp_path):service, store, _adapter = _service(tmp_path)baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex d8af7e3b8..d736b0376 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -730,6 +730,8 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal,model_refusal,backend_refusal,+ # A model-list save whose only impact is Agents that select a removed row.+ {**backend_refusal, "would_remove_hops": [], "would_interrupt": [gap]},supplier_refusal,):validator.validate(payload)@@ -745,7 +747,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():for payload in ({**route_refusal, "would_remove_hops": [], "would_interrupt": [gap]},{**model_refusal, "would_remove_hops": [], "would_interrupt": [gap]},- {**backend_refusal, "would_remove_hops": [], "would_interrupt": [gap]},+ {**backend_refusal, "would_remove_hops": [], "would_interrupt": []},{**supplier_refusal, "would_remove_hops": [hop], "would_interrupt": []},{**route_refusal, "would_remove_hops": [hop, hop]},{**supplier_refusal, "would_interrupt": [gap, gap]},diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 297d9b9b4..5457bf626 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -8877,6 +8877,10 @@ def test_supply_interruption_preserves_exact_structural_reason() -> None:source = _source("src_present01", "Present")service = _service(tmp_path, sources=[source])+ # A listed row with no Source behind it; an unlisted id is no model of this+ # backend and records no event at all.+ service.store.config.agents["claude"].models.append(ModelHubBackendModelConfig(id="shared-model"))+ service.store.config.agents["claude"].sources.order = []service.store.config.agents["claude"].routes["shared-model"] = routerouter = ModelHubRuntimeRouter(service=service,diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex d301b7d60..8b726dc89 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -6,6 +6,8 @@ import threadingimport timefrom dataclasses import dataclassfrom pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest@@ -37,6 +39,12 @@ from modules.agents.opencode.poll_loop import (_settlement_assistant_message,)from modules.agents.opencode.utils import resolve_opencode_reasoning_effort+from core.native_dispatch_phase import prewrite_failure_evidence+from tests.scenario_harness.model_hub import (+ UNLISTED_MODEL,+ unlisted_model_copy,+ unlisted_model_runtime,+)ATTEMPT_ID = "atm_1234567890abcdef1234567890abcdef"@@ -211,6 +219,92 @@ def test_opencode_hub_turn_with_empty_menu_uses_overlay_and_keeps_server_runningassert calls == ["configure", "ensure", "attach", "release", "failure", "ack"][email protected]("language", ["en", "zh"])+def test_opencode_turn_on_an_unlisted_model_fails_once_with_the_shared_copy(+ tmp_path,+ monkeypatch,+ language,+) -> None:+ """MH-UNLISTED-001: an OpenCode Agent whose default model left the list+ shows the shared refusal, not a wrapped exception, raw key, or a login+ prompt matched from words in the model id, and keeps the input for an+ explicit retry."""++ class _Server:+ async def configure_model_hub_overlay(self, overlay):+ return None++ async def ensure_running(self):+ return None++ async def ensure_directory_ready(self, _path):+ return None++ def get_default_agent_from_config(self):+ return None++ async def abort_session(self, _session_id, _path):+ return None++ async def _get_server():+ return server++ async def _noop(*_args, **_kwargs):+ return None++ async def _session_id(*_args):+ return "ses_unlisted"++ server = _Server()+ controller = unlisted_model_runtime(tmp_path, language)+ controller.get_opencode_overrides = lambda _context: (None, None, None)+ controller.emit_agent_message = AsyncMock()+ controller.agent_auth_service = SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=True),+ )+ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = controller+ agent.config = controller.config+ agent._get_server = _get_server+ agent._delete_ack = _noop+ agent._remove_ack_reaction = _noop+ agent.record_model_hub_native_failure = _noop+ agent._steering_states = {}+ agent.sessions = type("Sessions", (), {"remove_active_poll": staticmethod(lambda _session_id: None)})()+ agent._session_manager = type(+ "SessionManager",+ (),+ {+ "ensure_working_dir": staticmethod(_noop),+ "get_or_create_session_id": staticmethod(_session_id),+ "set_request_session": staticmethod(lambda *_args: None),+ "set_agent_session_id": staticmethod(lambda *_args: None),+ },+ )()++ context = MessageContext(user_id="user", channel_id="channel", platform="slack", platform_specific={})+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ request = AgentRequest(+ context=context,+ message="继续",+ user_message="继续",+ working_path=str(tmp_path),+ base_session_id="base",+ composite_session_id=f"base:{tmp_path}",+ session_key="slack::channel",+ vibe_agent_model=UNLISTED_MODEL,+ )++ asyncio.run(agent._process_message(request))++ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()+ notices = [call.args[2] for call in controller.emit_agent_message.await_args_list if call.args[1] == "notify"]+ assert notices == [f"❌ {unlisted_model_copy('opencode', language)}"]+ assert prewrite_failure_evidence(context) == {+ "reason": "model_hub_model_unlisted", "requires_explicit_retry": True,+ }++class _StubClient(BaseIMClient):def __init__(self, name: str, *, supports_editing: bool = True, run_until_stopped: bool = False):super().__init__(_StubConfig())diff --git a/tests/test_opencode_directory_bootstrap.py b/tests/test_opencode_directory_bootstrap.pyindex 875aeff08..27214dab6 100644--- a/tests/test_opencode_directory_bootstrap.py+++ b/tests/test_opencode_directory_bootstrap.py@@ -106,7 +106,7 @@ async def _first_turn(tmp_path, port: int, monkeypatch):reached_prompt: list[tuple[str, str, str] | None] = []failures: list[str] = []- async def emit_backend_failure(_controller, _context, _backend, _error, *, display_text, request):+ async def emit_backend_failure(_controller, _context, _backend, _error, *, display_text, request, **_kwargs):failures.append(display_text)monkeypatch.setattr("modules.agents.opencode.agent.emit_backend_failure", emit_backend_failure)diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex e4c803d04..63334efee 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -25,7 +25,7 @@ import { classifyModelHubFailure, type ModelHubFailureClass } from './asyncLifetimport type { CollectionReadAuthority } from './collectionReadAuthority';import { GuardDialog } from './GuardDialog';import { GuardImpact, type GuardPlan } from './GuardImpact';-import { confirmGuardPlan, guardedFailure, sendAgreed } from './guardedWrite';+import { confirmGuardPlan, sendAgreed, unansweredRefusal } from './guardedWrite';import { apiFailure, modelsApi, type SourceCreated } from './modelsApi';import {createContinuationSettlement,@@ -187,8 +187,9 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {} catch (error) {const failure = apiFailure(error);// Only an unconfirmed attempt asks: a confirmed one already resent the- // moving plan within its bound, and ends as the failure below.- const refusal = plan === null ? guardedFailure(error) : null;+ // moving plan within its bound, and ends as the failure below — unless+ // the plan now stops an Agent the confirmation did not show.+ const refusal = unansweredRefusal(error, plan !== null, plan);if (refusal) {settlement.release();continuation.settle(seq, () => {diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsxindex 4d09ad9d8..33ac0e649 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx@@ -183,20 +183,19 @@ describe('BackendModelCatalogDialog', () => {expect(write.mock.calls[0][1].models.map((entry: BackendModel) => entry.id)).toEqual(['alpha']);});- it('forces a confirmed focused removal through the guard without asking again, even when the plan moves', async () => {+ it('forces a confirmed focused removal through a hops-only guard without asking again, even when the plan moves', async () => {const user = userEvent.setup();const shown = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];const moved = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_b', model_id: 'beta-max', position: 1 }];- const gaps = [{ backend: 'claude' as const, model_id: 'beta', agents: [] }];- const refusal = (hops: typeof shown, interrupt: typeof gaps = []) => new ApiCallError(- 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, interrupt, [], hops, 409,+ const refusal = (hops: typeof shown) => new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,);vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], {routes: { beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] } },}));const write = vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValueOnce(refusal(shown))- .mockRejectedValueOnce(refusal(moved, gaps))+ .mockRejectedValueOnce(refusal(moved)).mockResolvedValue(agent([model('alpha')]));const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove' } });const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });@@ -206,7 +205,40 @@ describe('BackendModelCatalogDialog', () => {expect(write).toHaveBeenCalledTimes(3);expect(write.mock.calls[0][1].force).toBeUndefined();expect(write.mock.calls[1][1]).toMatchObject({ force: true, would_remove_hops: shown, would_interrupt: [] });- expect(write.mock.calls[2][1]).toMatchObject({ force: true, would_remove_hops: moved, would_interrupt: gaps });+ expect(write.mock.calls[2][1]).toMatchObject({ force: true, would_remove_hops: moved, would_interrupt: [] });+ });++ it.each([+ ['on its first refusal', 0],+ ['after its plan moves', 1],+ ])('MH-UNLISTED-002: shows the Agents a focused removal would stop %s before anything commits', async (_, hopsFirst) => {+ const user = userEvent.setup();+ const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];+ const gaps = [{ backend: 'claude' as const, model_id: 'beta', agents: ['pm'] }];+ const refusal = (interrupt: typeof gaps) => new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, interrupt, [], hops, 409,+ );+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], {+ routes: { beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] } },+ }));+ const write = vi.spyOn(modelsApi, 'putAgentModels');+ if (hopsFirst) write.mockRejectedValueOnce(refusal([]));+ write.mockRejectedValueOnce(refusal(gaps)).mockResolvedValue(agent([model('alpha')]));+ const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove' } });+ const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });+ await user.click(within(confirm).getByRole('button', { name: 'Remove' }));++ // The focused confirmation showed hops only, so it never agreed to stop pm.+ const guard = await screen.findByRole('dialog', { name: 'Save the model list?' });+ expect(within(guard).getByText('Agents pinned to it: pm')).toBeTruthy();+ expect(write).toHaveBeenCalledTimes(1 + hopsFirst);+ expect(write.mock.calls.every(([, body]) => body.would_interrupt === undefined || body.would_interrupt.length === 0)).toBe(true);+ expect(onClose).not.toHaveBeenCalled();++ await user.click(within(guard).getByRole('button', { name: 'Remove anyway' }));+ await waitFor(() => expect(onClose).toHaveBeenCalledWith({ removed: true }));+ expect(write.mock.calls.at(-1)?.[1]).toMatchObject({ force: true, would_remove_hops: hops, would_interrupt: gaps });+ expect(write.mock.calls.at(-1)?.[1].models.map((entry: BackendModel) => entry.id)).toEqual(['alpha']);});it('keeps a confirmed focused removal on screen until its forced resend lands', async () => {@@ -573,6 +605,65 @@ describe('BackendModelCatalogDialog', () => {expect(JSON.stringify(second.would_interrupt)).toBe(JSON.stringify([]));});+ it('MH-UNLISTED-002: names the Agents a removed row stops when the row has no route, then echoes that plan', async () => {+ const user = userEvent.setup();+ // No route goes with `beta`: the guard refuses only because Agents select it.+ const gaps = [{ backend: 'claude' as const, model_id: 'beta', agents: ['pm', '写作助手'] }];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, gaps, [], [], 409,+ ))+ .mockResolvedValue(agent([model('alpha')]));+ const { onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));+ const guard = await screen.findByRole('dialog', { name: 'Save the model list?' });+ expect(guard.textContent).toContain(i18n.t('settings.models.gateway.catalog.guardSubtitleInUse'));+ expect(guard.textContent).not.toContain(i18n.t('settings.models.gateway.catalog.guardSubtitle'));+ expect(within(guard).getByText('Agents pinned to it: pm, 写作助手')).toBeTruthy();++ await user.click(within(guard).getByRole('button', { name: 'Remove anyway' }));+ await waitFor(() => expect(onClose).toHaveBeenCalledWith(undefined));+ expect(write).toHaveBeenCalledTimes(2);+ const confirmed = write.mock.calls[1][1] as Record<string, unknown>;+ expect(confirmed.force).toBe(true);+ expect(JSON.stringify(confirmed.would_remove_hops)).toBe(JSON.stringify([]));+ expect(JSON.stringify(confirmed.would_interrupt)).toBe(JSON.stringify(gaps));+ });++ it('MH-UNLISTED-002: asks again before a confirmed save stops an Agent the guard did not show', async () => {+ const user = userEvent.setup();+ const shown = [{ backend: 'claude' as const, model_id: 'beta', agents: ['pm'] }];+ const grown = [{ backend: 'claude' as const, model_id: 'beta', agents: ['ops', 'pm'] }];+ const refusal = (gaps: typeof shown) => new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, gaps, [], [], 409,+ );+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(refusal(shown))+ .mockRejectedValueOnce(refusal(grown))+ .mockResolvedValue(agent([model('alpha')]));+ const { onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));+ const first = await screen.findByRole('dialog', { name: 'Save the model list?' });+ expect(within(first).getByText('Agents pinned to it: pm')).toBeTruthy();+ await user.click(within(first).getByRole('button', { name: 'Remove anyway' }));++ // pm was agreed to; ops was never shown, so the grown plan is asked, not forced.+ await screen.findByText('Agents pinned to it: ops, pm');+ expect(write).toHaveBeenCalledTimes(2);+ expect(onClose).not.toHaveBeenCalled();++ await user.click(within(screen.getByRole('dialog', { name: 'Save the model list?' })).getByRole('button', { name: 'Remove anyway' }));+ await waitFor(() => expect(onClose).toHaveBeenCalledWith(undefined));+ expect(write).toHaveBeenCalledTimes(3);+ expect(write.mock.calls[2][1]).toMatchObject({ force: true, would_remove_hops: [], would_interrupt: grown });+ });+it('keeps the confirmed guard mounted and busy until the forced save lands', async () => {const user = userEvent.setup();const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsxindex 243db86dc..c4db5b767 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx@@ -41,6 +41,7 @@ import { BackendModelEditorDialog } from './BackendModelEditorDialog';import { BackendModelPickerDialog } from './BackendModelPickerDialog';import { GuardDialog } from './GuardDialog';import { GuardImpact, type GuardPicture, type GuardPlan } from './GuardImpact';+import { agreementCovers } from './guardedWrite';import { apiFailure, modelsApi } from './modelsApi';import { movedOrder, sameIds } from './reorder';import { catalogSaveFailureKey, catalogSaveLeftUnloaded } from './serverCopy';@@ -527,7 +528,10 @@ export const BackendModelCatalogDialog: React.FC<{* this save — the guard dialog's confirm, or the focused removal's own. With* it, a guard refusal is resent forced with the server's plan; without it,* the refusal opens the one guard dialog. `confirmed` is the plan the forced- * write echoes.+ * write echoes, and the plan the user was shown. An agreement given without+ * one is the focused confirmation's, which shows only the hops this dialog+ * can see. Either way it covers only the Agents it showed (`agreementCovers`):+ * a refusal naming any other is asked over the list, never forced past the user.** Every resend runs inside this one tracked write, so the promise it returns* — and the confirmation surface waiting on it — spans the whole sequence.@@ -647,13 +651,15 @@ export const BackendModelCatalogDialog: React.FC<{// missing. A user who already agreed is not asked again — the write goes// again echoing the server's plan, even when that plan differs from the// one they saw, because what they agreed to was removing these models.+ // An agreement covers only the Agents it showed, so a plan naming any+ // other is asked over the list rather than forced past them.// A plan that keeps moving past the bound ends as the refusal below,// never as a second question. Otherwise the plan opens the one guard// dialog, and the draft stays exactly as the user left it behind it.const refusal = failure?.code === MODEL_IN_ROUTE ? failure : null;if (refusal && (refusal.wouldRemoveHops.length > 0 || refusal.wouldInterrupt.length > 0)) {const next: GuardPlan = { hops: refusal.wouldRemoveHops, gaps: refusal.wouldInterrupt };- if (!agreed) return next;+ if (!agreed || !agreementCovers(confirmed ?? null, next)) return next;if (resends < FORCED_RESENDS) {plan = next;resends += 1;@@ -960,7 +966,11 @@ export const BackendModelCatalogDialog: React.FC<{<GuardDialogopen={guardPlan !== null}title={t('settings.models.gateway.catalog.guardTitle')}- subtitle={t('settings.models.gateway.catalog.guardSubtitle')}+ // With no route hops, the plan is only the Agents that still select a+ // removed row, so the route sentence would describe nothing it shows.+ subtitle={guardPlan && guardPlan.hops.length === 0+ ? t('settings.models.gateway.catalog.guardSubtitleInUse')+ : t('settings.models.gateway.catalog.guardSubtitle')}confirmLabel={t('settings.models.guard.confirm.removeModel')}busy={busy}onCancel={() => setGuardPlan(null)}diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsxindex 4c3927288..854b7f969 100644--- a/ui/src/components/settings/models/RouteChainDialog.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.tsx@@ -23,7 +23,7 @@ import { cn } from "@/lib/utils";import { useIsMobile } from "@/lib/useIsMobile";import { GuardDialog } from "./GuardDialog";import { GuardImpact, type GuardPlan } from "./GuardImpact";-import { confirmGuardPlan, guardedFailure, sendAgreed } from "./guardedWrite";+import { confirmGuardPlan, sendAgreed, unansweredRefusal } from "./guardedWrite";import { RouteCandidatePopover } from "./RouteCandidatePopover";import { RecordedTurnBadge, RecordedTurnDetails, RouteRecordedTurn } from './RouteRecordedTurn';import { recordedOn, useRecordedTurn } from './recordedTurn';@@ -556,11 +556,11 @@ export const RouteChainDialog: React.FC<{return;}const refusal = failure?.code === "source_last_supplier" || failure?.code === "source_in_route_chain"- ? guardedFailure(error)+ ? unansweredRefusal(error, confirmation !== undefined, confirmation ?? null): null;- // Only an initial save reaches here with a plan: a confirmed one resends- // the recomputed plan itself, so the question is asked once per save.- if (refusal && !confirmation) {+ // A confirmed save resends the recomputed plan itself, so the question is+ // asked once per save — unless that plan stops an Agent it did not show.+ if (refusal) {setGuard(refusal);setPhase("ready");return;diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex 987ef3391..c34a689e2 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -88,10 +88,18 @@ const submitManagementWrite = async (action: UnknownWriteAction, forced: booleanreturn;}- // A deletion is confirmed before its first attempt, so a guard refusal is- // forced through with no second click.+ // A deletion is confirmed before its first attempt, which agrees to the hops+ // it takes but shows no Agent: the one the guard names is confirmed first.await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));+ if (forced) await confirmShownAgents();+};++/** Confirm the guard once it names the Agent the held plan would stop. */+const confirmShownAgents = async () => {+ const guard = await screen.findByRole('dialog');+ await within(guard).findByText(/Release bot/);+ await userEvent.click(within(guard).getByRole('button', { name: /^Remove source$|^移除供应商$/i }));};const noReauth = () => {@@ -432,9 +440,11 @@ describe('SourceDetailPanel', () => {expect(commits[0].impact).toEqual({ hops, gaps });});- it('forces a guarded source deletion with the server plan, byte for byte, without asking twice', async () => {+ it.each([+ ['takes only hops, without asking twice', []],+ ['would stop an Agent, once that Agent is shown', [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }]],+ ])('forces a guarded source deletion that %s, echoing the server plan byte for byte', async (_, gaps) => {const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 2, source_id: source.id, model_id: 'model-a' }];- const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];const requests: { url: string; init?: RequestInit }[] = [];vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {const url = String(input);@@ -453,6 +463,12 @@ describe('SourceDetailPanel', () => {await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));+ if (gaps.length > 0) {+ // The first confirmation showed no Agent, so nothing is removed until it does.+ await screen.findByText(/Release bot/);+ expect(requests).toHaveLength(1);+ await confirmShownAgents();+ }await waitFor(() => expect(requests).toHaveLength(2));expect(requests[0].url).not.toContain('force=true');@@ -597,6 +613,7 @@ describe('SourceDetailPanel', () => {await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));+ await confirmShownAgents();await userEvent.click(await screen.findByRole('button', { name: /^Try again$|^重试$/i }));await waitFor(() => expect(requests).toHaveLength(3));diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex bad4c624b..ccead06f5 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -15,7 +15,7 @@ import { classifyModelHubFailure } from './asyncLifetime';import { Field } from './dialogFields';import { GuardDialog } from './GuardDialog';import { GuardImpact } from './GuardImpact';-import { confirmGuardPlan, guardedFailure, sendAgreed } from './guardedWrite';+import { confirmGuardPlan, sendAgreed, unansweredRefusal } from './guardedWrite';import { ModelHubInfoHint } from './ModelHubInfoHint';import { SourcePrivateValue, SourcePrivacyToggle } from './SourcePrivacy';import { useSourceDetailsHidden } from './sourcePrivacyPreference';@@ -225,8 +225,9 @@ export const SourceDetailPanel: React.FC<{if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);else {// A confirmed refetch was already answered: a plan that kept moving- // past the resend bound ends as a failure, never a second question.- const refusal = plan === null ? guardedFailure(error) : null;+ // past the resend bound ends as a failure, never a second question —+ // unless it now stops an Agent the confirmation did not show.+ const refusal = unansweredRefusal(error, plan !== null, plan);if (refusal) {setGuard({ kind: 'refetch', plan: refusal });settlement.release();@@ -364,7 +365,7 @@ export const SourceDetailPanel: React.FC<{} catch (error) {if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);else {- const refusal = plan === null ? guardedFailure(error) : null;+ const refusal = unansweredRefusal(error, plan !== null, plan);if (refusal) {setGuard({ kind: 'removeModel', model, plan: refusal });settlement.release();@@ -504,7 +505,7 @@ export const SourceDetailPanel: React.FC<{} else if (classifyModelHubFailure(failure) === 'inconclusive') {await reconcileEditWrite(latest, draft, patch, sent, settlement);} else {- const refusal = forced ? null : guardedFailure(error);+ const refusal = unansweredRefusal(error, forced, plan);if (refusal) {dispatchManageStage({ type: 'guard_edit', draft, patch, plan: refusal });settlement.release();@@ -530,8 +531,9 @@ export const SourceDetailPanel: React.FC<{setPendingAction('other');return trackMutation(async (latest, settlement) => {// Deleting is confirmed before the first attempt, and that confirmation- // says it removes the source from every route that uses it — so whatever- // plan the guard names is already agreed to.+ // says it removes the source from every route that uses it — so the hops+ // the guard names are already agreed to. An Agent it would stop is not:+ // that plan is asked in the same dialog before anything is removed.let sent = plan;try {const answer = await sendAgreed(true, plan, (next) => {@@ -559,7 +561,9 @@ export const SourceDetailPanel: React.FC<{} else if (classifyModelHubFailure(failure) === 'inconclusive') {await reconcileDeleteWrite(latest, sent, settlement);} else {- dispatchManageStage({ type: 'fail_delete', plan: sent, forced: sent !== null, retryRead: false, before: latest });+ const refusal = unansweredRefusal(error, true, plan);+ if (refusal) dispatchManageStage({ type: 'guard_delete', plan: refusal });+ else dispatchManageStage({ type: 'fail_delete', plan: sent, forced: sent !== null, retryRead: false, before: latest });settlement.release();}}@@ -621,7 +625,7 @@ export const SourceDetailPanel: React.FC<{if (manageStage.kind === 'confirming_edit') {void submitEdit(manageStage.draft, manageStage.patch, manageStage.plan);}- if (manageStage.kind === 'confirming_delete') void submitDelete(null);+ if (manageStage.kind === 'confirming_delete') void submitDelete(manageStage.plan);};const confirmGuard = () => {if (!guard) return;diff --git a/ui/src/components/settings/models/guardedWrite.test.ts b/ui/src/components/settings/models/guardedWrite.test.tsnew file mode 100644index 000000000..5888448a1--- /dev/null+++ b/ui/src/components/settings/models/guardedWrite.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, vi } from 'vitest';++import type { GuardPlan } from './GuardImpact';+import { sendAgreed, unansweredRefusal } from './guardedWrite';+import { ApiCallError } from './modelsApi';++const hop = (position: number) => ({+ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position,+});+const gap = (model_id: string, agents: string[]) => ({ backend: 'claude' as const, model_id, agents });+const refusal = (plan: GuardPlan) => new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, plan.gaps, [], plan.hops, 409,+);++describe('sendAgreed', () => {+ const shown: GuardPlan = { hops: [hop(1)], gaps: [gap('beta', ['pm', '写作助手'])] };++ it.each([+ ['moved hops under the same Agents', { hops: [hop(2)], gaps: shown.gaps }, true],+ ['fewer Agents than were shown', { hops: [hop(1)], gaps: [gap('beta', ['pm'])] }, true],+ ['a gap for a model that was not shown', { hops: [hop(1)], gaps: [...shown.gaps, gap('gamma', [])] }, false],+ ['an Agent that was not shown', { hops: [hop(1)], gaps: [gap('beta', ['pm', '写作助手', 'ops'])] }, false],+ ])('MH-UNLISTED-002: forces an agreed plan only while it stops no Agent the user was not shown: %s', async (_, moved, forced) => {+ const write = vi.fn()+ .mockRejectedValueOnce(refusal(moved))+ .mockResolvedValue('saved');++ const outcome = sendAgreed(true, shown, write);++ if (forced) {+ await expect(outcome).resolves.toBe('saved');+ expect(write.mock.calls.map(([plan]) => plan)).toEqual([shown, moved]);+ } else {+ const error = await outcome.catch((caught: unknown) => caught);+ expect(write).toHaveBeenCalledTimes(1);+ expect(unansweredRefusal(error, true, shown)).toEqual(moved);+ }+ });++ it('treats an agreement given before the server spoke as showing no Agent', async () => {+ const hopsOnly: GuardPlan = { hops: [hop(1)], gaps: [] };+ const withAgent: GuardPlan = { hops: [hop(1)], gaps: [gap('beta', ['pm'])] };+ const write = vi.fn()+ .mockRejectedValueOnce(refusal(hopsOnly))+ .mockRejectedValueOnce(refusal(withAgent));++ const error = await sendAgreed(true, null, write).catch((caught: unknown) => caught);++ expect(write.mock.calls.map(([plan]) => plan)).toEqual([null, hopsOnly]);+ expect(unansweredRefusal(error, true, null)).toEqual(withAgent);+ });++ it('ends a covered plan that keeps moving as a failure, not a question', async () => {+ const write = vi.fn(async (plan: GuardPlan | null) => {+ throw refusal({ hops: [hop((plan?.hops[0]?.position ?? 0) + 1)], gaps: shown.gaps });+ });++ const error = await sendAgreed(true, shown, write).catch((caught: unknown) => caught);++ expect(write).toHaveBeenCalledTimes(3);+ expect(unansweredRefusal(error, true, shown)).toBeNull();+ expect(unansweredRefusal(error, false, null)).not.toBeNull();+ });+});diff --git a/ui/src/components/settings/models/guardedWrite.ts b/ui/src/components/settings/models/guardedWrite.tsindex bd288323d..44928d8b9 100644--- a/ui/src/components/settings/models/guardedWrite.ts+++ b/ui/src/components/settings/models/guardedWrite.ts@@ -15,28 +15,57 @@ export const guardedFailure = (error: unknown): GuardPlan | null => {return { hops: failure.wouldRemoveHops, gaps: failure.wouldInterrupt };};+/**+ * Whether agreeing to `shown` also agrees to a refusal that names `next`.+ *+ * Agreeing to a removal covers whichever hops go with it, so hops may move+ * freely. Stopping an Agent is a consequence of its own, so every gap `next`+ * names — and every Agent within it — must be one the user was shown. `null`+ * is an agreement given before the server spoke, which showed no gap at all.+ */+export const agreementCovers = (shown: GuardPlan | null, next: GuardPlan): boolean => next.gaps.every((gap) => {+ const seen = shown?.gaps.find((item) => item.backend === gap.backend && item.model_id === gap.model_id);+ return seen !== undefined && gap.agents.every((agent) => seen.agents.includes(agent));+});++/**+ * The plan a failed guarded write still has to ask the user about, or null.+ *+ * Without an agreement every guard refusal is a question. With one, only a+ * refusal the agreement does not cover is: a covered plan that kept moving past+ * the resend bound has been answered already, and ends as the failure it is.+ */+export const unansweredRefusal = (error: unknown, agreed: boolean, shown: GuardPlan | null): GuardPlan | null => {+ const refusal = guardedFailure(error);+ return refusal && (!agreed || !agreementCovers(shown, refusal)) ? refusal : null;+};+const FORCED_RESENDS = 2;/*** Send a guarded write, echoing `plan` as its confirmation when there is one.** Once the user has `agreed`, a guard that refuses the write names the plan as- * it stands now, and that answer already covers it: the write goes again with- * the new plan rather than asking the same question twice. Bounded, so a plan- * that never settles still ends as the refusal it is. `write` receives the plan- * each attempt echoes, so a caller can tell which one its outcome belongs to.+ * it stands now, and that answer already covers it as long as it stops no Agent+ * the user was not shown: the write goes again with the new plan rather than+ * asking the same question twice. A refusal the agreement does not cover is+ * thrown for its caller to ask, and `unansweredRefusal` tells the two apart.+ * Bounded, so a plan that never settles still ends as the refusal it is.+ * `write` receives the plan each attempt echoes, so a caller can tell which one+ * its outcome belongs to.*/export const sendAgreed = async <T,>(agreed: boolean,plan: GuardPlan | null,write: (plan: GuardPlan | null) => Promise<T>,): Promise<T> => {+ const shown = plan;for (let resends = 0; ; resends += 1) {try {return await write(plan);} catch (error) {const moved = agreed && resends < FORCED_RESENDS ? guardedFailure(error) : null;- if (!moved) throw error;+ if (!moved || !agreementCovers(shown, moved)) throw error;plan = moved;}}diff --git a/ui/src/components/settings/models/manage.test.ts b/ui/src/components/settings/models/manage.test.tsindex de9f88667..32ca7f54d 100644--- a/ui/src/components/settings/models/manage.test.ts+++ b/ui/src/components/settings/models/manage.test.ts@@ -167,7 +167,7 @@ describe('source management capabilities', () => {submitting_edit: { kind: 'submitting_edit', draft, patch, plan: null, forced: false, surface: 'edit' },confirming_edit: { kind: 'confirming_edit', draft, patch, plan },edit_failed: { kind: 'edit_failed', draft, patch, plan, forced: true, retryRead: true, before },- confirming_delete: { kind: 'confirming_delete' },+ confirming_delete: { kind: 'confirming_delete', plan: null },submitting_delete: { kind: 'submitting_delete', plan, forced: true },delete_failed: { kind: 'delete_failed', plan, forced: true, retryRead: true, before },committed_edit: { kind: 'committed_edit' },diff --git a/ui/src/components/settings/models/manage.ts b/ui/src/components/settings/models/manage.tsindex e82934d15..b6938acba 100644--- a/ui/src/components/settings/models/manage.ts+++ b/ui/src/components/settings/models/manage.ts@@ -60,7 +60,7 @@ export type ManageStage =| { kind: 'submitting_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; surface: 'edit' | 'guard' }| { kind: 'confirming_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan }| { kind: 'edit_failed'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }- | { kind: 'confirming_delete' }+ | { kind: 'confirming_delete'; plan: ManageGuardPlan | null }| { kind: 'submitting_delete'; plan: ManageGuardPlan | null; forced: boolean }| { kind: 'delete_failed'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }| { kind: 'committed_edit' }@@ -118,7 +118,7 @@ export const MANAGE_STAGE_RETRY = {forced: stage.forced,surface: 'edit',}),- confirming_delete: () => ({ kind: 'submitting_delete', plan: null, forced: false }),+ confirming_delete: (stage) => ({ kind: 'submitting_delete', plan: stage.plan, forced: stage.plan !== null }),submitting_delete: keepManageStage,delete_failed: (stage) => ({kind: 'submitting_delete',@@ -174,6 +174,7 @@ export type ManageStageEvent =| { type: 'begin_delete' }| { type: 'submit_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; surface: 'edit' | 'guard' }| { type: 'submit_delete'; plan: ManageGuardPlan | null }+ | { type: 'guard_delete'; plan: ManageGuardPlan }| { type: 'guard_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan }| { type: 'fail_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }| { type: 'fail_delete'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }@@ -196,7 +197,7 @@ const applyManageStageTransition = <Event,>(export const transitionManageStage = (stage: ManageStage, event: ManageStageEvent): ManageStage => {switch (event.type) {case 'begin_edit': return { kind: 'editing', draft: event.draft };- case 'begin_delete': return { kind: 'confirming_delete' };+ case 'begin_delete': return { kind: 'confirming_delete', plan: null };case 'submit_edit': return {kind: 'submitting_edit',draft: event.draft,@@ -210,6 +211,7 @@ export const transitionManageStage = (stage: ManageStage, event: ManageStageEvenplan: event.plan,forced: event.plan !== null,};+ case 'guard_delete': return { kind: 'confirming_delete', plan: event.plan };case 'guard_edit': return {kind: 'confirming_edit',draft: event.draft,diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 28f4eb7fe..1999490cb 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1057,6 +1057,7 @@"removeTitle": "Remove {{model}}?","guardTitle": "Save the model list?","guardSubtitle": "Removing these models also removes their routes.",+ "guardSubtitleInUse": "Agents still use these models. They cannot run until you choose another model for them.","empty": "No models yet. Add the first one.","noMatch": "No model matches this search","legacy": "This model engine build does not offer an editable model list yet. These are the models it currently exposes.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 747895018..1ad82ac3a 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1057,6 +1057,7 @@"removeTitle": "移除 {{model}}?","guardTitle": "保存模型列表?","guardSubtitle": "移除这些模型会同时移除它们的路由。",+ "guardSubtitleInUse": "仍有 Agent 在使用这些模型。移除后,需要为这些 Agent 改选其他模型才能继续运行。","empty": "还没有模型,先添加一个。","noMatch": "没有匹配的模型","legacy": "当前模型引擎版本还不支持编辑模型列表,以下是它当前提供的模型。",diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 7f35320c5..db9107f8d 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -907,6 +907,11 @@"routingCanceled": "Routing update canceled."},"modelHub": {+ "backends": {+ "claude": "Claude Code",+ "codex": "Codex",+ "opencode": "OpenCode"+ },"errors": {"source_not_found": "Model source not found.","flow_not_found": "Authorization flow not found.",@@ -988,6 +993,7 @@"waiting_without_retry": "This request could not complete. Automatic recovery has ended. You can retry model {model} or choose another model.","interrupted": "Model {model} is unavailable: {blockers}. Open Models to resolve it.","route_unconfigured": "Model {model} has no configured route. Open Models to configure one.",+ "model_unlisted": "Model {model} is not in the {backend} model list. Choose another model to continue.","request_incompatible": "This request is incompatible; switching Sources will not help.","request_incompatible_detail": "This request was rejected upstream and switching Sources will not help. Upstream said: {detail}"}diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e8bb965b2..b77916c07 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -907,6 +907,11 @@"routingCanceled": "已取消更新 Agent 路由设置。"},"modelHub": {+ "backends": {+ "claude": "Claude Code",+ "codex": "Codex",+ "opencode": "OpenCode"+ },"errors": {"source_not_found": "未找到模型供应商。","flow_not_found": "未找到授权流程。",@@ -988,6 +993,7 @@"waiting_without_retry": "本次请求未完成,自动恢复已结束。你可以重试模型 {model} 或切换模型。","interrupted": "模型 {model} 当前不可用:{blockers}。请前往「模型」页处理。","route_unconfigured": "模型 {model} 尚未配置路由。请前往「模型」页配置。",+ "model_unlisted": "模型 {model} 不在 {backend} 的模型列表中。请选择其他模型后继续。","request_incompatible": "此请求不兼容;切换模型供应商也无法解决。","request_incompatible_detail": "上游拒绝了此请求,切换模型供应商也无法解决。上游返回:{detail}"}