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): admit native subscription create and drop auth auto-open (#2217)
Call Whitea3692c9423e5
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex e4b38cbdd..728092681 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -505,7 +505,9 @@ class AgentAuthService:clients.append(flow.claude_client)return clients- def _acquire_native_lease(self, backend: str, *, source_id: str | None = None) -> NativeCredentialLease:+ def _acquire_native_lease(+ self, backend: str, *, source_id: str | None = None, new_source: bool = False+ ) -> NativeCredentialLease:try:lease = NativeCredentialLease((backend,)).acquire()except NativeMigrationBlockedError as error:@@ -521,7 +523,7 @@ class AgentAuthService:flow_id=getattr(owner, "flow_id", None),) from Nonetry:- lease.assert_auth_custody(backend, source_id=source_id)+ lease.assert_auth_custody(backend, source_id=source_id, new_source=new_source)return leaseexcept BaseException:lease.release()@@ -1318,6 +1320,7 @@ class AgentAuthService:provider_id: str | None = None,force_reset: bool = True,owner_ref: str | None = None,+ new_source: bool = False,claude_login_method: str | None = None,on_irreversible_start: Callable[[], Callable[[], None] | None] | None = None,) -> AgentAuthFlow | WebAuthFlow:@@ -1331,7 +1334,7 @@ class AgentAuthService:if existing is not None:await self._terminate_flow(existing)- lease = self._acquire_native_lease(backend, source_id=owner_ref)+ lease = self._acquire_native_lease(backend, source_id=owner_ref, new_source=new_source)try:provider = provider_idif backend == "opencode" and context is not None:@@ -2502,6 +2505,7 @@ class AgentAuthService:force_reset: bool = True,provider_id: Optional[str] = None,owner_ref: str | None = None,+ new_source: bool = False,on_irreversible_start: Callable[[], Callable[[], None] | None] | None = None,@@ -2517,6 +2521,9 @@ class AgentAuthService:must pass ``provider_id``; the URL (and optional device code) aresurfaced via ``WebAuthFlow.url`` / ``WebAuthFlow.device_code`` andcompletion follows its declared automatic or manual-code method.+ ``owner_ref`` binds the flow to a Model Hub Source; ``new_source``+ declares that Source is being created, which a Hub-routed backend+ admits only while its vendor has no native subscription yet."""if backend not in self.WEB_BACKENDS:raise ValueError(f"unsupported_backend:{backend}")@@ -2535,6 +2542,7 @@ class AgentAuthService:provider_id=provider_id,force_reset=force_reset,owner_ref=owner_ref,+ new_source=new_source,on_irreversible_start=on_irreversible_start,)except asyncio.CancelledError:diff --git a/core/backend_restart.py b/core/backend_restart.pyindex 21a4076b5..e4f3b6142 100644--- a/core/backend_restart.py+++ b/core/backend_restart.py@@ -121,13 +121,17 @@ class NativeCredentialLease:if backend not in self.backends or len(self._handles) != len(self.backends):raise RuntimeError("Native credential operation has no ownership")- def assert_auth_custody(self, backend: str, *, source_id: str | None = None) -> None:+ def assert_auth_custody(+ self, backend: str, *, source_id: str | None = None, new_source: bool = False+ ) -> None:"""Authorize a native writer from durable routing, while holding its lease.Runtime enablement is not credential ownership. A Hub backend may- maintain only the explicitly bound, retained native subscription;- generic Settings/IM login and API-key writes must use Hub instead.- Read without load-time migration writes: this is an admission check.+ maintain only the explicitly bound, retained native subscription, or+ create that subscription under a new Source id while the vendor's single+ native slot is empty; generic Settings/IM login and API-key writes must+ use Hub instead. Read without load-time migration writes: this is an+ admission check."""from config.v2_config import V2Config@@ -144,14 +148,17 @@ class NativeCredentialLease:if hub.agents[backend].mode == "direct":returnvendor = {"claude": "anthropic", "codex": "openai"}.get(backend)- if source_id is not None and vendor is not None and any(- source.id == source_id- and source.vendor == vendor- and source.kind == "subscription"- and source.supply_channel == "native_cli"- for source in hub.sources- ):- return+ if source_id is not None and vendor is not None:+ native = [+ source for source in hub.sources+ if source.vendor == vendor+ and source.kind == "subscription"+ and source.supply_channel == "native_cli"+ ]+ if any(source.id == source_id for source in native):+ return+ if new_source and not native and all(source.id != source_id for source in hub.sources):+ returnraise NativeMigrationBlockedError("native_auth_hub_owned", (backend,))def release(self) -> None:diff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.pyindex ce2f6d98c..163a6b278 100644--- a/core/handlers/model_hub/native_oauth.py+++ b/core/handlers/model_hub/native_oauth.py@@ -30,6 +30,7 @@ class AgentAuthService(Protocol):*,force_reset: bool = True,owner_ref: str | None = None,+ new_source: bool = False,on_irreversible_start: Callable[[], Callable[[], None] | None] | None = None,@@ -131,6 +132,7 @@ class AgentAuthNativeOAuthAdapter:source_id,vendor,force_reset=False,+ new_source=True,)async def start_reauth(@@ -155,6 +157,7 @@ class AgentAuthNativeOAuthAdapter:vendor: str,*,force_reset: bool,+ new_source: bool = False,on_irreversible_start: Callable[[], Callable[[], None] | None] | None = None,@@ -167,6 +170,7 @@ class AgentAuthNativeOAuthAdapter:backend,force_reset=force_reset,owner_ref=source_id,+ new_source=new_source,on_irreversible_start=on_irreversible_start,)flow_id = getattr(flow, "flow_id", None)diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.pyindex 0abd85608..be7e995ab 100644--- a/core/handlers/model_hub/oauth.py+++ b/core/handlers/model_hub/oauth.py@@ -499,6 +499,23 @@ class OAuthFlowRegistry:return flow_id, bindingreturn None+ def pending_creates(+ self,+ vendor: str,+ channel: OAuthChannel,+ ) -> tuple[tuple[str, OAuthFlowBinding], ...]:+ with self._lock:+ flows = self._read()+ return tuple(+ (flow_id, binding)+ for flow_id, binding in flows.items()+ if binding.vendor == vendor+ and binding.channel == channel+ and binding.intent == "create"+ and not binding.completed+ and binding.terminal_state is None+ )+def forget(self, flow_id: str) -> None:with self._lock:flows = self._read()diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex a357caabc..aaa06f981 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -1076,6 +1076,35 @@ class ModelHubService:None,)+ async def _settle_pending_native_creates(self, vendor: str) -> None:+ """Keep the native slot claimed until a finished create is committed.++ The CLI login releases its credential lease as soon as it finishes, but+ its Source is committed only by a later status read. In between, the+ slot looks empty to both the singleton check and CLI custody, so another+ start would be admitted and overwrite the credential that login just+ wrote. Commit a finished create first, so the singleton check sees it,+ and refuse while one is still in progress.+ """++ for flow_id, binding in self.oauth_flows.pending_creates(vendor, "native_cli"):+ try:+ flow = await self._oauth_status(flow_id, "native_cli")+ self._raise_if_flow_expired(flow_id, flow)+ except ModelHubError as error:+ # Both reads forget a flow that can no longer finish.+ if error.code in {"flow_not_found", "flow_expired"}:+ continue+ raise+ if flow.state == "success":+ await self._materialize_completed_oauth(flow_id, binding, flow)+ elif flow.state not in {"failed", "cancelled"}:+ raise ModelHubError(+ "native_login_in_progress",+ status=409,+ detail="modelHub.errors.native_login_in_progress",+ )+async def _engine_call(self, awaitable):try:return await awaitable@@ -1114,7 +1143,19 @@ class ModelHubService:raise ModelHubError("submission_rejected", status=422) from Noneexcept ModelHubError:raise- except Exception:+ except Exception as error:+ from core.backend_restart import NativeMigrationBlockedError++ # A native writer refusal is an answered state, not an engine+ # outage: reporting it as engine_down sends the user retrying a+ # start that the same refusal will block again.+ if isinstance(error, NativeMigrationBlockedError):+ code = (+ error.reason+ if error.reason in {"config_recovery", "migration_recovery_pending"}+ else "migration_native_busy"+ )+ raise ModelHubError(code, status=409) from Noneraise ModelHubError("engine_down", status=503) from Nonedef _bindings(self, config: ModelHubConfig) -> list[SourceBinding]:@@ -6547,6 +6588,7 @@ class ModelHubService:flow_cleanup_attempted = Falsetry:if oauth_channel == "native_cli":+ await self._settle_pending_native_creates(vendor)async with self._mutation_lock:# The sanctioned CLI keeps one credential per vendor, so# a second native Source would describe a credential thediff --git a/docs/plans/model-hub-native-takeover.md b/docs/plans/model-hub-native-takeover.mdindex b2c11e00f..b70a6a4e5 100644--- a/docs/plans/model-hub-native-takeover.md+++ b/docs/plans/model-hub-native-takeover.md@@ -344,7 +344,12 @@ reintroduce credentials after a successful handoff. The correction coversevery Avibe writer of those shared documents for the full read-modify-writeduration. Authentication writes also consult persisted Direct/native-Sourceownership after acquiring the lease; stopping the Hub runtime does not hand-custody back. Non-authentication edits may continue under the shared lease.+custody back. A Hub-owned backend admits a native login only for its bound+native Source, or for an explicit Model Hub create while that vendor's single+native slot is empty and the new Source id is unused; generic Settings and IM+login stay refused. That slot stays claimed from the start until the finished+create is committed as a Source: the next native start commits it or waits,+because the CLI lease ends before the Source exists. Non-authentication edits may continue under the shared lease.Claude's interrupted-OAuth settings backup is included in the migrationinventory and cleanup, so constructor recovery cannot restore a replaced key.This scope preserves legacy native subscription Sources until explicitdiff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex 7baddc4cf..202fbf974 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -706,7 +706,7 @@ registration, not something a reviewer is expected to infer from prose.| C9 — report-free reconciliation failure | For every committed mutation that skips its report because impact arrays are empty or unavailable after D-36 inference, register the pending/failure states, held write evidence and read-only Retry | [x] Route M6 is page-owned after the editor closes. It holds the returned chain plus empty tails, or the exact matching AgentChain GET readback plus unavailable response tails, while AR-M is pending. An Agents-first failure settles as the exact failed Retry subset while mode-dependent companions remain deferred and non-stale; every other AR-M3 result likewise retains every success and exposes Retry on the affected page projection only | [x] M1, or M2 through M0, enters Committed projection stale with the updated Source or committed absence plus exact empty/unavailable disposition held; Retry repeats only its complete-surface read | [x] A non-blocked M3/M4 empty envelope or RR-7 inferred commit with an unavailable response tail enters the same state; a blocked R3 result stays in Repair unresolved instead | [x] N/A — the menu commits nothing and invalidates no projection || C10 — mutation attempt scope and commit evidence | For every mutation covered by this frame group, name every projection its attempt may invalidate before the response is observed; both a received success envelope and authoritative D-36 commit evidence MUST pass through the owning M row before visible exit, with response-only members marked unavailable rather than invented | [x] R6 owns every received member; exact ordered D-36 readback enters page-owned Route M6 with `removed_hops` / `interrupted` unavailable. The editor closes only after that evidence is installed; the shared success toast is presentation feedback, not a substitute for M6 | [x] R1/R2 own received save/delete envelopes; D-36 inferred save/delete commits enter the same M1/M2 reads with response-only impact arrays unavailable | [x] RR-1–RR-10 name repair attempt scope; R3/R4 classify received Source outcome, while RR-7 inferred repair commit enters M3/M4 with its absent response tail explicitly unavailable | [x] N/A — vendor selection commits nothing; create's later mutation remains owned by §1.4/RR-3 rather than the menu || C11 — workflow progress evidence | A broad transport or state class may not stand in for a later workflow milestone; register what each returned stage or external gesture proves and the exact next gesture/read it authorizes | [x] The route write has no accepted/intermediate state: only R6 or exact ordered D-36 readback proves commit; a shaped rejection is terminal for that attempt, while a nonmatching read is only an observation and never proves an unanswered PUT terminal or authorizes its resend | [x] Save/delete expose no intermediate accepted state: only an envelope or D-36 subject read proves commit, and both route through C10 | [x] Paste `starting` / `awaiting_action` proves action is still required; `verifying` proves submission acceptance. Opening a vendor link proves no recovery and enters the channel observation phase: Hub Refetch, native acknowledged Reauthorize | [x] Vendor selection transfers one closed value into §1.4 Default; it is not evidence that OAuth acquisition or login began |-| C12 — delayed required presentation | If a required presentation value may be absent now and supplied later, name the bounded read owner that can deliver it without starting another producer or browser context | [x] N/A — route replacement has no delayed server-declared presentation | [x] N/A — frame 11 has no server-declared presentation | [x] PD-5 gives a paste form whose `auth_url` is null to the held flow's 2s status-read owner; the first non-null value invokes PD-2 on the original context | [x] Vendor selection transfers to §1.4; it does not own a flow or delayed presentation value |+| C12 — delayed required presentation | If a required presentation value may be absent now and supplied later, name the bounded read owner that can deliver it without starting another producer or browser context | [x] N/A — route replacement has no delayed server-declared presentation | [x] N/A — frame 11 has no server-declared presentation | [x] PD-5 gives a paste form whose `auth_url` is null to the held flow's 2s status-read owner; the first non-null value renders PD-2's link and copy control | [x] Vendor selection transfers to §1.4; it does not own a flow or delayed presentation value || C13 — terminal / absence attempt scope | Every terminal code and authoritative subject absence after a producer attempt MUST account for that attempt's full invalidation scope before visible handoff; scope is selected by the evidence milestone, never by channel alone | [x] The producer has no terminal-flow or subject-absence code; `direct_mode` enters DM-1/DM-2/DM-3 without claiming a target projection, while every proven commit still passes M6 | [x] Every `source_not_found` and inferred deletion enters M0; M2 is M0's deletion-attempt reconciliation | [x] Create E4 owns no pre-existing Source scope and create E6 re-reads `Source[]`. Every acquired-flow reauth terminal failure enters RR-5's full M3 read for Hub or native; a pre-flow reauth acquisition failure retains RR-6–RR-9's selected-Source read for either channel | [x] N/A — the menu has made no producer attempt and owns no terminal code || C14 — non-mutating failure exit | Every modal failure state MUST offer an exit that sends no mutation; a committed-state exit preserves write evidence and marks unread dependent projections stale rather than restoring the origin | [x] Terminal rejection may abandon through ET-8a; a mounted unknown attempt is read-only and ET-8b explicitly abandons it, while only a forced Direct handoff transfers unknown evidence to the page session. Neither a nonmatching observation nor a read failure may resend the old attempt. A proven commit closes the editor, reveals the installed page authority and leaves any M6 retry on that page; it never restores the origin or opens a Done report | [x] Edit/remove failures cancel to their held draft/origin; Committed projection stale has Done-equivalent dismissal in addition to read-only Retry | [x] OAuth/repair failures can dismiss through their registered cleanup or Done-equivalent committed exit; neither path resends repair | [x] The menu's Escape / outside exit sends nothing and restores Add subscription focus || C15 — page-form landing evidence | Every response, terminal or absence branch that changes the mounted page form MUST name the authoritative payload or read that selects the destination. Successful authority is consumed monotonically: sibling failure cannot erase it, exact mode evidence cannot be overwritten, and a later failure cannot roll the page back to an older projection | [x] AR is the sole composite-read result owner. It records each member's acquisition eligibility and observation epoch against every causal frontier that can invalidate that member, dispatches each successful AgentSupply for mode/page authority immediately, uses only exact AgentChain GET equality as D-36 Route evidence, and recalculates the applicable member set after either AgentSupply Direct or chain `direct_mode`. A failed Agents prerequisite defers rather than fabricates companion observations. LF is the closed landing read-set owner: exact Direct retains every settled independent Source authority; each exact Hub landing installs AgentSupply immediately, establishes a new Source landing frontier and cannot call Sources current until a successor Source observation satisfies it. DM errors retire an illegal editor but never invent a landing payload; PF-1 is fallback-only after installation | [x] R1/R2 and M0–M2 hand their exact returned or reread Source/absence evidence to the page. Their complete-surface results dispatch returned mode before installing a page form; an error class selects no destination by itself | [x] R3/R4 and M0/M3/M4 hand their exact returned or reread Source evidence to the page. Their complete-surface results dispatch returned mode before installing a page form; flow/error classes select failure handling, never a healthy landing | [x] N/A — the menu changes only its own reversible phase and hands one explicit local vendor selection to §1.4; no response or terminal branch changes the page form |@@ -808,8 +808,8 @@ applicable cell has no transition.| Fixture | Producer / evidence now held | Held origin | Intent | Producer-attempt invalidation scope | Returned Source outcome | Required disposition || --- | --- | --- | --- | --- | --- | --- |-| RR-1 | OAuth acquisition returns `flow.state` `starting`, `awaiting_action` or `verifying` | none for create; exact Source projection for reauth | create / reauth | Create has no pre-existing Source to invalidate. Hub reauth holds the selected Source scope. An accepted `native_cli` reauth has already invalidated every same-backend native Source plus the dependent Agent/order/chain projections | None yet: acquisition carries `flow`, not a repair tail. Flow state cannot assert that the Source is healthy or that paste input was accepted | PD-1 transfers the click-owned browser context to the flow; PD-2 navigates it whenever the active flow first carries non-null `auth_url` and keeps the visible fallback. Select the server-declared presentation form, then E3a/E3b owns progress: a paste form at `starting` / `awaiting_action` waits for the value, while `verifying` owns completion polling. The acquired flow owns cancellation and the registered invalidation scope until a later read settles it |-| RR-2 | OAuth acquisition returns any terminal flow | same as RR-1 | create / reauth | Same attempt scope as RR-1; terminal acquisition does not erase it | None yet: the terminal `flow` is not the materialized Source tail | Do **not** open or reconstruct a presentation form. PD-3 closes the unused context and immediately reads `GET /api/models/oauth/status/<flow_id>`; only that route materializes and returns the terminal tail. E2 remains inconclusive under §1.4's evidence-class matrix |+| RR-1 | OAuth acquisition returns `flow.state` `starting`, `awaiting_action` or `verifying` | none for create; exact Source projection for reauth | create / reauth | Create has no pre-existing Source to invalidate. Hub reauth holds the selected Source scope. An accepted `native_cli` reauth has already invalidated every same-backend native Source plus the dependent Agent/order/chain projections | None yet: acquisition carries `flow`, not a repair tail. Flow state cannot assert that the Source is healthy or that paste input was accepted | PD-1 opens no browser context; PD-2 renders the link and copy control whenever the active flow first carries non-null `auth_url`. Select the server-declared presentation form, then E3a/E3b owns progress: a paste form at `starting` / `awaiting_action` waits for the value, while `verifying` owns completion polling. The acquired flow owns cancellation and the registered invalidation scope until a later read settles it |+| RR-2 | OAuth acquisition returns any terminal flow | same as RR-1 | create / reauth | Same attempt scope as RR-1; terminal acquisition does not erase it | None yet: the terminal `flow` is not the materialized Source tail | Do **not** open or reconstruct a presentation form. PD-3 renders no link and immediately reads `GET /api/models/oauth/status/<flow_id>`; only that route materializes and returns the terminal tail. E2 remains inconclusive under §1.4's evidence-class matrix || RR-3 | Status or submit returns terminal success with the create tail | no Source origin | create | The newly returned Source and its placement projections; no held pre-create Source exists | The returned Source becomes 06's subject. It is not classified by repair outcome rules | §1.4 consumes every member, closes into 06 for the returned `source`, and carries its placement arrays || RR-4 | Status or submit returns terminal success with the repair tail | exact Source projection | reauth | M3's complete model surface; for native this includes every same-backend native sibling already named by RR-1 | Three exhaustive outcomes: `needs_action` / `error` → Repair unresolved regardless of pair count; non-blocked + non-empty `interrupted_pairs` → Repair impact reported; non-blocked + empty pairs → M3 handoff | R3 consumes every member. Hold returned `source`; render every non-empty `interrupted_pairs` block in the selected result. `recovered` remains past-state evidence only. Empty pairs never claim that repair succeeded || RR-5 | Status/submit returns E6's `discovery_failed` / `migration_item_conflict`; or an acquired reauth flow returns terminal `failed` / `cancelled`, E8 `flow_not_found`, or E9 `flow_expired` | none / exact Source projection | create / reauth | Create re-reads `Source[]`. Every acquired-flow reauth terminal failure reads M3's complete model surface **before** handoff, for Hub or native; native includes same-backend siblings. The acquired-flow terminal milestone, not the channel, selects this scope. RR-6–RR-9 pre-flow reauth acquisition failure keeps a selected-Source read for either channel | No successful repair tail exists. For reauth the exact Source is absent, present, or unread; a present reread is projection evidence, not a substitute success envelope. E6 may additionally hold R5's exact nonempty error-envelope `interrupted_pairs`, which remains rendered through the read; absence is no report, not empty success | Stop polling, hold the intent-specific failure and any exact R5 report, then perform the registered read. Absent or E7 → M0 / Source gone. A present settled E6 read keeps OAuth materialization failed and only then permits fresh acquisition; a present non-E6 terminal enters OAuth failed. Unread keeps the originating failure/report mounted and enables **only** read-only Retry of RR-5 before any resend. E2 stays in the bounded poll |@@ -972,10 +972,10 @@ state exit; held intent never bypasses the evidence column.| §1.3 | Empty order, held-out sources remaining | The ordered section is empty and the held-out section is not | F5 | `order.empty.ordered` | 排进来 → Dirty. 保存顺序 stays enabled — an empty order is a real configuration || §1.3 | Dirty (uncommitted moves) | 排进来, 移出, a drag, or a keyboard move | F5 — nothing has been sent, so nothing can fail | `order.action.include`, `order.action.exclude` | 保存顺序 → Saving; 取消 → discard, close || §1.3 | Saving | 保存顺序 pressed — send `{order: string[]}` to `PUT /api/models/agents/<backend>/sources`, which stores defaults and preserves manual overrides under effective guards `[contract]` | F1 | `order.save`, `order.fail.save`, `order.retry` | Success → close; failure → keep every move held and 重试 the same save |-| §1.4 | Default | A frame 13 vendor row has supplied the vendor | F5 | `addSub.title` … `addSub.hint.chatgpt` | The recommended option is pre-selected; selecting the other replaces it. 去登录 synchronously preallocates PD-1's blank browser context, then sends `POST /api/models/oauth/start`; RR-1/RR-2 classify any accepted flow **before** presentation: non-terminal transfers the context to PD-2, then `presentation.expects: none` → Awaiting sign-in, a paste presentation in E3a `starting` / `awaiting_action` → Awaiting paste-back, and a paste presentation already in E3b `verifying` → Awaiting paste-back completion; each navigates when `presentation.auth_url` is non-null now or on a later flow read. Terminal → immediate status read with no form reopened. Refused because that backend already holds its one `native_cli` Source `[contract]` → Already bound, and any other answer that is not a flow → Start failed; either path closes an unused blank context. Polling, re-render and reconciliation never auto-open a second context `[derived]` |+| §1.4 | Default | A frame 13 vendor row has supplied the vendor | F5 | `addSub.title` … `addSub.hint.chatgpt` | The recommended option is pre-selected; selecting the other replaces it. 去登录 sends `POST /api/models/oauth/start` and opens no browser context (PD-1); RR-1/RR-2 classify any accepted flow **before** presentation: non-terminal enters PD-2, then `presentation.expects: none` → Awaiting sign-in, a paste presentation in E3a `starting` / `awaiting_action` → Awaiting paste-back, and a paste presentation already in E3b `verifying` → Awaiting paste-back completion; each renders the link and copy control when `presentation.auth_url` is non-null now or on a later flow read. Terminal → immediate status read with no form reopened. Refused because that backend already holds its one `native_cli` Source `[contract]` → Already bound, and any other answer that is not a flow → Start failed. No acquisition, poll, re-render or reconciliation ever opens a browser context `[derived]` || §1.4 | Second pass `[derived]` | Re-opened while this backend already holds its one `native_cli` source `[contract]` | F5 | `addSub.opt.added` | The native row is inert whichever account that source holds; the hub row stays choosable and is selected on open, whatever the recommendation says |-| §1.4 | Awaiting sign-in | An acquired flow carries `presentation.expects: none` and no `device_code`; Form B remains G-33. `GET /api/models/oauth/status/<flow_id>` is polled every 2s until the §1.4 evidence-class matrix selects an exit `[contract]` | → OAuth failed / OAuth materialization failed. E2 transport/outage evidence, including `engine_down`, is inconclusive and the next 2s tick retries under the same bound (D-16); E4 or E8/E9 with the held Source present/unread stops at OAuth failed; only E6's two materialization codes stop at OAuth materialization failed | `addSub.signIn`; PD-4 resolves `presentation.instructions_key` and uses the device-code helper on null or lookup failure | PD-2 keeps the authorization link actionable. E5 `success` → `intent: create` closes **into 06 for the source that terminal names** with `added_to` and `adopted_by` in hand; `intent: reauth` → §1.11's R3 repair terminal `[contract]`; E4 → OAuth failed; E8/E9 first run RR-5's registered read, then absent → M0 / Source gone, present or unread → OAuth failed (the unread branch retains read-only Retry); E7 → M0 / Source gone; the polling bound passes with no terminal reading → OAuth failed — the bound is `OAuthFlow.expires_at` when the flow carries one `[contract]` and 15 minutes from acquisition when it does not `[derived]`; dismissed any of the three ways → Dismissing |-| §1.4 | Awaiting paste-back | The flow carries `presentation.expects: paste_code` or `paste_callback_url` and E3a reads `starting` / `awaiting_action` `[contract]`; entry is either the acquired form with an empty draft or a submit/reconciliation return with its held value | F5 until submit; while `auth_url` is null, PD-5 owns a 2s presentation-delivery read under the existing bound and E2 remains inconclusive | `addSub.paste.title.code`, `addSub.paste.title.callbackUrl`, `addSub.paste.subtitle`, `addSub.paste.label.code`, `addSub.paste.label.callbackUrl`, `addSub.paste.placeholder.code`, `addSub.paste.placeholder.callbackUrl`; PD-4 resolves `presentation.instructions_key`, with `addSub.paste.hint.code` / `addSub.paste.hint.callbackUrl` on null or lookup failure; `addSub.paste.submit`, `addSub.cancel` | The first non-null URL from acquisition or PD-5 invokes PD-2 on the one original browser context; no second flow/context is opened. V4 gates 提交 → Submitting paste-back; only that explicit gesture sends or resends the held value. 取消 / close / outside press → Dismissing (C7/C11/C12/DP-3) |+| §1.4 | Awaiting sign-in | An acquired flow carries `presentation.expects: none` and no `device_code`; Form B remains G-33. `GET /api/models/oauth/status/<flow_id>` is polled every 2s until the §1.4 evidence-class matrix selects an exit `[contract]` | → OAuth failed / OAuth materialization failed. E2 transport/outage evidence, including `engine_down`, is inconclusive and the next 2s tick retries under the same bound (D-16); E4 or E8/E9 with the held Source present/unread stops at OAuth failed; only E6's two materialization codes stop at OAuth materialization failed | `addSub.signIn`; PD-4 resolves `presentation.instructions_key` and uses the device-code helper on null or lookup failure | PD-2 keeps the authorization link and its copy control actionable. E5 `success` → `intent: create` closes **into 06 for the source that terminal names** with `added_to` and `adopted_by` in hand; `intent: reauth` → §1.11's R3 repair terminal `[contract]`; E4 → OAuth failed; E8/E9 first run RR-5's registered read, then absent → M0 / Source gone, present or unread → OAuth failed (the unread branch retains read-only Retry); E7 → M0 / Source gone; the polling bound passes with no terminal reading → OAuth failed — the bound is `OAuthFlow.expires_at` when the flow carries one `[contract]` and 15 minutes from acquisition when it does not `[derived]`; dismissed any of the three ways → Dismissing |+| §1.4 | Awaiting paste-back | The flow carries `presentation.expects: paste_code` or `paste_callback_url` and E3a reads `starting` / `awaiting_action` `[contract]`; entry is either the acquired form with an empty draft or a submit/reconciliation return with its held value | F5 until submit; while `auth_url` is null, PD-5 owns a 2s presentation-delivery read under the existing bound and E2 remains inconclusive | `addSub.paste.title.code`, `addSub.paste.title.callbackUrl`, `addSub.paste.subtitle`, `addSub.paste.label.code`, `addSub.paste.label.callbackUrl`, `addSub.paste.placeholder.code`, `addSub.paste.placeholder.callbackUrl`; PD-4 resolves `presentation.instructions_key`, with `addSub.paste.hint.code` / `addSub.paste.hint.callbackUrl` on null or lookup failure; `addSub.paste.submit`, `addSub.cancel` | The first non-null URL from acquisition or PD-5 renders PD-2's link and copy control; no second flow is started and no browser context is opened. V4 gates 提交 → Submitting paste-back; only that explicit gesture sends or resends the held value. 取消 / close / outside press → Dismissing (C7/C11/C12/DP-3) || §1.4 | Submitting paste-back | 提交 pressed — `POST /api/models/oauth/submit` with the held `{flow_id, value}` `[contract]` | F1 → Paste-back failed for E2; only E6 → OAuth materialization failed | `addSub.paste.submitting` | E5 dispatches by held intent: `create` closes into 06; `reauth` → §1.11's R3 repair terminal. E4 → OAuth failed; E8/E9 first reconcile the reauth attempt scope, then absent → M0 / Source gone, present or unread → OAuth failed (read-only Retry when unread). E3a `starting` / `awaiting_action` proves the value was not accepted and returns to Awaiting paste-back with it retained; E3b `verifying` alone → Awaiting paste-back completion. E2 transport/no answer → Paste-back failed; E7 → M0 / Source gone || §1.4 | Awaiting paste-back completion `[contract]` | Submit or the reconciliation read below answered with `OAuthFlow.state: verifying`, which is E3b's positive evidence that the held paste value was accepted | The same §1.4 evidence-class matrix and expiry/15-minute bound as Awaiting sign-in: E2, including `engine_down`, continues; only E6 stops at materialization failure | `addSub.paste.submitting`, `addSub.cancel` | E5 dispatches by held intent: `create` closes into 06; `reauth` → §1.11's R3 repair terminal. E4 → OAuth failed; E8/E9 first reconcile the reauth attempt scope, then absent → M0 / Source gone, present or unread → OAuth failed (read-only Retry when unread); E3b stays here; E3a returns to Awaiting paste-back with the value retained for an explicit submit; E6 → OAuth materialization failed; E7 → M0 / Source gone. 取消 / close / outside press → Dismissing || §1.4 | Paste-back failed `[derived]` | The submit request returned E2 evidence — transport/no answer or an outage such as `engine_down` — so its flow outcome is unconfirmed | F1, in place; the input, `flow_id` and intent are kept | `addSub.paste.fail`, `addSub.retry`, `addSub.cancel` | 重试 first re-reads `GET /api/models/oauth/status/<flow_id>` (D-36): E5 dispatches by held intent to 06 or §1.11's R3 repair terminal; E4 → OAuth failed; E8/E9 first reconcile the reauth attempt scope, then absent → M0 / Source gone, present or unread → OAuth failed (read-only Retry when unread); E6 → OAuth materialization failed; E3a `starting` / `awaiting_action` → Awaiting paste-back with the value retained, where only an explicit 提交 resends it; E3b `verifying` → Awaiting paste-back completion without resubmission; E2 leaves this state unchanged; E7 → M0 / Source gone. 取消 → Dismissing |@@ -1039,8 +1039,8 @@ state exit; held intent never bypasses the evidence column.| §1.10 | Source removal committed `[derived]` `[contract]` | R2 holds a successful delete response, or D-36 proved the exact Source absent; the source is already gone | F2 for M2's complete-surface read; the read cannot negate the held delete response | `sourceDetail.remove.settlement.title`; on a failed read `toast.refreshFailed` and `sourceDetail.retry` | Drop the detail into 01, remove the exact Source locally and announce the removal exactly once in the page toast. **No report is mounted and no exit is owed** `[derived]`: the refusal that preceded the forced delete already showed this plan and the second destructive press accepted it. The authoritative success arrays are still newer evidence than that preview, and they are consumed as M2's read scope rather than rendered again. A failed read enters Committed projection stale through M0 for only the members that failed; it never says the committed deletion is unconfirmed || §1.11 | Blocked source card | Frame 12's card delta is rendered for a source whose status is `needs_action` or `error`; both states reuse the same geometry and card target | F5 | `needs_action`: the selected `sourceDetail.status.needsAction.*` plus `upstream.state.supplyStopped` and its registered cause action. `error`: `sourceDetail.status.error` plus `upstream.state.supplyStopped`; Hub uses `sourceDetail.action.refetch`, while an unclassified `native_cli` login failure uses `upstream.repair.reauthorize` | Card → 06. For `needs_action`, OAuth expiry → Reauth confirmation; revoked key → Key entry; a known subscription vendor's balance/account link opens its §1.4 static destination → Vendor recovery observation; an `api_key` Source keeps the non-linked service-provider fallback. For `error`, Hub 重新拉取 → §1.6 Refetching; native 重新授权 → Reauth confirmation. A later payload always dispatches the status it actually reports || §1.11 | Vendor recovery observation `[derived]` `[contract]` | A subscription's 补充额度 or 联系厂商 destination was activated from Blocked source card. Opening the external page proves no recovery; the same single-action card shell stays mounted and enters this channel-selected observation phase | F5 — no model mutation or hidden poll is sent | the original cause plus `upstream.state.supplyStopped`; Hub `sourceDetail.action.refetch`; native `upstream.repair.reauthorizeToRefresh` | Hub 重新拉取 → §1.6 Refetching. Native 重新登录以刷新订阅状态 → Reauth confirmation and MUST pass its existing acknowledgement before reauth. A later payload that changes the Source state leaves this phase; a reload that still reads the blocker reconstructs Blocked source card. No branch treats opening or returning from the vendor page as recovery evidence |-| §1.11 | Reauth confirmation `[derived]` `[contract]` | 重新授权 or 重新登录以刷新订阅状态 pressed for a Hub or `native_cli` source from Blocked source card, Vendor recovery observation or the capability-gated source overflow | F5 — no request has been sent | `upstream.repair.reauthConfirm.title`; exactly one of `upstream.repair.reauthConfirm.detail.onFailure` or `upstream.repair.reauthConfirm.detail.immediate`; `upstream.repair.reauthConfirm.confirm`, `upstream.repair.reauthConfirm.cancel` | The confirmation phase and literal request value are shared, but the complete consequence body is selected by channel: Hub renders only `onFailure`; `native_cli` renders only `immediate`. 继续登录 synchronously preallocates PD-1's blank context, then sends `POST /api/models/sources/<id>/reauth` with `{acknowledge_irreversible: true}` → Reauthorizing; 取消 / close / Escape restores the exact invoking card/menu/observation origin and its focus target (C2/C3/C5/C8) |-| §1.11 | Reauthorizing | The shared acknowledgement was confirmed. The activating gesture has synchronously preallocated PD-1's blank context; `POST /api/models/sources/<id>/reauth` sends the confirmed `{acknowledge_irreversible: true}` for either supply channel `[contract]` | F1 before a flow is held → Repair failed, with every dismissal path locked while that request is pending (C4); PD-1 closes the unused context. After acquisition, §1.4 owns cancellation, 2s polling and F1–F5 | `upstream.repair.reauthorizing` | R3 and RR-1/RR-2 own acquisition: a non-terminal `flow` enters §1.4 with held `intent: reauth`, where E3a/E3b and PD-5 select the actual presentation/progress read; an already-terminal `flow` is status-read immediately and never presented. RR-4 classifies the materialized terminal by returned `source.state` before pair cardinality: blocked → Repair unresolved; non-blocked + pairs → Repair impact reported; non-blocked + empty → M3 handoff. E8 `flow_not_found` and E9 `flow_expired` / terminal failure run RR-5 before OAuth failed / M0 Source gone. Only E6 stops polling for materialization; R5 renders any exact error-envelope `interrupted_pairs` before RR-5's complete-surface refresh. E2 remains inconclusive. Create-only arrays are absent by contract |+| §1.11 | Reauth confirmation `[derived]` `[contract]` | 重新授权 or 重新登录以刷新订阅状态 pressed for a Hub or `native_cli` source from Blocked source card, Vendor recovery observation or the capability-gated source overflow | F5 — no request has been sent | `upstream.repair.reauthConfirm.title`; exactly one of `upstream.repair.reauthConfirm.detail.onFailure` or `upstream.repair.reauthConfirm.detail.immediate`; `upstream.repair.reauthConfirm.confirm`, `upstream.repair.reauthConfirm.cancel` | The confirmation phase and literal request value are shared, but the complete consequence body is selected by channel: Hub renders only `onFailure`; `native_cli` renders only `immediate`. 继续登录 sends `POST /api/models/sources/<id>/reauth` with `{acknowledge_irreversible: true}` → Reauthorizing; 取消 / close / Escape restores the exact invoking card/menu/observation origin and its focus target (C2/C3/C5/C8) |+| §1.11 | Reauthorizing | The shared acknowledgement was confirmed. No browser context is opened (PD-1); `POST /api/models/sources/<id>/reauth` sends the confirmed `{acknowledge_irreversible: true}` for either supply channel `[contract]` | F1 before a flow is held → Repair failed, with every dismissal path locked while that request is pending (C4). After acquisition, §1.4 owns cancellation, 2s polling and F1–F5 | `upstream.repair.reauthorizing` | R3 and RR-1/RR-2 own acquisition: a non-terminal `flow` enters §1.4 with held `intent: reauth`, where E3a/E3b and PD-5 select the actual presentation/progress read; an already-terminal `flow` is status-read immediately and never presented. RR-4 classifies the materialized terminal by returned `source.state` before pair cardinality: blocked → Repair unresolved; non-blocked + pairs → Repair impact reported; non-blocked + empty → M3 handoff. E8 `flow_not_found` and E9 `flow_expired` / terminal failure run RR-5 before OAuth failed / M0 Source gone. Only E6 stops polling for materialization; R5 renders any exact error-envelope `interrupted_pairs` before RR-5's complete-surface refresh. E2 remains inconclusive. Create-only arrays are absent by contract || §1.11 | Key entry `[derived]` | 更换 Key pressed from either Blocked source card or the capability-gated source overflow, or a guarded refusal is abandoned | F5 — the secret remains local and no request is sent until submit | `upstream.repair.replaceKey` | V3 gates submit. A valid submit holds the normalized key and sends `PUT /api/models/sources/<id>/credential` with `{key}` → Replacing key; cancel restores the exact invoking origin and focus target (C2/C3/C5/C7) || §1.11 | Replacing key | Key entry submitted, or the guarded confirm below was accepted — the latter reuses the held key and adds `force: true` `[contract]` | F3 on guard refusal; F1 otherwise → Repair failed, with the key kept under F1. All dismissal paths are locked until the request settles (C4) | `upstream.repair.replacingKey` | R4 consumes the standard Source-mutation success: a non-empty `removed_hops` and/or `interrupted` → Repair impact reported; both empty → hold the returned `source` while M4 reads the complete model surface; refusal → Key replacement refused; failure → Repair failed || §1.11 | Key replacement refused `[derived]` `[contract]` | The non-forced credential replacement returned the shared guarded `409`; the typed key and exact Key entry origin are held | F3 — shared `Qp6FI`, with only the operation strings below changed | `guard.title.replaceKey`, `guard.subtitle.replaceKey`, `guard.confirm.replaceKey`, `guard.label`, `guard.count`, `guard.hop.position`, `guard.hint.safe`, `guard.hint.interrupt`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | 仍要更换 re-sends the held `{key, force: true}` → Replacing key; 取消 / close / Escape → Key entry with the typed key kept, by C2/C5 |@@ -2847,23 +2847,22 @@ value accepted by the one contracted submit route and does not define a second f| Element | Displays | Interactive | On activate || --- | --- | --- | --- || paste head | The selected vendor and the flow's expected return | close | Dismissing |-| authorization link `[derived]` | The exact non-null `presentation.auth_url` | yes | Open the same provider URL without starting another flow (PD-2) |+| authorization link `[derived]` | The exact non-null `presentation.auth_url` | yes | Open the same provider URL in a new context, or copy it with the adjacent copy control, without starting another flow (PD-2) || paste input | Code or complete callback URL, selected by `presentation.expects` | yes | Keeps the value locally; empty means 提交 is disabled || helper | PD-4's resolved server-declared string; null or lookup failure uses the expects-specific generic hint | no | — || 取消 | Leave the flow | yes | Dismissing || 提交 | Send the held value | yes when non-empty | `POST /api/models/oauth/submit` with `{flow_id, value}` |-The provider handoff belongs to the start transition, while the visible row is its-same-flow recovery path `[contract]` `[derived]`. PD-1 preallocates the browser context-inside the 去登录 gesture; RR-1 transfers it to the **non-terminal** accepted flow, and PD-2-navigates when that flow first carries `presentation.auth_url` and keeps the exact URL-actionable in the dialog. RR-2 routes an-already-terminal acquisition straight to status and PD-3 closes the unused context. That-is how the user obtains the code or callback URL even when browser popup policy refused the-automatic handoff. The URL is server-declared; the client keeps no vendor-to-**OAuth**-URL+The provider handoff is the user's `[contract]` `[derived]`. No transition opens a browser+context: PD-1 sends the start without one, and PD-2 renders the exact URL as a link with a+copy control once the **non-terminal** accepted flow first carries `presentation.auth_url`.+The user opens the provider page by activating that link, or copies the URL into whichever+browser holds the right account — the one path that works the same in every browser, popup+policy and desktop shell. RR-2 routes an already-terminal acquisition straight to status and+PD-3 renders no link. The URL is server-declared; the client keeps no vendor-to-**OAuth**-URLtable, and the static top-up/support register above is never consulted for this transition.-Polling, re-rendering or reconciling a submit never **auto-opens** the authorization URL-again; the user may still activate the held link. A submit response is not assumed terminal,+Acquisition, polling, re-rendering or reconciling a submit never **auto-opens** the+authorization URL; the user may activate or copy the held link at any time. A submit response is not assumed terminal,but C11 forbids treating every non-terminal state as the same milestone. E3a `starting` /`awaiting_action` says the provider still needs the paste value and returns to the form withthat value retained; only the user's next explicit 提交 resends it. E3b `verifying` says the@@ -2971,11 +2970,11 @@ unusable:| ID | Evidence / moment | Browser-context ownership | In-dialog fallback / copy disposition || --- | --- | --- | --- |-| PD-1 | A create or reauth flow-producing control is activated while the browser still owns the user gesture | Synchronously open one blank external context **before** awaiting the start/reauth request. The request still runs when popup policy returns no context | Nothing is rendered yet. A refused/failed acquisition closes an unused blank context. A non-terminal flow owns it even while `auth_url` is null, because a later status read may supply the URL |-| PD-2 | Acquisition or a later read of the active non-terminal flow first carries non-null `presentation.auth_url` | Navigate the one PD-1 context to that exact URL. Never derive or rewrite it, and never auto-open another context during polling, submit or reconciliation | Keep the exact URL as a visible actionable link for the lifetime of the active form. It is the manual path when PD-1 was blocked or the external context was closed; activating it opens the same URL without restarting the flow |-| PD-3 | RR-2 receives a terminal flow, or an active flow terminates before PD-2 navigates | Close the unused PD-1 context and status-read or settle immediately; a terminal flow owns no provider handoff | Render no form and no stale authorization link |+| PD-1 | A create or reauth flow-producing control is activated | Send the start/reauth request and open **no** browser context: the provider page is the user's to open | Nothing is rendered yet. A refused/failed acquisition has nothing to close |+| PD-2 | Acquisition or a later read of the active non-terminal flow first carries non-null `presentation.auth_url` | Open nothing automatically — not on acquisition, polling, submit or reconciliation. Never derive or rewrite the URL | Keep the exact URL as a visible link with an adjacent copy control for the lifetime of the active form. Activating the link opens the same URL in a new context without restarting the flow; copying lets the user paste it into any browser |+| PD-3 | RR-2 receives a terminal flow, or an active flow terminates | Status-read or settle immediately; a terminal flow owns no provider handoff | Render no form and no stale authorization link || PD-4 | An active form carries `presentation.instructions_key` and `expects` | N/A — this is localized copy, not navigation | Resolve the open-vocabulary key through the existing `serverText` missing-key guard. A resolved key renders directly. A null **or unresolved** key renders the generic helper selected by `expects`: device-code, authorization-code paste or callback-URL paste. Never print the machine key and never use a vendor→instruction table |-| PD-5 | An active paste form in E3a carries `presentation.auth_url: null` | The one held flow and its one PD-1 context own a 2s status read under the existing dialog bound. Keep reading while the required URL is null; never start a second flow or browser context. E2 stays inconclusive, and the evidence-class matrix owns every other answer | Keep the held form and draft. The first read with a non-null URL invokes PD-2 on the original context and pauses this delivery-only poll while E3a still waits for explicit submit |+| PD-5 | An active paste form in E3a carries `presentation.auth_url: null` | The one held flow owns a 2s status read under the existing dialog bound. Keep reading while the required URL is null; never start a second flow or open a browser context. E2 stays inconclusive, and the evidence-class matrix owns every other answer | Keep the held form and draft. The first read with a non-null URL renders PD-2's link and copy control and pauses this delivery-only poll while E3a still waits for explicit submit |**`expects` says what comes back, not whether anything is shown** `[contract]``[contract-gap]` G-33. `expects: none` means the user@@ -5189,10 +5188,10 @@ other channel (C8).`POST /api/models/oauth/start`. RR-1/RR-2 classify the returned flow before any form: aterminal acquisition is status-read immediately and is never presented;- Forms A, B and C are selected from a **non-terminal** returned `presentation`, never a- vendor table. PD-1–PD-3 preallocate and navigate the gesture-owned browser context, then- keep the non-null `auth_url` as a visible same-flow fallback. PD-5 reads a held paste flow- every 2 seconds while that required URL is null, and its first non-null value navigates the- original PD-1 context without starting another flow or context. `expects` selects the branch,+ vendor table. PD-1–PD-3 open no browser context; the non-null `auth_url` is the+ user's handoff, rendered as a visible link with a copy control. PD-5 reads a held paste flow+ every 2 seconds while that required URL is null, and its first non-null value renders that+ link without starting another flow or opening a context. `expects` selects the branch,and PD-4 renders a resolved `instructions_key` or the expects-specific fallback when itis null or unresolved; G-33 remains only the missing Form B `device_code` output. Submit,the evidence-class matrix, 2s polling, timeout, cancel and the F1–F5 treatments arediff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.pyindex 0b7be9a4a..6032743eb 100644--- a/tests/scenario_harness/model_hub_native_oauth.py+++ b/tests/scenario_harness/model_hub_native_oauth.py@@ -1,13 +1,16 @@from __future__ import annotations+import asyncioimport uuidfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any, Mapping+from unittest.mock import AsyncMock-from config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig+from config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig, V2Config+from core.agent_auth_service import AgentAuthServicefrom core.handlers.model_hub.adapter import (DiscoveredModel,ObservationDiscovery,@@ -28,6 +31,7 @@ from core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import (ModelHubService,UnavailableEngineAdapter,+ V2ModelHubConfigStore,_NATIVE_VENDOR_BACKENDS,)from vibe.model_hub_runtime.adapter import _OAUTH_ENDPOINTS, hub_subscription_serving_protocol@@ -109,6 +113,7 @@ class FakeAgentAuthService:*,force_reset: bool = True,owner_ref: str | None = None,+ new_source: bool = False,on_irreversible_start=None,):if force_reset and on_irreversible_start is not None:@@ -227,6 +232,63 @@ class NativeOAuthScenarioHarness:)+class CustodiedNativeOAuthScenarioHarness:+ """Native Model Hub OAuth through the real AgentAuthService and CLI custody.++ Only the Claude CLI transport and its login probe are faked. The saved Hub+ ownership, the native credential lease, the shared flow lifecycle and the+ Model Hub config all run as shipped against the isolated test home.+ """++ auth_url = "https://claude.ai/oauth/authorize?fixture=1"+ account = {"active_auth_mode": "oauth", "email": "[email protected]"}++ def __init__(self, state_dir: Path):+ config = V2Config.default()+ config.model_hub.enabled = True+ for supply in config.model_hub.agents.values():+ supply.mode = "hub"+ config.save()+ self.agent_auth = AgentAuthService(SimpleNamespace(config=config))+ self.callbacks: list[tuple[str, str]] = []+ consent = asyncio.Event()++ async def wait_for_consent(_client, request, timeout=900.0):+ if request["subtype"] != "claude_oauth_wait_for_completion":+ raise AssertionError(f"unexpected control request: {request}")+ await consent.wait()+ return {}++ async def send_callback(_client, authorization_code, state):+ self.callbacks.append((authorization_code, state))+ consent.set()++ self.agent_auth._start_claude_control_flow = AsyncMock(+ return_value=(SimpleNamespace(), self.auth_url, None)+ )+ self.agent_auth._send_claude_control_request = wait_for_consent+ self.agent_auth._send_claude_callback = send_callback+ self.agent_auth._verify_login = AsyncMock(return_value=(True, '{"loggedIn": true}'))+ self.agent_auth._refresh_backend_runtime = AsyncMock()+ self.agent_auth._disconnect_claude_client = AsyncMock()+ self.service = ModelHubService(+ store=V2ModelHubConfigStore(),+ adapter=UnavailableEngineAdapter(),+ events=BoundedEventLog(state_dir / "events.json"),+ native_oauth_adapter=AgentAuthNativeOAuthAdapter(+ self.agent_auth,+ auth_status_reader=lambda _backend: self.account,+ ),+ oauth_flows=OAuthFlowRegistry(state_dir / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(state_dir / "revocations.json"),+ )++ async def login_settled(self, flow_id: str) -> None:+ """Wait until the CLI login has finished and released its lease."""++ await self.agent_auth._web_flows[flow_id].waiter_task++@dataclass(frozen=True)class HubOAuthStartForm:"""What one start asks of the user, as the engine declares it.diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 3826c3fe1..eadf25123 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -341,6 +341,16 @@ scenarios:layer: scenariobackend: sharedtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_quota_card_reauth_reaches_a_fresh_quota_reading+ - id: AUTH-SETUP-910+ name: Model Hub native subscription create reaches the CLI login while the backend is Hub-owned+ status: covered+ kind: historical_regression+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_owned_native_subscription_create_closes_the_loop+ supporting_tests:+ - tests/test_native_writer_custody.py::test_hub_backend_admits_creating_the_empty_native_subscription_slot+ - tests/test_model_hub_api.py::test_native_oauth_custody_refusal_is_not_reported_as_engine_down- id: AUTH-SETUP-119name: Runtime manual provider code reaches native persistence and controller-confirmed readinessstatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 858d6c1d8..65a1aa5f7 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -55,6 +55,7 @@ from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, Scenariofrom tests.ui_server_test_helpers import _save_config, csrf_headers, remote_session_cookiefrom storage import remote_access_authorization_servicefrom tests.scenario_harness.model_hub_native_oauth import (+ CustodiedNativeOAuthScenarioHarness,HubOAuthScenarioHarness,HubOAuthStartForm,NativeOAuthScenarioHarness,@@ -1830,6 +1831,63 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(started["flow"]["channel"], "native_cli")self.assertEqual(harness.agent_auth.start_calls, [("codex", False)])+ async def test_hub_owned_native_subscription_create_closes_the_loop(self):+ """Scenario: AUTH-SETUP-910.++ On an install whose Claude backend is already Hub-routed, adding the+ Claude subscription "managed by the Agent" must reach the CLI login and+ end in one native Source. The login runs under the real CLI custody+ check, so a refusal there is exactly what the user saw as "the model+ gateway is not responding".++ The CLI finishes and releases its credential lease before any status+ read commits the Source. Until then the native slot still looks empty,+ so a second start in that window must not open another login over the+ credential this one just wrote.+ """+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ harness = CustodiedNativeOAuthScenarioHarness(Path(state_dir.name))+ start = {"vendor": "anthropic", "channel": "native_cli"}++ started = await harness.service.oauth_start(dict(start))++ flow = started["flow"]+ flow_id = flow["flow_id"]+ self.assertEqual(flow["channel"], "native_cli")+ self.assertEqual(flow["presentation"]["auth_url"], harness.auth_url)+ harness.agent_auth._start_claude_control_flow.assert_awaited_once()++ with self.assertRaises(ModelHubError) as busy:+ await harness.service.oauth_start(dict(start))+ self.assertEqual(busy.exception.code, "native_login_in_progress")++ await harness.service.oauth_submit(+ {"flow_id": flow_id, "value": "auth-code#oauth-state"}+ )+ await harness.login_settled(flow_id)+ self.assertEqual(harness.callbacks, [("auth-code", "oauth-state")])+ self.assertEqual(V2Config.load().model_hub.sources, [])++ with self.assertRaises(ModelHubError) as occupied:+ await harness.service.oauth_start(dict(start))++ self.assertEqual(occupied.exception.code, "native_source_already_exists")+ harness.agent_auth._start_claude_control_flow.assert_awaited_once()+ (source,) = V2Config.load().model_hub.sources+ self.assertEqual(occupied.exception.data, {"existing_source_id": source.id})+ self.assertEqual(source.id, flow["source_id"])+ self.assertEqual(+ (source.vendor, source.supply_channel, source.account_label),+ ("anthropic", "native_cli", "[email protected]"),+ )+ self.assertEqual(source.state.status, "standby")++ completed = await harness.service.oauth_status(flow_id)++ self.assertEqual(completed["flow"]["state"], "success")+ self.assertEqual(completed["source"]["id"], source.id)+async def test_hub_reauth_requires_acknowledgement_and_reaches_consistent_terminal(self):"""Scenario: AUTH-SETUP-109.diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 5296e2136..a3172e8b9 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -28,6 +28,7 @@ from config.v2_config import (ModelHubSourceStateConfig,)from core.agent_auth_service import BackendLoginInProgressError+from core.backend_restart import NativeMigrationBlockedErrorfrom core.handlers.model_hub.adapter import (DiscoveredModel,EngineEnsureResult,@@ -5881,6 +5882,28 @@ def test_native_oauth_preserves_transient_login_conflict_identity(tmp_path):assert exc_info.value.data == {}+ "reason,code",+ [+ ("native_auth_hub_owned", "migration_native_busy"),+ ("migration_recovery_pending", "migration_recovery_pending"),+ ("config_recovery", "config_recovery"),+ ],+)+def test_native_oauth_custody_refusal_is_not_reported_as_engine_down(tmp_path, reason, code):+ class CustodyRefusedAdapter(FakeAdapter):+ async def start_oauth(self, source_id, vendor):+ raise NativeMigrationBlockedError(reason, ("claude",))++ service, _, _ = _service(tmp_path, CustodyRefusedAdapter())++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))++ assert exc_info.value.status == 409+ assert exc_info.value.code == code++def test_nonce_oauth_start_replays_committed_flow_before_native_slot_conflict(tmp_path):service, store, adapter = _service(tmp_path)request = {diff --git a/tests/test_native_writer_custody.py b/tests/test_native_writer_custody.pyindex 9e361139a..4526b42b2 100644--- a/tests/test_native_writer_custody.py+++ b/tests/test_native_writer_custody.py@@ -111,6 +111,31 @@ def test_retained_subscription_requires_matching_source_binding(backend, vendor)lease.assert_auth_custody(backend, source_id=source.id)[email protected]("backend,vendor", [("codex", "openai"), ("claude", "anthropic")])+def test_hub_backend_admits_creating_the_empty_native_subscription_slot(backend, vendor):+ saved_config(enabled=False)+ with NativeCredentialLease((backend,)) as lease:+ lease.assert_auth_custody(backend, source_id="src_new000001", new_source=True)+ # Generic Settings/IM login carries no Source to create.+ for source_id, new_source in ((None, True), ("src_new000001", False)):+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):+ lease.assert_auth_custody(backend, source_id=source_id, new_source=new_source)+ source = native_source(vendor=vendor)+ saved_config(source=source)+ with NativeCredentialLease((backend,)) as lease:+ # The vendor's single native credential already belongs to a Source.+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):+ lease.assert_auth_custody(backend, source_id="src_new000001", new_source=True)+ source.supply_channel = "hub"+ source.credential_ref = "fixture-ref"+ saved_config(source=source)+ with NativeCredentialLease((backend,)) as lease:+ # A Hub Source id cannot be reused as a new native Source.+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):+ lease.assert_auth_custody(backend, source_id=source.id, new_source=True)+ lease.assert_auth_custody(backend, source_id="src_new000001", new_source=True)++def test_other_vendor_source_cannot_authorize_backend():saved_config(source=native_source(vendor="anthropic"))with NativeCredentialLease(("codex",)) as lease:diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.tsindex 02c8ee521..40d571b94 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts@@ -9,7 +9,6 @@ import { ToastProvider } from '@/context/ToastProvider';import i18n from '@/i18n';import { OAuthConnectDialog } from './OAuthConnectDialog';import { ApiCallError, modelsApi, type OAuthResult } from './modelsApi';-import { disposeProviderTab } from './providerTab';import {initialSubscriptionChannel,nativeSubscriptionSlotTaken,@@ -20,8 +19,6 @@ import type { Source } from './types';afterEach(() => {cleanup();- disposeProviderTab('cleanup');- disposeProviderTab('cleanup');vi.useRealTimers();vi.restoreAllMocks();});@@ -61,19 +58,6 @@ const dialog = (props: Partial<React.ComponentProps<typeof OAuthConnectDialog>>const renderDialog = (props: Partial<React.ComponentProps<typeof OAuthConnectDialog>> = {}) =>render(dialog(props));-const providerTab = () => {- const tab = {- closed: false,- close: vi.fn(),- opener: {} as unknown,- location: { href: '' },- };- tab.close.mockImplementation(() => {- tab.closed = true;- });- return tab;-};-const deferred = <T,>() => {let resolve!: (value: T) => void;let reject!: (reason: unknown) => void;@@ -138,10 +122,32 @@ describe('add-subscription start recovery', () => {expect(start.mock.calls[0][2]).toMatch(/^ofn_[a-z0-9]{16,64}$/);});- it('keeps the Retry tab across effect cleanup and navigates the replacement flow', async () => {+ it('leaves the provider page to the user: sign-in opens no window and offers the link to click or copy', async () => {+ const authUrl = 'https://provider.example/authorize?code=1';+ const open = vi.spyOn(window, 'open');+ vi.spyOn(modelsApi, 'startOAuth').mockResolvedValue({+ flow_id: 'oaf_manual',+ client_nonce: 'ofn_manual',+ vendor: 'anthropic',+ channel: 'native_cli',+ state: 'awaiting_action',+ presentation: { expects: 'paste_code', auth_url: authUrl },+ expires_at: '2099-01-01T00:00:00Z',+ });+ renderDialog();++ await userEvent.click(screen.getByRole('button', { name: /Sign in|去登录/i }));++ const link = await screen.findByRole('link', { name: authUrl });+ expect(link.getAttribute('href')).toBe(authUrl);+ expect(link.getAttribute('target')).toBe('_blank');+ expect(screen.getByRole('button', { name: /^Copy$|^复制$/i })).toBeTruthy();+ expect(open).not.toHaveBeenCalled();+ });++ it('shows the replacement flow\'s link after Retry without opening a window', async () => {const authUrl = 'https://provider.example/retry';- const tab = providerTab();- vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);+ const open = vi.spyOn(window, 'open');const reauth = vi.spyOn(modelsApi, 'reauthSource').mockRejectedValueOnce(new ApiCallError('engine_down'))@@ -159,50 +165,8 @@ describe('add-subscription start recovery', () => {await userEvent.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));await waitFor(() => expect(reauth).toHaveBeenCalledTimes(2));- await waitFor(() => expect(tab.location.href).toBe(authUrl));- expect(tab.close).not.toHaveBeenCalled();- });-- it('disposes the blank tab when acquisition is refused', async () => {- const tab = providerTab();- vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);- vi.spyOn(modelsApi, 'startOAuth').mockRejectedValue(new ApiCallError('engine_down'));- renderDialog();-- await userEvent.click(screen.getByRole('button', { name: /Sign in|去登录/i }));- await screen.findByRole('button', { name: /^Retry$|^重试$/i });-- expect(tab.close).toHaveBeenCalledOnce();- expect(tab.location.href).toBe('');- });-- it('disposes without navigating an already-terminal nonce replay', async () => {- const authUrl = 'https://provider.example/stale';- const tab = providerTab();- vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);- const terminal = {- flow_id: 'oaf_terminal',- client_nonce: 'ofn_terminal',- vendor: 'anthropic',- channel: 'native_cli' as const,- state: 'failed' as const,- presentation: { expects: 'paste_code' as const, auth_url: authUrl },- error_key: 'settings.models.oauth.error.generic',- expires_at: '2099-01-01T00:00:00Z',- };- vi.spyOn(modelsApi, 'startOAuth').mockResolvedValue(terminal);- const status = vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({- flow: terminal,- created: null,- repaired: null,- });- renderDialog();-- await userEvent.click(screen.getByRole('button', { name: /Sign in|去登录/i }));- await waitFor(() => expect(status).toHaveBeenCalledWith(terminal.flow_id));-- expect(tab.close).toHaveBeenCalledOnce();- expect(tab.location.href).toBe('');+ expect((await screen.findByRole('link', { name: authUrl })).getAttribute('href')).toBe(authUrl);+ expect(open).not.toHaveBeenCalled();});});@@ -249,12 +213,6 @@ describe('reauth terminal', () => {describe('OAuth failure class behavior', () => {it('keeps a held flow when its timeout reread is inconclusive', async () => {vi.useFakeTimers();- const providerTab = {- closed: false,- close: vi.fn(),- opener: {},- };- vi.spyOn(window, 'open').mockReturnValue(providerTab as unknown as Window);const reauth = vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue({flow_id: 'oaf_timeout',intent: 'reauth',@@ -280,7 +238,6 @@ describe('OAuth failure class behavior', () => {expect(status).toHaveBeenCalledWith('oaf_timeout');expect(reauth).toHaveBeenCalledTimes(1);- expect(providerTab.close).toHaveBeenCalledOnce();});it.each([@@ -294,10 +251,8 @@ describe('OAuth failure class behavior', () => {finish: (pending: ReturnType<typeof deferred<OAuthResult>>, flow: OAuthResult['flow']) =>pending.resolve({ flow: { ...flow, state: 'failed' }, created: null, repaired: null }),},- ])('keeps Retry\'s tab when the timed-out flow ignores a late submit $label', async ({ finish }) => {+ ])('keeps Retry\'s replacement flow when the timed-out flow ignores a late submit $label', async ({ finish }) => {vi.useFakeTimers();- const tab = providerTab();- vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);const expiredFlow: OAuthResult['flow'] = {flow_id: 'oaf_late_submit',intent: 'reauth',@@ -336,15 +291,13 @@ describe('OAuth failure class behavior', () => {finish(submit, expiredFlow);await Promise.resolve();});- expect(tab.close).not.toHaveBeenCalled();await act(async () => {reread.resolve({ flow: expiredFlow, created: null, repaired: null });await Promise.resolve();});expect(reauth).toHaveBeenCalledTimes(2);- expect(tab.location.href).toBe(replacementUrl);- expect(tab.close).not.toHaveBeenCalled();+ expect(screen.getByRole('link', { name: replacementUrl }).getAttribute('href')).toBe(replacementUrl);});it('ignores a held-flow reread rejection after its journey is retired', async () => {diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex 7f6238b0a..f4a206af9 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -38,12 +38,6 @@ import {type FlowView,} from './asyncLifetime';import { apiFailure, modelsApi, type Adoption, type OAuthResult } from './modelsApi';-import {- commitProviderTabRetry,- disposeProviderTab,- preopenProviderTab,- takeProviderTabForNavigation,-} from './providerTab';import { REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';import {NATIVE_SUBSCRIPTION_EXISTS_FAILURE,@@ -198,9 +192,7 @@ export const OAuthConnectDialog: React.FC<{setChannel(initialSubscriptionChannel(vendor, sources));// A vendor with no chooser copy has no channel choice to put in front of the// user, so it opens straight into its flow — the same entry the re-auth- // journey takes above. The gesture that allocated its provider tab was the- // menu item that opened this dialog (PD-1), since there is no 去登录 here to- // allocate one.+ // journey takes above.setPhase(chooser === null ? 'flow' : 'choose');}, [chooser, isReauth, openSubject, reauth?.supply_channel, sources, vendor]);@@ -358,11 +350,6 @@ export const OAuthConnectDialog: React.FC<{// the guard above already makes that poll harmless, but there is no reason// to let it fire.if (isDone(step.action)) stop();- if (terminalArrivalMovedRows(step.action)) {- disposeProviderTab(- step.view.failureClass ?? (step.action === 'succeed' ? 'success' : undefined),- );- }return isDone(step.action);};settleRef.current = settle;@@ -390,13 +377,10 @@ export const OAuthConnectDialog: React.FC<{} catch (err) {// The success and rejection paths belong to the same read. Once// this authority is retired, neither outcome may update the view- // or dispose a provider tab owned by its replacement.+ // owned by its replacement.if (cancelled || flowAuthorityRef.current !== authority) return true;const failure = apiFailure(err);const failureClass = classifyOAuthFailure(failure);- // This reread did not start a provider journey, so the tab opened- // by the Retry gesture has no URL to receive.- disposeProviderTab(failureClass);// An unread flow is still held. Retry may ask again, but it may not// turn missing evidence into permission to mint a replacement.if (failureClass === 'inconclusive') return true;@@ -451,7 +435,6 @@ export const OAuthConnectDialog: React.FC<{pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);return;}- disposeProviderTab(failureClass);// The authority goes first because its answer is what decides whether these// pairs are the ones on screen — see `failureLanded`. The refetch below is// owed whatever it answers.@@ -555,7 +538,6 @@ export const OAuthConnectDialog: React.FC<{failureClass,});if (!isReauth) setStartFailureCode(failure?.detail ?? failure?.code ?? 'start_failed');- disposeProviderTab(failureClass);rowsBehindAreStale(failure, failureLanded(step.action));}})();@@ -589,7 +571,6 @@ export const OAuthConnectDialog: React.FC<{// first, and by then the attempt it belongs to is not merely settled but// GONE. Whatever gap report is on screen when it returns is somebody else's.const opened = openedFlowId;- disposeProviderTab('cleanup');if (heldFlowId.current === opened) heldFlowId.current = null;rereadHeldFlow.current = null;void releaseFlow(authority, owner, {@@ -664,7 +645,6 @@ export const OAuthConnectDialog: React.FC<{errorKey: oauthFailureKey(failure?.code, journey),failureClass,});- if (failureLanded(step.action)) disposeProviderTab(failureClass);rowsBehindAreStale(failure, failureLanded(step.action));} finally {if (isCurrent()) setSubmitting(false);@@ -678,7 +658,6 @@ export const OAuthConnectDialog: React.FC<{setNativeSlotTaken(true);setChannel('hub');setStartFailureCode(null);- disposeProviderTab(view.failureClass ?? 'retryable-provider');setPhase('choose');return;}@@ -689,7 +668,6 @@ export const OAuthConnectDialog: React.FC<{const freshAcquisition = startFailureCode === null;setStartFailureCode(null);if (freshAcquisition) clientNonce.current = null;- commitProviderTabRetry();setStartAttempt((attempt) => attempt + 1);setPhase('flow');};@@ -721,28 +699,6 @@ export const OAuthConnectDialog: React.FC<{: 'settings.models.oauth.pasteCode.hint';const step2Label = serverText(t, presentation?.instructions_key, step2Fallback) ?? '';- const flowActive = Boolean(- flow- && !view.settled- && (flow.state === 'starting' || flow.state === 'awaiting_action' || flow.state === 'verifying'),- );- React.useEffect(() => {- if (!flowActive || !presentation?.auth_url) return;- // Claimed at the point of use, not when the dialog opens: the re-auth journey's- // tab is allocated by the confirm gesture before this component exists, and a- // claim taken at mount is stranded by anything that remounts (StrictMode- // replays effects in development) with the tab still open and unreachable.- // Claiming here also means a run with nothing to navigate keeps the handoff.- const target = takeProviderTabForNavigation();- if (!target || target.closed) return;- try {- target.location.href = presentation.auth_url;- } catch {- // A popup may become inaccessible after opening; the visible link remains- // the fallback in that case.- }- }, [flowActive, presentation?.auth_url]);-// The chooser is only for a vendor whose copy exists. A hub-held subscription// has no channel choice to make, so it opens straight into its flow (the open// effect above), and this guard is the render-side half of the same rule: a@@ -889,10 +845,7 @@ export const OAuthConnectDialog: React.FC<{variant="brand"size="sm"className="model-hub-dialog-action"- onClick={() => {- preopenProviderTab();- setPhase('flow');- }}+ onClick={() => setPhase('flow')}>{t('settings.models.addSub.signIn')}<ArrowRight className="size-3.5" />@@ -1036,10 +989,7 @@ export const OAuthConnectDialog: React.FC<{variant="brand"size="sm"className="h-10 sm:h-9"- onClick={() => {- preopenProviderTab('retry');- void retryStart();- }}+ onClick={() => void retryStart()}>{t('settings.models.addSub.retry')}</Button>diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex e2f742595..4ff3209bf 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -936,8 +936,7 @@ describe('SettingsModelsPage surface branches', () => {it('opens a hub-only subscription straight into its flow, posted as a hub source', async () => {// A vendor no sanctioned CLI holds custody of has no channel choice, so §1.4- // skips its chooser phase and starts the flow on open. The gesture that- // allocated the provider tab was the menu item, not a 去登录 inside the dialog.+ // skips its chooser phase and starts the flow on open.const started = {flow_id: 'flow_hub_only',client_nonce: 'ofn_hub_only',@@ -1077,11 +1076,9 @@ describe('SettingsModelsPage surface branches', () => {await waitFor(() => expect(reauth).toHaveBeenCalledWith(blockedSubscription.id));});- // The confirm IS this journey's gesture — the dialog it opens POSTs as it mounts,- // so nothing after it can be granted a tab. Asserted where the user feels it: the- // provider page lands in the tab, instead of behind a blocked popup and a link- // the user has to notice.- it('lands the provider page in the tab the re-auth confirmation opened', async () => {+ // The provider page is the user's to open: the confirmation starts the flow and+ // the dialog shows the link, instead of the page opening a window by itself.+ it('shows the re-auth provider link without opening a window from the confirmation', async () => {const authUrl = 'https://provider.example/authorize?code=1';const started = {flow_id: 'flow_reauth',@@ -1093,17 +1090,15 @@ describe('SettingsModelsPage surface branches', () => {};vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(started);vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({ flow: started, created: null, repaired: null });- const tab = { closed: false, opener: {} as unknown, location: { href: '' } };- const open = vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);+ const open = vi.spyOn(window, 'open');renderPage([blockedSubscription]);await userEvent.click(await screen.findByRole('button', { name: /Claude native login/i }));await userEvent.click(await screen.findByRole('button', { name: /^Sign in$|^重新登录$/i }));await userEvent.click(await screen.findByRole('button', { name: /^Start sign-in$|^开始登录$/i }));- expect(open).toHaveBeenCalledWith('about:blank', '_blank');- expect(tab.opener).toBeNull();- await waitFor(() => expect(tab.location.href).toBe(authUrl));+ expect((await screen.findByRole('link', { name: authUrl })).getAttribute('href')).toBe(authUrl);+ expect(open).not.toHaveBeenCalled();});// A failed re-auth has already spent the irreversible half — the sibling sourcesdiff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex ebe9b7b0f..b23d0845c 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -66,11 +66,10 @@ import {} from './regionRead';import { freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntime, runtimeCanAttemptInstall, runtimeIsRunning } from './runtimeLifecycle';import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';-import { handOffProviderTab } from './providerTab';import { canReauth, reauthBodyKey, reauthCost } from './repair';import { resumeGatewayAdoption } from './gatewayAdoption';import { groupMigrationCandidates } from './migrationGrouping';-import { SUBSCRIPTION_MENU_ROWS, hasNativeSubscriptionCustody } from './subscriptionOptions';+import { SUBSCRIPTION_MENU_ROWS } from './subscriptionOptions';import { VendorGlyph } from './vendorGlyph';import { backendVisual } from './vendorMeta';import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';@@ -1650,12 +1649,6 @@ export const SettingsModelsPage: React.FC = () => {tabIndex={subscriptionPickerIndex === index ? 0 : -1}onClick={() => {subscriptionPickerHandoffRef.current = true;- // A hub-only vendor opens §1.4 straight into its flow — no- // chooser phase, so no 去登录 gesture inside the dialog to- // allocate the provider tab. This click is the journey's only- // gesture, exactly as the re-auth confirm is, so the tab is- // handed off here or the handoff is popup-blocked (PD-1).- if (!hasNativeSubscriptionCustody(vendor)) handOffProviderTab();setSubscriptionPickerOpen(false);setSubscriptionVendor(vendor);}}@@ -1760,9 +1753,6 @@ export const SettingsModelsPage: React.FC = () => {confirmLabel={t('settings.models.repair.reauthConfirm') as string}destructive={reauthCost(quotaReauthSource) === 'immediate'}onConfirm={() => {- // The journey's only user gesture, as in the detail panel: allocate- // the provider tab here so the dialog's POST is not popup-blocked.- handOffProviderTab();const target = quotaReauthSource;setQuotaReauthSource(null);setReauthSource(target);diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex ced2f81ae..bad4c624b 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -49,7 +49,6 @@ import {type SourceMutationSettlement,type TrackSourceMutation,} from './mutationSettlement';-import { handOffProviderTab } from './providerTab';import { reconcileUnknownWrite } from './reconcileUnknownWrite';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';@@ -784,12 +783,6 @@ export const SourceDetailPanel: React.FC<{confirmLabel={t('settings.models.repair.reauthConfirm') as string}destructive={reauthCost(source) === 'immediate'}onConfirm={() => {- // This click is the journey's only user gesture: the dialog it opens POSTs- // as it mounts, and a browser grants the provider tab to the gesture that- // asked for it, not to the response one round trip later. Allocate here and- // hand it over, or the provider handoff is popup-blocked and the user has- // to notice the fallback link.- handOffProviderTab();setConfirmingReauth(false);onReauth(source);}}diff --git a/ui/src/components/settings/models/providerTab.test.ts b/ui/src/components/settings/models/providerTab.test.tsdeleted file mode 100644index 3216499f3..000000000--- a/ui/src/components/settings/models/providerTab.test.ts+++ /dev/null@@ -1,277 +0,0 @@-// Node environment on purpose: the AST sweep below reads this directory through-// `import.meta.url`, which is only a file URL outside a browser-like environment.-// `window` is stubbed per test instead, which is all `providerTab` touches.-import { readdirSync, readFileSync } from 'node:fs';-import { fileURLToPath } from 'node:url';--import * as ts from 'typescript';-import { afterEach, describe, expect, it, vi } from 'vitest';--import {- commitProviderTabRetry,- disposeProviderTab,- handOffProviderTab,- preopenProviderTab,- takeHandedProviderTab,- takeProviderTabForNavigation,-} from './providerTab';--type FakeTab = {- closed: boolean;- opener: unknown;- location: { href: string };- close: ReturnType<typeof vi.fn>;-};--function fakeTab(closed = false): FakeTab {- const tab = {- closed,- opener: {},- location: { href: '' },- close: vi.fn(),- };- tab.close.mockImplementation(() => {- tab.closed = true;- });- return tab;-}--/** Install a `window.open` and report what it was asked for. */-function stubWindowOpen(behavior: () => Window | null): { calls: unknown[][] } {- const calls: unknown[][] = [];- vi.stubGlobal('window', {- open: (...args: unknown[]) => {- calls.push(args);- return behavior();- },- });- return { calls };-}--function sourceFiles(directory: URL): URL[] {- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {- const child = new URL(`${entry.name}${entry.isDirectory() ? '/' : ''}`, directory);- if (entry.isDirectory()) return sourceFiles(child);- return /\.(ts|tsx)$/.test(entry.name) && !/\.test\.(ts|tsx)$/.test(entry.name) ? [child] : [];- });-}--function providerTabConsumerFiles(directory: URL): URL[] {- return sourceFiles(directory).filter((url) => {- const path = fileURLToPath(url);- return path.endsWith('/providerTab.ts') || readFileSync(url, 'utf8').includes("from './providerTab'");- });-}--function directCloseSites(url: URL): string[] {- const path = fileURLToPath(url);- const source = ts.createSourceFile(- path,- readFileSync(url, 'utf8'),- ts.ScriptTarget.Latest,- true,- path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,- );- const found: string[] = [];- const visit = (node: ts.Node) => {- if (- ts.isCallExpression(node)- && ts.isPropertyAccessExpression(node.expression)- && node.expression.name.text === 'close'- ) {- const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;- found.push(path.slice(path.lastIndexOf('/') + 1) + ':' + line);- }- ts.forEachChild(node, visit);- };- visit(source);- return found;-}--/** Names a call by its identifier, so `foo()` and `obj.foo()` read the same. */-function calledNames(node: ts.Node): Set<string> {- const names = new Set<string>();- const visit = (child: ts.Node) => {- if (ts.isCallExpression(child)) {- const target = child.expression;- if (ts.isIdentifier(target)) names.add(target.text);- else if (ts.isPropertyAccessExpression(target)) names.add(target.name.text);- if (- ts.isIdentifier(target) &&- target.text === 'setPhase' &&- child.arguments.length > 0 &&- ts.isStringLiteral(child.arguments[0])- ) {- names.add(`setPhase:${child.arguments[0].text}`);- }- }- ts.forEachChild(child, visit);- };- ts.forEachChild(node, visit);- return names;-}--/**- * Every inline JSX event handler in this feature, with what it does: whether it- * puts an OAuth journey into its flow phase, and whether it allocates the- * provider tab while the user's gesture is still on the stack.- *- * Found by walking, never listed: a handler added later is swept by construction.- * The limit is honest — a handler that delegates to a named function defined- * elsewhere is not followed, which is why both journeys are also asserted- * end-to-end in `SettingsModelsPage.render.test.tsx`.- */-function journeyStartHandlers(url: URL): { site: string; allocates: boolean }[] {- const path = fileURLToPath(url);- const source = ts.createSourceFile(- path,- readFileSync(url, 'utf8'),- ts.ScriptTarget.Latest,- true,- path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,- );- const starts = ['retryStart', 'onReauth', 'setPhase:flow'];- const allocators = ['preopenProviderTab', 'handOffProviderTab'];- const found: { site: string; allocates: boolean }[] = [];- const visit = (node: ts.Node) => {- if (- ts.isJsxAttribute(node) &&- node.initializer &&- ts.isJsxExpression(node.initializer) &&- node.initializer.expression &&- ts.isFunctionLike(node.initializer.expression)- ) {- const handler = node.initializer.expression;- const names = calledNames(handler);- if (starts.some((name) => names.has(name))) {- const line = source.getLineAndCharacterOfPosition(handler.getStart(source)).line + 1;- found.push({- site: `${path.slice(path.lastIndexOf('/') + 1)}:${line} ${node.name.getText(source)}`,- allocates: allocators.some((name) => names.has(name)),- });- }- }- ts.forEachChild(node, visit);- };- visit(source);- return found;-}--afterEach(() => {- vi.unstubAllGlobals();- // A committed retry intentionally survives one disposal, so two calls make- // cleanup independent of the state a failed assertion stopped at.- disposeProviderTab('cleanup');- disposeProviderTab('cleanup');-});--describe('provider tab', () => {- it('severs opener on the tab it allocates', () => {- const tab = fakeTab();- const { calls } = stubWindowOpen(() => tab as unknown as Window);-- expect(preopenProviderTab()).toBe(tab);- expect(calls).toEqual([['about:blank', '_blank']]);- expect(tab.opener).toBeNull();- });-- it.each([- ['a blocked popup', () => null],- ['a throwing window.open', () => { throw new Error('blocked'); }],- ])('reports no tab for %s', (_label, behavior) => {- stubWindowOpen(behavior as () => Window | null);-- expect(preopenProviderTab()).toBeNull();- });-- it('hands the gesture-allocated tab to the journey exactly once', () => {- const tab = fakeTab();- stubWindowOpen(() => tab as unknown as Window);-- handOffProviderTab();-- expect(takeHandedProviderTab()).toBe(tab);- // A second claim must not hand the same tab to a later journey: it has been- // navigated to the provider by then, and reusing it would replace the page- // the user is working in.- expect(takeHandedProviderTab()).toBeNull();- });-- it('does not hand over a tab the user closed', () => {- stubWindowOpen(() => fakeTab(true) as unknown as Window);-- handOffProviderTab();-- expect(takeHandedProviderTab()).toBeNull();- });-- it('has no tab to hand over before a gesture asks for one', () => {- expect(takeHandedProviderTab()).toBeNull();- });-- it('retains a committed Retry tab across cleanup for the replacement journey', () => {- const tab = fakeTab();- stubWindowOpen(() => tab as unknown as Window);-- expect(preopenProviderTab('retry')).toBe(tab);- commitProviderTabRetry();- disposeProviderTab('cleanup');-- expect(tab.close).not.toHaveBeenCalled();- expect(takeHandedProviderTab()).toBe(tab);- });-- it('does not turn an initial tab into a Retry handoff', () => {- const tab = fakeTab();- stubWindowOpen(() => tab as unknown as Window);-- preopenProviderTab();- commitProviderTabRetry();- disposeProviderTab('cleanup');-- expect(tab.close).toHaveBeenCalledOnce();- expect(takeHandedProviderTab()).toBeNull();- });-- it('disposes a Retry tab when no replacement journey was committed', () => {- const tab = fakeTab();- stubWindowOpen(() => tab as unknown as Window);-- preopenProviderTab('retry');- disposeProviderTab('inconclusive');-- expect(tab.close).toHaveBeenCalledOnce();- expect(takeHandedProviderTab()).toBeNull();- });-- it('ends ownership when the provider tab is taken for navigation', () => {- const tab = fakeTab();- stubWindowOpen(() => tab as unknown as Window);-- preopenProviderTab();- expect(takeProviderTabForNavigation()).toBe(tab);- disposeProviderTab('success');-- expect(tab.close).not.toHaveBeenCalled();- });-- // The invariant behind both re-auth findings on b594ef986: a journey's provider- // tab must be allocated by the gesture that starts it. The create journey's- // gesture is inside the dialog, the re-auth journey's is the confirm outside it,- // and the browser grants the tab to neither one after the start response.- it('allocates the provider tab in every gesture that starts a journey', () => {- const handlers = sourceFiles(new URL('./', import.meta.url)).flatMap(journeyStartHandlers);-- // The pattern must exist somewhere, or this asserts nothing at all.- expect(handlers.length).toBeGreaterThan(0);- expect(handlers.filter(({ allocates }) => !allocates)).toEqual([]);- });-- it('keeps every direct provider-tab close inside the lifetime owner', () => {- const closes = providerTabConsumerFiles(new URL('./', import.meta.url)).flatMap(directCloseSites);-- // The owner must actually close a tab, or this invariant would prove nothing.- expect(closes.length).toBeGreaterThan(0);- expect(closes.filter((site) => !site.startsWith('providerTab.ts:'))).toEqual([]);- });-});diff --git a/ui/src/components/settings/models/providerTab.ts b/ui/src/components/settings/models/providerTab.tsdeleted file mode 100644index 5c02ad071..000000000--- a/ui/src/components/settings/models/providerTab.ts+++ /dev/null@@ -1,127 +0,0 @@-/**- * One owner for the tab the provider's authorization page is navigated into.- *- * A browser only grants `window.open` inside the gesture that asked for it, and- * the auth URL arrives one round trip later — so the tab must be allocated by- * the gesture that STARTS an OAuth journey, never by the response that needs it.- * `OAuthConnectDialog` satisfies that for the journeys whose gesture lives- * inside it (Sign in, Retry), but the re-auth journey's gesture is the confirm- * OUTSIDE it: the dialog POSTs as it mounts, so by the time it could open a tab- * the gesture is already over and the popup is blocked.- *- * Hence the handoff below. The tab is a single browser-wide resource with a- * lifetime that spans the gesture → mount boundary, which is exactly what a- * component ref cannot hold; threading a live `Window` through page state and a- * prop would model that lifetime as data and copy it. One module owns the- * allocation, handoff, claim, navigation, retention and disposal.- */--import type { OAuthFailureClass } from './asyncLifetime';--type ProviderTabState = 'handed' | 'claimed' | 'retry-pending' | 'retry-committed';-type ProviderTabPurpose = 'initial' | 'retry';-type ProviderTabRecord = { tab: Window; state: ProviderTabState };--/** The one browser tab this feature owns, from allocation through disposal. */-let providerTab: ProviderTabRecord | null = null;--/** Reasons are carried from the shared OAuth classifier to the one disposer. */-export type ProviderTabDisposalReason = OAuthFailureClass | 'success' | 'cleanup';--const closeTab = (tab: Window) => {- if (tab.closed) return;- try {- tab.close();- } catch {- // Cross-origin or already-closing windows can reject access.- }-};--/** Drop an old record before a new gesture allocates the single owned tab. */-const discardOwnedTab = () => {- if (!providerTab) return;- closeTab(providerTab.tab);- providerTab = null;-};--/**- * The single `window.open` for provider handoffs: blank, and with `opener`- * severed, because the provider page is navigated into it later and would- * otherwise be able to drive this window (reverse tabnabbing).- */-export function preopenProviderTab(purpose: ProviderTabPurpose = 'initial'): Window | null {- discardOwnedTab();- try {- const tab = window.open('about:blank', '_blank');- if (tab) {- try {- tab.opener = null;- } catch {- // Some browser WindowProxy implementations expose a read-only opener.- }- providerTab = { tab, state: purpose === 'retry' ? 'retry-pending' : 'claimed' };- }- return tab;- } catch {- return null;- }-}--/**- * Allocate the tab for a journey that starts outside the dialog that will use- * it. Called from the gesture; claimed by the dialog as it opens.- */-export function handOffProviderTab(): void {- const tab = preopenProviderTab();- if (tab && providerTab) providerTab.state = 'handed';-}--/**- * Claim the handed tab, exactly once. Returns null when no gesture handed one- * over, or when the user closed it in the meantime — both mean "this journey- * has no tab", which the visible fallback link already covers.- *- * Every dialog open claims, including a journey that allocates its own tab, so- * a handoff whose journey never opened cannot survive into a later one.- */-export function takeHandedProviderTab(): Window | null {- if (!providerTab || providerTab.state !== 'handed') return null;- if (providerTab.tab.closed) {- providerTab = null;- return null;- }- providerTab.state = 'claimed';- return providerTab.tab;-}--/** Commit the retry handoff only once the next flow is definitely starting. */-export function commitProviderTabRetry(): void {- if (providerTab?.state === 'retry-pending') providerTab.state = 'retry-committed';-}--/**- * Take the owned tab for navigation and end this module's ownership. A settled- * flow therefore cannot navigate a tab later, even if its auth URL is present.- */-export function takeProviderTabForNavigation(): Window | null {- if (!providerTab) return null;- const tab = providerTab.tab;- providerTab = null;- if (tab.closed) return null;- return tab;-}--/**- * Dispose the owned tab, or retain a committed Retry tab across effect cleanup.- * The caller supplies the shared classifier's value; no second terminal- * predicate is allowed in this owner or its callers.- */-export function disposeProviderTab(reason?: ProviderTabDisposalReason): void {- if (!providerTab) return;- if (providerTab.state === 'retry-committed' && reason === 'cleanup') {- providerTab.state = 'handed';- return;- }- closeTab(providerTab.tab);- providerTab = null;-}diff --git a/ui/src/components/settings/models/subscriptionOptions.ts b/ui/src/components/settings/models/subscriptionOptions.tsindex 56200fe0a..23af0b1f1 100644--- a/ui/src/components/settings/models/subscriptionOptions.ts+++ b/ui/src/components/settings/models/subscriptionOptions.ts@@ -33,8 +33,8 @@ export type SubscriptionVendor = (typeof SUBSCRIPTION_VENDORS)[number];* gains a chooser when Avibe sanctions a CLI for it and someone writes what the* choice costs, and a vendor without either is hub-held and starts straight into* its flow. Two tables would let them disagree, and the disagreement is not- * cosmetic — the gesture that allocates the provider tab lives in the menu for a- * vendor with no chooser and in the dialog for one with a chooser (PD-1).+ * cosmetic — a vendor with a chooser shows its channel choice before any login+ * starts, and one without starts its login as the dialog opens.*/const SUBSCRIPTION_CHOOSER = {anthropic: { copy: 'claude', brand: 'Claude' },diff --git a/ui/src/lib/pwaNavigation.test.ts b/ui/src/lib/pwaNavigation.test.tsindex 541b1e76d..4e49685cb 100644--- a/ui/src/lib/pwaNavigation.test.ts+++ b/ui/src/lib/pwaNavigation.test.ts@@ -235,7 +235,6 @@ describe('programmatic PWA navigation', () => {.sort((left, right) => left.path.localeCompare(right.path));expect(directCalls).toEqual([- { path: 'components/settings/models/providerTab.ts', count: 1 },{ path: 'components/workbench/ShowPageLaunchControl.tsx', count: 1 },{ path: 'lib/pwaNavigation.ts', count: 1 },]);