Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(claude): separate auth observation, authorization and launch capability (#2617)

Call Whiteae80c21dc55e
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 77acfff8e..c35704cc4 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -305,6 +305,43 @@ def sanitize_process_output(text: str) -> str:
return cleaned.strip()
+_CLAUDE_FIRST_PARTY_OAUTH_METHODS = frozenset({
+ "claude.ai",
+ "claude-ai",
+ "oauth",
+ "oauth-token",
+ "setup-token",
+ "claude-code-oauth-token",
+ "subscription",
+ "claude-subscription",
+})
+
+
+def claude_status_proves_first_party_oauth(text: str) -> bool:
+ """Interpret the explicit login verifier's ``claude auth status --json`` output.
+
+ Only a logged-in first-party Claude OAuth method is proof of an account
+ login. A concrete API-key/helper or other-provider method is not, and
+ neither is an unrecognised or unparseable response.
+ """
+ try:
+ payload = json.loads(text)
+ except (TypeError, json.JSONDecodeError):
+ return False
+ if not isinstance(payload, dict) or payload.get("loggedIn") is not True:
+ return False
+ for key in ("authMethod", "authProvider", "source", "provider"):
+ raw = payload.get(key)
+ if not isinstance(raw, str):
+ continue
+ normalized = re.sub(r"[\s_]+", "-", raw.strip().lower())
+ if normalized:
+ # A concrete primary method cannot be overruled by a secondary
+ # provider hint. Unknown methods do not prove first-party OAuth.
+ return normalized in _CLAUDE_FIRST_PARTY_OAUTH_METHODS
+ return False
+
+
def verify_opencode_auth_list_output(text: str, provider: str | None = None) -> bool:
"""Return True when `opencode auth list` shows credentials for the target provider."""
normalized_lines = []
@@ -440,6 +477,10 @@ class WebAuthFlow:
expires_at_iso: str | None = None
source_signed_in: bool | None = None
source_account_label: str | None = None
+ # Operation-owned receipt: this flow's consent was verified and its
+ # native/config commit landed. Set before runtime application, which may
+ # still fail; it is not a claim about any later credential selection.
+ authorization_completed: bool = False
native_cli: bool = False
native_lease: NativeCredentialLease | None = field(default=None, repr=False)
# The controller-owned OpenCode generation one OpenCode login runs on.
@@ -2113,6 +2154,7 @@ class AgentAuthService:
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
env=self._build_claude_full_subprocess_env(force_oauth=force_oauth),
+ cwd=await _native_auth_thread(self._resolve_backend_probe_cwd, "claude", prepare=True),
)
stdout, _ = await self._communicate_native_auth_probe(process)
text = stdout.decode("utf-8", errors="replace").strip()
@@ -2122,7 +2164,7 @@ class AgentAuthService:
if force_oauth and flow.claude_oauth_attempt is None:
await self._restore_transient_claude_oauth_probe_backup(settings_backup)
return False, text
- logged_in = bool(payload.get("loggedIn"))
+ logged_in = isinstance(payload, dict) and payload.get("loggedIn") is True
if force_oauth and not logged_in and flow.claude_oauth_attempt is None:
await self._restore_transient_claude_oauth_probe_backup(settings_backup)
return (logged_in, text)
@@ -2857,6 +2899,7 @@ class AgentAuthService:
"device_code": flow.device_code,
"awaiting_code": flow.awaiting_code,
"error": flow.error,
+ "authorization_completed": getattr(flow, "authorization_completed", False),
}
if flow.callback_kind is not None:
result["callback_kind"] = flow.callback_kind
@@ -4006,6 +4049,9 @@ class AgentAuthService:
claude_oauth_attempt=flow.claude_oauth_attempt,
)
if ok:
+ # Model Hub completion consumes this flow's own verification;
+ # no later Settings read or status process re-decides it.
+ flow.source_signed_in = claude_status_proves_first_party_oauth(detail)
await self._commit_web_login(flow)
flow.state = "success"
else:
@@ -4074,6 +4120,9 @@ class AgentAuthService:
else:
await self._persist_backend_auth_mode(flow.backend, "oauth", strict=True)
await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=True)
+ # Authorization is complete once committed. A later application
+ # failure fails the flow but must not erase this receipt.
+ flow.authorization_completed = True
await self._invoke_post_web_success_hook(flow.backend, persist=False)
task = asyncio.create_task(commit())
@@ -4399,9 +4448,22 @@ class AgentAuthService:
) -> dict[str, Any]:
owned = lease is None
lease = self._acquire_native_lease("claude") if owned else lease
+ async def cleanup_and_reconcile() -> dict[str, Any]:
+ result = await self._clear_claude_oauth_credentials_owned()
+ # Standalone cleanup owns its runtime reconciliation. API-key saves
+ # borrow a lease and already reconcile once at their outer writer.
+ if owned:
+ try:
+ await self._invoke_post_web_success_hook("claude", persist=False)
+ result["restart"] = {"ok": True, "message": ""}
+ except Exception as err: # noqa: BLE001
+ logger.warning("Claude cleanup completed but runtime application failed")
+ result["restart"] = {"ok": False, "message": sanitize_process_output(str(err))}
+ return result
+
try:
lease.assert_auth_custody("claude")
- return await finish_native_operation(self._clear_claude_oauth_credentials_owned())
+ return await finish_native_operation(cleanup_and_reconcile())
finally:
if owned:
lease.release()
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 71e167b86..82e66a6e7 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -432,6 +432,10 @@ class OAuthFlowState:
# verbatim on one bounded line, for display beside ``error_key``. Null in
# every other state and whenever there is nothing to add to the key.
error_detail: str | None = None
+ # Native authorization/config commit succeeded, but this attempt's runtime
+ # application failed. This does not undo Source materialization or assert
+ # the runtime's current health.
+ application_failed: bool = False
class InvokeHandle(Protocol):
diff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.py
index 0f60603e2..d2cde1f3b 100644
--- a/core/handlers/model_hub/native_oauth.py
+++ b/core/handlers/model_hub/native_oauth.py
@@ -101,10 +101,6 @@ def _signed_in(backend: str, status: Mapping[str, Any]) -> bool:
return True
if active_auth_mode not in {None, "none"}:
return False
- if backend == "claude":
- if active_auth_mode == "none":
- return False
- return status.get("has_oauth_credentials") is True
if backend == "codex":
# AgentAuthService reports success only after its own Codex CLI probe.
# The Settings status reader cannot see tokens in the default keyring,
@@ -211,18 +207,22 @@ class AgentAuthNativeOAuthAdapter:
def completed_source_status(self, flow_id: str) -> NativeOAuthSourceStatus:
payload = self._agent_auth_service.get_web_flow_status(flow_id)
- if payload.get("ok") is not True or payload.get("state") != "success":
+ committed_claude = (
+ payload.get("vendor") == "anthropic"
+ and payload.get("state") == "failed"
+ and payload.get("authorization_completed") is True
+ )
+ if payload.get("ok") is not True or (payload.get("state") != "success" and not committed_claude):
raise KeyError(flow_id)
status = payload.get("source_status")
if not isinstance(status, Mapping):
raise KeyError(flow_id)
- signed_in = status.get("signed_in")
- if not isinstance(signed_in, bool):
- signed_in = True
+ signed_in = status.get("signed_in") is True
account_label = status.get("account_label")
return NativeOAuthSourceStatus(
signed_in=signed_in,
account_label=account_label if isinstance(account_label, str) else None,
+ application_failed=committed_claude,
)
@staticmethod
@@ -234,6 +234,7 @@ class AgentAuthNativeOAuthAdapter:
"url": getattr(flow, "url", None),
"device_code": getattr(flow, "device_code", None),
"error": getattr(flow, "error", None),
+ "authorization_completed": getattr(flow, "authorization_completed", False),
"source_id": getattr(flow, "source_id", None),
"vendor": getattr(flow, "vendor", None),
"expires_at_iso": getattr(flow, "expires_at_iso", None),
@@ -260,6 +261,15 @@ class AgentAuthNativeOAuthAdapter:
"failed": "failed",
"cancelled": "cancelled",
}.get(str(payload.get("state")), "failed")
+ application_failed = (
+ vendor == "anthropic" and state == "failed"
+ and payload.get("authorization_completed") is True
+ )
+ if application_failed:
+ # Source configuration belongs to the committed authorization, not
+ # to the controller's application result. Materialize it once using
+ # the same receipt, without another login or a polling side effect.
+ state = "success"
source_status = payload.get("source_status")
if (
state == "success"
@@ -268,7 +278,14 @@ class AgentAuthNativeOAuthAdapter:
or not isinstance(source_status.get("signed_in"), bool)
)
):
- resolved = await self._read_source_status(_VENDOR_BACKENDS[vendor])
+ backend = _VENDOR_BACKENDS[vendor]
+ # A Claude flow carries its own verification. One without it
+ # proved nothing, and a Settings read cannot decide it afterwards.
+ resolved = (
+ NativeOAuthSourceStatus(signed_in=False, account_label=None)
+ if backend == "claude"
+ else await self._read_source_status(backend)
+ )
self._agent_auth_service.set_flow_source_status(
flow_id,
signed_in=resolved.signed_in,
@@ -278,7 +295,7 @@ class AgentAuthNativeOAuthAdapter:
error_detail = None
if state == "failed":
error_key = _TIMEOUT_ERROR_KEY if payload.get("error") == "timed_out" else _GENERIC_ERROR_KEY
- if error_key == _GENERIC_ERROR_KEY:
+ if error_key != _TIMEOUT_ERROR_KEY:
error_detail = oauth_failure_detail(payload.get("error"))
elif state == "cancelled":
error_key = _GENERIC_ERROR_KEY
@@ -303,6 +320,7 @@ class AgentAuthNativeOAuthAdapter:
retained_material_disposition=RetainedMaterialDisposition.NONE,
retained_credential_ref=None,
error_detail=error_detail,
+ application_failed=application_failed,
)
async def _read_source_status(self, backend: str) -> NativeOAuthSourceStatus:
@@ -324,8 +342,6 @@ def create_native_oauth_adapter() -> AgentAuthNativeOAuthAdapter:
from vibe import api
def read_auth_status(backend: str) -> Mapping[str, Any]:
- if backend == "claude":
- return api.get_claude_auth()
if backend == "codex":
return api.get_codex_auth()
raise NativeOAuthUnavailableError
diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.py
index 677bd3f92..5fec05072 100644
--- a/core/handlers/model_hub/oauth.py
+++ b/core/handlers/model_hub/oauth.py
@@ -94,6 +94,7 @@ class NativeOAuthSourceStatus:
signed_in: bool
account_label: str | None
+ application_failed: bool = False
class NativeOAuthAdapter(OAuthAdapter, Protocol):
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 7f824a34b..5e51e7032 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -1217,6 +1217,8 @@ def _oauth_payload(
payload["client_nonce"] = client_nonce
if flow.state == "failed" and flow.error_detail:
payload["error_detail"] = flow.error_detail
+ if getattr(flow, "application_failed", False) is True:
+ payload["application_failed"] = True
return payload
@@ -3261,6 +3263,15 @@ class ModelHubService:
except (KeyError, OSError):
pass
failed = binding.intent == "create" and source.state.status == "error"
+ application_failed = False
+ if binding.channel == "native_cli" and binding.vendor == "anthropic" and not failed:
+ try:
+ # The existing flow retains this historical receipt for its
+ # normal TTL. No status CLI or new persistence is involved.
+ receipt = self.native_oauth_adapter.completed_source_status(flow_id)
+ application_failed = getattr(receipt, "application_failed", False) is True
+ except (KeyError, NativeOAuthUnavailableError):
+ pass # An expired receipt does not undo a saved Source.
return OAuthFlowState(
flow_id=flow_id,
source_id=source.id,
@@ -3292,6 +3303,7 @@ class ModelHubService:
if binding.channel == "hub"
else None
),
+ application_failed=application_failed,
)
def _completed_reauth_result(
diff --git a/docs/plans/2026-09-18-shared-backend-connection.md b/docs/plans/2026-09-18-shared-backend-connection.md
index 8636b7de7..77d3cab09 100644
--- a/docs/plans/2026-09-18-shared-backend-connection.md
+++ b/docs/plans/2026-09-18-shared-backend-connection.md
@@ -130,16 +130,20 @@ ledger, config generations, schema or second lifecycle controller is added.
cannot erase that failure. Only explicit successful apply clears it.
- `GET /api/backend/{backend}/connection` produces `BackendConnectionState`:
`{ok, backend, installed, enabled, supply_mode: direct | hub,
- auth: subscription | api_key | none | unknown,
+ auth: subscription | api_key | external | none | unknown,
application: applied | draining | failed | stopped | unknown, ready,
- entry_eligible, permission_required?, message?}`. In Direct mode, existing native auth
- readers/provider catalog produce `auth`; no model-call test is added. A
- provider counts only with an effective API/OAuth entry, not a keyless/local
- catalog row. Codex keychain uncertainty is `unknown` regardless of saved mode.
-- `ready` requires the same backend installed/enabled, confirmed credential
- source, controller applied and (OpenCode only) existing tool permission.
- `entry_eligible` additionally accepts a confirmed stopped controller with
- persisted auth. A running service with unavailable IPC stays unknown.
+ entry_eligible, permission_required?, message?}`. Direct Claude reports
+ `auth: external`: authentication belongs to Claude, and this read does not
+ inspect credentials or predict their selection. Other native auth readers /
+ provider catalogs retain their existing projections; no model-call test is
+ added. A keyless/local OpenCode catalog row is not credential evidence.
+ Codex keychain uncertainty is `unknown` regardless of saved mode.
+- `ready` requires the same backend installed/enabled, controller applied and
+ (OpenCode only) existing tool permission. Managed credentials retain their
+ admission checks; `external` Direct Claude requires custody and launch
+ capability, not a passive login claim. `entry_eligible` additionally accepts
+ a confirmed stopped controller. A running service with unavailable IPC stays
+ unknown. See [Claude observation ownership](claude-auth-observation-ownership.md).
- A fresh GET observes the persisted authentication owner and the last Avibe application, not
continuous remote credential validity or external-file hot reload. This
limitation applies equally to Settings; known apply failure takes precedence.
diff --git a/docs/plans/claude-auth-observation-ownership.md b/docs/plans/claude-auth-observation-ownership.md
new file mode 100644
index 000000000..05e85bd37
--- /dev/null
+++ b/docs/plans/claude-auth-observation-ownership.md
@@ -0,0 +1,147 @@
+# Claude authentication: observation, operation, and execution ownership
+
+Owner decision: 2026-10-14, session `ses7vjeb43k5u`. The user approved this
+fundamental correction after rejecting the patch loop in #2550/#2599. Implement
+from master, not by extending either unmerged implementation.
+
+## Product contract
+
+A passive read must not perform authentication, and must not pretend to predict
+Claude's eventual credential selection. Three facts have different authorities:
+
+| Fact | Authority | Meaning |
+| --- | --- | --- |
+| Saved configuration / native material observed | read-only Settings inventory | a local fact, not effective auth or token validity |
+| Explicit authorization completed | the owning login flow | this operation committed, not perpetual readiness |
+| Backend can start / this execution succeeded | runtime/application and actual execution | launch capability / a result in that execution's context |
+
+Direct Claude delegates authentication to Claude. Avibe still owns the chosen
+Agent/model and runtime lifecycle. Missing or opaque passive credential evidence
+must neither claim signed out nor prevent an explicitly requested execution.
+
+Gateway-held Model Hub Sources retain their existing custody and admission
+checks. Existing `native_cli` subscription records are a compatibility boundary:
+do not migrate/delete/reclassify them or loosen their routing rules implicitly.
+Their explicit login completion must consume the owning operation's verification,
+not call the generic Settings inventory to infer authentication a second time.
+Their UI must identify CLI-managed credentials rather than promise Hub custody.
+An independent redesign of per-turn native-Source admission is out of scope.
+
+## Concrete interfaces
+
+### Claude Settings inventory (`get_claude_auth`)
+
+- Remove the passive Claude subprocess probe, its cwd creation and its env helper.
+- No Git traversal, user/project/local precedence emulator, dynamic-helper
+ execution, remote validation, background probing or validity cache.
+- Preserve editable user-settings / legacy V2 API-key metadata and existing
+ save/remove writers. These fields describe what the editor manages only.
+- Read `read_native_oauth("claude", allow_secret=False)` for native-store evidence.
+- Add `auth_managed_by: "claude"` and
+ `oauth_store_state: "present" | "absent" | "unknown"`.
+ `present` means inspectable native OAuth material, not logged in; opaque,
+ denied, invalid or unreadable evidence is `unknown`.
+- Keep `has_oauth_credentials` as the compatibility raw-presence boolean
+ (`oauth_store_state == "present"`). Add `can_remove_oauth_credentials` for
+ offering explicit scoped native cleanup independently of sign-in certainty.
+- Retain the legacy `active_auth_mode` wire field conservatively as `"none"`
+ with `auth_mode_uncertain: true` for this delegated-auth observation. New
+ consumers must not use it as an authentication or configuration-save verdict.
+ `auth_mode` continues to describe the saved editing choice, not runtime truth.
+
+### Direct Claude connection (`get_backend_connection`)
+
+- Add `"external"` to the existing `auth` enum, used for Direct Claude.
+- `ready` means the installed/enabled backend has applied configuration and can
+ accept an execution attempt; `entry_eligible` retains the existing applied /
+ stopped distinction. Neither field asserts authentication for `auth=external`.
+- Preserve configuration-recovery, custody/takeover, pending migration, disabled,
+ CLI-installed and application/draining/failure gates. Unknown auth is not a
+ reason to bypass those gates.
+- Do not inspect native credentials to grant Direct launch capability. Keep the
+ existing coherent ownership check/exclusion; remove only the auth inference.
+- Do not relax gateway-held Source admission or change per-turn router code to
+ make a default-directory observation look like turn-specific authorization.
+
+### Explicit login receipt
+
+- The existing `WebAuthFlow` owns additive `authorization_completed: bool`,
+ default false. Set it only after verified consent and native/config commit,
+ before the existing post-success runtime-application hook. A later apply
+ failure must not erase the authorization fact. Preserve cleanup, cancellation,
+ leases, timeouts and flow retention; do not introduce another lifecycle.
+- Publish the receipt on start/status responses where that flow is serialized.
+- A committed Claude authorization can materialize its Source even if that
+ operation's runtime-application hook fails. Project the authorization as
+ success with optional `application_failed: true`, and use the existing
+ exactly-once Source materialization. Do not poll/retry application as a side
+ effect of status reads. UI reports the application warning independently;
+ runtime readiness still belongs to its existing application owner.
+- Model Hub Claude completion uses verification captured by that owning flow
+ (existing `source_signed_in` / `source_status` may carry it). Do not call
+ `get_claude_auth` or launch a second status process to re-decide completion.
+- Preserve the legacy native subscription's first-party verification contract:
+ a concrete API-key/other-provider result is not proof of OAuth. If needed,
+ move the existing pure CLI-response interpretation into the explicit verifier
+ and reuse its existing configured-cwd helper, not a filesystem interpreter.
+ Do not unconditionally stamp a source ready from a passive read or an error.
+
+### UI consumers and cleanup
+
+- Claude Settings edits saved configuration and presents inventory as observed,
+ absent or unknown. No green signed-in/connected claim from file presence.
+- `auth=external` is presented as native authentication / ready to start, not
+ authenticated. An authorization receipt is presented as authorization complete;
+ pending/failed application is shown independently and may be refreshed without
+ re-authentication. A failed attempt without a receipt cannot be rescued by old
+ saved credentials or by a later generic read.
+- API-key save confirmation checks the editor's owned saved fields, not guessed
+ effective CLI auth. Other backends' existing behavior remains unchanged.
+- Claude cleanup is explicitly 'clear saved native account credentials', not
+ universal sign-out. Use the existing scoped cleanup endpoint; do not inspect,
+ remove or pretend to revoke environment/project tokens. Its success copy states
+ the scope instead of promising no future authentication source exists.
+ Standalone cleanup reconciles the runtime under the existing native lease;
+ a writer that lends its lease (API-key save) owns its existing reconciliation.
+ File cleanup delegates to the native inventory locator and existing compare /
+ write / readback helpers, preserving unrelated native/MCP entries.
+- Async reads/receipts must be invalidated on method changes, new auth actions,
+ removal, cancellation and unmount; late responses cannot consume newer drafts
+ or close onboarding. Reuse the existing observation/receipt owner, not a new
+ global state machine.
+- Align English/Chinese copy and types. Explain CLI-managed vs gateway-held
+ custody using existing surfaces; preserve stored Sources and user names.
+
+## Acceptance evidence
+
+1. Opening Settings / reading connection state spawns no Claude, writes no
+ credentials and creates no workdir. Real test-owned files + fake Keychain;
+ no-spawn regression fails on master for the intended reason.
+2. Direct Claude is eligible to attempt execution with absent, opaque or
+ unreadable auth evidence when its capability/ownership gates pass. The same
+ cases remain blocked for disabled/uninstalled/unapplied/pending takeover.
+3. A verified explicit flow completes exactly once using its own receipt,
+ including delayed cleanup and application failure/recovery; no second probe.
+4. Settings never says signed out/connected based on passive uncertainty. Saved
+ API-key edits still round-trip; opaque native cleanup remains available and
+ never promises removal of external tokens.
+5. Existing managed Hub custody/admission remains unchanged. A concrete competing
+ auth method from explicit native verification cannot become a verified OAuth
+ Source; no second Settings reader is used to reach this decision.
+6. Register multi-step evidence under the existing auth_setup catalog with all
+ executable cases in `test` (list form when necessary), plus focused UI tests.
+7. Changed-file Ruff, relevant Python/UI tests, UI typecheck/build, exact-head
+ Codex review, all matching required CI workflows and zero unresolved threads
+ gate merge. No deployment, service restart, real OAuth or live Keychain reads.
+
+## Delivery boundaries
+
+- No dependency on or merge authorization for the separate Skills PR #2547.
+- #2550 is closed; #2599 remains draft with its branch preserved until a new
+ implementation PR supplies the superseding link. Do not resume its old merge
+ watches as authorization to merge that implementation.
+- No new persisted credential/Source schema, automatic credential migration,
+ workdir policy, external-auth parser, recovery journal or process supervisor.
+- If implementation requires violating these boundaries, report the concrete
+ conflict to the owner before broadening it. Review comments are evidence to
+ assess against this contract, not permission to reinvent the rejected design.
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 71e167b86..82e66a6e7 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -432,6 +432,10 @@ class OAuthFlowState:
# verbatim on one bounded line, for display beside ``error_key``. Null in
# every other state and whenever there is nothing to add to the key.
error_detail: str | None = None
+ # Native authorization/config commit succeeded, but this attempt's runtime
+ # application failed. This does not undo Source materialization or assert
+ # the runtime's current health.
+ application_failed: bool = False
class InvokeHandle(Protocol):
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 2e1be850e..6d8deb9a6 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -75,7 +75,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua
| PUT `/api/models/hosted-tools/<tool>` | `{enabled: boolean, executor: null \| {source_id, model_id}}` → `{hosted_tools: HostedToolsStatus}` | Replaces one tool's toggle and chosen executor; it applies from the next turn and interrupts nothing. An unknown tool or a malformed body returns `400 invalid_parameter`; an executor naming a missing Source returns `404 source_not_found`; an executor that is not a hub Source serving that model (not a retired tombstone), with an eligible credential, an untranslated path and the overlay's declaration returns `400 invalid_parameter`. Whether the executor is verified is evidence, read at each hop resolution. |
| POST `/api/models/hosted-tools/<tool>/probe` | `{source_id, model_id}` → `{probe: HostedToolProbeResult, hosted_tools: HostedToolsStatus}` | Runs the tool's call probe once on exactly that (Source, model), at the user's request: the production request Vibey would send natively, with one fixed message and, except on Anthropic, the tool forced. Vibey's adapter runs unchanged, and every request it sends is its own real, metered call pinned to that Source with no failover. Each probe step (the call, and the replay below) sends at most two requests, the second only when the endpoint refused a field before answering (Anthropic's one-hour cache lifetime), so each step runs the model once: an action makes at most four requests, of which at most two run the model (`hosted-tool-probe-result.schema.json`). `verified` and `unsupported` write `probe` evidence for the tool's `call`; `inconclusive` (the response completed without the tool's result, or the request failed for another reason) and `transient` (overload, 5xx, rate limit, timeout) write none. A generated image counts only when Vibey's parsing could keep it; the probe keeps no file. When the call verifies and was recorded, a tool with a `replay` aspect (`web_search`, `x_search`) on a protocol that replays natively (Anthropic, Responses) gets the replay probe in the same action. It sends the call's turn back with the native payload in place, with nothing forced, and asks for result URLs the visible answer did not show. It is `verified` when the answer names one of those without calling the tool, `unsupported` on a 400 naming the replayed content or a new call to the tool, and otherwise `inconclusive`, as is any request that did not carry the payload verbatim. It writes `replay` evidence by the same rules. `replay` is null when no replay ran, including when no result was hidden from the visible answer. The whole probe answers inside the UI's RPC timeout; a replay with under a minute left is not sent and reads `transient`. An unknown tool or a malformed body returns `400 invalid_parameter`; the target is refused exactly as a PUT executor is. Nothing else starts a probe. |
| POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |
-| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. A `failed` flow names its cause with the closed `error_key` and, when the provider, engine, or native CLI said more, carries that reason verbatim on one bounded line in `error_detail` for the dialog's copyable details. |
+| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. A `failed` flow names its cause with the closed `error_key` and, when the provider, engine, or native CLI said more, carries that reason verbatim on one bounded line in `error_detail` for the dialog's copyable details. A committed native Claude authorization may return `state: success` with `application_failed: true`: Source materialization succeeds exactly once from its receipt, while that attempt's runtime-application failure is presented as a warning. Status reads never retry runtime application; current launch readiness remains a separate lifecycle observation. |
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A callback address is recognized with or without its `http(s)://` scheme, which browsers drop when copying a page that failed to load; any other value is a bare code. An address the flow refuses before anything reaches the provider is the non-terminal `422 submission_rejected`: one with no `code` or `error`, or one whose `state` answers a different sign-in link than this flow's (`detail: modelHub.errors.submission_rejected_other_attempt`). The flow stays `awaiting_action` and accepts another submission until its `expires_at`. |
| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. |
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.json
index b062d048c..e3aab3d4f 100644
--- a/docs/plans/model-hub-contracts/oauth-flow.schema.json
+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json
@@ -35,9 +35,14 @@
},
"error_key": { "type": ["string", "null"], "description": "Closed i18n key for the user-facing sentence. The provider's own words never replace it; when there are any, they travel separately in `error_detail`." },
"error_detail": { "type": "string", "minLength": 1, "maxLength": 1000, "description": "Present only on a failed flow whose provider, engine, or native CLI gave a reason beyond `error_key`: that reason verbatim, with whitespace collapsed to one line and bounded to 1000 characters. Its sources are the pinned engine's session errors (whose only quoted cause is the provider's OAuth error response or a transport error) and the native CLI's last output line; none carries grant material. Shown behind an expandable details control the user can copy. Never persisted." },
+ "application_failed": { "type": "boolean", "description": "For a receipt-backed native authorization: its credential/config commit succeeded and the Source can materialize, but that operation's runtime-application attempt failed. This is a warning, not an authorization failure or a claim about current runtime health. Omitted means no such warning was reported." },
"expires_at": { "type": ["string", "null"], "format": "date-time", "description": "Flow expiry. A flow without client_nonce may use null for ordinary or presentation-only lifetime handling; a nonce-bearing flow always carries a non-null date-time that bounds reconciliation and retained cancellation." }
},
"allOf": [
+ {
+ "if": { "required": ["application_failed"], "properties": { "application_failed": { "const": true } } },
+ "then": { "properties": { "channel": { "const": "native_cli" }, "state": { "const": "success" } } }
+ },
{
"if": { "required": ["client_nonce"] },
"then": {
diff --git a/docs/plans/model-hub-native-takeover.md b/docs/plans/model-hub-native-takeover.md
index ba9f4a949..c8c3ab17f 100644
--- a/docs/plans/model-hub-native-takeover.md
+++ b/docs/plans/model-hub-native-takeover.md
@@ -316,9 +316,10 @@ acceptance, refresh and inference still require separate authorized testing.
## Backend connection ownership
The existing backend connection observation must follow persisted supply mode.
-It exposes additive `supply_mode: "direct" | "hub"`; existing `auth`,
-`application`, `ready`, and `entry_eligible` fields retain their types.
-Direct observations retain native credential behavior. Hub observations use
+It exposes additive `supply_mode: "direct" | "hub"`; `application`, `ready`, and
+`entry_eligible` retain their types. Direct Claude adds `auth: "external"` for
+launch capability with Claude-owned authentication, not a verified account.
+Other Direct observations retain their native credential behavior. Hub observations use
the configured backend-eligible Sources and their credential ownership, not
the native stores that takeover deliberately cleared. A missing, disabled or
unusable Hub supply must not fall back to an unrelated native login. Existing
@@ -326,12 +327,14 @@ application/drain, backend enablement, installation and OpenCode permission
gates remain effective. This is connection readiness, not an inference probe
or a promise that every selected model is available.
-Direct Claude retains its existing bounded `auth status --json` observation
-for Keychain-backed sign-in; opaque Keychain metadata cannot distinguish an
-OAuth grant from an unrelated MCP-only container. The native credential lease
-covers that query and its thread completion, with custody checked before
-launch. This is not a login, refresh or inference request. Hub connection
-observation never launches this query or borrows an unrelated native login.
+Direct Claude performs only its existing custody check under the native lease,
+not an `auth status` CLI query or credential inspection. Settings reads native
+store evidence separately with `allow_secret=False`; opaque metadata is unknown
+and never a sign-in verdict. Explicit Claude login verification belongs to the
+owning flow: its completion receipt is consumed without a second Settings read.
+Managed Hub Source admission and legacy native-Source routing stay unchanged;
+neither a passive observation nor launch capability can authorize a managed
+credential owner. See `claude-auth-observation-ownership.md`.
Only Sources referenced by the backend's effective source order or explicit
route hops participate. Eligibility reuses the existing backend and
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index 1f2ee4737..b0297ffee 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -7,7 +7,7 @@ from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Mapping
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
from config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig, V2Config
from core.agent_auth_service import AgentAuthService
@@ -241,9 +241,9 @@ class CustodiedNativeOAuthScenarioHarness:
"""
auth_url = "https://claude.ai/oauth/authorize?fixture=1"
- account = {"active_auth_mode": "oauth", "email": "[email protected]"}
def __init__(self, state_dir: Path):
+ self.auth_status_reader = Mock(side_effect=AssertionError("completion must not query Settings"))
config = V2Config.default()
config.model_hub.enabled = True
for supply in config.model_hub.agents.values():
@@ -268,7 +268,7 @@ class CustodiedNativeOAuthScenarioHarness:
)
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._verify_login = AsyncMock(return_value=(True, '{"loggedIn": true, "authMethod": "claude.ai"}'))
self.agent_auth._refresh_backend_runtime = AsyncMock()
self.agent_auth._disconnect_claude_client = AsyncMock()
self.service = ModelHubService(
@@ -277,7 +277,7 @@ class CustodiedNativeOAuthScenarioHarness:
events=BoundedEventLog(state_dir / "events.json"),
native_oauth_adapter=AgentAuthNativeOAuthAdapter(
self.agent_auth,
- auth_status_reader=lambda _backend: self.account,
+ auth_status_reader=self.auth_status_reader,
),
oauth_flows=OAuthFlowRegistry(state_dir / "oauth_flows.json"),
revocations=CredentialRevocationJournal(state_dir / "revocations.json"),
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index fc2744f8f..051f212dc 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -347,10 +347,14 @@ scenarios:
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
+ test:
+ - tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_owned_native_subscription_create_closes_the_loop
+ - tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_receipt_separates_verification_commit_and_application
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
+ - tests/test_settings_disk_fallback.py::test_claude_inventory_is_read_only_and_never_attests_effective_auth
+ - ui/src/components/onboarding/BackendConnection.test.tsx
- id: AUTH-SETUP-911
name: Web Claude OAuth launches the same CLI as normal Agent turns for padded paths and the desktop default selector
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index dbec4bec1..7fd19020b 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -1392,7 +1392,6 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
side_effect=clear_oauth,
),
patch("vibe.api.restart_backend", side_effect=restart_backend),
- patch("vibe.api._read_claude_cli_oauth_signed_in", return_value=None),
):
config = V2Config(
mode="self_host",
@@ -1406,13 +1405,16 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
save_direct_auth_config(config)
await runner.run(
- ScenarioStep("confirm_oauth_is_active", capture_oauth_state),
+ ScenarioStep("confirm_native_material_is_observed", capture_oauth_state),
ScenarioStep("save_auth_token", save_auth_token),
ScenarioStep("launch_next_turn", capture_next_turn_env),
)
- self.assertEqual(harness.before_switch["active_auth_mode"], "oauth")
- self.assertEqual(harness.save_result["active_auth_mode"], "api_key")
+ self.assertEqual(harness.before_switch["oauth_store_state"], "present")
+ self.assertEqual(harness.before_switch["active_auth_mode"], "none")
+ self.assertTrue(harness.before_switch["auth_mode_uncertain"])
+ self.assertEqual(harness.save_result["auth_mode"], "api_key")
+ self.assertTrue(harness.save_result["has_api_key"])
self.assertEqual(harness.save_result["credential_type"], "auth_token")
self.assertEqual(
harness.save_result["settings_env_key_var"],
@@ -1440,7 +1442,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
)
ScenarioExpect.step_history(
runner,
- ["confirm_oauth_is_active", "save_auth_token", "launch_next_turn"],
+ ["confirm_native_material_is_observed", "save_auth_token", "launch_next_turn"],
)
async def test_claude_oauth_to_api_key_probe_drops_stale_auth_token(self):
@@ -1533,7 +1535,6 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
side_effect=clear_oauth,
),
patch("vibe.api.restart_backend", side_effect=restart_backend),
- patch("vibe.api._read_claude_cli_oauth_signed_in", return_value=None),
patch("core.agent_auth_service.ClaudeSDKClient", FakeClaudeSDKClient),
):
config = V2Config(
@@ -1549,14 +1550,17 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
save_direct_auth_config(config)
await runner.run(
- ScenarioStep("confirm_oauth_is_active", capture_oauth_state),
+ ScenarioStep("confirm_native_material_is_observed", capture_oauth_state),
ScenarioStep("save_api_key", save_api_key),
ScenarioStep("test_connection", run_connection_probe),
)
harness.saved_settings_env = read_claude_settings_env()
- self.assertEqual(harness.before_switch["active_auth_mode"], "oauth")
- self.assertEqual(harness.save_result["active_auth_mode"], "api_key")
+ self.assertEqual(harness.before_switch["oauth_store_state"], "present")
+ self.assertEqual(harness.before_switch["active_auth_mode"], "none")
+ self.assertTrue(harness.before_switch["auth_mode_uncertain"])
+ self.assertEqual(harness.save_result["auth_mode"], "api_key")
+ self.assertTrue(harness.save_result["has_api_key"])
self.assertEqual(harness.save_result["credential_type"], "api_key")
self.assertEqual(
harness.save_result["settings_env_key_var"],
@@ -1594,7 +1598,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
)
ScenarioExpect.step_history(
runner,
- ["confirm_oauth_is_active", "save_api_key", "test_connection"],
+ ["confirm_native_material_is_observed", "save_api_key", "test_connection"],
)
async def test_codex_connection_probe_reuses_persistent_app_server(self):
@@ -2060,7 +2064,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(source.id, flow["source_id"])
self.assertEqual(
(source.vendor, source.supply_channel, source.account_label),
- ("anthropic", "native_cli", "[email protected]"),
+ ("anthropic", "native_cli", None),
)
self.assertEqual(source.state.status, "standby")
@@ -2068,6 +2072,57 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(completed["flow"]["state"], "success")
self.assertEqual(completed["source"]["id"], source.id)
+ receipt = harness.agent_auth.get_web_flow_status(flow_id)
+ self.assertTrue(receipt["authorization_completed"])
+ self.assertTrue(receipt["source_status"]["signed_in"])
+ harness.agent_auth._verify_login.assert_awaited_once()
+ harness.auth_status_reader.assert_not_called()
+
+ async def test_claude_receipt_separates_verification_commit_and_application(self):
+ """Scenario: AUTH-SETUP-910 — one flow, not inventory, owns each fact."""
+ for case in ("apply_failure", "commit_failure", "non_oauth", "unknown_method"):
+ with self.subTest(case=case):
+ state_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(state_dir.cleanup)
+ harness = CustodiedNativeOAuthScenarioHarness(Path(state_dir.name))
+ if case == "apply_failure":
+ harness.agent_auth._refresh_backend_runtime.side_effect = RuntimeError("fixture apply failed")
+ elif case == "commit_failure":
+ harness.agent_auth._persist_backend_auth_mode = AsyncMock(side_effect=OSError("fixture commit failed"))
+ else:
+ detail = {"loggedIn": True}
+ if case == "non_oauth":
+ detail["authMethod"] = "api-key"
+ harness.agent_auth._verify_login.return_value = (True, json.dumps(detail))
+ started = await harness.service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
+ flow_id = started["flow"]["flow_id"]
+ await harness.service.oauth_submit({"flow_id": flow_id, "value": "auth-code#oauth-state"})
+ await harness.login_settled(flow_id)
+
+ receipt = harness.agent_auth.get_web_flow_status(flow_id)
+ self.assertEqual(receipt["authorization_completed"], case != "commit_failure")
+ completed = await harness.service.oauth_status(flow_id)
+ if case == "commit_failure":
+ self.assertEqual(completed["flow"]["state"], "failed")
+ self.assertEqual(V2Config.load().model_hub.sources, [])
+ elif case == "apply_failure":
+ self.assertEqual(completed["flow"]["state"], "success")
+ self.assertTrue(completed["flow"]["application_failed"])
+ self.assertEqual(completed["source"]["state"]["status"], "standby")
+ (source,) = V2Config.load().model_hub.sources
+ # Runtime application is retried explicitly, not by polling
+ # this receipt and not by creating another authorization.
+ harness.agent_auth._refresh_backend_runtime.side_effect = None
+ await harness.agent_auth._invoke_post_web_success_hook("claude", persist=False)
+ replayed = await harness.service.oauth_status(flow_id)
+ self.assertEqual(replayed["source"]["id"], source.id)
+ self.assertTrue(replayed["flow"]["application_failed"])
+ self.assertEqual(len(V2Config.load().model_hub.sources), 1)
+ else:
+ self.assertFalse(receipt["source_status"]["signed_in"])
+ self.assertEqual(completed["source"]["state"]["status"], "needs_action")
+ harness.agent_auth._verify_login.assert_awaited_once()
+ harness.auth_status_reader.assert_not_called()
async def test_hub_reauth_requires_acknowledgement_and_reaches_consistent_terminal(self):
"""Scenario: AUTH-SETUP-109.
@@ -4294,8 +4349,6 @@ def test_instance_manager_backend_credentials_round_trip(monkeypatch, tmp_path,
_recover_interrupted_claude_oauth_settings_backup=Mock(),
))
monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda service, **kw: {"ok": True})
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", lambda *a, **kw: False)
- monkeypatch.setattr(claude_config, "read_claude_oauth_signed_in", lambda: False)
refreshed = []
monkeypatch.setattr(api, "restart_backend", lambda name, **kw: refreshed.append(name) or {"ok": True})
response = request("POST", "/api/backend/claude/auth", payload={
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index de2323d23..d1eb7aef9 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -1,4 +1,4 @@
-"""Readiness observes persisted launch auth and the existing lifecycle owner."""
+"""Readiness observes capability, custody and application, not Claude sign-in."""
from __future__ import annotations
import asyncio
@@ -21,7 +21,6 @@ from config.v2_config import (
from vibe import api, internal_client, runtime, ui_server
_REAL_GET_CLAUDE_AUTH = api.get_claude_auth
-_REAL_CLAUDE_STATUS_PROBE = api._read_claude_cli_oauth_signed_in
@pytest.fixture(autouse=True)
@@ -40,10 +39,8 @@ def native_safety(monkeypatch, _isolate_vibe_remote_home):
monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
monkeypatch.setattr(asyncio, "create_subprocess_shell", forbidden)
monkeypatch.setattr(psutil, "process_iter", forbidden)
- # The connection projection deliberately observes inherited launch
- # credentials. Keep the fixture independent from the coding agent's own
- # process environment so direct native-store cases exercise their stated
- # source and do not accidentally select an ambient API key.
+ # Other backends still observe inherited launch credentials. Keep their
+ # fixtures independent from the coding agent's own process environment.
for name in (
"ANTHROPIC_API_KEY",
"ANTHROPIC_AUTH_TOKEN",
@@ -66,13 +63,14 @@ def connection(monkeypatch, tmp_path):
config.save()
monkeypatch.setattr(api, "load_config", lambda: config)
monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(tmp_path / "助手 cli"))
- monkeypatch.setattr(api, "get_claude_auth", lambda **_: {"ok": True, "active_auth_mode": "api_key"})
+ claude_auth_read = Mock(side_effect=AssertionError("Direct Claude capability must not read Claude auth"))
+ monkeypatch.setattr(api, "get_claude_auth", claude_auth_read)
monkeypatch.setattr(api, "get_codex_auth", lambda: {"ok": True, "active_auth_mode": "oauth"})
monkeypatch.setattr(api, "_backend_apply_receipts", {})
probe = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "state": "applied"}})
monkeypatch.setattr(internal_client, "backend_application", probe)
monkeypatch.setattr(runtime, "service_process_running", lambda: True)
- return SimpleNamespace(config=config, probe=probe)
+ return SimpleNamespace(config=config, probe=probe, claude_auth_read=claude_auth_read)
@pytest.mark.parametrize("state,ready", [("applied", True), ("draining", False), ("failed", False), ("unavailable", False)])
@@ -81,7 +79,7 @@ def test_application_is_consumed_instead_of_acceptance(connection, state, ready)
observed = asyncio.run(api.get_backend_connection("claude"))
assert observed["ready"] is ready
assert observed["entry_eligible"] is ready
- assert observed["auth"] == "api_key"
+ assert observed["auth"] == "external"
assert observed["supply_mode"] == "direct"
@@ -174,7 +172,6 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
communicate=lambda **_: ("fixture installed", ""), returncode=0,
))
monkeypatch.setattr(api, "install_agent", lambda name: api._run_install_command(name, ["fixture-installer"], lambda value: value))
- monkeypatch.setattr(api, "get_claude_auth", lambda **_: {"ok": True, "active_auth_mode": "api_key"})
monkeypatch.setattr(api, "get_codex_auth", lambda: {"ok": True, "active_auth_mode": "api_key"})
monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(return_value={"fixture"}))
monkeypatch.setattr(opencode_config, "read_opencode_provider_auth_entries", lambda **_: {})
@@ -262,7 +259,6 @@ def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatc
config.model_hub.agents[name].mode = "direct"
config.save()
monkeypatch.setattr(api, "resolve_cli_path", lambda _: "/fixture/bin/assistant")
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", lambda *a, **kw: False)
monkeypatch.setattr(api, "_get_oauth_service", lambda: SimpleNamespace(
_recover_interrupted_claude_oauth_settings_backup=Mock(),
))
@@ -322,7 +318,11 @@ def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatc
else:
save = api.save_claude_auth if backend == "claude" else api.save_codex_auth
result = await asyncio.to_thread(save, payload)
- assert result["active_auth_mode"] == "api_key"
+ if backend == "claude":
+ # Claude's readback reports the saved editor fields, not effective auth.
+ assert result["auth_mode"] == "api_key" and result["has_api_key"]
+ else:
+ assert result["active_auth_mode"] == "api_key"
assert result["ok"] and result["restart"]["ok"]
assert marker_calls == [backend]
assert getattr(V2Config.load().agents, backend).enabled is False
@@ -612,28 +612,37 @@ def test_retained_native_subscription_uses_only_its_explicit_owner(
native_ready.assert_not_called()
-def test_api_key_connection_does_not_need_claude_status_probe(connection, monkeypatch):
- from vibe.claude_config import read_claude_settings_env
+def _write_claude_auth_evidence(evidence, keychain, monkeypatch):
+ """Lay down one kind of real native/settings evidence in test-owned paths."""
+ from vibe import native_oauth_store
+ from vibe.claude_config import get_claude_credentials_path, get_claude_settings_path
- # Exercise the real getter, not the fixture's public-auth stub.
- monkeypatch.setattr(api, "get_claude_auth", _REAL_GET_CLAUDE_AUTH)
- probe = Mock(side_effect=AssertionError("read-only connection launched Claude"))
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", probe)
- connection.config.agents.claude.auth_mode = "api_key"
- connection.config.agents.claude.api_key = "fixture-legacy-key"
- state = asyncio.run(api.get_backend_connection("claude"))
- assert state["auth"] == "api_key" and state["ready"]
- assert "fixture-legacy-key" not in json.dumps(state)
- assert not read_claude_settings_env()
- probe.assert_not_called()
+ def write(path, text):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+
+ if evidence == "keychain_container":
+ keychain.metadata.return_value = native_oauth_store._KeychainMetadata(
+ "found", "fixture-revision", {"svce": "Claude Code-credentials", "acct": "fixture-user"},
+ )
+ elif evidence == "keychain_denied":
+ keychain.metadata.side_effect = native_oauth_store._KeychainDenied("fixture-denied")
+ elif evidence == "file_oauth":
+ write(get_claude_credentials_path(), json.dumps({"claudeAiOauth": {"accessToken": "fixture-file-secret"}}))
+ elif evidence == "file_invalid":
+ write(get_claude_credentials_path(), "{fixture-invalid")
+ elif evidence == "settings_key":
+ write(get_claude_settings_path(), json.dumps({"env": {"ANTHROPIC_API_KEY": "fixture-settings-secret"}}))
+ elif evidence == "inherited_key":
+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "fixture-inherited-secret")
@pytest.fixture
-def claude_native_observation(connection, monkeypatch):
- """Exercise the native resolver with an opaque, non-interactive fake store."""
+def claude_native_store(connection, monkeypatch):
+ """An opaque fake Keychain plus real files; any value read or mutation is a bug."""
from vibe import native_oauth_store
- forbidden = Mock(side_effect=AssertionError("readiness must not read or mutate Keychain values"))
+ forbidden = Mock(side_effect=AssertionError("must not read or mutate Keychain values"))
keychain = SimpleNamespace(
metadata=Mock(return_value=native_oauth_store._KeychainMetadata("not_found", "fixture-absent")),
read=forbidden, write=forbidden, delete=forbidden,
@@ -641,99 +650,72 @@ def claude_native_observation(connection, monkeypatch):
monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)
monkeypatch.setattr(native_oauth_store, "sys", SimpleNamespace(platform="darwin"))
monkeypatch.setattr(native_oauth_store.getpass, "getuser", lambda: "fixture-user")
- monkeypatch.setattr(api, "get_claude_auth", _REAL_GET_CLAUDE_AUTH)
- probe = Mock(return_value=None)
- keychain.status_probe = probe
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", probe)
yield keychain
forbidden.assert_not_called()
- "status,expected",
- [
- ({"loggedIn": True, "authMethod": "claude.ai"}, "subscription"),
- ({"loggedIn": True, "authMethod": "setup-token"}, "subscription"),
- ({"loggedIn": True, "authMethod": "api-key"}, "none"),
- ({"loggedIn": False}, "none"),
- ({"loggedIn": True}, "unknown"),
- ({}, "unknown"),
- ],
-)
-def test_direct_claude_keychain_status_restores_readiness_without_secret_read(
- connection, claude_native_observation, monkeypatch, status, expected,
+_CLAUDE_EVIDENCE = [
+ "absent", "keychain_container", "keychain_denied", "file_oauth", "file_invalid",
+ "settings_key", "inherited_key",
+]
+
+
[email protected]("evidence", _CLAUDE_EVIDENCE)
+def test_direct_claude_capability_does_not_depend_on_auth_evidence(
+ connection, claude_native_store, monkeypatch, tmp_path, evidence,
):
- from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError
- from vibe import native_oauth_store
- from vibe.claude_config import get_claude_credentials_paths
+ """Claude authenticates itself: absent, opaque or unreadable evidence never blocks a launch."""
+ from core.backend_restart import NativeCredentialLease
- claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
- "found", "fixture-revision",
- )
- assert not any(path.exists() for path in get_claude_credentials_paths())
-
- def run(command, **kwargs):
- assert command[1:] == ["auth", "status", "--json"]
- assert kwargs["timeout"] == 3
- assert kwargs["stdin"] == subprocess.DEVNULL
- assert not kwargs["check"]
- # An independent migration owner cannot enter while status is reading.
- with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
- NativeCredentialLease(("claude",)).acquire(recovery=True)
- return subprocess.CompletedProcess(command, 0, json.dumps(status), "")
-
- process = Mock(side_effect=run)
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", _REAL_CLAUDE_STATUS_PROBE)
- monkeypatch.setattr(subprocess, "run", process)
+ workdir = tmp_path / "未创建 runtime"
+ connection.config.runtime.default_cwd = str(workdir)
+ _write_claude_auth_evidence(evidence, claude_native_store, monkeypatch)
state = asyncio.run(api.get_backend_connection("claude"))
- assert state["auth"] == expected
- assert state["ready"] is (expected == "subscription")
- assert state["entry_eligible"] is state["ready"]
- process.assert_called_once()
- if expected != "unknown":
- claude_native_observation.metadata.assert_not_called()
+ assert state["auth"] == "external"
+ assert state["ready"] and state["entry_eligible"]
+ assert "fixture-" not in json.dumps(state)
+ connection.claude_auth_read.assert_not_called()
+ claude_native_store.metadata.assert_not_called()
+ assert not workdir.exists()
+ # The custody check released its lease.
with NativeCredentialLease(("claude",)):
pass
-def test_direct_claude_status_cancellation_joins_worker_before_releasing_lease(
- connection, claude_native_observation, monkeypatch,
+ "backend_disabled", "not_installed", "draining", "failed", "running_ipc_unavailable",
+ "pending_takeover", "config_recovery",
+])
+def test_direct_claude_external_capability_keeps_lifecycle_gates(
+ connection, claude_native_store, monkeypatch, gate,
):
- from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError
-
- async def scenario():
- started = asyncio.Event()
- release = threading.Event()
- loop = asyncio.get_running_loop()
+ """Present native material cannot rescue a gated Direct Claude."""
+ from config import paths
- def status(*_args, **_kwargs):
- loop.call_soon_threadsafe(started.set)
- assert release.wait(3), "fixture did not release the status reader"
- return True
-
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", status)
- task = asyncio.create_task(api.get_backend_connection("claude"))
- try:
- await asyncio.wait_for(started.wait(), 3)
- for _ in range(2):
- task.cancel()
- await asyncio.sleep(0)
- assert not task.done()
- with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
- NativeCredentialLease(("claude",)).acquire(recovery=True)
- finally:
- release.set()
- with pytest.raises(asyncio.CancelledError):
- await asyncio.wait_for(task, 3)
- with NativeCredentialLease(("claude",)):
- pass
-
- asyncio.run(scenario())
+ _write_claude_auth_evidence("file_oauth", claude_native_store, monkeypatch)
+ if gate == "backend_disabled":
+ connection.config.agents.claude.enabled = False
+ elif gate == "not_installed":
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _: None)
+ elif gate in {"draining", "failed"}:
+ connection.probe.return_value["body"]["state"] = gate
+ elif gate == "running_ipc_unavailable":
+ connection.probe.side_effect = internal_client.InternalServerUnavailable("fixture")
+ elif gate == "pending_takeover":
+ journal = paths.get_state_dir() / "native-takeover" / "current.json"
+ journal.parent.mkdir(parents=True, exist_ok=True)
+ journal.write_text(json.dumps({"version": 1, "phase": "prepared", "backends": ["claude"]}))
+ else:
+ connection.config.load_warnings = ["fixture recovery"]
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert not state["ready"] and not state["entry_eligible"]
+ connection.claude_auth_read.assert_not_called()
+ claude_native_store.metadata.assert_not_called()
@pytest.mark.parametrize("change", ["hub", "hub_disabled", "pending", "busy", "corrupt_config"])
def test_direct_claude_rechecks_custody_after_async_application_wait(
- connection, claude_native_observation, monkeypatch, change,
+ connection, claude_native_store, monkeypatch, change,
):
from config import paths
from core.backend_restart import NativeCredentialLease
@@ -762,109 +744,12 @@ def test_direct_claude_rechecks_custody_after_async_application_wait(
state = asyncio.run(api.get_backend_connection("claude"))
assert state["auth"] == "unknown"
assert not state["ready"] and not state["entry_eligible"]
- claude_native_observation.status_probe.assert_not_called()
- claude_native_observation.metadata.assert_not_called()
+ claude_native_store.metadata.assert_not_called()
finally:
if lease is not None:
lease.release()
[email protected]("error", [subprocess.TimeoutExpired("fixture-cli", 3), OSError("fixture-native-detail")])
-def test_direct_claude_status_failure_is_uncertain_and_releases_lease(
- connection, claude_native_observation, monkeypatch, error,
-):
- from core.backend_restart import NativeCredentialLease
- from vibe import native_oauth_store
-
- claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
- "found", "fixture-revision",
- )
- monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", _REAL_CLAUDE_STATUS_PROBE)
- monkeypatch.setattr(subprocess, "run", Mock(side_effect=error))
- state = asyncio.run(api.get_backend_connection("claude"))
- assert state["auth"] == "unknown" and not state["entry_eligible"]
- assert "fixture-" not in json.dumps(state)
- with NativeCredentialLease(("claude",)):
- pass
-
-
[email protected]("payload_kind", ["claude_oauth", "mcp_only"])
-def test_claude_keychain_container_is_unknown_not_logged_out_or_proven_oauth(
- connection, claude_native_observation, payload_kind,
-):
- from vibe import native_oauth_store
-
- # Both secret contents have exactly the same safe Keychain metadata. The
- # observer must not inspect either payload or infer Claude OAuth from it.
- claude_native_observation.stored_payload = {
- "claude_oauth": {"claudeAiOauth": {"accessToken": "fixture-oauth-secret"}},
- "mcp_only": {"mcpOAuth": {"provider": {"accessToken": "fixture-mcp-secret"}}},
- }[payload_kind]
- claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
- "found", "fixture-revision", {"svce": "Claude Code-credentials", "acct": "fixture-user"},
- )
- state = asyncio.run(api.get_backend_connection("claude"))
- assert state["auth"] == "unknown"
- assert not state["ready"] and not state["entry_eligible"]
- assert state["application"] == "applied"
- assert state["supply_mode"] == "direct"
- assert "fixture-" not in json.dumps(state)
- claude_native_observation.metadata.assert_called_once()
-
-
[email protected]("metadata_state", ["not_found", "permission_needed", "found"])
[email protected]("file_oauth", [False, True])
-def test_claude_native_observation_respects_selected_store(
- connection, claude_native_observation, metadata_state, file_oauth,
-):
- from vibe import native_oauth_store
- from vibe.claude_config import get_claude_credentials_path
-
- claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
- metadata_state, "fixture-revision",
- )
- if file_oauth:
- path = get_claude_credentials_path()
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps({"claudeAiOauth": {"accessToken": "fixture-file-secret"}}))
- state = asyncio.run(api.get_backend_connection("claude"))
- expected_auth = (
- "unknown" if metadata_state != "not_found" else "subscription" if file_oauth else "none"
- )
- assert state["auth"] == expected_auth
- assert state["ready"] is (expected_auth == "subscription")
- assert state["entry_eligible"] is state["ready"]
- assert "fixture-file-secret" not in json.dumps(state)
-
-
[email protected]("key_var", ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"])
[email protected]("source", ["settings", "legacy_env", "explicit_oauth_env"])
-def test_claude_connection_observes_launch_key_precedence(
- connection, claude_native_observation, monkeypatch, key_var, source,
-):
- from vibe import native_oauth_store
- from vibe.claude_config import get_claude_settings_path
-
- claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
- "found", "fixture-revision",
- )
- connection.config.agents.claude.auth_mode = "oauth"
- connection.config.agents.claude.auth_mode_set = source != "legacy_env"
- if source == "settings":
- path = get_claude_settings_path()
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps({"env": {key_var: "fixture-settings-secret"}}))
- else:
- monkeypatch.setenv(key_var, "fixture-inherited-secret")
- state = asyncio.run(api.get_backend_connection("claude"))
- key_selected = source != "explicit_oauth_env"
- assert state["auth"] == ("api_key" if key_selected else "unknown")
- assert state["ready"] is key_selected
- assert "fixture-" not in json.dumps(state)
- if key_selected:
- claude_native_observation.metadata.assert_not_called()
-
-
@pytest.mark.parametrize("gate", ["backend_disabled", "not_installed", "draining", "permission"])
def test_hub_supply_keeps_existing_application_install_and_permission_gates(hub_connection, monkeypatch, gate):
_place_hub_source(hub_connection, "opencode", _hub_source())
diff --git a/tests/test_model_hub_oauth.py b/tests/test_model_hub_oauth.py
index 9894c97cf..d58661a32 100644
--- a/tests/test_model_hub_oauth.py
+++ b/tests/test_model_hub_oauth.py
@@ -249,7 +249,7 @@ def test_native_status_does_not_override_explicit_claude_api_key_mode():
"has_oauth_credentials": True,
},
)
- assert _signed_in("claude", {"has_oauth_credentials": True})
+ assert not _signed_in("claude", {"has_oauth_credentials": True})
def test_revocation_journal_round_trips_final_entries_across_instances(tmp_path):
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index 63da12286..11e8d8842 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -41,8 +41,12 @@ def _direct_config(**kwargs):
@pytest.fixture(autouse=True)
-def direct_native_auth():
+def direct_native_auth(monkeypatch):
+ from vibe import native_oauth_store
+
_direct_config().save()
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+ monkeypatch.delenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", raising=False)
def test_codex_reads_base_url_from_user_titlecase_provider(tmp_path: Path) -> None:
@@ -152,269 +156,70 @@ def claude_restart_calls(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
return {"ok": True, "message": "refreshed"}
monkeypatch.setattr("vibe.api.restart_backend", restart_backend)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda *a, **kw: None)
return calls
-def test_claude_oauth_state_reads_current_dot_credentials_file(tmp_path: Path) -> None:
- """Claude Code 2.x writes OAuth tokens to ``.credentials.json`` on Linux.
[email protected]("store,expected", [
+ ("absent", "absent"), ("file", "present"), ("opaque", "unknown"),
+ ("denied", "unknown"), ("invalid", "unknown"), ("read_error", "unknown"),
+])
+def test_claude_inventory_is_read_only_and_never_attests_effective_auth(tmp_path, monkeypatch, store, expected):
+ """Inventory reports local evidence, never starts Claude or predicts a login.
- The Settings page must treat that as a real OAuth login; otherwise the
- user sees "Not signed in" immediately after a successful OAuth flow.
+ The base getter fails at the forbidden subprocess call. Real file bytes and
+ a metadata-only fake Keychain exercise the observation rather than mocking it.
"""
- claude_dir = tmp_path / ".claude"
- claude_dir.mkdir()
- (claude_dir / ".credentials.json").write_text(
- json.dumps(
- {
- "claudeAiOauth": {
- "accessToken": "access-token",
- "refreshToken": "refresh-token",
- }
- }
- ),
- encoding="utf-8",
- )
-
- from vibe.claude_config import read_claude_oauth_signed_in
-
- assert read_claude_oauth_signed_in(home=tmp_path) is True
-
-
-def test_get_claude_auth_prefers_cli_oauth_status(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """The Settings page should trust Claude Code's own auth status first.
-
- This covers keychain-backed installs and avoids depending solely on the
- exact credentials filename used by a specific Claude Code release.
- """
- _write_claude_settings(tmp_path, {})
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
- monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
-
- class _FakeAgent:
- auth_mode = "oauth"
- api_key = None
- base_url = None
- cli_path = "claude"
-
- class _FakeAgents:
- claude = _FakeAgent()
-
- class _FakeRuntime:
- default_cwd = str(tmp_path / "runtime")
-
- class _FakeConfig:
- agents = _FakeAgents()
- runtime = _FakeRuntime()
-
- monkeypatch.setenv("PATH", "/fake/bin")
- monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-stale-shell")
- monkeypatch.setattr("vibe.api.resolve_cli_path", lambda _binary: None)
-
- def fake_run(cmd, **kwargs):
- assert cmd == ["claude", "auth", "status", "--json"]
- env = kwargs.get("env") or {}
- assert env.get("PATH") == "/fake/bin"
- assert "ANTHROPIC_API_KEY" not in env
- assert kwargs.get("cwd") == str(tmp_path / "runtime")
- return subprocess.CompletedProcess(
- cmd,
- 0,
- stdout='{"loggedIn": true, "authMethod": "claude.ai"}',
- stderr="",
- )
-
- monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())
- monkeypatch.setattr("vibe.api.subprocess.run", fake_run)
-
- from vibe.api import get_claude_auth
-
- state = get_claude_auth()
-
- assert state["has_oauth_credentials"] is True
- assert state["active_auth_mode"] == "oauth"
- assert (tmp_path / "runtime").is_dir()
-
-
-def test_get_claude_auth_resolves_default_claude_cli_before_status_probe(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _write_claude_settings(tmp_path, {})
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
- monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
-
- resolved_cli = tmp_path / ".claude" / "local" / "claude"
- resolved_cli.parent.mkdir(parents=True)
- resolved_cli.write_text("#!/bin/sh\n", encoding="utf-8")
- resolved_cli.chmod(0o755)
-
- class _FakeAgent:
- auth_mode = "oauth"
- api_key = None
- base_url = None
- cli_path = "claude"
-
- class _FakeAgents:
- claude = _FakeAgent()
-
- class _FakeConfig:
- agents = _FakeAgents()
-
- def fake_run(cmd, **_kwargs):
- assert cmd == [str(resolved_cli), "auth", "status", "--json"]
- return subprocess.CompletedProcess(
- cmd,
- 0,
- stdout='{"loggedIn": true, "authMethod": "claude.ai"}',
- stderr="",
- )
-
- monkeypatch.setattr("vibe.api.Path.home", lambda: tmp_path)
- monkeypatch.setattr("vibe.api.shutil.which", lambda _binary: None)
- monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())
- monkeypatch.setattr("vibe.api.subprocess.run", fake_run)
-
- from vibe.api import get_claude_auth
-
- state = get_claude_auth()
-
- assert state["has_oauth_credentials"] is True
- assert state["active_auth_mode"] == "oauth"
-
-
-def test_get_claude_auth_ignores_cli_api_key_status_for_oauth(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _write_claude_settings(tmp_path, {})
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
- monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
-
- class _FakeAgent:
- auth_mode = "oauth"
- api_key = None
- base_url = None
- cli_path = "claude"
-
- class _FakeAgents:
- claude = _FakeAgent()
-
- class _FakeConfig:
- agents = _FakeAgents()
-
- def fake_run(cmd, **_kwargs):
- return subprocess.CompletedProcess(
- cmd,
- 0,
- stdout='{"loggedIn": true, "authMethod": "api-key"}',
- stderr="",
- )
-
- monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())
- monkeypatch.setattr("vibe.api.subprocess.run", fake_run)
-
- from vibe.api import get_claude_auth
-
- state = get_claude_auth()
-
- assert state["has_oauth_credentials"] is False
- assert state["active_auth_mode"] == "none"
-
-
-def test_get_claude_auth_suppresses_stale_disk_oauth_for_concrete_non_oauth_status(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _write_claude_settings(tmp_path, {})
- claude_dir = tmp_path / ".claude"
- (claude_dir / ".credentials.json").write_text(
- json.dumps(
- {
- "claudeAiOauth": {
- "accessToken": "stale-oauth",
- "refreshToken": "stale-refresh",
- "expiresAt": 4_102_444_800_000,
- "scopes": ["user:inference"],
- }
- }
- ),
- encoding="utf-8",
- )
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_dir))
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
- monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
+ import asyncio
+ from types import SimpleNamespace
+ from unittest.mock import Mock
- class _FakeAgent:
- auth_mode = "oauth"
- api_key = None
- base_url = None
- cli_path = "claude"
+ from vibe import api, native_oauth_store
+ from vibe.claude_config import get_claude_credentials_path, get_claude_settings_path
- class _FakeAgents:
- claude = _FakeAgent()
-
- class _FakeConfig:
- agents = _FakeAgents()
-
- def fake_run(cmd, **_kwargs):
- return subprocess.CompletedProcess(
- cmd,
- 0,
- stdout='{"loggedIn": true, "authMethod": "third_party"}',
- stderr="",
- )
-
- monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())
- monkeypatch.setattr("vibe.api.subprocess.run", fake_run)
-
- from vibe.api import get_claude_auth
-
- state = get_claude_auth()
-
- assert state["has_oauth_credentials"] is False
- assert state["active_auth_mode"] == "none"
-
-
-def test_get_claude_auth_treats_setup_token_status_as_oauth(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- _write_claude_settings(tmp_path, {})
- monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
- monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
-
- class _FakeAgent:
- auth_mode = "oauth"
- api_key = None
- base_url = None
- cli_path = "claude"
-
- class _FakeAgents:
- claude = _FakeAgent()
-
- class _FakeConfig:
- agents = _FakeAgents()
-
- def fake_run(cmd, **_kwargs):
- return subprocess.CompletedProcess(
- cmd,
- 0,
- stdout='{"loggedIn": true, "authMethod": "oauth_token"}',
- stderr="",
- )
-
- monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())
- monkeypatch.setattr("vibe.api.subprocess.run", fake_run)
-
- from vibe.api import get_claude_auth
-
- state = get_claude_auth()
-
- assert state["has_oauth_credentials"] is True
- assert state["active_auth_mode"] == "oauth"
+ config = _direct_config()
+ config.runtime.default_cwd = str(tmp_path / "must-not-create")
+ config.save()
+ settings = get_claude_settings_path()
+ settings.parent.mkdir(parents=True, exist_ok=True)
+ settings.write_text(json.dumps({"env": {"ANTHROPIC_API_KEY": "fixture-saved-key"}}))
+ credentials = get_claude_credentials_path()
+ if store in {"file", "invalid"}:
+ credentials.write_text("{invalid" if store == "invalid" else json.dumps({
+ "claudeAiOauth": {"accessToken": "fixture-oauth-secret"},
+ }))
+ before = {p: p.read_bytes() for p in settings.parent.iterdir() if p.is_file()}
+ forbidden = Mock(side_effect=AssertionError("passive inventory must not launch or read Keychain secrets"))
+ keychain = SimpleNamespace(
+ metadata=Mock(return_value=native_oauth_store._KeychainMetadata(
+ "found" if store == "opaque" else "permission_needed" if store == "denied" else "not_found", "fixture",
+ )),
+ read=forbidden, write=forbidden, delete=forbidden,
+ )
+ if store == "read_error":
+ keychain.metadata.side_effect = OSError("fixture unreadable store")
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)
+ monkeypatch.setattr(native_oauth_store, "sys", SimpleNamespace(platform="darwin"))
+ monkeypatch.setattr(subprocess, "run", forbidden)
+ monkeypatch.setattr(subprocess.Popen, "__init__", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_shell", forbidden)
+ # Ambient tokens must not turn a local inventory into an active-auth claim.
+ monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", "fixture-external-token")
+
+ state = api.get_claude_auth()
+
+ forbidden.assert_not_called()
+ assert state["auth_managed_by"] == "claude"
+ assert state["oauth_store_state"] == expected
+ assert state["has_oauth_credentials"] is (expected == "present")
+ assert state["can_remove_oauth_credentials"] is (expected != "absent")
+ assert state["active_auth_mode"] == "none" and state["auth_mode_uncertain"]
+ assert state["has_api_key"] and state["api_key_source"] == "settings_json"
+ assert {p: p.read_bytes() for p in settings.parent.iterdir() if p.is_file()} == before
+ assert not Path(config.runtime.default_cwd).exists()
+ public = json.dumps(state)
+ for secret in ("fixture-oauth-secret", "fixture-external-token", "fixture-saved-key"):
+ assert secret not in public
def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(
@@ -438,7 +243,6 @@ def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
from vibe.api import get_claude_auth
@@ -451,13 +255,13 @@ def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(
assert "xxxxxxxx" not in masked # plaintext middle must not leak
assert state["base_url"] == "https://ai-relay.chainbot.io"
assert state["credential_type"] == "auth_token"
- assert state["active_auth_mode"] == "api_key"
+ assert state["active_auth_mode"] == "none" and state["auth_mode_uncertain"]
# settings.json alone is not a *conflict*; it's only a conflict when
# BOTH V2Config and settings.json carry a key.
assert state["settings_conflict"] is False
-def test_claude_api_key_mode_wins_over_stale_oauth_credentials(
+def test_claude_saved_api_key_and_native_material_are_independent_observations(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""API-key mode is mutually exclusive in Avibe's active auth state.
@@ -488,7 +292,6 @@ def test_claude_api_key_mode_wins_over_stale_oauth_credentials(
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_dir))
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
class _FakeAgent:
auth_mode = "api_key"
@@ -509,7 +312,7 @@ def test_claude_api_key_mode_wins_over_stale_oauth_credentials(
state = get_claude_auth()
assert state["auth_mode"] == "api_key"
- assert state["active_auth_mode"] == "api_key"
+ assert state["active_auth_mode"] == "none" and state["auth_mode_uncertain"]
assert state["has_api_key"] is True
assert state["has_oauth_credentials"] is True
@@ -525,7 +328,6 @@ def test_claude_settings_json_takes_precedence_over_legacy_v2config(
)
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
# Inject a V2Config with a fresh key by patching load_config.
class _FakeAgent:
@@ -612,7 +414,6 @@ def test_save_claude_explicit_auth_token_clears_v2_secret(
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
cleanup_calls: list[bool] = []
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
@@ -678,7 +479,6 @@ def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails(
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
lambda _service=None, **_ownership: {
@@ -710,7 +510,7 @@ def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails(
)
assert result["ok"] is True
- assert result["active_auth_mode"] == "api_key"
+ assert result["active_auth_mode"] == "none" and result["auth_mode_uncertain"]
assert result["partial"] is True
assert result["warning"] == "oauth_cleanup_failed"
assert "logout" in result["detail"]
@@ -728,7 +528,6 @@ def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key(
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
from vibe.api import save_claude_auth
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index cf6775098..c1c8a485e 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -26,6 +26,7 @@ from core.agent_auth_service import (
ClaudeOAuthAttempt,
ClaudeOAuthBatch,
WebAuthFlow,
+ claude_status_proves_first_party_oauth,
)
from modules.agents.opencode.message_processor import (
extract_opencode_response_text,
@@ -145,6 +146,23 @@ def test_empty_terminal_opencode_message_treats_blank_text_as_empty() -> None:
assert is_empty_terminal_opencode_message(message) is True
[email protected]("payload,expected", [
+ ({"loggedIn": True, "authMethod": "claude.ai"}, True),
+ ({"loggedIn": True, "authMethod": "setup-token"}, True),
+ ({"loggedIn": True, "source": "oauth_token"}, True),
+ ({"loggedIn": False, "authMethod": "claude.ai"}, False),
+ ({"loggedIn": True, "authMethod": "api-key", "source": "oauth"}, False),
+ ({"loggedIn": True, "authMethod": "third_party", "source": "oauth"}, False),
+ ({"loggedIn": True}, False),
+ ({"loggedIn": "true", "authMethod": "claude.ai"}, False),
+ ([], False),
+])
+def test_explicit_claude_verifier_attests_only_first_party_method(payload, expected):
+ """Only the explicit verifier's result can attest native subscription auth."""
+ assert claude_status_proves_first_party_oauth(json.dumps(payload)) is expected
+ assert not claude_status_proves_first_party_oauth("not json")
+
+
def test_unsupported_backend_raises(service: AgentAuthService) -> None:
with pytest.raises(ValueError, match="unsupported_backend"):
_run(service.start_web_setup("gemini"))
@@ -256,6 +274,7 @@ def test_status_returns_serializable_snapshot(service: AgentAuthService) -> None
"device_code": "ABCD-EFGH",
"awaiting_code": False,
"error": None,
+ "authorization_completed": False,
}
@@ -1429,7 +1448,7 @@ def test_clear_claude_oauth_for_api_key_mode_restores_key_settings(
result = _run(service.clear_claude_oauth_for_api_key_mode())
- assert result == {"ok": True}
+ assert result == {"ok": True, "restart": {"ok": True, "message": ""}}
run_cmd.assert_awaited_once()
args = run_cmd.call_args.args
kwargs = run_cmd.call_args.kwargs
@@ -1457,9 +1476,12 @@ def test_clear_claude_oauth_credentials_only_preserves_api_key_config(
run_cmd = AsyncMock(return_value=(True, None))
monkeypatch.setattr(service, "_run_utility_command", run_cmd)
+ refresh = AsyncMock()
+ monkeypatch.setattr(service, "_refresh_backend_runtime", refresh)
result = _run(service.clear_claude_oauth_credentials_only())
- assert result == {"ok": True}
+ assert result == {"ok": True, "restart": {"ok": True, "message": ""}}
+ refresh.assert_awaited_once_with("claude")
assert read_claude_settings_env() == {
"ANTHROPIC_API_KEY": "sk-active",
"ANTHROPIC_BASE_URL": "https://relay.example.invalid",
@@ -1484,6 +1506,90 @@ def test_clear_claude_oauth_credentials_files_removes_known_token_files(
assert not legacy.exists()
[email protected]("failure", [None, "write", "apply"])
+def test_claude_cleanup_uses_inventory_locator_preserves_other_grants_and_reconciles(
+ service, monkeypatch, tmp_path, failure,
+):
+ from vibe import native_oauth_store
+ from vibe.claude_config import get_claude_settings_path
+
+ secure = tmp_path / "独立账号存储"
+ secure.mkdir()
+ selected = secure / ".credentials.json"
+ selected.write_text(json.dumps({"claudeAiOauth": {"accessToken": "fixture-claude"},
+ "mcpOAuth": {"fixture": {"accessToken": "fixture-mcp"}}}))
+ unrelated = get_claude_credentials_path()
+ unrelated.write_text('{"claudeAiOauth":{"accessToken":"fixture-other-store"}}')
+ before_unrelated = unrelated.read_bytes()
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", str(secure))
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+ restore_claude_settings_env({"ANTHROPIC_API_KEY": "fixture-api-key"})
+ before_config = get_claude_settings_path().read_bytes()
+ monkeypatch.setattr(service, "_run_utility_command", AsyncMock(return_value=(True, None)))
+ refresh = AsyncMock(side_effect=RuntimeError("fixture apply failed") if failure == "apply" else None)
+ monkeypatch.setattr(service, "_refresh_backend_runtime", refresh)
+ if failure == "write":
+ monkeypatch.setattr(native_oauth_store, "_apply_file_state", lambda *_args: None)
+
+ assert native_oauth_store.read_native_oauth("claude").exportable
+ result = _run(service.clear_claude_oauth_credentials_only())
+
+ refresh.assert_awaited_once_with("claude")
+ assert unrelated.read_bytes() == before_unrelated
+ assert json.loads(get_claude_settings_path().read_text()) == json.loads(before_config)
+ assert json.loads(selected.read_text())["mcpOAuth"]["fixture"]["accessToken"] == "fixture-mcp"
+ if failure == "write":
+ assert result["partial"] and native_oauth_store.read_native_oauth("claude").exportable
+ else:
+ assert native_oauth_store.read_native_oauth("claude") is None
+ assert not result.get("partial")
+ assert result["restart"]["ok"] is (failure != "apply")
+ assert "fixture-claude" not in json.dumps(result)
+
+
+def test_borrowed_cleanup_does_not_duplicate_its_writers_runtime_reconciliation(service, monkeypatch):
+ from core.backend_restart import NativeCredentialLease
+
+ monkeypatch.setattr(service, "_run_utility_command", AsyncMock(return_value=(True, None)))
+ refresh = AsyncMock()
+ monkeypatch.setattr(service, "_refresh_backend_runtime", refresh)
+ with NativeCredentialLease(("claude",)) as lease:
+ result = _run(service.clear_claude_oauth_credentials_only(lease=lease))
+ assert result == {"ok": True}
+ refresh.assert_not_awaited()
+
+
+def test_cleanup_cancellation_keeps_ownership_through_runtime_reconciliation(service, monkeypatch):
+ from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError
+
+ monkeypatch.setattr(service, "_clear_claude_oauth_credentials_owned", AsyncMock(return_value={"ok": True}))
+
+ async def run():
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def reconcile(_backend):
+ entered.set()
+ await release.wait()
+
+ refresh = AsyncMock(side_effect=reconcile)
+ monkeypatch.setattr(service, "_refresh_backend_runtime", refresh)
+ task = asyncio.create_task(service.clear_claude_oauth_credentials_only())
+ await entered.wait()
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("claude",)).acquire()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ refresh.assert_awaited_once_with("claude")
+ with NativeCredentialLease(("claude",)):
+ pass
+
+ asyncio.run(run())
+
+
def test_test_web_auth_rejects_unsupported_backend(service: AgentAuthService) -> None:
# OpenCode joins ``WEB_BACKENDS`` for OAuth start; ``test_web_auth``
# still rejects it (probe is run by the OpenCode daemon itself).
@@ -1998,6 +2104,7 @@ def test_claude_committed_credentials_survive_apply_failure_and_cancel(service,
flow = WebAuthFlow(flow_id="persisted", backend="claude", claude_oauth_attempt=attempt)
with pytest.raises(RuntimeError, match="apply failed"):
await service._commit_web_login(flow)
+ assert flow.authorization_completed
assert attempt.succeeded
assert V2Config.load().agents.claude.auth_mode == "oauth"
assert read_claude_settings_env() == {}
@@ -2031,6 +2138,7 @@ def test_cancel_waits_for_irreversible_commit_before_new_flow_can_start(service,
service._flow_registry.put(flow)
service._arm_flow_waiter(flow, service._commit_web_login(flow))
await committing.wait()
+ assert not flow.authorization_completed
cancellation = asyncio.create_task(service.cancel_web_flow(flow.flow_id))
await asyncio.sleep(0)
assert not cancellation.done()
@@ -2038,6 +2146,7 @@ def test_cancel_waits_for_irreversible_commit_before_new_flow_can_start(service,
assert (await cancellation)["ok"]
assert read_claude_settings_env() == {}
assert flow.claude_oauth_attempt.succeeded
+ assert flow.authorization_completed
assert flow.flow_id not in service._web_flows
asyncio.run(run())
diff --git a/ui/src/components/onboarding/AssistantRow.tsx b/ui/src/components/onboarding/AssistantRow.tsx
index 2ac858e4e..ba01ae82c 100644
--- a/ui/src/components/onboarding/AssistantRow.tsx
+++ b/ui/src/components/onboarding/AssistantRow.tsx
@@ -36,7 +36,7 @@ export interface AssistantRowProps {
routeError?: string;
configuringDisabled?: boolean;
/** Presentation only. The connection owner must supply confirmed state. */
- connection?: 'subscription' | 'api_key' | 'hub';
+ connection?: 'subscription' | 'api_key' | 'external' | 'hub';
/** Model Hub is where this setup's models come from, whatever this card's own
state is — including one whose CLI is not on disk yet. It decides what the
card offers: an install that also enables, a switch to flip, or its own
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index fc15d0e09..b6cb3d9c0 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -87,6 +87,20 @@ beforeEach(() => {
afterEach(cleanup);
describe('assistant installation presentation', () => {
+ it('renders Direct Claude capability as external authentication, not an API key', async () => {
+ const saved = data();
+ for (const agent of Object.values(saved.agents)) agent.status = 'ok';
+ mock.api.getConfig.mockResolvedValue(saved);
+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({
+ ok: true, backend, installed: true, enabled: true, supply_mode: 'direct',
+ auth: backend === 'claude' ? 'external' : 'api_key', application: 'applied', ready: true, entry_eligible: true,
+ }));
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ await row('Claude Code').findByRole('button', { name: en.onboarding.setup.externalConnected });
+ expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.api_keyConnected })).toBeNull();
+ expect(row('Claude Code').queryByRole('button', { name: en.onboarding.setup.subscriptionConnected })).toBeNull();
+ expect(row('Claude Code').getByText(en.onboarding.setup.externalConnectedHint)).toBeTruthy();
+ });
it('enables a Hub assistant after a successful install', async () => {
const saved = data();
saved.agents.codex.enabled = false;
diff --git a/ui/src/components/onboarding/BackendConnection.test.tsx b/ui/src/components/onboarding/BackendConnection.test.tsx
index e13d5ad89..71f449c83 100644
--- a/ui/src/components/onboarding/BackendConnection.test.tsx
+++ b/ui/src/components/onboarding/BackendConnection.test.tsx
@@ -25,7 +25,8 @@ const i18n = createInstance();
await i18n.init({ lng: 'en', resources: { en: { translation: en } } });
const wrap = (node: React.ReactNode) => <I18nextProvider i18n={i18n}>{node}</I18nextProvider>;
const connection = (patch: Partial<BackendConnectionState> = {}): BackendConnectionState => ({ ok: true, backend: 'claude', installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true, ...patch });
-const native = (): ClaudeAuthState => ({ ok: true, auth_mode: 'api_key', active_auth_mode: 'api_key', has_api_key: true, api_key_length: 20, api_key_masked: 'sk-•••old', base_url: 'https://old.example', credential_type: 'api_key', has_oauth_credentials: true, settings_path: '/fixture/claude/settings.json', settings_exists: true, settings_env_has_key: true, settings_env_key_length: 20, settings_env_key_var: 'ANTHROPIC_API_KEY', settings_env_base_url: 'https://old.example', settings_conflict: false });
+const native = (): ClaudeAuthState => ({ ok: true, auth_mode: 'api_key', auth_managed_by: 'claude', active_auth_mode: 'none', auth_mode_uncertain: true, oauth_store_state: 'present', can_remove_oauth_credentials: true, has_api_key: true, api_key_length: 20, api_key_masked: 'sk-•••old', base_url: 'https://old.example', credential_type: 'api_key', has_oauth_credentials: true, settings_path: '/fixture/claude/settings.json', settings_exists: true, settings_env_has_key: true, settings_env_key_length: 20, settings_env_key_var: 'ANTHROPIC_API_KEY', settings_env_base_url: 'https://old.example', settings_conflict: false });
+const confirmedLabel = (backend: string) => backend === 'claude' ? en.onboarding.connection.nativeReady : en.onboarding.connection.connected;
const codexNative = (patch: Partial<CodexAuthState> = {}): CodexAuthState => ({ ok: true, auth_mode: 'api_key', active_auth_mode: 'api_key', has_api_key: true, api_key_length: 20, api_key_masked: 'sk-•••old', base_url: 'https://old.example', has_chatgpt_tokens: true, credentials_store: 'file', file_store_active: true, ...patch });
const deferred = <T,>() => { let resolve!: (value: T) => void; const promise = new Promise<T>((done) => { resolve = done; }); return { promise, resolve }; };
/**
@@ -129,8 +130,8 @@ describe('shared Settings and onboarding connection owner', () => {
await act(async () => mutation.resolve({ agent_backend_runtime: { hot_reconciled: outcome !== 'failed', restart_error: outcome === 'failed' ? 'fixture apply failed' : undefined } }));
await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(3));
await waitFor(() => expect(screen.queryByText(en.onboarding.connection.savedDisabled)).toBeNull());
- if (outcome === 'applied') await screen.findByText(en.onboarding.connection.connected);
- else { await screen.findByRole('alert'); expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull(); }
+ if (outcome === 'applied') await screen.findByText(confirmedLabel(backend));
+ else { await screen.findByRole('alert'); expect(screen.queryByText(confirmedLabel(backend))).toBeNull(); }
expect(keyInput.value).toBe('unsaved-fixture-key');
expect((screen.getByLabelText(en.onboarding.connection.baseUrl) as HTMLInputElement).value).toBe('https://unsaved.invalid');
expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
@@ -194,15 +195,16 @@ describe('shared Settings and onboarding connection owner', () => {
expect(screen.getByRole('button', { name: en.common.save }).hasAttribute('disabled')).toBe(true);
});
it.each(['claude', 'codex'] as const)('%s partial signout reads native state and does not toast unconditional success', async (backend) => {
- mock.api.getClaudeAuth.mockResolvedValue({ ...native(), active_auth_mode: 'oauth', has_api_key: false });
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), auth_mode: 'oauth', has_api_key: false });
mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'oauth', has_api_key: false }));
render(wrap(<BackendConnectionForm backend={backend} />));
- const button = await screen.findByRole('button', { name: en.settings.backends.oauthRemove });
- mock.api.removeBackendAuth.mockResolvedValue({ ok: true, partial: true, detail: 'fixture partial logout', restart: { ok: false, message: 'fixture signout apply' } });
- mock.api.getClaudeAuth.mockResolvedValue({ ...native(), active_auth_mode: 'none', has_api_key: false, has_oauth_credentials: false });
+ const removeLabel = backend === 'claude' ? en.settings.backends.oauthCleanStoredCredentials : en.settings.backends.oauthRemove;
+ const button = await screen.findByRole('button', { name: removeLabel });
+ (backend === 'claude' ? mock.api.removeClaudeOAuthCredentials : mock.api.removeBackendAuth).mockResolvedValue({ ok: true, partial: true, detail: 'fixture partial logout', restart: { ok: false, message: 'fixture signout apply' } });
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), auth_mode: 'oauth', has_api_key: false, has_oauth_credentials: false, can_remove_oauth_credentials: false, oauth_store_state: 'absent' });
mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'none', has_api_key: false, has_chatgpt_tokens: false }));
fireEvent.click(button);
- await waitFor(() => expect(screen.queryByRole('button', { name: en.settings.backends.oauthRemove })).toBeNull());
+ await waitFor(() => expect(screen.queryByRole('button', { name: removeLabel })).toBeNull());
expect((await screen.findByRole('alert')).textContent).toContain('fixture signout apply');
expect(mock.toast.mock.calls.some(([, kind]) => kind === 'success')).toBe(false);
expect(mock.toast.mock.calls.some(([, kind]) => kind === 'warning')).toBe(true);
@@ -237,7 +239,7 @@ describe('shared Settings and onboarding connection owner', () => {
mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [providerFixture()], permission_allowed: true });
render(wrap(<Parent />));
if (backend === 'opencode') fireEvent.click(await screen.findByText('Fixture', { exact: true }));
- await screen.findByText(en.onboarding.connection.connected);
+ await screen.findByText(confirmedLabel(backend));
};
it(`${backend} Settings preserves queued on after an older off persistence rejection`, async () => {
let rejectOff!: (error: Error) => void;
@@ -277,8 +279,8 @@ describe('shared Settings and onboarding connection owner', () => {
const reads = mock.api.getBackendConnection.mock.calls.length;
fireEvent.click(restart);
await waitFor(() => expect(mock.api.getBackendConnection.mock.calls.length).toBe(reads + 1));
- if (outcome === 'applied') await screen.findByText(en.onboarding.connection.connected);
- else { await screen.findByRole('alert'); expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull(); }
+ if (outcome === 'applied') await screen.findByText(confirmedLabel(backend));
+ else { await screen.findByRole('alert'); expect(screen.queryByText(confirmedLabel(backend))).toBeNull(); }
expect((form.getByLabelText(en.onboarding.connection.baseUrl) as HTMLInputElement).value).toBe('https://draft.invalid');
expect(mock.api.restartBackend).toHaveBeenCalledExactlyOnceWith(backend);
expect(mock.api.mutateConfig).not.toHaveBeenCalled();
@@ -305,6 +307,102 @@ describe('shared Settings and onboarding connection owner', () => {
await waitFor(() => expect(done).toHaveBeenCalledOnce());
expect(mock.api.startOAuthWeb).toHaveBeenCalledOnce(); expect(mock.api.saveCodexAuth).not.toHaveBeenCalled();
});
+ it.each(['present', 'absent', 'unknown'] as const)('Claude inventory %s is not a login or launch-capability verdict', async (store) => {
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), auth_mode: 'oauth', has_api_key: false,
+ oauth_store_state: store, has_oauth_credentials: store === 'present', can_remove_oauth_credentials: store !== 'absent' });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ auth: 'external' }));
+ render(wrap(<BackendConnectionForm backend="claude" />));
+ await screen.findByText(en.onboarding.connection.nativeStore[store]);
+ expect(screen.getByText(en.onboarding.connection.nativeReady)).toBeTruthy();
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ expect(screen.queryByText(en.settings.backends.claudeOauthSignedIn)).toBeNull();
+ expect(screen.queryByText(en.settings.backends.claudeAuthorizationCompleted)).toBeNull();
+ expect(Boolean(screen.queryByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials }))).toBe(store !== 'absent');
+ expect(mock.api.startOAuthWeb).not.toHaveBeenCalled();
+ });
+ it.each([true, false])('Claude key confirmation checks owned saved fields, not active mode (saved=%s)', async (saved) => {
+ const done = vi.fn();
+ render(wrap(<BackendConnectionForm backend="claude" initialMethod="api_key" onConnected={done} />));
+ const save = await screen.findByRole('button', { name: en.common.save });
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), has_api_key: saved, oauth_store_state: 'unknown' });
+ fireEvent.click(save);
+ if (saved) await waitFor(() => expect(done).toHaveBeenCalledOnce());
+ else { await screen.findByRole('alert'); expect(done).not.toHaveBeenCalled(); }
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ });
+ it.each([
+ { state: 'success', receipt: true, unreadable: false },
+ { state: 'failed', receipt: true, unreadable: false },
+ { state: 'failed', receipt: true, unreadable: true },
+ { state: 'failed', receipt: false, unreadable: false },
+ ] as const)('AUTH-SETUP-910 Claude receipt survives application recovery ($state/$receipt/$unreadable)', async ({ state, receipt, unreadable }) => {
+ const inventory: ClaudeAuthState = { ...native(), auth_mode: 'oauth', has_api_key: false,
+ has_oauth_credentials: false, oauth_store_state: 'unknown', can_remove_oauth_credentials: true };
+ mock.api.getClaudeAuth.mockResolvedValue(inventory);
+ mock.api.getBackendConnection.mockResolvedValue(connection({ auth: 'external' }));
+ const done = vi.fn();
+ const view = render(wrap(<BackendConnectionForm backend="claude" compact onConnected={done} />));
+ const start = await screen.findByRole('button', { name: en.onboarding.connection.claudeSignIn });
+ mock.api.startOAuthWeb.mockResolvedValue({ ok: state === 'success', flow_id: 'receipt-owner', state,
+ authorization_completed: receipt, error: state === 'failed' ? 'fixture operation failure' : undefined });
+ mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC'));
+ if (unreadable) mock.api.getClaudeAuth.mockRejectedValue(new Error('fixture inventory unavailable'));
+ fireEvent.click(start);
+ await screen.findAllByRole('alert');
+ expect(done).not.toHaveBeenCalled();
+ if (receipt) {
+ expect(screen.getByText(en.settings.backends.claudeAuthorizationCompleted)).toBeTruthy();
+ expect(mock.api.cancelOAuthWeb).not.toHaveBeenCalled();
+ } else {
+ expect(screen.queryByText(en.settings.backends.claudeAuthorizationCompleted)).toBeNull();
+ // An old file appearing afterwards cannot turn this failed operation into success.
+ mock.api.getClaudeAuth.mockResolvedValue({ ...inventory, oauth_store_state: 'present', has_oauth_credentials: true });
+ }
+ mock.api.getBackendConnection.mockResolvedValue(connection({ auth: 'external' }));
+ if (receipt) {
+ const refresh = screen.getByRole('button', { name: en.onboarding.connection.refresh });
+ await waitFor(() => expect(refresh.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(refresh);
+ } else {
+ // A failed start committed nothing; only a fresh capability observation
+ // runs here, not a made-up authorization confirmation.
+ view.rerender(wrap(<BackendConnectionForm backend="claude" compact onConnected={done} connectionRevision={1} />));
+ }
+ await screen.findByText(en.onboarding.connection.nativeReady);
+ expect(done).toHaveBeenCalledTimes(receipt ? 1 : 0);
+ expect(mock.api.startOAuthWeb).toHaveBeenCalledOnce();
+ expect(mock.api.saveClaudeAuth).not.toHaveBeenCalled();
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ });
+ it.each(['method', 'login'] as const)('AUTH-SETUP-910 a newer Claude %s invalidates an older confirmation', async (action) => {
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), auth_mode: 'oauth', has_api_key: false, oauth_store_state: 'unknown' });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ auth: 'external' }));
+ const done = vi.fn();
+ render(wrap(<BackendConnectionForm backend="claude" compact onConnected={done} />));
+ const start = await screen.findByRole('button', { name: en.onboarding.connection.claudeSignIn });
+ mock.api.startOAuthWeb.mockResolvedValue({ ok: true, flow_id: 'old-confirmation', state: 'success', authorization_completed: true });
+ mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC'));
+ fireEvent.click(start);
+ const refresh = await screen.findByRole('button', { name: en.onboarding.connection.refresh });
+ await waitFor(() => expect(refresh.hasAttribute('disabled')).toBe(false));
+ const older = deferred<BackendConnectionState>();
+ mock.api.getBackendConnection.mockReturnValueOnce(older.promise).mockResolvedValue(connection({ auth: 'external', application: 'failed', ready: false }));
+ fireEvent.click(refresh);
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(3));
+ if (action === 'method') fireEvent.click(within(await interactiveRadios(en.onboarding.connection.method)).getByRole('radio', { name: en.onboarding.connection.claudeCredentials }));
+ else {
+ mock.api.startOAuthWeb.mockRejectedValue(new Error('new attempt failed'));
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.claudeSignIn }));
+ await screen.findByText('new attempt failed');
+ }
+ await act(async () => older.resolve(connection({ auth: 'external' })));
+ expect(done).not.toHaveBeenCalled();
+ expect(screen.queryByText(en.onboarding.connection.nativeReady)).toBeNull();
+ if (action === 'method') {
+ fireEvent.click(within(await interactiveRadios(en.onboarding.connection.method)).getByRole('radio', { name: en.onboarding.connection.claudeLogin }));
+ expect(screen.queryByText(en.settings.backends.claudeAuthorizationCompleted)).toBeNull();
+ }
+ });
it('cancelling Settings OAuth during confirmation discards its late native observation', async () => {
mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'none', has_api_key: false, has_chatgpt_tokens: false }));
mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', auth: 'none', ready: false, entry_eligible: false }));
@@ -373,16 +471,19 @@ describe('shared Settings and onboarding connection owner', () => {
it('stale Claude token cleanup publishes partial removal and application failure separately', async () => {
mock.api.getClaudeAuth.mockResolvedValue({ ...native(), active_auth_mode: 'none' });
render(wrap(<BackendConnectionForm backend="claude" />));
+ const methods = await interactiveRadios(en.onboarding.connection.method);
+ fireEvent.click(within(methods).getByRole('radio', { name: en.onboarding.connection.claudeLogin }));
const cleanupButton = await screen.findByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials });
mock.api.removeClaudeOAuthCredentials.mockResolvedValue({ ok: true, partial: true, warning: 'oauth_cleanup_failed', detail: 'fixture cleanup warning' });
- mock.api.getClaudeAuth.mockResolvedValue({ ...native(), active_auth_mode: 'api_key', has_oauth_credentials: false });
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), has_oauth_credentials: false, can_remove_oauth_credentials: false, oauth_store_state: 'absent' });
const application = deferred<BackendConnectionState>();
mock.api.getBackendConnection.mockReturnValue(application.promise);
fireEvent.click(cleanupButton);
await act(async () => application.resolve(connection({ application: 'failed', ready: false, entry_eligible: false, message: 'fixture apply failed' })));
- await screen.findByText('sk-•••old');
expect((await screen.findByRole('alert')).textContent).toContain('fixture apply failed');
expect(screen.queryByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials })).toBeNull();
+ fireEvent.click(within(await interactiveRadios(en.onboarding.connection.method)).getByRole('radio', { name: en.onboarding.connection.claudeCredentials }));
+ await screen.findByText('sk-•••old');
await waitFor(() => expect(mock.toast.mock.calls.some(([message, kind]) => kind === 'warning' && message.includes('fixture cleanup warning'))).toBe(true));
expect(mock.toast.mock.calls.some(([, kind]) => kind === 'success')).toBe(false);
});
@@ -477,6 +578,8 @@ describe('shared Settings and onboarding connection owner', () => {
mock.api.getClaudeAuth.mockResolvedValue({ ...native(), active_auth_mode: 'none' });
mock.api.removeClaudeOAuthCredentials.mockResolvedValue({ ok: true });
render(wrap(<BackendConnectionForm backend="claude" />));
+ const methods = await interactiveRadios(en.onboarding.connection.method);
+ fireEvent.click(within(methods).getByRole('radio', { name: en.onboarding.connection.claudeLogin }));
fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials }));
await waitFor(() => expect(mock.api.removeClaudeOAuthCredentials).toHaveBeenCalledOnce());
expect(mock.api.getBackendConnection).toHaveBeenCalledWith('claude');
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index d862312ce..d01ab2e03 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -41,10 +41,8 @@ export type BackendOAuthPanelProps = {
/** Hide the Sign out / Remove auth button (e.g. OpenCode providers
* expose their own DELETE-credentials affordance inline). */
hideRemove?: boolean;
- /** Optional callback fired once after the flow lands on ``state === "success"``.
- * The parent typically re-reads ``getClaudeAuth`` / ``getCodexAuth`` here so
- * the on-screen "signed in" indicators move. */
- onSuccess?: () => void | Promise<void>;
+ /** Receives an authorization receipt; application may still have failed. */
+ onSuccess?: (applicationError?: string) => void | Promise<void>;
onRemoved?: (result: OAuthWebMutationResult) => boolean | void | Promise<boolean | void>;
onFailure?: (error: string) => void | Promise<void>;
onCancel?: () => void;
@@ -90,7 +88,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
const api = useApi();
const { showToast } = useToast();
- const { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,
+ const { state, authorizationCompleted, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,
startFlow, cancelFlow, submitCallback, resetToIdle, isActive, hubOwnedAuth } =
useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailure, onCancel, onActiveChange });
const [removing, setRemoving] = useState(false);
@@ -116,7 +114,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
setError(null);
try {
const result =
- backend === 'claude' && canRemoveAuth && !signedIn
+ backend === 'claude'
? await api.removeClaudeOAuthCredentials()
: await api.removeBackendAuth(backend);
if (!removalOwner.current.mounted) return;
@@ -145,12 +143,14 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
detail: result.detail || result.warning || 'logout_failed',
}), 'warning');
}
- const observed = onRemoved ? await onRemoved(result) : await onSuccess?.();
+ const observed = await onRemoved?.(result);
if (!removalOwner.current.mounted) return;
if (result.restart?.ok === false) {
- setError(result.restart.message || t('onboarding.connection.applyFailed'));
+ // The connection owner reports application failure separately from
+ // authorization; do not turn cleanup into a second sign-in error.
+ if (!onRemoved) setError(result.restart.message || t('onboarding.connection.applyFailed'));
} else if (!result.partial && observed !== false) {
- showToast(t('settings.backends.oauthRemoved'), 'success');
+ showToast(t(backend === 'claude' ? 'settings.backends.claudeNativeCredentialsCleared' : 'settings.backends.oauthRemoved'), 'success');
}
} catch (err) {
if (!removalOwner.current.mounted) return;
@@ -192,7 +192,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
})();
const showRemoveAuth = canRemoveAuth ?? (signedIn || state === 'success');
const removeLabel =
- backend === 'claude' && canRemoveAuth && !signedIn
+ backend === 'claude'
? t('settings.backends.oauthCleanStoredCredentials')
: t('settings.backends.oauthRemove');
@@ -203,13 +203,12 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
<p className="text-[12px] leading-relaxed text-muted">{subtitle}</p>
</div>
- {signedIn && state === 'idle' && (
+ {backend !== 'claude' && signedIn && state === 'idle' && (
<div className="flex items-start gap-2 rounded-md border border-mint/30 bg-mint-soft/40 px-3 py-2">
<CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-mint-ink" />
<div className="flex flex-col gap-0.5">
<p className="text-[12px] text-mint-ink">
{(() => {
- if (backend === 'claude') return t('settings.backends.claudeOauthSignedIn');
if (backend === 'codex') return t('settings.backends.codexOauthSignedIn');
return t('settings.backends.opencodeProviderOauthSignedIn');
})()}
@@ -221,10 +220,10 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
</div>
)}
- {state === 'success' && signedIn && (
+ {(backend === 'claude' ? authorizationCompleted : state === 'success' && signedIn) && (
<div className="flex items-start gap-2 rounded-md border border-mint/30 bg-mint-soft/40 px-3 py-2">
<CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-mint-ink" />
- <p className="text-[12px] text-mint-ink">{t('settings.backends.oauthSuccess')}</p>
+ <p className="text-[12px] text-mint-ink">{t(backend === 'claude' ? 'settings.backends.claudeAuthorizationCompleted' : 'settings.backends.oauthSuccess')}</p>
</div>
)}
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
index 0ef114671..1159a55a1 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts
+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
@@ -136,6 +136,26 @@ describe('add-subscription start recovery', () => {
expect(start.mock.calls[0][2]).toMatch(/^ofn_[a-z0-9]{16,64}$/);
});
+ it('AUTH-SETUP-910 keeps a saved native source and warns about failed runtime application', async () => {
+ const flow = {
+ flow_id: 'oaf_committed_auth', vendor: 'anthropic', channel: 'native_cli' as const,
+ state: 'success' as const, application_failed: true,
+ presentation: { expects: 'none' as const }, expires_at: '2099-01-01T00:00:00Z',
+ };
+ const start = vi.spyOn(modelsApi, 'startOAuth').mockResolvedValue(flow);
+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({
+ flow, created: { source: subscription(), added_to: [], adopted_by: [] }, repaired: null,
+ });
+ vi.spyOn(modelsApi, 'cancelOAuth').mockResolvedValue(undefined);
+ const connected = vi.fn();
+ renderDialog({ onConnected: connected });
+ await userEvent.click(screen.getByRole('button', { name: /Sign in|去登录/i }));
+ await waitFor(() => expect(connected.mock.calls.filter(([source]) => source?.id === 'src_subscription')).toHaveLength(1));
+ expect(screen.getAllByText(i18n.t('settings.models.oauth.error.nativeApply')).length).toBeGreaterThan(0);
+ expect(start).toHaveBeenCalledOnce();
+ expect(screen.queryByText(i18n.t('settings.models.oauth.error.generic'))).toBeNull();
+ });
+
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');
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 4faf313bb..6cdae6e90 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -352,21 +352,26 @@ export const OAuthConnectDialog: React.FC<{
// report. An absent tail is the only arrival with no verdict to speak for
// it, and 「连接成功」 is what it has always said.
const toast = verdict ? REPAIR_TOAST[verdict.kind] : null;
+ const applicationFailed = result.flow.application_failed === true;
+ const warnApplication = applicationFailed && (!toast || toast.tone === 'success');
showToast(
- t(toast?.key ?? 'settings.models.oauth.status.success') as string,
- toast?.tone ?? 'success',
+ t(warnApplication ? 'settings.models.oauth.error.nativeApply' : toast?.key ?? 'settings.models.oauth.status.success') as string,
+ warnApplication ? 'warning' : toast?.tone ?? 'success',
);
// The toast is the whole report of a clean repair, so the journey ends
// with it: 「nothing was stranded」 is a field the server sends, and only a
// verdict that leaves something to read keeps the dialog on screen. An
// absent tail says nothing to read either, so it closes too.
- if (!verdict || repairSettles(verdict)) onCloseRef.current();
+ if (!applicationFailed && (!verdict || repairSettles(verdict))) onCloseRef.current();
} else if (step.action === 'succeed') {
// The Source already exists. The status/submit call that first reports
// success materializes it server-side and consumes the flow binding doing
// it — there is nothing left to finalize, and a POST /sources afterwards
// is refused as `flow_not_found` on a connect that in fact succeeded.
- showToast(t('settings.models.oauth.status.success') as string, 'success');
+ showToast(
+ t(result.flow.application_failed ? 'settings.models.oauth.error.nativeApply' : 'settings.models.oauth.status.success') as string,
+ result.flow.application_failed ? 'warning' : 'success',
+ );
if (created) onConnectedRef.current(created.source, created);
}
// Both branches above end with the same fact about the page behind them, and
@@ -909,6 +914,7 @@ export const OAuthConnectDialog: React.FC<{
</DialogTitle>
</DialogHeader>
+ {flow?.application_failed && <p role="status" className="text-sm text-muted">{t('settings.models.oauth.error.nativeApply')}</p>}
{failureClass && (
<div className="flex flex-col gap-2">
<div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive-ink">
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index be3ce2fa3..20224f752 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -775,6 +775,8 @@ export type OAuthFlow = {
/** A failed flow's own reason (provider, engine, or CLI), verbatim on one
* bounded line; shown behind the copyable details control. */
error_detail?: string;
+ /** Native authorization committed, but its runtime-application attempt failed. */
+ application_failed?: boolean;
expires_at?: string | null;
};
diff --git a/ui/src/components/settings/nativeAuthOwnership.test.tsx b/ui/src/components/settings/nativeAuthOwnership.test.tsx
index 4fa0032d4..9d17e9f19 100644
--- a/ui/src/components/settings/nativeAuthOwnership.test.tsx
+++ b/ui/src/components/settings/nativeAuthOwnership.test.tsx
@@ -198,7 +198,7 @@ describe('native authentication ownership presentation', () => {
});
it('maps OAuth removal refusal to the existing Model Hub action', async () => {
- mock.api.removeBackendAuth.mockResolvedValue({
+ mock.api.removeClaudeOAuthCredentials.mockResolvedValue({
ok: false,
error: 'native_auth_hub_owned',
reauth_channel: 'hub',
@@ -214,7 +214,7 @@ describe('native authentication ownership presentation', () => {
'/settings/backends/claude',
);
- fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.oauthRemove }));
+ fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials }));
expect(await screen.findByText(en.settings.backends.nativeAuthHubOwned)).toBeTruthy();
expect(screen.getByRole('link', { name: en.settings.backends.openModelHub })).toBeTruthy();
expect(screen.queryByText('native_auth_hub_owned')).toBeNull();
diff --git a/ui/src/components/settings/oauth/useBackendOAuth.ts b/ui/src/components/settings/oauth/useBackendOAuth.ts
index c29e78cbc..e3e24320e 100644
--- a/ui/src/components/settings/oauth/useBackendOAuth.ts
+++ b/ui/src/components/settings/oauth/useBackendOAuth.ts
@@ -14,7 +14,7 @@ const POLL_DEADLINE_MS = 16 * 60 * 1000;
export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailure, onCancel, onActiveChange, onPendingChange }: {
backend: OAuthBackend;
opencodeProviderId?: string;
- onSuccess?: () => void | Promise<void>;
+ onSuccess?: (applicationError?: string) => void | Promise<void>;
/** Observe persisted credentials when a terminal server failure follows commit. */
onFailure?: (error: string) => void | Promise<void>;
/** Invalidate an in-flight confirmation before explicit cancellation. */
@@ -33,6 +33,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
const [submitting, setSubmitting] = useState(false);
const [starting, setStarting] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [authorizationCompleted, setAuthorizationCompleted] = useState(false);
const [hubOwnedAuth, setHubOwnedAuth] = useState(false);
const owner = useRef({ generation: 0, mounted: true, flowId: '', busy: false, submitting: false, deadline: 0 });
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
@@ -82,7 +83,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
owner.current.flowId = '';
owner.current.busy = false;
owner.current.submitting = false;
- setState('idle'); setUrl(null); setDeviceCode(null); setCode(''); setError(null); setHubOwnedAuth(false);
+ setState('idle'); setUrl(null); setDeviceCode(null); setCode(''); setError(null); setHubOwnedAuth(false); setAuthorizationCompleted(false);
setStarting(false); setSubmitting(false);
callbacks.current.onActiveChange?.(false);
};
@@ -95,6 +96,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
setStarting(false);
setSubmitting(false);
setHubOwnedAuth(true);
+ setAuthorizationCompleted(false);
setError(null);
setState('failed');
settled(generation);
@@ -102,23 +104,26 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
};
const accept = async (data: OAuthWebStartResult, generation: number) => {
if (!current(generation)) return;
- if (!data.ok) {
- if (isNativeAuthHubOwned(data)) {
- settleHubOwnedAuth(generation);
- return;
- }
- throw new Error(data.detail || data.error || 'flow_not_found');
+ if (isNativeAuthHubOwned(data)) {
+ settleHubOwnedAuth(generation);
+ return;
}
+ const receipt = backend === 'claude' && data.authorization_completed === true;
+ if (receipt) setAuthorizationCompleted(true);
+ if (!data.ok && !receipt) throw new Error(data.detail || data.error || 'flow_not_found');
if (data.callback_kind) setCallbackKind(data.callback_kind);
if (data.url) setUrl(data.url);
if (data.device_code) setDeviceCode(data.device_code);
- if (data.state === 'success') {
+ if (data.state === 'success' || (receipt && (data.state === 'failed' || data.state === 'cancelled'))) {
+ if (backend === 'claude' && data.authorization_completed === false) throw new Error(t('onboarding.connection.unconfirmed'));
stopPolling();
- // The success consumer must re-read effective auth/application before the
- // presentation can claim success. It may reject while application fails.
+ // A terminal authorization receipt is not a runtime-application verdict.
+ // Claude consumers may retain the receipt while application is retried;
+ // neither metadata readback nor unmount may cancel this completed login.
+ if (backend === 'claude') { setAuthorizationCompleted(true); owner.current.flowId = ''; }
setState('verifying');
- await callbacks.current.onSuccess?.();
- if (!current(generation)) return;
+ await callbacks.current.onSuccess?.(data.state === 'success' ? undefined : data.detail || data.error || t('onboarding.connection.applyFailed'));
+ if (!current(generation)) { settled(generation); return; }
owner.current.flowId = '';
owner.current.busy = false;
settled(generation);
@@ -166,7 +171,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
callbacks.current.onPendingChange?.(true);
owner.current.busy = true;
owner.current.deadline = Date.now() + POLL_DEADLINE_MS;
- setStarting(true); setState('starting'); setError(null); setHubOwnedAuth(false); setCode(''); setUrl(null); setDeviceCode(null); setCallbackKind(null);
+ setStarting(true); setState('starting'); setError(null); setHubOwnedAuth(false); setAuthorizationCompleted(false); setCode(''); setUrl(null); setDeviceCode(null); setCallbackKind(null);
callbacks.current.onActiveChange?.(true);
try {
const result = backend === 'opencode'
@@ -227,6 +232,6 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
}
};
const isActive = state === 'starting' || state === 'awaiting_code' || state === 'verifying';
- return { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError, hubOwnedAuth,
+ return { state, authorizationCompleted, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError, hubOwnedAuth,
isActive, startFlow, cancelFlow, submitCallback, resetToIdle };
}
diff --git a/ui/src/components/settings/providers/BackendConnectionForm.tsx b/ui/src/components/settings/providers/BackendConnectionForm.tsx
index 14405b289..a6234c884 100644
--- a/ui/src/components/settings/providers/BackendConnectionForm.tsx
+++ b/ui/src/components/settings/providers/BackendConnectionForm.tsx
@@ -72,7 +72,7 @@ const unsaved = (draft: Draft) => draft.value !== '' || draft.editing;
* the question it answers is whether the person has moved on since, and `null`
* says this write carried no URL to settle.
*/
-type Submission = { method: Method; baseUrl: string | null; credential: Credential | null; sent: Draft | null };
+type Submission = { method: Method; baseUrl: string | null; credential: Credential | null; sent: Draft | null; authorizationCompleted?: boolean };
const sameDraft = (left: Draft, right: Draft) => left.value === right.value && left.editing === right.editing;
/**
@@ -143,6 +143,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
const [active, setActive] = useState(false);
const [applyPending, setApplyPending] = useState(false);
const [authReadable, setAuthReadable] = useState(false);
+ const [inventoryError, setInventoryError] = useState('');
const [hubOwnedAuth, setHubOwnedAuth] = useState(false);
const observation = useRef(0);
const touched = useRef(new Set<Editable>());
@@ -199,7 +200,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
} = {}) => {
const token = ++observation.current;
const current = () => lifetime.current.mounted && token === observation.current;
- setConnected(false); setSavedDisabled(false); setError(receiptError);
+ setConnected(false); setSavedDisabled(false); setError(receiptError); setInventoryError('');
const [application] = await Promise.allSettled([api.getBackendConnection(backend)]);
if (!current()) return false;
const messages = receiptError ? [receiptError] : [];
@@ -229,7 +230,9 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
if (fresh.native && 'credential_type' in fresh.native) setCredential(fresh.native.credential_type || 'api_key');
}
if (!compact && pristine()) {
- const effective = fresh.native?.active_auth_mode;
+ const effective = backend === 'claude' && fresh.native
+ ? fresh.native.has_api_key ? 'api_key' : fresh.native.auth_mode
+ : fresh.native?.active_auth_mode;
setMethod(effective && effective !== 'none' ? effective : fresh.provider?.active_auth_type === 'api' ? 'api_key' : backend === 'opencode' && !provider?.oauth_available ? 'api_key' : initialMethod);
}
}
@@ -243,14 +246,22 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
setLoading(false);
let hasAuth = false;
let keylessSettings = false;
- if (auth.status === 'rejected') messages.push(errorMessage(auth.reason) || t('onboarding.connection.readFailed'));
- else {
+ if (auth.status === 'rejected') {
+ const detail = errorMessage(auth.reason) || t('onboarding.connection.readFailed');
+ if (backend === 'claude') setInventoryError(detail);
+ if (backend !== 'claude' || expected?.method === 'api_key') messages.push(detail);
+ } else {
const fresh = auth.value;
const effective = fresh.native?.active_auth_mode || (fresh.provider?.active_auth_type === 'oauth' ? 'oauth' : fresh.provider?.active_auth_type === 'api' ? 'api_key' : 'none');
const uncertain = fresh.native && 'auth_mode_uncertain' in fresh.native && fresh.native.auth_mode_uncertain;
- hasAuth = ['oauth', 'api_key'].includes(effective) && !uncertain;
+ hasAuth = backend === 'claude'
+ ? Boolean(fresh.native?.has_api_key || expected?.authorizationCompleted)
+ : ['oauth', 'api_key'].includes(effective) && !uncertain;
keylessSettings = !compact && Boolean(fresh.provider?.custom && fresh.provider.configured && effective === 'none');
- if (expected && ((!keylessSettings && effective !== expected.method) || uncertain)) messages.push(t('onboarding.connection.unconfirmed'));
+ if (backend === 'claude') {
+ // Only attest the saved fields this editor owns, never CLI selection.
+ if (expected?.method === 'api_key' && !fresh.native?.has_api_key) messages.push(t('onboarding.connection.unconfirmed'));
+ } else if (expected && ((!keylessSettings && effective !== expected.method) || uncertain)) messages.push(t('onboarding.connection.unconfirmed'));
// Claude's two credential types are one method. `active_auth_mode` reads
// `api_key` for a token exactly as it does for a key, so the method above
// cannot tell a token write that landed from one that did not — only the
@@ -267,10 +278,11 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
if (stored !== expected.credential) messages.push(t('onboarding.connection.unconfirmed'));
}
}
+ if (backend === 'claude' && expected?.method === 'oauth' && !expected.authorizationCompleted) messages.push(t('onboarding.connection.unconfirmed'));
setError([...new Set(messages)].join(' '));
setApplyPending(messages.length > 0);
const confirmed = messages.length === 0;
- setConnected(confirmed && hasAuth && Boolean(connection?.ready));
+ setConnected(confirmed && (backend === 'claude' || hasAuth) && Boolean(connection?.ready));
setSavedDisabled(confirmed && hasAuth && connection?.enabled === false && !keylessSettings);
return confirmed;
}, [read, api, backend, compact, provider?.oauth_available, initialMethod, t]);
@@ -309,8 +321,9 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
});
};
const confirm = async (submission: Submission, receiptError = '') => {
- pendingConfirmation.current = submission;
- if (!await observe({ expected: submission, receiptError })) return false;
+ const receipt = { ...submission };
+ pendingConfirmation.current = receipt;
+ if (!await observe({ expected: receipt, receiptError }) || pendingConfirmation.current !== receipt) return false;
pendingConfirmation.current = null;
consume(submission);
await onConnectedRef.current?.();
@@ -319,15 +332,20 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
// Signing in settles the account, not the key someone was part-way through
// typing, and not an address they were part-way through changing either.
const OAUTH: Submission = { method: 'oauth', baseUrl: null, credential: null, sent: null };
- const confirmOAuth = async () => {
- if (!await confirm(OAUTH)) throw new Error(t('onboarding.connection.applyPending'));
+ const confirmOAuth = async (applicationError = '') => {
+ const confirmed = await confirm({ ...OAUTH, authorizationCompleted: backend === 'claude' }, applicationError);
+ if (!confirmed && backend !== 'claude') throw new Error(t('onboarding.connection.applyPending'));
};
const observeOAuthFailure = async (receiptError: string) => {
- pendingConfirmation.current = OAUTH;
+ pendingConfirmation.current = backend === 'claude' ? null : OAUTH;
await observe({ receiptError });
};
+ const changeOAuthActive = (value: boolean) => {
+ if (value) { pendingConfirmation.current = null; observation.current += 1; }
+ setActive(value);
+ };
const oauth = useBackendOAuth({ backend, opencodeProviderId: provider?.id, onSuccess: confirmOAuth,
- onFailure: observeOAuthFailure, onCancel: () => { pendingConfirmation.current = null; observation.current += 1; }, onActiveChange: setActive, onPendingChange: onWriteState });
+ onFailure: observeOAuthFailure, onCancel: () => { pendingConfirmation.current = null; observation.current += 1; }, onActiveChange: changeOAuthActive, onPendingChange: onWriteState });
const refresh = async () => {
const expected = pendingConfirmation.current;
if (expected) await confirm(expected);
@@ -356,7 +374,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
: Boolean(native?.has_api_key) && (backend !== 'claude' || storedCredential === credential));
const mask = native?.api_key_masked || currentProvider?.api_key_masked || '••••••••';
const uncertain = native && 'auth_mode_uncertain' in native && native.auth_mode_uncertain;
- const signedIn = authReadable && (native?.active_auth_mode === 'oauth' || currentProvider?.active_auth_type === 'oauth');
+ const signedIn = backend !== 'claude' && authReadable && (native?.active_auth_mode === 'oauth' || currentProvider?.active_auth_type === 'oauth');
const urlValid = (() => {
if (!baseUrl.trim()) return !provider?.custom;
try { const url = new URL(baseUrl.trim()); return ['http:', 'https:'].includes(url.protocol) && Boolean(url.hostname); }
@@ -442,7 +460,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
// footer still while the body changes underneath them.
return <div className="backend-connection-form">
{!hubOwnedAuth && !(compact && active && backend !== 'codex') && (backend !== 'opencode' || (!compact && provider?.oauth_available)) && <MethodRadio
- value={method} onChange={(value) => { if (!busy && !loading) { pendingConfirmation.current = null; touched.current.add('method'); setMethod(value); setError(''); setConnected(false); } }} disabled={busy || loading}
+ value={method} onChange={(value) => { if (!busy && !loading) { pendingConfirmation.current = null; observation.current += 1; oauth.resetToIdle(); touched.current.add('method'); setMethod(value); setError(''); setConnected(false); } }} disabled={busy || loading}
ariaLabel={t('onboarding.connection.method')}
options={[{ id: 'oauth', label: backend === 'claude' ? t('onboarding.connection.claudeLogin') : backend === 'codex' ? t('onboarding.connection.codexSignIn') : t('onboarding.connection.subscription') },
{ id: 'api_key', label: backend === 'claude' ? t('onboarding.connection.claudeCredentials') : backend === 'codex' ? t('onboarding.connection.openaiKey') : apiKeyLabel }]} />}
@@ -457,20 +475,25 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
: 'onboarding.connection.providerIntro', { name: provider?.name })}</p>}
{!loading && hubOwnedAuth && <HubOwnedAuthNotice onNavigate={compact ? onCancel : undefined} />}
{!loading && !hubOwnedAuth && <>
- {uncertain && <p className="connection-notice">{t('onboarding.connection.uncertain')}</p>}
+ {backend === 'claude' ? <>
+ <p className="connection-notice">{t('onboarding.connection.claudeManagedAuth')}</p>
+ {native && 'oauth_store_state' in native && native.oauth_store_state && <p className="connection-notice">{t(`onboarding.connection.nativeStore.${native.oauth_store_state}`)}</p>}
+ {inventoryError && <p className="connection-notice">{inventoryError}</p>}
+ </> : uncertain && <p className="connection-notice">{t('onboarding.connection.uncertain')}</p>}
{native && 'file_store_active' in native && method === 'api_key' && !native.file_store_active && !uncertain && <p className="connection-notice">{t('settings.backends.codexCredentialsStoreKeyringWarn', { store: native.credentials_store })}</p>}
{native && 'settings_conflict' in native && native.settings_conflict && <p className="connection-notice">{t('settings.backends.claudeSettingsConflictTitle')}: {t('settings.backends.claudeSettingsConflictBody', { var: native.settings_env_key_var || 'ANTHROPIC_API_KEY', path: native.settings_path })}</p>}
{applyPending && <Button variant="secondary" disabled={busy} onClick={() => void refresh()}>{t('onboarding.connection.refresh')}</Button>}
- {connected && <p className="connection-confirmed" role="status"><CheckCircle2 size={16} />{t('onboarding.connection.connected')}</p>}
+ {connected && <p className="connection-confirmed" role="status"><CheckCircle2 size={16} />{t(backend === 'claude' ? 'onboarding.connection.nativeReady' : 'onboarding.connection.connected')}</p>}
{savedDisabled && <p className="text-xs text-muted break-words" role="status">{t('onboarding.connection.savedDisabled')}</p>}
{error && <div role="alert" className="connection-error">{error}{!native && !currentProvider && <Button variant="secondary" onClick={() => void observe()}>{t('common.retry')}</Button>}</div>}
{method === 'oauth' && (!compact ? <BackendOAuthPanel backend={backend} opencodeProviderId={provider?.id} signedIn={signedIn}
- title={title} subtitle={hint} hideRemove={backend === 'opencode'} onSuccess={confirmOAuth} onRemoved={removed} onFailure={observeOAuthFailure} onCancel={() => { pendingConfirmation.current = null; observation.current += 1; }} onActiveChange={setActive}
- canRemoveAuth={authReadable && Boolean(native && ('has_oauth_credentials' in native ? native.has_oauth_credentials : native.has_chatgpt_tokens))}
+ title={title} subtitle={hint} hideRemove={backend === 'opencode'} onSuccess={confirmOAuth} onRemoved={removed} onFailure={observeOAuthFailure} onCancel={() => { pendingConfirmation.current = null; observation.current += 1; }} onActiveChange={changeOAuthActive}
+ canRemoveAuth={authReadable && Boolean(native && ('has_oauth_credentials' in native ? native.can_remove_oauth_credentials ?? native.has_oauth_credentials : native.has_chatgpt_tokens))}
signedInDetail={native && 'chatgpt_account' in native && native.chatgpt_account ? [native.chatgpt_account.email, native.chatgpt_account.plan_type, (native.chatgpt_account.organizations?.find((org) => org.is_default) || native.chatgpt_account.organizations?.[0])?.title].filter(Boolean).join(' · ') : undefined} /> : <>
{oauth.hubOwnedAuth && <HubOwnedAuthNotice onNavigate={onCancel} />}
{oauth.error && !oauth.hubOwnedAuth && <p className="connection-error" role="alert">{oauth.error}</p>}
{!oauth.isActive ? <div className="connection-account"><h3>{title}</h3><p>{hint}</p>
+ {backend === 'claude' && oauth.authorizationCompleted && <p className="connection-confirmed">{t('settings.backends.claudeAuthorizationCompleted')}</p>}
{signedIn && <p className="connection-confirmed">{t('onboarding.connection.savedSubscription')}</p>}
<div><Button variant="brand" onClick={() => void oauth.startFlow()} disabled={oauth.starting}><ExternalLink size={15} />{startLabel}</Button></div>
</div> : <div className="connection-auth-steps">
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index 742b5de4a..1c09ca603 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -1009,7 +1009,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
connection={hubRoute
? 'hub'
: mode === 'direct' && !connectionErrors[name] && connections[name]?.ready
- ? (connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key')
+ ? (connections[name]?.auth === 'external' ? 'external' : connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key')
: undefined}
hubManaged={hubRoute}
enabled={agent.enabled}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8243f1625..48de9a3c1 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1989,7 +1989,8 @@ export type BackendConnectionState = {
backend: AgentBackendId;
installed: boolean;
enabled: boolean;
- auth: 'subscription' | 'api_key' | 'none' | 'unknown';
+ // external: launch capability only; the native backend owns authentication.
+ auth: 'subscription' | 'api_key' | 'external' | 'none' | 'unknown';
application: 'applied' | 'draining' | 'failed' | 'stopped' | 'unknown';
ready: boolean;
entry_eligible: boolean;
@@ -2111,17 +2112,17 @@ export type ClaudeApiKeySource = 'v2config' | 'settings_json' | null;
export type ClaudeAuthState = {
ok: boolean;
auth_mode: ClaudeAuthMode;
- // Live source the CLI is actually inheriting at launch (api_key when
- // V2Config injects ``ANTHROPIC_API_KEY`` and strips OAuth env vars,
- // oauth when Claude Code reports or stores a usable first-party login).
+ // Legacy field; native authentication is not inferred by this inventory.
active_auth_mode: ActiveAuthMode;
+ auth_managed_by?: 'claude';
+ auth_mode_uncertain?: boolean;
+ oauth_store_state?: 'present' | 'absent' | 'unknown';
+ can_remove_oauth_credentials?: boolean;
has_api_key: boolean;
api_key_length: number;
api_key_masked: string | null;
api_key_source?: ClaudeApiKeySource;
- // Raw Claude Code account-token signal. This may remain true while Avibe
- // is actively using API-key mode, so UI "signed in" indicators should use
- // active_auth_mode instead.
+ // Inspectable native material only, not a signed-in or effective-auth claim.
has_oauth_credentials: boolean;
base_url: string | null;
settings_path: string | null;
@@ -2166,6 +2167,8 @@ export type OAuthWebState =
export type OAuthWebStartResult = {
ok: boolean;
+ // This operation committed authorization, independently of runtime apply.
+ authorization_completed?: boolean;
flow_id?: string;
backend?: WebOAuthBackend;
state?: OAuthWebState;
@@ -2180,6 +2183,7 @@ export type OAuthWebStartResult = {
export type OAuthWebStatus = {
ok: boolean;
+ authorization_completed?: boolean;
flow_id?: string;
backend?: WebOAuthBackend;
state?: OAuthWebState;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a2dc5ab38..e7ca31cf7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -701,6 +701,8 @@
"oauthStarting": "Starting OAuth flow…",
"oauthVerifying": "Verifying credentials…",
"oauthSuccess": "Signed in successfully.",
+ "claudeAuthorizationCompleted": "Authorization completed and saved. Runtime application is a separate step.",
+ "claudeNativeCredentialsCleared": "Saved native account credentials cleared. Environment and project authentication settings are unchanged.",
"oauthFailed": "OAuth flow failed: {{detail}}",
"oauthPollTimedOut": "Login did not complete within the allowed time. Please retry.",
"oauthUrlCopied": "URL copied to clipboard.",
@@ -1970,7 +1972,7 @@
"native": {
"label": "Use natively",
"desc": {
- "claude": "Claude Code uses this subscription directly; the credential stays on this machine."
+ "claude": "Claude Code manages this native sign-in on this machine; credentials stay in its own store."
}
},
"hub": {
@@ -2040,6 +2042,7 @@
"timeout": "Authorization timed out, please reconnect",
"generic": "Connection failed, please retry",
"finalize": "Authorized, but couldn't create the source — please retry",
+ "nativeApply": "Authorization and source configuration were saved, but this attempt could not apply the backend configuration. Check and retry application in backend settings.",
"finalizeReauth": "Signed in, but this source still isn't working — please retry",
"details": {
"show": "Show details",
@@ -5690,6 +5693,8 @@
"api_key": "API Key",
"subscriptionConnected": "Subscription connected",
"api_keyConnected": "API Key connected",
+ "externalConnected": "Ready to start",
+ "externalConnectedHint": "Claude Code manages authentication when you run it. This is not a sign-in check.",
"claudeGuide": "Sign in with Claude or enter an API key",
"codexGuide": "Sign in with ChatGPT or use an OpenAI API key",
"opencodeGuide": "Choose either way to connect",
@@ -5754,6 +5759,13 @@
"showKey": "Show credential",
"hideKey": "Hide credential",
"connected": "Connected",
+ "nativeReady": "Ready to start · authentication is managed by Claude Code",
+ "claudeManagedAuth": "These are saved native settings, not a prediction of which credentials a session will use. Claude Code manages authentication when it runs.",
+ "nativeStore": {
+ "present": "Native OAuth material detected. This does not verify the account or token.",
+ "absent": "No native OAuth material observed. Claude Code may use other authentication sources.",
+ "unknown": "The native credential store could not be inspected. This does not mean you are signed out."
+ },
"savedSubscription": "Subscription credentials detected",
"savedDisabled": "Credentials saved. This assistant is currently disabled.",
"readFailed": "Unable to read connection state. Try again.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 724e0a08c..6229733af 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -701,6 +701,8 @@
"oauthStarting": "正在启动 OAuth 流程…",
"oauthVerifying": "正在验证凭据…",
"oauthSuccess": "登录成功。",
+ "claudeAuthorizationCompleted": "授权已完成并保存。运行时配置是否应用是另一项状态。",
+ "claudeNativeCredentialsCleared": "已清理本机保存的账号凭据。环境变量和项目中的认证设置未被修改。",
"oauthFailed": "OAuth 失败:{{detail}}",
"oauthPollTimedOut": "登录在允许时间内未完成,请重试。",
"oauthUrlCopied": "链接已复制到剪贴板。",
@@ -1970,7 +1972,7 @@
"native": {
"label": "由 Agent 管理",
"desc": {
- "claude": "Claude Code 直接用这个订阅,凭据只留在本机。"
+ "claude": "本机 Claude Code 管理这份原生登录,凭据保存在它自己的存储中。"
}
},
"hub": {
@@ -2040,6 +2042,7 @@
"timeout": "授权超时,请重新连接",
"generic": "连接失败,请重试",
"finalize": "已完成授权,但创建模型供应商失败,请重试",
+ "nativeApply": "授权和模型供应商配置已保存,但本次未能应用后端配置。请在后端设置中检查并重试应用。",
"finalizeReauth": "已重新登录,但这个供应商还是不可用,请重试",
"details": {
"show": "查看详情",
@@ -5690,6 +5693,8 @@
"api_key": "API Key",
"subscriptionConnected": "订阅已连接",
"api_keyConnected": "API Key 已连接",
+ "externalConnected": "可以启动",
+ "externalConnectedHint": "执行时由 Claude Code 管理认证;此状态不表示已验证登录。",
"claudeGuide": "通过 Claude 登录或填入 API Key",
"codexGuide": "通过 ChatGPT 登录,或使用 OpenAI API Key",
"opencodeGuide": "选择一种方式连接即可",
@@ -5754,6 +5759,13 @@
"showKey": "显示凭据",
"hideKey": "隐藏凭据",
"connected": "已连接",
+ "nativeReady": "可以启动 · 认证由 Claude Code 管理",
+ "claudeManagedAuth": "这里显示已保存的本机配置,不预测会话将选用哪种凭据。执行时由 Claude Code 管理认证。",
+ "nativeStore": {
+ "present": "检测到本机 OAuth 材料,但未验证账号或令牌是否有效。",
+ "absent": "未观察到本机 OAuth 材料;Claude Code 仍可能使用其他认证来源。",
+ "unknown": "无法确认原生凭据存储的内容,这不代表已经退出登录。"
+ },
"savedSubscription": "已检测到订阅凭据",
"savedDisabled": "凭据已保存。此助手当前未启用。",
"readFailed": "无法读取连接状态,请重试",
diff --git a/vibe/api.py b/vibe/api.py
index 83cfcad79..53936f014 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -10693,17 +10693,20 @@ def _hub_backend_connection_auth(config: V2Config, backend: str) -> str:
return "none"
-def _direct_claude_connection_auth() -> dict:
- """Keep the bounded native status reader inside the takeover exclusion."""
+def _assert_direct_claude_custody() -> None:
+ """Admit Direct Claude only under the takeover exclusion; read no credential."""
with NativeCredentialLease(("claude",)) as lease:
# The caller's config may predate an await or a completed takeover.
# acquire() checks pending recovery; custody must be reread under lease.
lease.assert_auth_custody("claude")
- return get_claude_auth(connection_observation=True)
async def get_backend_connection(name: str) -> dict:
- """Observe persisted credential custody and application, without a model call."""
+ """Observe persisted credential custody and application, without a model call.
+
+ Direct Claude reports ``auth: "external"``: Claude authenticates itself,
+ so ``ready`` / ``entry_eligible`` mean an execution may be attempted.
+ """
from core.backend_restart import pending_native_backends
from vibe import internal_client, runtime
@@ -10775,13 +10778,14 @@ async def get_backend_connection(name: str) -> dict:
modes.update({pid: "api" for pid in key_ids})
effective = next((mode for mode in modes.values() if mode in {"api", "oauth"}), None)
result["auth"] = {"api": "api_key", "oauth": "subscription"}.get(effective, "none")
+ elif name == "claude":
+ # Claude owns authentication: Direct capability never depends on
+ # passive credential evidence. Join the worker so the custody
+ # check's lease is released before this observation settles.
+ await finish_native_operation(asyncio.to_thread(_assert_direct_claude_custody))
+ result["auth"] = "external"
else:
- if name == "claude":
- # Cancelling to_thread does not stop its native status process.
- # Join the worker and retain its lease through the entire tail.
- auth = await finish_native_operation(asyncio.to_thread(_direct_claude_connection_auth))
- else:
- auth = await asyncio.to_thread(get_codex_auth)
+ auth = await asyncio.to_thread(get_codex_auth)
if not auth.get("ok") or auth.get("auth_mode_uncertain"):
return result
result["auth"] = {"oauth": "subscription", "api_key": "api_key", "none": "none"}.get(auth.get("active_auth_mode"), "unknown")
@@ -10797,7 +10801,9 @@ async def get_backend_connection(name: str) -> dict:
# IPC or native read-only checks. Do not admit against a pending journal.
if native and name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):
return result
- credential_ready = enabled and result["auth"] in {"subscription", "api_key"} and not result.get("permission_required")
+ # ``external`` is launch capability with Claude-owned authentication; it
+ # asserts no login. Every other gate above still applies to it.
+ credential_ready = enabled and result["auth"] in {"subscription", "api_key", "external"} and not result.get("permission_required")
result["ready"] = credential_ready and result["application"] == "applied"
result["entry_eligible"] = credential_ready and result["application"] in {"applied", "stopped"}
return result
@@ -11073,103 +11079,6 @@ def _mask_api_key(api_key: str | None) -> str | None:
return f"{'•' * 6}{last4}"
-def _read_claude_cli_oauth_signed_in(
- cli_path: str | None,
- *,
- env: dict[str, str] | None = None,
- cwd: str | None = None,
-) -> bool | None:
- """Ask Claude Code whether a first-party OAuth account is signed in.
-
- This is the most accurate Settings signal because it covers both
- keychain-backed installs and Linux/Docker's on-disk credentials file.
- Keep it best-effort and quiet: if Claude is missing, slow, or emits an
- unexpected shape, callers fall back to disk inspection.
- """
- configured = (cli_path or "claude").strip() or "claude"
- binary = resolve_cli_path(configured) or configured
- try:
- result = subprocess.run(
- [binary, "auth", "status", "--json"],
- stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- timeout=3,
- check=False,
- env=env,
- cwd=cwd,
- )
- except (FileNotFoundError, OSError, subprocess.SubprocessError):
- return None
- text = (result.stdout or "").strip()
- if not text:
- return None
- try:
- payload = json.loads(text)
- except json.JSONDecodeError:
- return None
- if not isinstance(payload, dict):
- return None
- logged_in = payload.get("loggedIn")
- if logged_in is False:
- return False
- if logged_in is not True:
- return None
-
- # ``auth status`` reports Claude Code's overall auth state. API-key
- # sources can also be "logged in", so only treat it as OAuth when the
- # CLI identifies the source as Claude.ai / first-party OAuth.
- saw_concrete_source = False
- for key in ("authMethod", "authProvider", "provider", "source"):
- raw = payload.get(key)
- if isinstance(raw, str):
- normalized = re.sub(r"[\s_]+", "-", raw.strip().lower())
- if not normalized:
- continue
- saw_concrete_source = True
- if normalized in {
- "claude.ai",
- "claude-ai",
- "oauth",
- "oauth-token",
- "setup-token",
- "claude-code-oauth-token",
- "subscription",
- "claude-subscription",
- }:
- return True
- if any(token in normalized for token in ("api-key", "apikey", "api key", "auth-token", "apihelper", "api-helper")):
- return False
- if saw_concrete_source:
- return False
- return None
-
-
-def _resolve_claude_status_probe_cwd(config: Any | None) -> str | None:
- candidates = (
- getattr(getattr(config, "claude", None), "cwd", None),
- getattr(getattr(config, "runtime", None), "default_cwd", None),
- )
- for raw in candidates:
- if isinstance(raw, str) and raw.strip():
- path = os.path.abspath(os.path.expanduser(raw.strip()))
- try:
- os.makedirs(path, exist_ok=True)
- return path
- except OSError as exc:
- logger.warning("Failed to prepare Claude auth status cwd=%s: %s", path, exc)
- return None
-
-
-def _build_claude_status_probe_env(claude_env: dict[str, str] | None) -> dict[str, str] | None:
- if claude_env is None:
- return None
- from vibe.claude_config import materialize_claude_subprocess_env
-
- return materialize_claude_subprocess_env(claude_env)
-
-
# ---------------------------------------------------------------------------
# Web Settings → Backends OAuth flow plumbing.
#
@@ -11325,6 +11234,8 @@ async def start_oauth_web_async(
"ok": False,
"error": flow.error or "start_failed",
"flow_id": flow.flow_id,
+ "state": flow.state,
+ "authorization_completed": flow.authorization_completed,
}
return {
"ok": True,
@@ -11336,6 +11247,7 @@ async def start_oauth_web_async(
"awaiting_code": flow.awaiting_code,
"callback_kind": flow.callback_kind,
"provider": flow.provider,
+ "authorization_completed": flow.authorization_completed,
}
@@ -11971,35 +11883,45 @@ def save_codex_auth(payload: dict) -> dict:
return state
-def get_claude_auth(*, connection_observation: bool = False) -> dict:
- """Return the user-facing Claude auth state for the Settings UI.
+def _claude_oauth_store_state() -> str:
+ """Classify safe native-store inventory without reading a secret value.
+
+ ``present`` is inspectable Claude OAuth material, not a login. A Keychain
+ container, denied/unreadable/invalid evidence or a failed read is
+ ``unknown``: it proves neither a usable account nor its absence.
+ """
+ from vibe.native_oauth_store import read_native_oauth
+
+ try:
+ snapshot = read_native_oauth("claude", allow_secret=False)
+ except Exception:
+ logger.debug("Claude native OAuth inventory could not be observed")
+ return "unknown"
+ if snapshot is None:
+ return "absent"
+ return "present" if snapshot.exportable else "unknown"
+
- Claude differs from Codex in two structural ways:
+def get_claude_auth() -> dict:
+ """Return the Claude Settings inventory: saved configuration and native evidence.
- 1. ``~/.claude/settings.json`` is the source of truth for API-key
- env overrides because Claude Code layers that file on top of the
- inherited process env at launch.
- 2. OAuth state is owned by Claude Code, so we first ask
- ``claude auth status --json``. If that probe is unavailable, fall
- back to the Linux/Docker credentials file signal.
+ Claude owns authentication. This passive read never launches Claude,
+ never predicts which credential Claude will select at launch, and never
+ creates a working directory. It reports two local facts:
- Legacy V2Config keys are read only as a migration fallback so old
- installs still render their current state before the next save moves
- the key into Claude's own settings file.
+ 1. The configuration this editor manages: the API-key / token /
+ Base URL ``env`` in ``~/.claude/settings.json`` (Claude's own file),
+ with legacy V2Config keys read only as a migration fallback.
+ 2. Native OAuth store inventory (``oauth_store_state``), which is not
+ effective authentication or token validity.
- ``connection_observation`` is the leased Direct connection projection:
- use actual launch-key precedence and explicit uncertainty if neither the
- bounded status query nor the selected native store proves OAuth.
+ ``active_auth_mode`` is a legacy wire field kept conservatively at
+ ``"none"`` with ``auth_mode_uncertain``; ``auth_mode`` is the saved
+ editing choice, not runtime truth.
"""
- from vibe.claude_config import (
- read_claude_auth_state,
- read_claude_oauth_signed_in,
- read_claude_settings_env,
- build_claude_subprocess_env,
- )
+ from vibe.claude_config import read_claude_auth_state, read_claude_settings_env
disk_state = read_claude_auth_state()
- disk_oauth_signed_in = False if connection_observation else read_claude_oauth_signed_in()
settings_env = read_claude_settings_env()
settings_key = settings_env.get("ANTHROPIC_API_KEY") or settings_env.get("ANTHROPIC_AUTH_TOKEN") or ""
settings_base = settings_env.get("ANTHROPIC_BASE_URL") or ""
@@ -12010,62 +11932,13 @@ def get_claude_auth(*, connection_observation: bool = False) -> dict:
configured_mode = getattr(cfg, "auth_mode", None)
configured_key = getattr(cfg, "api_key", None) or ""
configured_base = getattr(cfg, "base_url", None) or ""
- configured_cli_path = getattr(cfg, "cli_path", None)
- status_probe_cwd = _resolve_claude_status_probe_cwd(config)
except Exception:
configured_mode = None
configured_key = ""
configured_base = ""
- configured_cli_path = None
- status_probe_cwd = None
configured_key = configured_key.strip() if isinstance(configured_key, str) else ""
configured_base = configured_base.strip() if isinstance(configured_base, str) else ""
- if connection_observation:
- # Settings are applied by Claude after Avibe's launch environment.
- # Reuse its composition so explicit OAuth masks inherited keys while
- # legacy environment keys and persisted settings still take precedence.
- launch_env = build_claude_subprocess_env(cfg if "cfg" in locals() else None)
- launch_env.update(settings_env)
- if launch_env.get("ANTHROPIC_API_KEY") or launch_env.get("ANTHROPIC_AUTH_TOKEN"):
- return {"ok": True, "active_auth_mode": "api_key"}
- try:
- claude_status_env = _build_claude_status_probe_env(
- build_claude_subprocess_env(
- cfg if "cfg" in locals() else None,
- force_oauth=True,
- )
- )
- except Exception:
- claude_status_env = None
- # Direct connection observation owns the native lease through this bounded
- # status query. Hub observations never call this native reader.
- cli_oauth_signed_in = _read_claude_cli_oauth_signed_in(
- configured_cli_path if isinstance(configured_cli_path, str) else None,
- env=claude_status_env,
- cwd=status_probe_cwd,
- )
- if connection_observation:
- if cli_oauth_signed_in is not None:
- return {"ok": True, "active_auth_mode": "oauth" if cli_oauth_signed_in else "none"}
- from vibe.native_oauth_store import read_native_oauth
-
- try:
- snapshot = read_native_oauth("claude", allow_secret=False)
- except Exception:
- # An unavailable observer is not proof of logout. Do not expose
- # native errors or metadata in the public connection response.
- return {"ok": True, "auth_mode_uncertain": True}
- if snapshot is None:
- return {"ok": True, "active_auth_mode": "none"}
- if snapshot.exportable:
- return {"ok": True, "active_auth_mode": "oauth"}
- # Keychain attributes describe a container, which may hold only MCP
- # credentials. Neither that presence nor denied access proves OAuth.
- return {"ok": True, "auth_mode_uncertain": True}
- oauth_signed_in = (
- cli_oauth_signed_in if cli_oauth_signed_in is not None else disk_oauth_signed_in
- )
# settings.json wins: it is the file Claude Code itself layers on top
# of inherited env. V2Config is a legacy fallback only.
@@ -12080,22 +11953,7 @@ def get_claude_auth(*, connection_observation: bool = False) -> dict:
else:
auth_mode = "oauth"
- settings_conflict = False
-
- # ``active_auth_mode`` reflects what the running CLI is actually using
- # at launch.
- if effective_key and auth_mode == "api_key":
- active_auth_mode = "api_key"
- elif oauth_signed_in and auth_mode == "oauth":
- active_auth_mode = "oauth"
- elif effective_key:
- active_auth_mode = "api_key"
- elif oauth_signed_in:
- active_auth_mode = "oauth"
- else:
- active_auth_mode = "none"
-
- # Which storage the live API key came from — helps the UI explain the
+ # Which storage the saved API key came from — helps the UI explain the
# state ("Key configured in settings.json"). Plaintext never leaves
# the server; only the mask is forwarded.
if settings_key:
@@ -12105,15 +11963,21 @@ def get_claude_auth(*, connection_observation: bool = False) -> dict:
else:
api_key_source = None
+ oauth_store_state = _claude_oauth_store_state()
+
return {
"ok": True,
"auth_mode": auth_mode,
- "active_auth_mode": active_auth_mode,
+ "auth_managed_by": "claude",
+ "active_auth_mode": "none",
+ "auth_mode_uncertain": True,
+ "oauth_store_state": oauth_store_state,
"has_api_key": has_api_key,
"api_key_length": len(effective_key),
"api_key_masked": _mask_api_key(effective_key),
"api_key_source": api_key_source,
- "has_oauth_credentials": oauth_signed_in,
+ "has_oauth_credentials": oauth_store_state == "present",
+ "can_remove_oauth_credentials": oauth_store_state != "absent",
"base_url": effective_base or None,
"settings_path": disk_state.get("settings_path"),
"settings_exists": bool(disk_state.get("settings_exists")),
@@ -12126,7 +11990,7 @@ def get_claude_auth(*, connection_observation: bool = False) -> dict:
else ("api_key" if configured_key else None)
),
"settings_env_base_url": disk_state.get("settings_env_base_url"),
- "settings_conflict": settings_conflict,
+ "settings_conflict": False,
}
diff --git a/vibe/claude_config.py b/vibe/claude_config.py
index b2f7ce7aa..0a2f869bd 100644
--- a/vibe/claude_config.py
+++ b/vibe/claude_config.py
@@ -14,8 +14,9 @@ This module owns the narrow settings.json mutation surface:
OAuth tokens minted by ``claude login`` may live in an OS keychain or in
Claude Code's own credential file depending on platform/version. The Settings
-UI prefers ``claude auth status --json`` and uses the on-disk credential file
-as a fallback signal.
+UI reads native-store evidence without launching Claude, and reports opaque
+stores as unknown. Only an explicit login flow can report its own authorization
+completion; passive inventory does not attest runtime credential selection.
"""
from __future__ import annotations
@@ -128,17 +129,10 @@ def get_claude_credentials_path(home: Path | None = None) -> Path:
def clear_claude_oauth_credentials_files(home: Path | None = None) -> list[str]:
- """Remove known file-backed Claude Code OAuth credential stores."""
- removed: list[str] = []
- for path in get_claude_credentials_paths(home):
- try:
- path.unlink()
- removed.append(str(path))
- except FileNotFoundError:
- continue
- except OSError as exc:
- raise OSError(f"Failed to remove Claude OAuth credentials file {path}: {exc}") from exc
- return removed
+ """Clear the inventory-selected native OAuth files, preserving other data."""
+ from vibe.native_oauth_store import clear_claude_native_oauth_files
+
+ return clear_claude_native_oauth_files(home)
def get_claude_oauth_settings_backup_path(home: Path | None = None) -> Path:
@@ -146,37 +140,6 @@ def get_claude_oauth_settings_backup_path(home: Path | None = None) -> Path:
return get_claude_home(home) / OAUTH_SETTINGS_ENV_BACKUP_NAME
-def read_claude_oauth_signed_in(home: Path | None = None) -> bool:
- """Best-effort probe for whether Claude has a usable OAuth session.
-
- True iff Claude's on-disk credentials file exists and carries something
- that looks like an OAuth token bundle. We don't attempt to introspect
- keychain-backed installs (macOS) — those return False here but the UI
- can still light up the OAuth banner after a successful in-app login.
- """
- for path in get_claude_credentials_paths(home):
- if not path.exists():
- continue
- try:
- data = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- continue
- if not isinstance(data, dict):
- continue
- # Claude writes nested ``claudeAiOauth`` payloads in newer builds; flat
- # ``access_token``/``refresh_token`` keys also occur. Accept either.
- nested = data.get("claudeAiOauth") if isinstance(data.get("claudeAiOauth"), dict) else None
- if nested and any(
- isinstance(nested.get(field), str) and nested.get(field)
- for field in ("access_token", "refresh_token", "accessToken", "refreshToken")
- ):
- return True
- for field in ("access_token", "refresh_token", "accessToken", "refreshToken"):
- if isinstance(data.get(field), str) and data.get(field):
- return True
- return False
-
-
def _load_settings(path: Path) -> Dict[str, Any]:
if not path.exists():
return {}
diff --git a/vibe/native_oauth_store.py b/vibe/native_oauth_store.py
index d342a454d..b59935747 100644
--- a/vibe/native_oauth_store.py
+++ b/vibe/native_oauth_store.py
@@ -1688,6 +1688,35 @@ def _read_claude(home: Path | None, *, allow_secret: bool) -> NativeOAuthSnapsho
)
+def clear_claude_native_oauth_files(home: Path | None = None) -> list[str]:
+ """Clear selected file-backed Claude grants, preserving unrelated entries.
+
+ The caller owns the native credential lease. Use the inventory's locator
+ and the existing compare/write/readback machinery; no Keychain value is
+ read and no cleanup journal is persisted.
+ """
+ operations = []
+ changed = []
+ for path in native_credentials_paths("claude", home):
+ status, payload, raw = _read_json_file(path)
+ if status == "missing":
+ continue
+ if status != "ok" or payload is None or raw is None:
+ raise NativeOAuthPermissionError("native credential file could not be safely cleaned")
+ after = _remove_claude_oauth(payload)
+ if _claude_oauth_payload(after) is not None:
+ after = _remove_claude_oauth(after)
+ if after == payload and payload:
+ continue
+ operations.append(_file_operation(path, _json_file_state_from_raw(raw), _state_for_json_payload(after, raw)))
+ changed.append(str(path))
+ if operations:
+ edit = _edit("claude", "explicit-native-cleanup", operations)
+ apply_keychain_edit(edit)
+ check_keychain_edit(edit, applied=True)
+ return changed
+
+
def read_native_oauth(
backend: str,
*,