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.

feat(onboarding): share backend connections and confirm workspace readiness (#2032)

Max6ed01cd57432
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index e5f1d7a39..256af73b9 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -396,6 +396,8 @@ class WebAuthFlow:
url: str | None = None
device_code: str | None = None
awaiting_code: bool = False
+ callback_kind: str | None = None
+ submitted_code: asyncio.Future[str] | None = None
error: str | None = None
last_status_text: str | None = None
# Per-provider context for OpenCode flows; ``None`` for Claude / Codex
@@ -1125,9 +1127,10 @@ class AgentAuthService:
waiter: Coroutine[Any, Any, None],
) -> None:
"""Publish and enforce one deadline from the waiter's start boundary."""
- flow.expires_at_iso = (
- datetime.now(timezone.utc) + timedelta(seconds=self.setup_timeout_seconds)
- ).isoformat()
+ if flow.expires_at_iso is None:
+ flow.expires_at_iso = (
+ datetime.now(timezone.utc) + timedelta(seconds=self.setup_timeout_seconds)
+ ).isoformat()
flow.waiter_task = asyncio.create_task(waiter)
def _remaining_flow_timeout(self, flow: AgentAuthFlow | WebAuthFlow) -> float:
@@ -2231,8 +2234,7 @@ class AgentAuthService:
callback code via ``submit_web_code``. For OpenCode the caller
must pass ``provider_id``; the URL (and optional device code) are
surfaced via ``WebAuthFlow.url`` / ``WebAuthFlow.device_code`` and
- completion is auto-detected by OpenCode's daemon — no code submit
- from the user.
+ completion follows its declared automatic or manual-code method.
"""
if backend not in self.WEB_BACKENDS:
raise ValueError(f"unsupported_backend:{backend}")
@@ -2276,6 +2278,26 @@ class AgentAuthService:
if flow is None:
return {"ok": False, "error": "flow_not_found"}
if flow.backend == "opencode":
+ if flow.callback_kind == "code":
+ if (
+ flow.state != "awaiting_code" or not flow.awaiting_code
+ or flow.submitted_code is None or flow.submitted_code.done()
+ ):
+ return {"ok": False, "error": "not_awaiting_code"}
+ raw = (code or "").strip()
+ if not raw:
+ return {"ok": False, "error": "invalid_format"}
+ if self._remaining_flow_timeout(flow) <= 0:
+ await self._terminate_web_flow(flow, final_state="failed", error="timed_out")
+ return {"ok": False, "error": "timed_out"}
+ # The start-time waiter keeps the same deadline and ownership.
+ # Resolving once before any await excludes duplicate submissions.
+ flow.awaiting_code = False
+ flow.state = "verifying"
+ flow.submitted_code.set_result(raw)
+ return {"ok": True}
+ if flow.state not in {"awaiting_code", "verifying"}:
+ return {"ok": False, "error": "not_awaiting_code"}
return await self._submit_opencode_callback_url(flow, code)
if flow.backend != "claude":
return {"ok": False, "error": "code_not_supported"}
@@ -2360,6 +2382,8 @@ class AgentAuthService:
"awaiting_code": flow.awaiting_code,
"error": flow.error,
}
+ if flow.callback_kind is not None:
+ result["callback_kind"] = flow.callback_kind
if any(
getattr(flow, name, None) is not None
for name in ("source_id", "vendor", "expires_at_iso")
@@ -3226,18 +3250,16 @@ class AgentAuthService:
if match:
flow.device_code = match.group(1)
flow.last_status_text = instructions
+ mode = authorize.get("method")
+ if mode not in {None, "auto", "code"}:
+ raise RuntimeError("opencode_authorize_unsupported_method")
+ flow.callback_kind = "code" if mode == "code" else "device" if flow.device_code else "redirect"
flow.state = "awaiting_code"
- # OpenCode auto-detects completion (device poll or local callback);
- # no user-submitted code to enter. The waiter long-polls the daemon.
- flow.awaiting_code = False
+ flow.awaiting_code = mode == "code"
+ if flow.awaiting_code:
+ flow.submitted_code = asyncio.get_running_loop().create_future()
self._arm_flow_waiter(
- flow,
- self._wait_for_opencode_oauth_web(
- flow,
- provider_id,
- method_index,
- prompt_answers,
- ),
+ flow, self._wait_for_opencode_oauth_web(flow, provider_id, method_index, prompt_answers),
)
async def _submit_opencode_callback_url(self, flow: WebAuthFlow, code: str) -> dict[str, Any]:
@@ -3293,7 +3315,13 @@ class AgentAuthService:
method_index: int,
prompt_answers: dict[str, Any],
) -> None:
- try:
+ async def exchange() -> None:
+ code = None
+ if flow.submitted_code is not None:
+ # Expire even if the browser disappears, without contacting
+ # the provider until an explicit code reaches this waiter.
+ code = await flow.submitted_code
+ flow.submitted_code = None
server = await self._opencode_server()
if server is None:
raise RuntimeError("opencode_server_unavailable")
@@ -3302,17 +3330,23 @@ class AgentAuthService:
method=method_index,
prompt_answers=prompt_answers,
timeout=self._remaining_flow_timeout(flow),
+ **({"code": code} if code is not None else {}),
)
+
+ try:
+ # One start-time budget, including user input and server lookup.
+ # wait_for also supports the project's minimum Python 3.10 runtime.
+ await asyncio.wait_for(exchange(), self._remaining_flow_timeout(flow))
flow.state = "verifying"
# OpenCode persists into auth.json itself. Clear any Vibe-managed
# provider option key so the new OAuth entry becomes the effective
# credential, then ping the controller-refresh hook so the running
# OpenCode agent (and the Settings page on the next poll) sees the
# new auth state.
- await self._clear_opencode_provider_options_key_for_oauth(provider_id)
- await self._invoke_post_web_success_hook(flow.backend)
+ await self._commit_web_login(flow)
flow.state = "success"
except asyncio.TimeoutError:
+ flow.awaiting_code = False
flow.state = "failed"
flow.error = "timed_out"
except asyncio.CancelledError:
@@ -3388,8 +3422,7 @@ class AgentAuthService:
flow.state = "verifying"
ok, detail = await self._verify_web_login(flow.backend, force_oauth=flow.backend == "claude")
if ok:
- await self._invoke_post_web_success_hook(flow.backend)
- await self._refresh_backend_runtime(flow.backend)
+ await self._commit_web_login(flow)
flow.state = "success"
else:
flow.state = "failed"
@@ -3422,9 +3455,7 @@ class AgentAuthService:
claude_oauth_attempt=flow.claude_oauth_attempt,
)
if ok:
- await self._invoke_post_web_success_hook(flow.backend)
- await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=True)
- await self._refresh_backend_runtime(flow.backend)
+ await self._commit_web_login(flow)
flow.state = "success"
else:
await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)
@@ -3480,7 +3511,32 @@ class AgentAuthService:
if task and not task.done():
task.cancel()
- async def _invoke_post_web_success_hook(self, backend: str) -> None:
+ async def _commit_web_login(self, flow: WebAuthFlow) -> None:
+ """Finish one verified consent before cancellation can restore its backup.
+
+ Threaded config writes and marker delivery cannot be cancelled midway.
+ Settle them under the owning flow waiter, then let cancellation complete.
+ """
+ async def commit() -> None:
+ if flow.backend == "opencode":
+ await self._clear_opencode_provider_options_key_for_oauth(flow.provider)
+ else:
+ await self._persist_backend_auth_mode(flow.backend, "oauth", strict=True)
+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=True)
+ await self._invoke_post_web_success_hook(flow.backend, persist=False)
+
+ task = asyncio.create_task(commit())
+ try:
+ await asyncio.shield(task)
+ except asyncio.CancelledError:
+ # Do not return a cancellation receipt while the credential/apply
+ # operation is still capable of mutating the next opened flow.
+ try:
+ await task
+ finally:
+ raise
+
+ async def _invoke_post_web_success_hook(self, backend: str, *, persist: bool = True) -> None:
# OAuth completed via the web UI implies the user wants
# ``auth_mode = "oauth"``. Persist it before the controller-refresh
# hook fires so the live agent reloads with the right mode rather
@@ -3493,15 +3549,15 @@ class AgentAuthService:
# Skipped for opencode: ``OpenCodeConfig`` has no ``auth_mode``
# field (auth is per-provider, not global), so persisting one
# would add a stray attribute and could mislead future readers.
- if backend != "opencode":
- await self._persist_backend_auth_mode(backend, "oauth")
+ if persist and backend != "opencode":
+ await self._persist_backend_auth_mode(backend, "oauth", strict=True)
hook = self._post_web_success_hook
if not callable(hook):
+ await self._refresh_backend_runtime(backend)
return
- try:
- await asyncio.to_thread(hook, backend)
- except Exception as err: # noqa: BLE001
- logger.warning("post_web_success_hook failed for %s: %s", backend, err)
+ # Failure must reach the flow's terminal result. Credentials may have
+ # been persisted, but an unacknowledged/failed apply is not connection.
+ await asyncio.to_thread(hook, backend)
def _capture_codex_relay_for_oauth(self) -> tuple[dict | None, bool]:
"""Read the live relay identity before OAuth cleanup.
@@ -3842,7 +3898,7 @@ class AgentAuthService:
"""Backward-compatible name for API-key save cleanup."""
return await self.clear_claude_oauth_credentials_only()
- async def _persist_backend_auth_mode(self, backend: str, auth_mode: str) -> None:
+ async def _persist_backend_auth_mode(self, backend: str, auth_mode: str, *, strict: bool = False) -> None:
"""Persist V2Config.agents.<backend>.auth_mode for web and IM flows."""
captured_codex_relay: dict | None = None
observed_codex_api_key_auth = False
@@ -3998,6 +4054,8 @@ class AgentAuthService:
"Failed to persist auth_mode=%s after web flow for %s: %s",
auth_mode, backend, err,
)
+ if strict:
+ raise
async def _terminate_web_flow(
self,
@@ -4006,19 +4064,19 @@ class AgentAuthService:
final_state: WebFlowState,
error: str | None = None,
) -> None:
- await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)
if flow.reader_task and not flow.reader_task.done():
flow.reader_task.cancel()
try:
await flow.reader_task
except asyncio.CancelledError:
pass
- if flow.waiter_task and not flow.waiter_task.done():
+ if flow.waiter_task and flow.waiter_task is not asyncio.current_task() and not flow.waiter_task.done():
flow.waiter_task.cancel()
try:
await flow.waiter_task
except asyncio.CancelledError:
pass
+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)
if flow.process is not None and flow.process.returncode is None:
try:
flow.process.terminate()
@@ -4031,6 +4089,13 @@ class AgentAuthService:
if flow.claude_client is not None:
await self._disconnect_claude_client(flow.claude_client)
flow.claude_client = None
- flow.state = final_state
- if error:
- flow.error = error
+ if flow.submitted_code is not None:
+ flow.submitted_code.cancel()
+ flow.submitted_code = None
+ flow.awaiting_code = False
+ # Cleanup can race with a completed waiter. Preserve its terminal
+ # outcome instead of relabelling success/failure as a later cancel.
+ if flow.state not in self._WEB_FLOW_TERMINAL_STATES:
+ flow.state = final_state
+ if error:
+ flow.error = error
diff --git a/core/backend_restart.py b/core/backend_restart.py
index c2ca3de3a..13bcc5848 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -41,14 +41,17 @@ class BackendRestartCoordinator:
self._poll_interval = max(0.001, poll_interval)
self._tasks: dict[str, asyncio.Task[None]] = {}
self._request_locks: dict[str, asyncio.Lock] = {}
+ self._outcomes: dict[str, dict[str, str]] = {}
async def request_restart(self, backend: str) -> str:
"""Begin or join a restart and return without waiting for a long drain."""
lock = self._request_locks.setdefault(backend, asyncio.Lock())
async with lock:
existing = self._tasks.get(backend)
- if existing is not None and not existing.done():
- return "draining"
+ if existing is not None:
+ if not existing.done():
+ return "draining"
+ self._on_done(backend, existing)
agent_service = self.controller.agent_service
session_turns = self.controller.session_turns
@@ -56,11 +59,12 @@ class BackendRestartCoordinator:
session_turns.begin_backend_drain(backend)
try:
await agent_service.prepare_backend_restart(backend)
- except Exception:
+ had_active_work = await self._has_active_turns(backend)
+ except BaseException as exc:
+ self._outcomes[backend] = {"state": "failed", "error": str(exc) or type(exc).__name__}
agent_service.end_backend_drain(backend)
await session_turns.end_backend_drain(backend, resume_deferred=False)
raise
- had_active_work = await self._has_active_turns(backend)
task = asyncio.create_task(self._run(backend), name=f"backend-restart:{backend}")
self._tasks[backend] = task
task.add_done_callback(lambda completed, name=backend: self._on_done(name, completed))
@@ -74,15 +78,57 @@ class BackendRestartCoordinator:
return "draining"
def _on_done(self, backend: str, task: asyncio.Task[None]) -> None:
- if self._tasks.get(backend) is task:
+ current = self._tasks.get(backend) is task
+ if current:
self._tasks.pop(backend, None)
try:
task.result()
+ if current:
+ self._outcomes[backend] = {"state": "applied"}
except asyncio.CancelledError:
+ if current:
+ self._outcomes[backend] = {"state": "failed", "error": "cancelled"}
logger.info("Backend restart cancelled for %s", backend)
- except Exception:
+ except Exception as exc:
+ if current:
+ self._outcomes[backend] = {"state": "failed", "error": str(exc) or type(exc).__name__}
logger.exception("Backend restart failed for %s", backend)
+ def snapshot(self, backend: str) -> dict[str, str | bool]:
+ """Read application without starting another cutover or credential probe."""
+ lock = self._request_locks.get(backend)
+ if lock is not None and lock.locked():
+ return {"state": "draining"}
+ task = self._tasks.get(backend)
+ if task is not None:
+ if not task.done():
+ return {"state": "draining"}
+ if task.cancelled():
+ return {"state": "failed", "error": "cancelled"}
+ error = task.exception()
+ if error is not None:
+ return {"state": "failed", "error": str(error) or type(error).__name__}
+ outcome = self._outcomes.get(backend)
+ if task is None and outcome and outcome["state"] == "failed":
+ return dict(outcome)
+ from config.v2_compat import AppCompatConfig
+
+ config = getattr(self.controller, "config", None)
+ registered = backend in self.controller.agent_service.agents
+ # Optional compat sections are None only for disabled backends. Claude
+ # stays registered with an explicit flag. Use loaded state, never disk
+ # or a stale successful outcome to excuse unexpected missing agents.
+ if isinstance(config, AppCompatConfig):
+ disabled = (backend in {"codex", "opencode"} and getattr(config, backend) is None and not registered) or (
+ backend == "claude" and registered and config.claude.enabled is False
+ )
+ if disabled:
+ return {"state": "applied", "disabled": True}
+ # Startup-installed agents need no recent restart receipt.
+ if not registered:
+ return {"state": "unavailable"}
+ return {"state": "applied"}
+
async def _has_active_turns(self, backend: str) -> bool:
service = self.controller.agent_service
if service.runtime_turn_tokens_for_backend(backend):
diff --git a/core/internal_server.py b/core/internal_server.py
index e17302e09..95c314274 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1035,6 +1035,17 @@ def create_app(
logger.exception("internal Agent Activity cache invalidation failed")
return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+ @app.get("/internal/backend-application/{backend}")
+ async def _backend_application(backend: str) -> Any:
+ from modules.agents.catalog import AGENT_BACKENDS
+
+ if backend not in AGENT_BACKENDS:
+ return JSONResponse(status_code=400, content={"ok": False, "error": "unsupported_backend"})
+ coordinator = getattr(controller, "backend_restart_coordinator", None)
+ if coordinator is None:
+ return JSONResponse(status_code=503, content={"ok": False, "error": "backend_runtime_unavailable"})
+ return {"ok": True, "controller_pid": os.getpid(), **coordinator.snapshot(backend)}
+
@app.post("/internal/reconcile-agent-backends")
async def _reconcile_agent_backends(request: Request) -> Any:
"""Hot-apply persisted Agent backend config on the controller loop."""
diff --git a/docs/INSTALL_FOR_AI.md b/docs/INSTALL_FOR_AI.md
index a4c6dea04..37feec399 100644
--- a/docs/INSTALL_FOR_AI.md
+++ b/docs/INSTALL_FOR_AI.md
@@ -102,12 +102,24 @@ vibe
This starts the local service and opens the Web UI setup wizard. If a browser does not open automatically, check the terminal output for the local URL.
-In the wizard, help the user choose:
-
-1. Chat platform: Slack, Discord, Telegram, WeChat, or Lark / Feishu.
-2. Agent backend: Claude Code, OpenCode, or Codex.
-3. Project working directory.
-4. Channel or chat scopes that should be enabled.
+In the wizard, help the user install or detect Claude Code, Codex, or OpenCode,
+then connect one assistant with a subscription or API key. Existing valid
+credentials count; starting another login preserves them until the new login
+commits. Settings → Backends uses the same connection and recovery controls.
+OpenCode retains its explicit **Allow tool calls** action.
+
+Select **Enter workspace** explicitly. A stopped service starts at this point;
+the wizard confirms application and an available Agent before completing setup.
+Pending application, uncertain keychain auth, or a failed start stays recoverable
+on this screen. For OpenCode, if the Agent's provider is unconnected or its exact
+model is absent from that provider's merged native/custom catalog, choose a
+compatible model in the inline recovery and apply it explicitly. The wizard never chooses a model or changes an existing usable default silently.
+
+IM is optional for a fresh installation. Configure Slack, Discord, Telegram,
+WeChat, or Lark / Feishu later in Settings. Existing enabled but incomplete IM
+configuration opens an explicit **Repair saved messaging configuration** action
+using the existing platform form. Repair only its reported missing credentials;
+setup does not disable adapters or erase their configuration to bypass validation.
Platform docs:
@@ -129,7 +141,8 @@ This guides the user through avibe.bot sign-in, pairing, and a secure tunnel. Us
## Step 6: Smoke Test
-After setup, ask the user to send a short message in the enabled chat:
+After setup, open the Web workspace, select an available Agent, and ask the user
+to send a short message in a new conversation:
```text
Say hello and tell me which project directory you are running in.
@@ -141,13 +154,17 @@ Then verify:
vibe status
```
-If messages do not arrive, run:
+If the Web response does not arrive, inspect the selected Agent, backend
+connection and application status in Settings, then run:
```bash
vibe doctor
```
-Check platform-specific docs for missing permissions, disabled bot privacy settings, or unselected channels.
+Only if an IM platform was explicitly configured, repeat the message in an enabled
+IM chat. For IM delivery failures, check the platform-specific docs for missing
+permissions, bot privacy settings, or unselected channels. A Web-only installation
+does not need an IM chat to complete this smoke test.
## Common Fixes
diff --git a/docs/plans/2026-09-17-onboarding-design-fidelity.md b/docs/plans/2026-09-17-onboarding-design-fidelity.md
index b90d94f16..e399ba710 100644
--- a/docs/plans/2026-09-17-onboarding-design-fidelity.md
+++ b/docs/plans/2026-09-17-onboarding-design-fidelity.md
@@ -1,5 +1,14 @@
# Onboarding design fidelity repair — issue #2017
+> Status: #2017 merged through #2028. The 2026-09-18 owner amendment in
+> [the active #2011 contract](2026-09-18-shared-backend-connection.md) supersedes
+> every historical no-header-logo and vertically centered Welcome assertion below.
+> Web uses the existing BrandLogo at top left and language at right. Both steps
+> share title/subtitle top anchors and typography at the same viewport, with normal
+> flow and scrolling. The 1104 cap and authored animation remain unchanged.
+> Browser tests now measure actual EN/ZH transitions at desktop, tall and narrow
+> viewports; centering Welcome independently is no longer an acceptance invariant.
+
PR #2015 merged successfully but did not faithfully reproduce the approved Welcome and assistant-setup design. The owner rejected the visual fidelity on 2026-09-17 and explicitly identified the existing animated Show Page as the implementation reference. At 16:55 the owner additionally required the designed widths and adaptation to different screens.
## Authority and scope
diff --git a/docs/plans/2026-09-17-shared-web-desktop-design.md b/docs/plans/2026-09-17-shared-web-desktop-design.md
index a62a9b775..b9c1b4aaf 100644
--- a/docs/plans/2026-09-17-shared-web-desktop-design.md
+++ b/docs/plans/2026-09-17-shared-web-desktop-design.md
@@ -11,13 +11,14 @@ The owner requested 3–4 clear, independently reviewable GitHub issues. The fol
Issues #2010–#2012 are shared React/Python Web/Desktop work and can be accepted one at a time. Issue #2013 starts only after the first three accepted results are in the shared master path and targets the long-lived `desktop` branch. Each issue body records its reuse points, acceptance criteria, and out-of-scope boundary. The issue comments record the dependency order.
-## Current status: implementation started for #2010 only
+## Current status: #2011 and #2012 active
-Owner session: `sestqz5wvu5ty`. Active scope confirmed: 2026-09-17 15:36 Asia/Shanghai.
-
-The owner confirmed the complete design set on 2026-09-17 13:14 Asia/Shanghai and requested issue-first delivery. Issue #2010 is now the only active implementation slice. Do not dispatch #2011, #2012, or #2013 until #2010 is accepted by the owner. The source SHA below records the planning baseline; implementation code remains isolated in its assigned worktree.
-
-The implementation agent must inspect the complete final Dark/Light and Chinese/English design set through Pencil before coding. The implementation lanes and technical contracts below describe the active #2010 slice and the later queued slices.
+#2010 and its fidelity repair #2017 are merged through PRs #2015 and #2028.
+The owner authorized #2011 implementation on 2026-09-18 and #2012 in parallel
+at 02:36 Asia/Shanghai. Each uses a separate worktree from master `4019b704c`,
+with one product writer. #2013 remains deferred. The active #2011 contract is
+`2026-09-18-shared-backend-connection.md`; its owner amendments supersede earlier
+no-logo/centered-Welcome statements and sequential dispatch restrictions here.
## Owner decisions and delivery boundary
@@ -27,7 +28,7 @@ The implementation agent must inspect the complete final Dark/Light and Chinese/
- Reuse Settings -> Backends authorization and save semantics. Reuse the existing AgentRoutePicker and DirectoryBrowser interactions.
- Keep existing product logo assets. Logo exploration boards are out of scope.
- The design is shared by Web and Desktop. The owner approved the complete design set on 2026-09-17; implementation must align both themes and languages together, preserve System mode, and use existing i18n ownership.
-- Current authorization covers implementation of #2010 only, followed by owner acceptance. Shared master work precedes desktop-specific integration; merging, releasing, or changing the local running service requires its own applicable authorization.
+- Current authorization covers #2011 and #2012 in parallel. Shared master work precedes desktop-specific integration; merging, releasing, or changing the local running service requires separate authorization.
Planning source snapshot: `7c028d74ebc4eb82b39a09991fcb09c8400253b0`.
Design source: `/Users/max/workspace/ai/avibe/avibe-docs/design_desktop.pen`.
@@ -94,7 +95,7 @@ Deliver sidebar248 with header search/inbox and actual count; fixed navigation g
## Verification and delivery gates
-Each issue uses an isolated worktree and a real non-draft PR targeting `master`, never merges without authorization. Delivery is sequential: #2010 is active from the committed contract baseline; prepare each subsequent issue from current master only after the preceding issue is accepted. Do not dispatch the historical parallel lane plan as an active mandate or stack product PRs.
+Each issue uses an isolated worktree and a real non-draft PR targeting `master`, never merges without authorization. Delivery follows the owner-authorized #2011/#2012 parallel division in the active contracts. Both begin from master; do not stack product PRs. Integrate #2011 before verifying the dependent #2012 completion banner.
Load `pr-delivery-loop` and `background-watch-hook`; use exact-head Codex bot pass, zero unresolved threads across all heads, and all expected CI successful. One forever combined PR/CI watch per lane with timeout0; notify orchestrator at first PR creation so it arms its independent gate watch before subsequent pushes. Inventory findings by reviewed head and root-cause class before fixing; repeated class on two reviewed heads or three findings heads after model rewrite stops patching for orchestrator diagnosis.
@@ -102,14 +103,14 @@ Run focused behavior tests, auth_setup scenario cases when auth changes, require
## Follow-on and pending inputs
-- The complete design set and #2010 start signal were received. #2011–#2013 remain queued until owner acceptance of each preceding issue; #2010 review repairs retain its existing authentication and completion boundaries.
+- #2010/#2017 are merged; #2011/#2012 are active and #2013 remains queued. The native desktop slice follows shared integration.
- Stage2 native desktop: after shared work is integrated, update from the shared master result and implement system Settings/menu/window specifics in desktop-based task worktrees. Preserve loopback/capability boundaries and existing lifecycle. No desktop->master wholesale merge is implied.
- Master merge and release: wait for explicit owner instruction after concrete PR gates and acceptance evidence.
## Earlier pause verification
-On 2026-09-17, two implementation runs had been dispatched before the owner clarified the design-completion gate. Both were canceled and their session queues were verified empty. Both isolated implementation worktrees remained clean at the contract-only commit `ee14c1ad9`; neither had product-code changes or later implementation commits. The scheduled implementation liveness task was removed and no implementation watch remained armed. These earlier sessions remain canceled. The current #2010-only dispatch supersedes that pause for its assigned worktree; the shared-shell lane remains inactive.
+On 2026-09-17, two implementation runs had been dispatched before the owner clarified the design-completion gate. Both were canceled and their session queues were verified empty. Both isolated implementation worktrees remained clean at the contract-only commit `ee14c1ad9`; neither had product-code changes or later implementation commits. The scheduled implementation liveness task was removed and no implementation watch remained armed. These earlier sessions remain canceled. The owner-authorized #2011 and #2012 lanes now supersede that historical pause in separate worktrees.
- Onboarding: session `sestvg9hbksrs`, canceled run `2c40a884e87f`, branch `feat/shared-onboarding`.
- Shared shell/home/General: session `seshdfv3uqjxj`, canceled run `54372ae4d030`, branch `feat/shared-workspace-ui`.
-- Historical contract baseline: branch `feat/shared-web-design-contract`. Its pause instruction was superseded for #2010 by the active issue-specific plan; it does not authorize starting the other issue lanes.
+- Historical contract baseline: branch `feat/shared-web-design-contract`. Its historical pause is superseded by the active issue-specific contracts for #2011 and #2012; #2013 remains deferred.
diff --git a/docs/plans/2026-09-18-shared-backend-connection.md b/docs/plans/2026-09-18-shared-backend-connection.md
new file mode 100644
index 000000000..2f90127c6
--- /dev/null
+++ b/docs/plans/2026-09-18-shared-backend-connection.md
@@ -0,0 +1,496 @@
+# Shared backend connection and setup readiness — issue #2011
+
+## Authorization and baseline
+
+Owner session `sestqz5wvu5ty` explicitly requested implementation of #2011 on 2026-09-18 at 02:16:59 Asia/Shanghai. #2010 and its fidelity follow-up #2017 are merged (#2015 and #2028). #2011 and #2012 are active in separate worktrees with separate sole writers; #2013 remains deferred. Previous sequential and #2010-only pause language is superseded by the owner’s parallel authorization.
+
+Repository: avibe-bot/avibe. Branch: `feat/shared-backend-connection`. Assigned worktree: `/Users/max/workspace/ai/avibe/.worktrees/avibe/shared-backend-connection`. Starting master: `4019b704c99afe16223d475fccd9e1cb94a109d7`, verified against GitHub and containing #2028. The local clone has a narrow origin fetch refspec: `git fetch origin master` alone may leave origin/master stale. Refresh explicitly with `git fetch origin refs/heads/master:refs/remotes/origin/master` and verify the SHA before later integration.
+
+## Outcome and preserved boundaries
+
+A first-time user can install any supported assistant, apply one subscription or key connection through the same logic as Settings → Backends, and explicitly enter the workspace without configuring IM. A valid existing connection counts. Executable discovery, selecting a method, seeing a code, opening a browser, or an optimistic UI flag never counts as a connection. One unrelated missing/installing/upgrading assistant cannot block another usable assistant.
+
+Use the approved 568px dialog family in `/Users/max/workspace/ai/avibe/avibe-docs/design_desktop.pen`. Preserve #2028's 1104px shared width, responsive geometry, assets and automatic animation with no playback controls. Use existing en/zh localization and Light/Dark/System ownership. Existing selectors retain their interaction. Do not reinterpret the design as a full Settings page squeezed into a modal.
+
+This issue does not implement Workbench/General Settings, native Desktop presentation, a new credential store, Model Hub management, real credential onboarding on this machine, or a release. It does not change App authorization rules, member/remote eligibility, or continuing access for previously completed setup. A user's later credential expiry does not force them through setup again.
+
+## Contract and ownership
+
+One implementation writer owns this complete React/Python connection flow; a read-only design lane supplies source evidence. The separate #2012 writer consumes the frozen public readiness interface without modifying this lane’s owners.
+
+1. **Installation:** existing detect/install/lifecycle producers own CLI discovery and canonical paths. `found` is installation evidence only; a rejected probe is unknown/error, not confirmed missing. Keep per-backend ownership, live local toggles, canonical non-ASCII paths, stale-result protection and the reconciliation fixes from #2015.
+2. **Claude:** `ApiContext.getClaudeAuth` / `saveClaudeAuth` and their existing Python handlers own effective state and persistence. `active_auth_mode`, `has_api_key`, `credential_type`, `has_oauth_credentials`, and runtime apply receipts must be interpreted consistently with Settings. Support subscription/manual callback, API Key and Auth Token. No plaintext credential readback or copying into another store.
+3. **Codex:** `getCodexAuth` / `saveCodexAuth` own auth state and key/base-URL persistence. Preserve the distinction between saved `auth_mode`, effective `active_auth_mode`, and `auth_mode_uncertain` (keychain-backed credentials must not be falsely declared absent or valid). Subscription uses the existing device flow. A confirmed existing connection should not require a new login or a new mandatory billable model call.
+4. **OpenCode:** `getOpencodeProviders`, `setOpencodeProviderAuth`, default-provider configuration and the existing runtime provider-auth catalog own provider identity, methods and active auth. OAuth uses the OpenCode-specific provider start endpoint and existing backend flow status/cancel/submit semantics. Never route an OpenCode provider choice to Claude/Codex or Model Hub auth storage, or hard-code a replacement provider catalog.
+5. **OAuth lifecycle:** share/extract `BackendOAuthPanel`, `OAuthFlowParts`, `useOAuthFlowLock` and their existing controller logic as appropriate. Lock method/provider changes during an active handshake; reject duplicate submit. Close/Escape/Cancel cancel the active operation without removing prior saved credentials. Handle close during pending start, pending poll/save and late completion so orphaned flows and stale success cannot update another backend or a closed/reopened dialog. Terminal flow success must refresh effective server state before rendering connected.
+6. **Save/apply:** preserve absent/null/empty-key and URL semantics, masked-key behavior, existing credentials, errors with editable inputs, and notices/partial outcomes. A failed live application must not be mislabeled successful connection. No client-side second restart after accepted backend reconciliation. Existing Settings and the compact onboarding view must share behavior rather than separate handlers that drift.
+7. **Readiness:** derive from authoritative installation and effective applied auth for the same backend. Pending/failed/uncertain reads remain non-success with retry/recovery, not false disconnected claims. Preserve explicit enablement and routing semantics; before choosing how a disabled-but-authenticated backend becomes usable, trace the existing configuration owner and document the smallest consistent behavior. Never auto-enable on render/detection. Any new API/readiness field must have its actual producer, consumer and uncertainty semantics documented in this plan before implementation, using existing state before adding a mechanism.
+8. **Completion:** `Wizard` remains the orchestration owner and writes the existing `setup_completed` using narrow config mutations only after explicit Enter workspace and fresh readiness. Do not require IM/platform/channel/Summary steps on this new completion path. Preserve existing platform/config state and any separately used management surfaces. Navigate to `/` with React Router state `{ onboardingCompleted: true }`; this is a transient navigation fact for #2012, not authentication, persisted state or a fabricated available-Agent record. Do not implement the #2012 banner now. Prove a usable existing Agent/default resolution remains available after completion.
+
+## Source and reuse inventory before edits
+
+Read `AGENTS.md`, `.agents/skills/pr-delivery-loop/SKILL.md`, `docs/plans/2026-09-17-shared-web-desktop-design.md`, `docs/plans/2026-09-17-onboarding-design-fidelity.md`, `docs/plans/setup-backend-runtime-reconcile.md`, and the current issue body. The old 2026-09-15 design handoff is historical: current issue semantics and final canvas annotations govern when it contradicts the compact setup flow.
+
+Read final auth boards through Pencil: initial IDs from the existing shared plan are `V0zHJ`, `OHULW`, `MvT2k`, `oLe1U`, `FwRTK`, `laAX1`, `MtOWg`, `KWKHX`, `JtVGU`, `r2y97O`, `D6uRiy`, `MGCD0`; re-discover current names, frame variants and descendants rather than assuming this list is complete. Use explicit `filePath`: another agent is working on Miao's active canvas. Read/export only; do not mutate, save or copy designs. Record actual frames, geometry, tokens, states and remaining deliberate exceptions. Missing Light EN duplicates can compose approved English copy with the same Light tokens; do not invent a new design.
+
+Inventory backend form/controllers and the full Python apply/cancel path before extracting. Relevant existing files include `settings/providers/{BackendProviderConfig,ClaudeProviderConfig,CodexProviderConfig,OpencodeProviderConfig,opencodeProviderAuth}`, `settings/BackendOAuthPanel`, `settings/oauth/OAuthFlowParts`, `settings/shared/{useOAuthFlowLock,useBackendRuntime}`, `context/ApiContext`, `Wizard`, `steps/AgentDetection`, `onboarding/AssistantRow`, `lib/wizardConfigMutations`, existing backend auth service/handlers and `vibe/api.py` / `vibe/ui_server.py`.
+
+## Allowed implementation scope
+
+- Above setup/auth/provider components and directly related reusable hooks/forms, tests and scoped onboarding styles; relevant localization keys only.
+- Minimal additive `ApiContext` types/methods and existing Python auth/setup/config owners where traced call paths require it; no unrelated schema migration or auth architecture rewrite.
+- `tests/scenarios/auth_setup/` catalog and scenario cases, directly relevant unit/consumer/browser tests and this plan. Consolidate the shared plan's active status to #2011 and prior slice completion without rewriting unrelated history.
+- Global theme primitives/tokens, App routing/AuthGuard semantics, Model Hub implementation and other redesign issues are outside scope; route a concrete necessary deviation to PM before editing.
+
+## Verification and acceptance
+
+Read `standards/scenario-testing/AGENTS.md`, `tests/scenarios/INDEX.yaml`, the auth_setup catalog, observations and listed harness cases. Scenario IDs must be real catalog entries introduced/updated in the same change, never invented in the PR description.
+
+- Cover each backend's key/subscription path, Claude Auth Token, OpenCode provider-specific device/browser/manual capability, stored valid/uncertain auth and effective-vs-saved mode.
+- Exercise real consuming components for close/Escape/cancel, delayed start/save/poll, method locks, duplicate submit, retry retaining input, stale replies and serial config reconciliation.
+- Cover one ready backend with other missing/upgrading/error rows; installation-only disabled entry; no automatic navigation; explicit completion without IM; existing-user state preserved; non-ASCII paths and concurrent narrow config changes.
+- Add closed-loop auth_setup scenarios using existing real service/config owners with test-owned fake upstream/CLI boundaries, so persistence→apply→effective read→readiness is actually exercised. Mock-only UI screenshots do not prove real OAuth/install.
+- Browser verification against exported final dialogs in en/zh and Light/Dark: representative desktop and narrow viewport, all relevant states, keyboard focus/cancel/overflow. Batch first review and one targeted correction confirmation; do not endlessly polish or regenerate matrices without a new failure.
+- Run focused tests, applicable Python/Ruff checks, UI build/lint, theme/catalog and current translation/type gates. Broaden only for real failures/concerns; CI handles slow repository-wide checks.
+
+All probes are hermetic: redirect the entire HOME/XDG/CLI-config/token/keychain path to test-owned resources and deny uncontrolled external requests. Do not use this machine's saved auth, production profiles, running Avibe service or tenant instances. No primary-checkout edits or `.runtime` writes; use test-owned local processes for evidence. Incus remains deferred here because its runner writes primary metadata. Record real isolated installation/live OAuth as residual manual acceptance where not performed; never silently perform it with the owner's credentials.
+
+## Delivery and liveness
+
+The owner authorized implementation, tests, branch commits, push and non-draft PR delivery; not merge. Finish the bounded implementation and required evidence, then send PM a concrete diff/current head and evidence for one pre-push visual/consumer spot-check. This is an internal PM gate, not a new owner permission request. Continue independent tests/documentation while PM checks; explicitly deliver the report to `sestqz5wvu5ty` if a background command consumes the usual callback.
+
+After PM checks: open non-draft PR to master, `Closes #2011`, read back title/body/base/head, immediately seed and arm one durable combined PR+lint lane Watch (`--forever`, both timeout layers 0, independent persistent cursor). New-PR bootstrap exception applies. Notify PM with PR/full head/Watch ID so PM arms its independent Watch. **Never manually post `@codex review`; cyhhao triggers automatically.** Observe pickup and report a verified gap instead of duplicate triggering.
+
+Paginate all findings/threads and count reviewed heads/root-cause classes each round. Two heads with a repeated class, or three findings-bearing heads after a model rewrite, stop blind repair for PM diagnosis; green tests do not waive the breaker. Final report precedes lane Watch cleanup. No merge, release, service restart or work on the parallel #2012 / deferred #2013 implementation.
+
+## Progress
+
+- [x] Owner start instruction and latest master verified; isolated worktree created.
+- [x] Native design evidence and Settings/API ownership inventory.
+- [x] Implement shared connection forms/lifecycle and authoritative readiness/completion.
+- [ ] Focused/scenario/browser verification and independent PM spot-check.
+- [ ] PR, exact-head Codex review, complete CI and zero unresolved threads.
+- [ ] Owner acceptance / separately authorized merge.
+
+## Whole-path inventory and UI extraction (2026-09-18)
+
+- `AgentDetection` owns per-backend discovery/install/canonical paths and live
+ enable drafts; `Wizard` owns explicit completion. The old unconditional
+ OpenCode permission gate must become specific to OpenCode's readiness.
+- Settings providers currently own native credential reads and saves. Extract a
+ shared connection form used by Settings and the compact dialog; runtime,
+ Model Hub supply controls, provider/model management and optional billable
+ probes remain in Settings. No new credential persistence.
+- `BackendOAuthPanel` owns start/status/submit/cancel. Extract its controller for
+ both presentations. An operation generation invalidates stale async work;
+ unmount/cancel invalidates first, cancels known flows, and cancels a late start
+ by its returned flow ID. Duplicate start/submit use synchronous ownership.
+ Native backend login uses `force_reset=false`: merely starting or cancelling
+ login must not run logout. The existing Claude settings backup owns recovery.
+- Key save keeps absent key = reuse, empty/null base URL = clear, and no OAuth
+ base-URL writes. Masked values are display-only. Errors retain entered values.
+ Save/apply warnings and fresh effective reads are shared across consumers.
+- Native `Get` confirmed 568px / padding24 / gap20 / radius16 / shadow 0 18 48
+ (#00000088 Dark), 40px method segment, 42px fields, 38px actions, 40px logo
+ well with 28px existing logo; title20/600, target12, introduction13/1.55.
+ Full observer packet supplies Light and all language/state variants.
+
+### Exact type additions before their consumers
+
+- `OpencodeMutationResult.restart?: BackendRestartResult`: producer already
+ exists in `save_opencode_provider_auth_async`; both Settings and connection
+ form consume it. `ok:true` means persisted, `restart.ok:false` means failed
+ live apply and must retain a recoverable state, never connected.
+- `OAuthWebStartResult.backend` and `OAuthWebStatus.backend` include `opencode`:
+ existing Python producers already emit this value; the originating backend
+ remains the controller identity for every later operation.
+- Shared UI form accepts `{backend, provider?, onConnected?, onCancel?, compact?}`.
+ `provider` is a runtime catalog row and is required only for OpenCode. Its
+ read/save callbacks always target OpenCode ownership. `onConnected` runs only
+ after persisted/apply results and a fresh effective read agree; dismissal
+ invalidates that callback without pretending a submitted write was undone.
+
+Runtime/readiness IPC additions follow the approved disposition and exact
+producer/consumer contract below. Canonical `V2Config.default()` is workbench-only. Existing
+incomplete enabled IM drafts retain the existing completion validator and data.
+
+### PM-approved runtime observation boundary
+
+PM approved the scoped IPC/coordinator extension on 2026-09-18. No persistent
+ledger, config generations, schema or second lifecycle controller is added.
+
+- `BackendRestartCoordinator.snapshot(backend)` produces `{state, error?}` with
+ `state: applied | draining | failed | unavailable`. It reads the existing
+ task, retained last outcome and actual registered backend. Prepare failures,
+ task failures and cancellation remain failed until a successful application.
+- Verified UDS `GET /internal/backend-application/{backend}` projects that state
+ through the existing allowlist. The UI's existing API owner combines it with
+ original save/OAuth receipts. A bounded process-local receipt per backend
+ retains failure to deliver a refresh marker; querying an idle controller
+ cannot erase that failure. Only explicit successful apply clears it.
+- `GET /api/backend/{backend}/connection` produces `BackendConnectionState`:
+ `{ok, backend, installed, enabled, auth: subscription | api_key | none | unknown,
+ application: applied | draining | failed | stopped | unknown, ready,
+ entry_eligible, permission_required?, message?}`. The 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.
+- A fresh GET observes native launch auth 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.
+- Wizard explicitly rechecks candidates, starts only a confirmed stopped
+ service through the existing start owner, confirms usable application/Agent
+ selection, and writes only `setup_completed` before navigation. If start
+ requires completion first, the ordering and failure recovery will be tested
+ and documented before choosing that route. Existing invalid enabled IM drafts
+ retain credential validation and the inline saved-platform recovery below.
+
+### Owner amendment and parallel delivery
+
+On 2026-09-18 the owner restored the existing Web `BrandLogo` at the left of the
+header (language remains right) and required Welcome and setup to share the
+same top-anchored title/subtitle geometry, including wrapped narrow copy. This
+supersedes the earlier centered Welcome and no-logo statements. Both screens
+use the same normal-flow layout and scroll on short windows. No host detection
+or playback controls are added.
+
+#2011 and #2012 now run in parallel from master `4019b704c`, in separate task
+worktrees with one writer each. #2011 owns auth/install/runtime/API/Wizard and
+onboarding, this plan and the shared plan's status consolidation. #2012 owns
+Workbench/sidebar/Composer/General/Settings shell and `App.tsx` General wiring;
+AuthGuard is unchanged. Global `index.css`, primitive additions and language
+presentation belong to #2012; #2011 consumes existing public APIs and uses
+scoped styles. Shared localization edits are disjoint (`onboarding`/auth/provider
+versus `sharedWorkspace`/General/workbench/nav/layout), preserving sibling text.
+#2013 native work remains deferred. No primary worktree, merge or service update.
+
+The canonical exported consumer interface is `BackendConnectionState` and
+`ApiContext.getBackendConnection(name: 'claude' | 'codex' | 'opencode'):
+Promise<BackendConnectionState>`. Its fields are listed above. #2012 consumes
+`ready === true` only to corroborate the transient completion banner, with real
+Agent/default identity. `enabled` alone and `onboardingCompleted` authorize
+nothing. Ordinary existing Workbench remains accessible when readiness expires.
+No second auth/start/save/restart in that consumer. Integration verifies the
+actual transition after #2011 merge; separate fixtures do not prove the seam.
+
+First start does not require `setup_completed` in the service start owner.
+Wizard therefore checks entry eligibility, explicitly starts a stopped service,
+re-reads runtime application and real enabled Agents, preserves a usable default
+(or selects an existing ready Agent if the seeded default is unusable), then
+saves only `setup_completed=true` and navigates. A failed start leaves completion
+false. The existing enabled-IM validator remains the final save boundary.
+
+### Runtime-declared OpenCode callback mode (PM disposition, 2026-09-18)
+
+`WebAuthFlow`, its start/status serializers and `OAuthWebStartResult` /
+`OAuthWebStatus` add optional `callback_kind: 'code' | 'device' | 'redirect'`.
+The producer maps OpenCode authorize `method: code` to `code`; its start-time
+waiter retains the selected method index and prompt inputs. `auto` (and missing
+method for compatibility) uses `device` when a device code exists, otherwise
+`redirect`. Unknown explicit methods fail start. Claude/Codex can omit this
+field; their existing callback/device contract is unchanged.
+
+Manual-code flows arm the existing waiter at start. `_arm_flow_waiter` remains
+the only deadline publisher; the waiter first awaits a flow-owned in-memory
+`submitted_code: Future[str] | None`, then uses the remaining deadline for the
+callback. An abandoned browser expires and releases provider admission without
+polling. Explicit nonempty submit resolves the future once and never replaces
+the waiter or deadline; cancellation owns that same task. These flows make no
+callback request before submission, and send the code only to the existing
+OpenCode callback endpoint. `OpenCodeServerManager.wait_provider_oauth` adds an
+optional code argument; reserved method/code fields cannot be replaced by prompt
+answers. The scope extension includes this one transport method and direct
+transport tests, with the auth_setup runtime-provider scenario consuming it.
+No backend readiness fields or parallel-lane interfaces change.
+
+Installation jobs reconcile every refresh-capable backend, including Claude,
+through the existing rolling-refresh owner after persisting the detected CLI
+path. The job reports a failed application receipt as failure; a draining
+receipt remains non-ready until the coordinator confirms application. A stopped
+controller keeps apply-on-next-start semantics. Neither the frontend nor entry
+adds another restart. Tests consume actual job/config/coordinator/readiness
+owners with isolated non-ASCII paths and cover applied/draining/failed/stopped
+states for all three backends.
+
+The additive connection GET has an explicit Member management rule alongside
+backend runtime/auth/install operations. Owner and Member can read it; Editor,
+Viewer and unauthenticated remote callers cannot reach its readiness consumer.
+Unknown routes retain the Owner default, supported backend validation remains
+inside native dispatch, and the existing lower-tier read-role baseline is
+unchanged. This corrects a CI-discovered omitted route classification without
+changing credential write permissions.
+
+The internal application projection also returns `controller_pid` from the
+serving process. Failed UI apply receipts retain the already-existing runtime
+owner PID. A registered backend in a confirmed *new* controller clears an old
+failed delivery receipt because startup loaded persisted config; an unchanged
+controller (including recovered IPC and a new browser page) cannot erase it.
+This uses existing process identity only, with no generation/config-epoch scheme.
+The public BackendConnectionState contract remains unchanged.
+
+### OpenCode Agent/model recovery (PM disposition, 2026-09-18 03:29)
+
+Backend readiness remains the frozen auth/application contract above. Explicit
+completion separately checks accessible enabled Agent routing: Claude/Codex keep
+existing usability rules; OpenCode Direct provider-qualified models require
+that provider's effective API/OAuth auth. Catalog membership or configured=true
+alone does not prove that auth. Hub uses its existing canonical model catalog
+and supply owner, never Direct prefix parsing. Preserve a usable current default
+and allow another usable backend to bypass an unrelated OpenCode mismatch.
+
+When no usable Agent exists and an accessible manageable OpenCode Agent has the
+Direct mismatch, expose an inline recovery using the existing model catalog,
+Combobox and updateVibeAgent. Display the Agent and current model; require an
+explicit compatible model selection and Apply. Do not choose a model, create an
+Agent or infer untouched intent from builtin source/timestamps. Save only model
+(and effort only if the catalog explicitly requires a compatibility change).
+After save rerun fresh connection/default/completion checks. Display, cancel and
+catalog reads never write. Unavailable/empty catalogs and failed saves retain
+credentials, old persisted selection and the setup gate, with local retry.
+
+Focused consumers cover Anthropic/Poe-only auth, seeded OpenAI mismatch,
+explicit model persistence, cancellation/failure, preserved custom default and
+another usable backend. A hermetic auth_setup scenario crosses the real Agent
+store/default, OpenCode route resolution and narrow setup completion. Desktop
+and narrow browser recovery checks extend the existing frozen dialog evidence;
+no new dialog capture matrix or changes to #2012-owned picker files are needed.
+
+### Actual-image review and targeted confirmation
+
+The read-only observer viewed all 16 frozen final renders. PM confirmed compact
+labels must use Credential type / API Key / Auth Token and generic provider key
+labels; Settings retains its technical variable disclosure. Locked segmented
+controls use whole-control opacity .6 once, with disabled radio semantics and
+visible mint selection. Scoped focus-visible styling uses the existing ring
+token. Light primary white-on-mint is the approved pairing; disabled opacity .4
+and enabled state are verified separately, without a palette change.
+
+The inherited generic backend glyphs were initially excluded. The owner’s
+2026-09-18 07:16 request supersedes that exclusion for onboarding brand marks
+only; unrelated Settings/Workbench glyphs and tile accents remain unchanged.
+Text-flow height differences (428 versus native 423/434; 536 versus 552) are
+accepted. EN Light and narrow compose approved tokens/copy because no complete
+authored counterparts exist. The frozen 16 captures stay unchanged; only small
+corrected label/lock/focus/Light action crops and model recovery are added.
+
+### Saved incomplete IM recovery (PM disposition, 2026-09-18 03:48)
+
+Before explicit startup/completion, Wizard reads fresh config and its server
+platform catalog. Existing platformHasRunnableConfig/credential_fields and
+redacted has_* markers identify already-enabled incomplete adapters; WeChat
+retains its runtime-waits-for-QR exception. Canonical enabled=[] has no IM step.
+Only the explicit Repair saved messaging configuration action mounts the
+existing embedded platform editor, extracted unchanged from Settings into a
+shared switch. No AuthGuard, platform selection, enablement or routing changes.
+
+Apply derives configChanges only within the affected config_key, preserving
+other fields and concurrent edits. Existing form validation and masked-secret
+semantics remain; no automatic auth test, second restart or setup_completed
+write in the editor. Failure retains drafts, cancellation writes nothing. After
+a successful repair the normal fresh completion checks run again. Generic
+completion failures offer local retry rather than an unreachable Settings link.
+AUTH-SETUP-120 covers real API preservation/validation; actual Wizard consumers
+cover explicit mounting, narrow payloads, failure/cancel and canonical bypass.
+
+### Verification record and observation limits
+
+- Native source: 36 dialogs and 9 boards read/exported with explicit document
+ identity. The observer viewed all 16 initial final renders, then all 9
+ corrected crops; D1/D2/D4 resolved with no new defect. Frozen evidence is
+ `/tmp/issue2011/final-render/` and `/tmp/issue2011/corrected-render/`; the latter
+ includes model recovery at desktop/narrow. Separate narrow Slack recovery
+ verifies existing-form reachability. No source design changes were made.
+- AUTH-SETUP-119 crosses manual provider callback transport, test-owned native
+ persistence, coordinator drain and ASGI application projection. 120 covers
+ canonical no-IM and saved incomplete IM narrow repair, and actual Wizard
+ consumers cover explicit repair/masked secrets/failure/cancel. 121 covers
+ Anthropic/Poe provider auth, real Agent/default persistence, route resolution
+ and completion. IDs were checked unique locally and absent on remote master.
+- Existing auth regression, focused lifecycle/native-route/readiness tests,
+ actual consuming UI tests and the 70-test onboarding browser suite pass.
+ Additional focused browser checks verify corrected label bounds, focus ring,
+ Light action opacity and locked selection, model recovery and legacy repair.
+ Final gate logs are recorded in the PR report against the committed head.
+- Fixtures own config/HOME/XDG/native paths and local upstream transports.
+ Screenshot/UI mocks do not prove real provider OAuth or installation. No
+ production credentials, native keychain, real CLI login, billable model call,
+ local runtime restart, Incus, primary checkout or design mutation was used.
+- Readiness observes native launch credentials and Avibe-owned application. It
+ does not continuously validate upstream tokens or certify externally edited
+ files were hot-applied. Upstream automatic OAuth already sent to a provider
+ may commit externally; cancellation settles Avibe-owned work and prevents
+ stale UI effects, rather than claiming remote transaction rollback.
+
+### Review circuit breaker and complete boundary repair (2026-09-18 04:50)
+
+Two genuine findings-bearing heads (`b664dd95d5`, `31766481c8`) exposed the same
+OAuth lifetime class: the first omitted deadline enforcement, and its repair
+used an API unavailable on supported Python 3.10. PM paused editing, inspected
+all six threads and existing owners, and authorized these bounded repairs before
+another push. No architecture/schema rewrite or owner escalation is required.
+
+- The one start-time OAuth waiter uses Python-3.10-compatible `wait_for` for
+ the input/server/callback exchange. Credential commit remains outside that
+ timeout under the existing settlement shield. Actual isolated Python 3.10
+ tests cover the same lifetime properties as the current-runtime suite.
+- The coordinator recognizes intentionally absent Codex/OpenCode registration
+ only when its loaded `AppCompatConfig` has that backend set to `None`, as
+ `to_app_config` and successful unregister already specify. Missing config or
+ unexpectedly missing enabled registration stays unavailable; pending/failed
+ outcomes win. Claude remains registered and carries its enabled flag in its
+ loaded compat config. Applied configuration does not imply enabled/readiness.
+ The internal projection adds optional `disabled: true` only with confirmed
+ applied disabled config. The public reader preserves unknown if disk now says
+ enabled while the controller still reports disabled; this prevents mixing two
+ observations into false readiness before enablement has actually applied.
+ The public shape is unchanged. Settings confirms native credential readback
+ plus applied/stopped state and reports saved-but-disabled without enabling it
+ or presenting connected. Unknown IPC and failed receipts never count as saved
+ application. The form's completion callback refreshes parent data only.
+ Settings uses the existing Save/Saving labels and a muted, wrapping status for
+ saved credentials on a currently disabled backend. The existing runtime hook
+ increments `connectionRevision` after a config mutation settles (including
+ failure); All three backend parents pass it to the shared form (OpenCode was completed in the round 3 closure below). This only triggers
+ fresh native/application reads, never readiness from an optimistic toggle.
+ Status refresh preserves key, URL and method drafts without remounting. There
+ is no duplicate enable control, event bus or polling; pending application
+ retains the existing explicit refresh action.
+- Discord's auxiliary guild selections use one small shared helper around the
+ existing settings API, after narrow credential mutation. It preserves access
+ management capability, explicit Discord platform and touched-empty semantics;
+ partial failure retains the mounted selection and cannot complete setup.
+- Only successful permission reads may add an OpenCode permission gate. The
+ documented malformed-file fail-open exception does not grant permission or
+ prove credentials/application, and the original file remains untouched.
+
+### Round 3: authoritative observation closure (2026-09-18 06:09)
+
+PM audited all 11 threads across three findings-bearing heads and diagnosed the
+repeated persistence/application/UI-observation class before resuming this work.
+The public connection contract, persistence owners and navigation event remain
+unchanged. A settled write must refresh persisted auth/config independently of
+application success; failures remain visible and never confer readiness. Reads
+are observers, not another mutation/restart. New intent and component lifetime
+invalidate older observations without replacing unrelated drafts.
+
+Caller inventory and bounded closure:
+
+- `BackendConnectionForm` owns key Save/Remove, compact OAuth confirmation and
+ native/application refresh for the dialog plus Claude/Codex/OpenCode Settings.
+ Its observer publishes native success even when IPC fails, preserves explicit
+ apply receipts/notices, distinguishes unreadable auth from absent auth, and
+ lets Refresh follow the effective mode after removal without writing again.
+- `BackendOAuthPanel` is used only by that form. Sign out and Claude stale-token
+ cleanup refresh the parent after committed/partial removal and preserve apply
+ failure instead of announcing unconditional success. `useBackendOAuth` already
+ awaits its success consumer and invalidates explicit cancellation separately
+ from panel inactivity/unmount; its deadline/backend lifecycle remains unchanged.
+ Removal warnings are published before readback may switch effective mode and
+ unmount the panel. Codex uses its native `has_chatgpt_tokens` field for removal,
+ while Claude uses `has_oauth_credentials`. Model Hub uses its own `OAuthConnectDialog` and
+ is outside this change.
+- All three Settings parents consume `useBackendRuntime.connectionRevision`,
+ including expanded OpenCode providers. The existing hook notifies observers
+ after config and runtime lifecycle settlement; applied failure cannot undo a
+ committed enabled/path write. Serialized toggles and current-intent guards
+ prevent an older rejection from rolling back a newer action. Lifecycle chip
+ `onChanged` updates the installed path; its existing `onOperationChange(false)`
+ notifies observers on every settlement, including failed restart/upgrade.
+ Direct install settlement also refreshes observers, even when apply fails.
+ Delayed detection/lifecycle results preserve newer CLI drafts. The only typed
+ runtime fixture is `e2e/badge-triggers/fixture.tsx`; its required revision is 0.
+- Wizard `AgentDetection` keeps its existing mutation queue. Per-backend intent
+ and read guards ensure fresh connection `enabled` repairs a failed optimistic
+ toggle, including explicit Retry; cached config/modal results cannot overwrite
+ a later intent. Unreadable state remains unresolved and blocks that candidate.
+- OpenCode Direct Agent eligibility requires effective provider auth and exact
+ model membership in the existing merged native/user-config catalog. The first
+ prefix chooses the provider; the rest is the model ID. Bare IDs require the
+ explicitly configured default provider. Empty/missing lists leave the route
+ unverified without changing backend readiness. Registered custom models and
+ existing usable defaults survive; Hub supply and other backends are unchanged.
+- Installation smoke testing starts in the Web workspace, with IM verification
+ conditional on explicitly configured platforms. Tests never perform that live
+ model/message operation.
+
+The accepted two-file CI fixture repair remains byte-for-byte unchanged in this
+combined round. Focused consumers cover failed-before transitions, all backend
+parents, queued intent races, partial removal and model catalog ownership. No
+new store, schema, restart mechanism, generic events, polling or automatic model
+selection is introduced. Frozen captures apply only to unchanged presentation.
+
+Validation for the round 3 repair committed as `c59df6fffc69fc9067e1afe7166db0cbcc89224a`:
+
+- Hermetic old-head comparison runs the current selected consumer tests against
+ the committed `f6a556b` product sources in a temporary copy: 21 failures and
+ one passing empty-model guard. The corresponding repaired subset passes.
+- The actual Agent/default → provider catalog → route → completion scenario
+ retains AUTH-SETUP-121 and now covers native and registered custom models for
+ Anthropic and Poe, including slash IDs. AUTH-SETUP-120 and the real Wizard
+ continue to cover canonical no-IM and saved-platform recovery. No IDs added.
+- Focused validation: 133 UI consumers across onboarding and the lifecycle chip;
+ 109 Python tests covering the complete config-merge file and AUTH-SETUP-120/121;
+ 22 repaired before/after cases; 8 Chromium badge cases, 4 WebKit badge cases and
+ 2 EN/ZH390 Settings browser cases, plus desktop/narrow model recovery cases. UI build/lint/test-type/consumer-type/theme/
+ catalog checks and changed Python Ruff pass. Global scenario inventory finds
+ 736 unique IDs across 15 catalogs, with all 46 auth/setup targets present.
+- All auth/model/config writes in these checks use test-owned state; daemon,
+ CLI, network and service boundaries are fake. No live smoke/model/auth test
+ was run. Python OAuth/native implementation is unchanged in this round.
+- The frozen original16/corrected9/round2 captures remain intact. The round3
+ browser check generated a separate pair of EN/ZH390 Settings regression
+ images under `/tmp/issue2011/r3-browser-settings`; these are test evidence,
+ not a claim of additional independent design approval. The model recovery
+ browser fixture now includes the actual provider models list; separate
+ desktop/narrow captures are under `/tmp/issue2011/r3-browser-model`. Presentation tokens,
+ layout, locale strings and the existing disabled-provider visibility policy
+ are unchanged.
+- Round 3 delivered at `c59df6fffc69fc9067e1afe7166db0cbcc89224a`: exact-head
+ Codex comment5722353880 passed, lint35284387433 and all18 jobs succeeded,
+ all11 threads resolved. PM independently confirmed readiness for owner visual
+ acceptance at 07:12; this is not owner acceptance or merge authorization.
+ Three historical findings-bearing heads and their diagnosed classes remain
+ recorded; subsequent bytes require fresh review/CI. Both original Watches
+ remain armed with unchanged cursors through verified merged/closed lifecycle.
+
+### Owner-requested onboarding brand marks (2026-09-18 07:19)
+
+The owner image and `avibe-docs/design_desktop.pen` govern this bounded visual
+correction. Source SHA256 is
+`115c69604b50e32823bcead4bd6c9269c8178b58d66a73b2e00db4a06d2caeb3`;
+PM's read-only extraction is `/tmp/issue2011/design/owner-logo-source.json`.
+The source file and packet are never modified.
+
+- Opt-in `BackendIcon` brand rendering uses the exact authored vector geometry,
+ Claude fill `#D97757`, and foreground/currentColor for Codex and OpenCode.
+ Existing block/glyph consumers and unknown-backend fallback keep their behavior.
+- Welcome `CollaborationStory` uses the bare 28px marks with full24x24 canvas
+ (dAO38/o2x2l0/Rxw0c and Light equivalents POffH/JYkg4/PK61u).
+ `AssistantRow` and `BackendConnectionDialog` retain existing logo wells;
+ OpenCode uses its authored22.4x28 path with viewBox4,2,16,20 inside the28px
+ frame (VE60T and dialog v9S8Li). No stretching or generic substitutes.
+- All onboarding identity consumers are these three call sites. AgentDetection's
+ remaining direct glyph is in the legacy Settings page branch, so it remains
+ unchanged. No global metadata/color mapping, layout, copy, auth, runtime,
+ model, dependency, Python or parallel-lane changes.
+- The scoped Impeccable refinement preserves the owner direction. Existing
+ consumer/build/lint/type checks and one desktop/390 Light/Dark browser batch
+ cover rendering, exact paths, fills, aspect and decorative accessibility.
+ Evidence goes to `/tmp/issue2011/owner-logo-render/`, preserving all earlier
+ captures. New screenshots require actual independent observer inspection;
+ an empty local image viewer is not visual signoff. PM must inspect the quiet
+ complete diff before any commit/push; no merge is authorized.
+
+The bounded logo batch passed four hermetic browser cases (desktop1200 and390,
+Light/Dark), freezing12 captures: Welcome collaboration, setup assistants and
+representative OpenCode dialog for each case. All exact source paths match;
+computed Claude fill is rgb(217,119,87), mono fill follows foreground, and
+OpenCode's fitted SVG is22.4x28 within the unchanged28px frame. The existing
+132 onboarding consumers, UI build, lint, test/i18n types, browser types,
+theme/catalog checks and diff check pass. One Impeccable detector pass returned
+no findings. The temporary capture harness is retained only in the evidence
+directory, not shipped. No Python rerun is needed for this static visual change.
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 724da5751..b4530806b 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -2469,6 +2469,7 @@ class OpenCodeServerManager:
method: int = 0,
prompt_answers: Optional[Dict[str, Any]] = None,
timeout: float = 900.0,
+ code: str | None = None,
) -> Dict[str, Any]:
"""Block until ``POST /provider/<id>/oauth/callback`` resolves.
@@ -2487,9 +2488,10 @@ class OpenCodeServerManager:
``aiohttp.ServerDisconnectedError``.
"""
await self.ensure_running()
- payload = {"method": method}
- if prompt_answers:
- payload.update(prompt_answers)
+ payload = {key: value for key, value in (prompt_answers or {}).items() if key not in {"method", "code"}}
+ payload["method"] = method
+ if code is not None:
+ payload["code"] = code
# Skip ``_request_scope`` (the per-call semaphore) too — it
# serialises all OpenCode HTTP calls behind a single lock, so
# holding it for 15 minutes would block every other UI request
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 533274fb6..7bd81e1aa 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -327,4 +327,25 @@ scenarios:
layer: scenario
backend: web
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_cloud_pairing_origin_reaches_effective_ui_listener
+ - id: AUTH-SETUP-119
+ name: Runtime manual provider code reaches native persistence and controller-confirmed readiness
+ status: covered
+ kind: happy_path
+ layer: scenario
+ backend: opencode
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_manual_provider_connection_reaches_controller_confirmed_readiness
+ - id: AUTH-SETUP-120
+ name: Explicit completion preserves canonical no-IM setup and invalid legacy IM recovery
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: web
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_setup_completion_preserves_canonical_and_legacy_platform_configuration
+ - id: AUTH-SETUP-121
+ name: Native and registered custom OpenCode models preserve Agent ownership and complete setup
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: opencode
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_explicit_opencode_model_recovery_preserves_agent_and_completes
next_priority: []
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 169eedf81..0242585bd 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -3495,3 +3495,268 @@ def test_instance_manager_backend_credentials_round_trip(monkeypatch, tmp_path,
readback = request("GET", "/api/backend/claude/auth")
assert readback.status_code == 200
assert "isolated-test-credential" not in json.dumps(readback.get_json())
+
+
+def test_manual_provider_connection_reaches_controller_confirmed_readiness(monkeypatch, tmp_path):
+ """AUTH-SETUP-119: runtime manual-code transport -> native store -> apply -> read."""
+ from core.backend_restart import BackendRestartCoordinator
+ from core.internal_server import create_app
+ from modules.agents.opencode.server import OpenCodeServerManager
+ from vibe import api, internal_client
+ from vibe.opencode_config import get_opencode_auth_path, upsert_opencode_provider_api_key
+ from tests.test_backend_restart import _AgentService, _controller
+
+ isolated = tmp_path / "测试 用户"
+ isolated.mkdir()
+ monkeypatch.setenv("HOME", str(isolated))
+ monkeypatch.setenv("AVIBE_HOME", str(isolated / "avibe"))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(isolated / "config"))
+ monkeypatch.setenv("XDG_DATA_HOME", str(isolated / "data"))
+ config = V2Config.default()
+ config.agents.opencode.enabled = True
+ config.save()
+ upsert_opencode_provider_api_key("test-provider", "old-test-key")
+ api.setup_opencode_permission()
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(isolated / "bin/opencode"))
+ monkeypatch.setattr(api, "_backend_apply_receipts", {})
+
+ async def scenario():
+ service = _AgentService()
+ service.agents = {"opencode": object()}
+ service.active = True
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ controller.backend_restart_coordinator = coordinator
+ internal_app = create_app(controller)
+ callbacks = []
+
+ async def callback(request):
+ body = await request.json()
+ callbacks.append(body)
+ assert body == {"deployment": "fixture", "method": 1, "code": "test-consent-code"}
+ auth_path = get_opencode_auth_path()
+ auth_path.parent.mkdir(parents=True, exist_ok=True)
+ auth_path.write_text(json.dumps({"test-provider": {"type": "oauth", "access": "test-access", "refresh": "test-refresh"}}))
+ return web.json_response({"ok": True})
+
+ upstream = web.Application()
+ upstream.router.add_post('/provider/test-provider/oauth/callback', callback)
+ server = web.AppRunner(upstream)
+ await server.setup()
+ site = web.TCPSite(server, "127.0.0.1", 0)
+ await site.start()
+ port = site._server.sockets[0].getsockname()[1]
+ transport = SimpleNamespace(base_url=f"http://127.0.0.1:{port}", ensure_running=AsyncMock())
+
+ class Provider:
+ async def get_provider_auth(self):
+ return {"test-provider": [{"type": "api"}, {"type": "oauth"}]}
+
+ async def start_provider_oauth(self, provider_id, **kwargs):
+ assert provider_id == "test-provider" and kwargs["method"] == 1
+ return {"method": "code", "url": "https://provider.invalid/authorize"}
+
+ async def wait_provider_oauth(self, provider_id, **kwargs):
+ return await OpenCodeServerManager.wait_provider_oauth(transport, provider_id, **kwargs)
+
+ harness = AuthSetupScenarioHarness()
+ auth = harness.service
+ monkeypatch.setattr(auth, "_opencode_server", AsyncMock(return_value=Provider()))
+ monkeypatch.setattr(auth, "_OPENCODE_OAUTH_PROMPT_ANSWERS", {"test-provider": {"deployment": "fixture", "method": 999, "code": "must-not-override"}})
+ # No-hook consumers retain the existing coordinator application owner.
+ monkeypatch.setattr(auth, "_refresh_backend_runtime", coordinator.request_restart)
+ monkeypatch.setattr(api, "load_config", V2Config.load)
+
+ async def projection(name):
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=internal_app), base_url="http://localhost") as client:
+ response = await client.get(f"/internal/backend-application/{name}")
+ return {"status_code": response.status_code, "body": response.json()}
+
+ monkeypatch.setattr(internal_client, "backend_application", projection)
+ runner = ScenarioRunner(harness)
+
+ async def start(h):
+ h.web_flow = await auth.start_web_setup("opencode", provider_id="test-provider", force_reset=False)
+ assert h.web_flow.callback_kind == "code"
+ assert h.web_flow.waiter_task is not None
+ assert not callbacks
+
+ async def submit(h):
+ result = await auth.submit_web_code(h.web_flow.flow_id, "test-consent-code")
+ assert result["ok"]
+ duplicate = await auth.submit_web_code(h.web_flow.flow_id, "test-consent-code")
+ assert not duplicate["ok"]
+ await h.web_flow.waiter_task
+ assert h.web_flow.state == "success"
+ state = await api.get_backend_connection("opencode")
+ assert state["auth"] == "subscription"
+ assert state["application"] == "draining" and not state["ready"]
+
+ async def apply(h):
+ service.active = False
+ await coordinator.wait("opencode")
+ assert (await api.get_backend_connection("opencode"))["ready"]
+ refresh.assert_awaited_once_with("opencode", False)
+ assert len(callbacks) == 1
+ assert await api._read_opencode_config_api_key("test-provider") is None
+
+ try:
+ await runner.run(ScenarioStep("start", start), ScenarioStep("submit", submit), ScenarioStep("apply", apply))
+ ScenarioExpect.step_history(runner, ["start", "submit", "apply"])
+ finally:
+ await server.cleanup()
+
+ asyncio.run(scenario())
+
+
+def test_setup_completion_preserves_canonical_and_legacy_platform_configuration(monkeypatch, tmp_path):
+ """AUTH-SETUP-120: no mandatory IM; saved invalid IM remains actionable."""
+ from config.v2_config import DiscordConfig
+ from tests.ui_server_test_helpers import csrf_headers
+ from vibe import internal_client
+ monkeypatch.setattr(internal_client, "reconcile_platforms", AsyncMock(return_value={
+ "status_code": 200, "body": {"ok": True},
+ }))
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "配置 空间"))
+ config = V2Config.default()
+ assert config.platforms.enabled == []
+ config.save()
+ client = app.test_client()
+ result = client.post('/api/config', json={"setup_completed": True}, headers=csrf_headers(client))
+ assert result.status_code == 200, result.get_json()
+ assert V2Config.load().setup_completed
+ assert V2Config.load().platforms.enabled == []
+
+ config = V2Config.load()
+ config.setup_completed = False
+ config.platforms.enabled = ["slack"]
+ config.slack.bot_token = ""
+ config.save()
+ result = client.post('/api/config', json={"setup_completed": True}, headers=csrf_headers(client))
+ assert result.status_code == 400
+ assert "slack" in json.dumps(result.get_json()).lower()
+ assert V2Config.load().platforms.enabled == ["slack"]
+ assert not V2Config.load().setup_completed
+
+ # The actual embedded form sends only changed credential leaves. Another
+ # actor's unrelated update between read and repair must survive.
+ config = V2Config.load()
+ config.runtime.default_cwd = str(tmp_path / "并发工作目录")
+ config.slack.app_token = "xapp-test-app-token"
+ config.save()
+ repair = client.post('/api/config', json={"slack": {"bot_token": "xoxb-test-bot-token"}}, headers=csrf_headers(client))
+ assert repair.status_code == 200, repair.get_json()
+ assert not V2Config.load().setup_completed
+ assert V2Config.load().runtime.default_cwd == str(tmp_path / "并发工作目录")
+ result = client.post('/api/config', json={"setup_completed": True}, headers=csrf_headers(client))
+ assert result.status_code == 200, result.get_json()
+ restored = V2Config.load()
+ assert restored.platforms.enabled == ["slack"]
+ assert restored.slack.bot_token == "xoxb-test-bot-token"
+
+ # Discord's same embedded form has an auxiliary guild-settings write. The
+ # credential patch cannot persist that selection by itself. Exercise the
+ # real settings owner before completion (Wizard consumer covers failure and
+ # retry of that second write with the mounted selected checkboxes).
+ config = V2Config.load()
+ config.setup_completed = False
+ config.platforms.enabled = ["discord"]
+ config.discord = DiscordConfig(bot_token="")
+ config.save()
+ settings = client.post('/api/settings', json={"platform": "discord", "guilds": {"old": {"enabled": True}}}, headers=csrf_headers(client))
+ assert settings.status_code == 200
+ repair = client.post('/api/config', json={"discord": {"bot_token": "fixture-discord-token"}}, headers=csrf_headers(client))
+ assert repair.status_code == 200, repair.get_json()
+ assert not V2Config.load().setup_completed
+ assert client.get('/api/settings?platform=discord').get_json()["guild_allowlist"] == ["old"]
+ for selected in ({"selected": {"enabled": True}}, {}):
+ saved = client.post('/api/settings', json={"platform": "discord", "guilds": selected}, headers=csrf_headers(client))
+ assert saved.status_code == 200, saved.get_json()
+ assert client.get('/api/settings?platform=discord').get_json()["guild_allowlist"] == list(selected)
+ assert V2Config.load().platforms.enabled == ["discord"]
+ assert V2Config.load().slack.bot_token == "xoxb-test-bot-token"
+ result = client.post('/api/config', json={"setup_completed": True}, headers=csrf_headers(client))
+ assert result.status_code == 200, result.get_json()
+
+
[email protected]("provider", ["anthropic", "poe"])
[email protected]("model_id", ["explicit-model", "family/custom-model"])
+def test_explicit_opencode_model_recovery_preserves_agent_and_completes(monkeypatch, tmp_path, provider, model_id):
+ """AUTH-SETUP-121: compatible model -> real Agent/default -> route -> completion."""
+ from core.vibe_agents import VibeAgentStore
+ from modules.agents.opencode.agent import resolve_opencode_model_dict
+ from vibe import api
+ from vibe.opencode_config import upsert_opencode_provider_api_key, upsert_opencode_provider_model
+
+ config = V2Config.default()
+ config.agents.opencode.enabled = True
+ config.agents.opencode.default_provider = provider
+ config.save()
+ upsert_opencode_provider_api_key(provider, "fixture-only-key")
+ if model_id == "family/custom-model":
+ # A user-managed model absent from the vendor catalog is a real route
+ # only when registered in the existing native provider config owner.
+ upsert_opencode_provider_model(provider, model_id)
+ api.setup_opencode_permission()
+ server = SimpleNamespace(
+ get_providers=AsyncMock(return_value={"all": [
+ {"id": provider, "name": provider}, {"id": "openai", "name": "OpenAI"},
+ ], "connected": [provider]}),
+ get_provider_auth=AsyncMock(return_value={provider: [{"type": "api"}]}),
+ get_native_available_models=AsyncMock(return_value={"providers": [
+ {"id": provider, "models": {"explicit-model": {}}},
+ ]}),
+ close_http_session=AsyncMock(),
+ )
+ monkeypatch.setattr(api, "_opencode_get_server", AsyncMock(return_value=server))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(tmp_path / "测试/bin/opencode"))
+ # Isolated application evidence, never the machine's running controller.
+ from vibe import internal_client
+ monkeypatch.setattr(internal_client, "backend_application", AsyncMock(return_value={
+ "status_code": 200, "body": {"ok": True, "state": "applied", "controller_pid": 123},
+ }))
+ monkeypatch.setattr(api, "_backend_apply_receipts", {})
+ client = app.test_client()
+ headers = csrf_headers(client)
+ rows = client.get('/api/agents').get_json()
+ agent = next(row for row in rows["agents"] if row["backend"] == "opencode")
+ assert agent["model"] == "openai/gpt-5.6-sol"
+ client.post('/api/agents/default', json={"name": agent["name"]}, headers=headers)
+ store = VibeAgentStore()
+ try:
+ before = store.require(agent["name"])
+ catalog = asyncio.run(api.get_opencode_providers_async())
+ assert catalog["ok"]
+ connected = {row["id"] for row in catalog["providers"] if row["active_auth_type"] in {"api", "oauth"}}
+ assert connected == {provider}
+ route = resolve_opencode_model_dict(before.model, provider)
+ assert route["providerID"] not in connected
+ assert not V2Config.load().setup_completed
+ # Opening, cancelling and a rejected edit do not alter the old row.
+ invalid = client.patch(f'/api/agents/{agent["name"]}', json={"backend": "claude"}, headers=headers)
+ assert invalid.status_code == 400
+ assert store.require(agent["name"]).model == before.model
+ selected = next(row for row in catalog["providers"] if row["id"] == provider)
+ assert model_id in selected["models"]
+ result = client.patch(f'/api/agents/{agent["name"]}', json={"model": f"{provider}/{model_id}"}, headers=headers)
+ assert result.status_code == 200, result.get_json()
+ persisted = store.require(agent["name"])
+ assert persisted.model == f"{provider}/{model_id}"
+ assert persisted.reasoning_effort == before.reasoning_effort
+ assert persisted.system_prompt == before.system_prompt
+ assert persisted.metadata == before.metadata
+ assert store.get_default_agent().name == before.name
+ route = resolve_opencode_model_dict(persisted.model, provider)
+ assert route == {"providerID": provider, "modelID": model_id}
+ assert route["modelID"] in selected["models"]
+ assert route["providerID"] in connected
+ assert asyncio.run(api.get_backend_connection('opencode'))["ready"]
+ completed = client.post('/api/config', json={"setup_completed": True}, headers=headers)
+ assert completed.status_code == 200, completed.get_json()
+ assert V2Config.load().setup_completed
+ assert V2Config.load().platforms.enabled == []
+ assert store.get_default_agent().name == before.name
+ finally:
+ store.close()
diff --git a/tests/test_api_runtime_refresh.py b/tests/test_api_runtime_refresh.py
index 8707c33c0..c3097b034 100644
--- a/tests/test_api_runtime_refresh.py
+++ b/tests/test_api_runtime_refresh.py
@@ -5,10 +5,11 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from vibe import api
+from vibe import api, runtime
def test_restart_backend_reports_claude_failure_when_controller_unacknowledged(monkeypatch) -> None:
+ monkeypatch.setattr(runtime, "service_process_running", lambda: True)
monkeypatch.setattr(api, "_request_controller_restart", lambda name, **kwargs: (False, None))
result = api.restart_backend("claude")
@@ -25,6 +26,7 @@ def test_restart_backend_passes_metadata_to_controller_marker(monkeypatch) -> No
captured["metadata"] = kwargs.get("metadata")
return True, None
+ monkeypatch.setattr(runtime, "service_process_running", lambda: True)
monkeypatch.setattr(api, "_request_controller_restart", fake_request)
result = api.restart_backend("codex", metadata={"reason": "manual_backend_restart"})
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index eb34fff4f..43c30cac6 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -1110,10 +1110,20 @@ def test_settings_platforms_apply_uses_parent_platform_identity():
def test_settings_platforms_persists_discord_guild_scope_before_auto_enable():
source = Path("ui/src/components/settings/SettingsPlatformsPage.tsx").read_text(encoding="utf-8")
- assert "const savePlatformSettings = async (platform: string, nextData: any)" in source
- assert "platform === 'discord'" in source
- assert "await api.saveSettings({" in source
- assert "await savePlatformSettings(platform, nextData);" in source
+ helper = Path("ui/src/components/settings/shared/savePlatformSettings.ts").read_text(encoding="utf-8")
+ assert "import { savePlatformSettings } from './shared/savePlatformSettings';" in source
+ # Follow the shared auxiliary save owner; the Wizard's Discord form consumer
+ # and AUTH-SETUP-120 exercise actual selection, failure/retry and persistence.
+ assert "canManageAccessMembers && platform === 'discord' && Array.isArray(guilds)" in helper
+ assert "guilds.length > 0 || data.discordGuildAllowlistTouched === true" in helper
+ assert "await api.saveSettings({" in helper
+ assert "}, 'discord');" in helper
+ apply_handler = source[source.index("const handleApplyPlatform = async"):]
+ auxiliary_save = apply_handler.index(
+ "await savePlatformSettings(api, platform, nextData, canManageAccessMembers);"
+ )
+ enable = apply_handler.index("updateEnabledPlatforms({ add: [platform] })")
+ assert auxiliary_save < enable
def test_platform_runnable_config_keeps_wechat_token_optional():
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
new file mode 100644
index 000000000..138ce8076
--- /dev/null
+++ b/tests/test_backend_connection.py
@@ -0,0 +1,326 @@
+"""Readiness observes persisted launch auth and the existing lifecycle owner."""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from config.v2_config import V2Config
+from vibe import api, internal_client, runtime, ui_server
+
+
+def connection(monkeypatch, tmp_path):
+ config = V2Config.default()
+ config.agents.claude.enabled = True
+ config.agents.codex.enabled = True
+ config.agents.opencode.enabled = True
+ 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"})
+ 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)
+
+
[email protected]("state,ready", [("applied", True), ("draining", False), ("failed", False), ("unavailable", False)])
+def test_application_is_consumed_instead_of_acceptance(connection, state, ready):
+ connection.probe.return_value["body"]["state"] = state
+ observed = asyncio.run(api.get_backend_connection("claude"))
+ assert observed["ready"] is ready
+ assert observed["entry_eligible"] is ready
+ assert observed["auth"] == "api_key"
+
+
+def test_stopped_entry_is_distinct_from_running_broken_ipc(connection, monkeypatch):
+ connection.probe.side_effect = internal_client.InternalServerUnavailable("missing IPC")
+ unknown = asyncio.run(api.get_backend_connection("claude"))
+ assert unknown["application"] == "unknown"
+ assert not unknown["ready"] and not unknown["entry_eligible"]
+ monkeypatch.setattr(runtime, "service_process_running", lambda: False)
+ stopped = asyncio.run(api.get_backend_connection("claude"))
+ assert stopped["application"] == "stopped"
+ assert stopped["entry_eligible"] and not stopped["ready"]
+
+
+def test_marker_failure_survives_new_reads_and_only_explicit_apply_retry_clears(connection, monkeypatch):
+ monkeypatch.setattr(api, "_request_controller_restart", lambda *args, **kwargs: (False, None))
+ assert not api.restart_backend("claude")["ok"]
+ for _ in range(3):
+ failed = asyncio.run(api.get_backend_connection("claude"))
+ assert failed["application"] == "failed" and not failed["ready"]
+ assert asyncio.run(api.get_backend_connection("codex"))["ready"]
+ monkeypatch.setattr(api, "_request_controller_restart", lambda *args, **kwargs: (True, None))
+ assert api.restart_backend("claude")["ok"]
+ assert asyncio.run(api.get_backend_connection("claude"))["ready"]
+
+
+def test_keychain_uncertainty_and_disabled_backend_are_not_ready(connection, monkeypatch):
+ monkeypatch.setattr(api, "get_codex_auth", lambda: {"ok": True, "active_auth_mode": "oauth", "auth_mode_uncertain": True})
+ assert asyncio.run(api.get_backend_connection("codex"))["auth"] == "unknown"
+ connection.config.agents.claude.enabled = False
+ assert not asyncio.run(api.get_backend_connection("claude"))["ready"]
+
+
+def test_opencode_permission_does_not_gate_another_backend_or_launch_daemon(connection, monkeypatch):
+ from vibe import opencode_config
+ monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(return_value={"provider"}))
+ monkeypatch.setattr(opencode_config, "read_opencode_provider_auth_entries", lambda **_: {})
+ monkeypatch.setattr(api, "opencode_permission_status", lambda: {"ok": True, "permission_allowed": False})
+ daemon = AsyncMock(side_effect=AssertionError("readiness must not launch a daemon"))
+ monkeypatch.setattr(api, "_opencode_get_server", daemon)
+ state = asyncio.run(api.get_backend_connection("opencode"))
+ assert state["auth"] == "api_key" and state["permission_required"] and not state["entry_eligible"]
+ assert asyncio.run(api.get_backend_connection("claude"))["ready"]
+ daemon.assert_not_called()
+
+
+def test_native_asgi_connection_route_auth_allowlist_and_body(connection):
+ client = ui_server.app.test_client()
+ response = client.get("/api/backend/claude/connection")
+ assert response.status_code == 200
+ assert response.get_json()["ready"] is True
+ assert response.headers["Cache-Control"] == "private, no-store"
+ assert client.get("/api/backend/other/connection").status_code == 400
+ remote = client.get("/api/backend/claude/connection", environ_base={"REMOTE_ADDR": "203.0.113.44"})
+ assert remote.status_code in {401, 403, 503}
+ assert not remote.get_json().get("ready")
+
+
+def test_only_confirmed_new_controller_clears_old_failed_delivery(connection, monkeypatch):
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_: 100)
+ api.record_backend_apply_receipt("claude", {"ok": False, "message": "marker not delivered"})
+ connection.probe.return_value["body"]["controller_pid"] = 100
+ assert not asyncio.run(api.get_backend_connection("claude"))["ready"]
+ connection.probe.return_value["body"]["controller_pid"] = 101
+ assert asyncio.run(api.get_backend_connection("claude"))["ready"]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("application", ["applied", "draining", "failed", "stopped"])
+def test_install_job_applies_persisted_path_before_admitting_connection(monkeypatch, tmp_path, backend, application):
+ """The real install-job result and readiness consume the same rolling apply."""
+ from core.backend_restart import BackendRestartCoordinator
+ from vibe import opencode_config
+
+ config = V2Config.default()
+ for name in ("claude", "codex", "opencode"):
+ getattr(config.agents, name).enabled = True
+ getattr(config.agents, backend).cli_path = "/old/missing-cli"
+ config.save()
+ installed_path = str(tmp_path / "安装 后端/bin" / backend)
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _: installed_path)
+ monkeypatch.setattr(api.subprocess, "Popen", lambda *a, **kw: SimpleNamespace(
+ 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 **_: {})
+ monkeypatch.setattr(api, "opencode_permission_status", lambda: {"ok": True, "permission_allowed": True})
+ monkeypatch.setattr(runtime, "service_process_running", lambda: application != "stopped")
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_: 123 if application != "stopped" else None)
+ monkeypatch.setattr(api, "_backend_apply_receipts", {})
+ monkeypatch.setattr(api, "_AGENT_INSTALL_JOBS", {})
+ monkeypatch.setattr(api, "_AGENT_INSTALL_LATEST_BY_BACKEND", {})
+
+ async def run():
+ service = SimpleNamespace(
+ agents={name: object() for name in ("claude", "codex", "opencode")},
+ active=application == "draining",
+ begin_backend_drain=Mock(), end_backend_drain=Mock(),
+ prepare_backend_restart=AsyncMock(),
+ )
+ service.runtime_turn_tokens_for_backend = lambda name: {"fixture": "turn"} if service.active and name == backend else {}
+ controller = SimpleNamespace(config=config, agent_service=service, session_turns=SimpleNamespace(
+ begin_backend_drain=Mock(), end_backend_drain=AsyncMock(),
+ ))
+ applied = []
+
+ async def refresh(name, _forced):
+ applied.append(name)
+ if application == "failed":
+ raise RuntimeError("fixture apply failed")
+ controller.config = V2Config.load()
+
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ loop = asyncio.get_running_loop()
+
+ def marker(name, **_kwargs):
+ assert getattr(V2Config.load().agents, name).cli_path == installed_path
+ try:
+ asyncio.run_coroutine_threadsafe(coordinator.request_restart(name), loop).result(2)
+ return True, None
+ except Exception as exc:
+ return True, str(exc)
+
+ async def projection(name):
+ if application == "stopped":
+ raise internal_client.InternalServerUnavailable("fixture stopped")
+ return {"status_code": 200, "body": {"ok": True, "controller_pid": 123, **coordinator.snapshot(name)}}
+
+ monkeypatch.setattr(api, "_request_controller_restart", marker)
+ monkeypatch.setattr(internal_client, "backend_application", projection)
+ started = api.start_agent_install_job(backend)
+ async def finished_job():
+ while (job := api.get_agent_install_job(started["job_id"]))["status"] == "running":
+ await asyncio.sleep(0.001)
+ return job
+ job = await asyncio.wait_for(finished_job(), 3)
+ assert job["path"] == installed_path
+ assert getattr(V2Config.load().agents, backend).cli_path == installed_path
+ state = await api.get_backend_connection(backend)
+ assert state["application"] == application, (job, state)
+ assert state["ready"] is (application == "applied")
+ assert state["entry_eligible"] is (application in {"applied", "stopped"})
+ assert job["ok"] is (application != "failed")
+ if application == "stopped":
+ assert job["restart"]["apply_on_next_start"] and not applied
+ elif application == "draining":
+ assert getattr(controller.config.agents, backend).cli_path == "/old/missing-cli"
+ service.active = False
+ await coordinator.wait(backend)
+ assert (await api.get_backend_connection(backend))["ready"]
+ assert getattr(controller.config.agents, backend).cli_path == installed_path
+ assert applied == [backend]
+ elif application == "applied":
+ assert getattr(controller.config.agents, backend).cli_path == installed_path
+ assert applied == [backend]
+ else:
+ assert getattr(controller.config.agents, backend).cli_path == "/old/missing-cli"
+ other = "codex" if backend != "codex" else "claude"
+ assert (await api.get_backend_connection(other))["ready"]
+
+ asyncio.run(run())
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatch, backend):
+ from config.v2_compat import to_app_config
+ from core.agent_auth_service import AgentAuthService
+ from core.backend_restart import BackendRestartCoordinator
+ from modules.agents.claude_agent import ClaudeAgent
+
+ config = V2Config.default()
+ for name in ("claude", "codex", "opencode"):
+ getattr(config.agents, name).enabled = name == backend
+ 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())
+ monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda *_: {"ok": True})
+ monkeypatch.setattr(api, "_refresh_opencode_provider_catalog_async", AsyncMock(return_value={"ok": True}))
+ monkeypatch.setattr(api, "_backend_apply_receipts", {})
+ monkeypatch.setattr(runtime, "service_process_running", lambda: True)
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_: 123)
+
+ async def run():
+ service = SimpleNamespace(
+ agents={}, active=False, begin_backend_drain=Mock(), end_backend_drain=Mock(),
+ prepare_backend_restart=AsyncMock(), runtime_turn_tokens_for_backend=lambda _: {},
+ )
+ controller = SimpleNamespace(config=to_app_config(config), agent_service=service,
+ session_turns=SimpleNamespace(begin_backend_drain=Mock(), end_backend_drain=AsyncMock()))
+ # Claude's loaded compat object remains registered even when disabled.
+ claude = SimpleNamespace(config=controller.config, controller=controller, refresh_auth_state=AsyncMock())
+ claude.refresh_runtime_config = lambda value: ClaudeAgent.refresh_runtime_config(claude, value)
+ service.agents["claude"] = claude
+ if backend != "claude":
+ service.agents[backend] = SimpleNamespace(shutdown_runtime=AsyncMock())
+ async def refresh(name, value):
+ if name == "claude":
+ await claude.refresh_runtime_config(value)
+ return True
+ return False
+ service.refresh_runtime_config = refresh
+ owner = AgentAuthService(controller)
+ coordinator = BackendRestartCoordinator(controller, owner._apply_backend_runtime_refresh)
+ async def projection(name):
+ return {"status_code": 200, "body": {"ok": True, **coordinator.snapshot(name)}}
+ monkeypatch.setattr(internal_client, "backend_application", projection)
+ # Persisted disable alone must not reinterpret an unexpectedly missing
+ # enabled registration as applied (a stale successful outcome cannot help).
+ if backend != "claude":
+ agent = service.agents.pop(backend)
+ assert coordinator.snapshot(backend)["state"] == "unavailable"
+ service.agents[backend] = agent
+ getattr(config.agents, backend).enabled = False
+ config.save()
+ await coordinator.request_restart(backend)
+ loop = asyncio.get_running_loop()
+ marker_calls = []
+ def marker(name, **_kwargs):
+ marker_calls.append(name)
+ asyncio.run_coroutine_threadsafe(coordinator.request_restart(name), loop).result(2)
+ return True, None
+ monkeypatch.setattr(api, "_request_controller_restart", marker)
+ payload = {"auth_mode": "api_key", "api_key": "fixture-saved-key"}
+ if backend == "opencode":
+ result = await asyncio.to_thread(lambda: asyncio.run(api.save_opencode_provider_auth_async("fixture", payload)))
+ assert await api._read_opencode_config_api_key("fixture") == "fixture-saved-key"
+ 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"
+ assert result["ok"] and result["restart"]["ok"]
+ assert marker_calls == [backend]
+ assert getattr(V2Config.load().agents, backend).enabled is False
+ for _ in range(2):
+ state = await api.get_backend_connection(backend)
+ assert state["application"] == "applied"
+ assert not state["enabled"] and not state["ready"] and not state["entry_eligible"]
+ # Startup from the same loaded disabled shape is also authoritative.
+ startup = BackendRestartCoordinator(controller, owner._apply_backend_runtime_refresh)
+ assert startup.snapshot(backend) == {"state": "applied", "disabled": True}
+ # A concurrent disk enable cannot borrow the disabled controller's
+ # applied state before that enablement is reconciled.
+ getattr(config.agents, backend).enabled = True
+ config.save()
+ stale = await api.get_backend_connection(backend)
+ assert stale["application"] == "unknown" and not stale["ready"] and not stale["entry_eligible"]
+ getattr(config.agents, backend).enabled = False
+ config.save()
+ # A failed subsequent prepare retains the failure even when disabled.
+ service.prepare_backend_restart.side_effect = RuntimeError("fixture failure")
+ with pytest.raises(RuntimeError, match="fixture failure"):
+ await coordinator.request_restart(backend)
+ assert (await api.get_backend_connection(backend))["application"] == "failed"
+ monkeypatch.setattr(internal_client, "backend_application", AsyncMock(side_effect=internal_client.InternalServerUnavailable()))
+ unknown = await api.get_backend_connection(backend)
+ assert unknown["application"] == "unknown" and not unknown["ready"]
+
+ asyncio.run(run())
+
+
[email protected]("contents,required", [
+ ('{ malformed', False), ('{}', True), ('{"permission":"ask"}', True),
+ ('{"permission":"deny"}', True), ('{"permission":"allow"}', False),
+ ('{"permission":{"*":"allow"}}', False),
+])
+def test_permission_read_policy_consumes_real_file_without_overwriting(connection, monkeypatch, contents, required):
+ from vibe.opencode_config import get_opencode_config_paths, get_opencode_auth_path
+
+ config_path = get_opencode_config_paths(api.Path.home())[0]
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(contents)
+ auth_path = get_opencode_auth_path()
+ auth_path.parent.mkdir(parents=True, exist_ok=True)
+ auth_path.write_text('{"fixture":{"type":"api","key":"fixture-only-key"}}')
+ monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(return_value=set()))
+ result = asyncio.run(api.get_backend_connection("opencode"))
+ assert result["permission_required"] is required
+ assert result["ready"] is (not required)
+ assert result["auth"] == "api_key"
+ if contents == '{ malformed':
+ assert api.setup_opencode_permission()["ok"] is False
+ assert config_path.read_text() == contents
+ connection.probe.return_value["body"]["state"] = "failed"
+ assert not asyncio.run(api.get_backend_connection("opencode"))["ready"]
+ connection.probe.return_value["body"]["state"] = "applied"
+ assert asyncio.run(api.get_backend_connection("claude"))["ready"]
diff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.py
index e830d569d..a87d82c6e 100644
--- a/tests/test_backend_restart.py
+++ b/tests/test_backend_restart.py
@@ -194,3 +194,80 @@ def test_controller_rejects_unknown_backend_reconcile() -> None:
asyncio.run(Controller.reconcile_agent_backends(controller, ["unknown"]))
controller.backend_restart_coordinator.request_restart.assert_not_awaited()
+
+
+def test_application_projection_tracks_prepare_drain_failure_retry_and_registration():
+ async def run():
+ service = _AgentService()
+ service.agents = {"opencode": object(), "claude": object()}
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ assert coordinator.snapshot("opencode") == {"state": "applied"}
+ assert coordinator.snapshot("codex") == {"state": "unavailable"}
+
+ preparing = asyncio.Event()
+ release = asyncio.Event()
+
+ async def prepare(_backend):
+ preparing.set()
+ await release.wait()
+
+ service.prepare_backend_restart = prepare
+ request = asyncio.create_task(coordinator.request_restart("opencode"))
+ await preparing.wait()
+ assert coordinator.snapshot("opencode") == {"state": "draining"}
+ assert coordinator.snapshot("claude") == {"state": "applied"}
+ service.active = True
+ release.set()
+ assert await request == "draining"
+ assert coordinator.snapshot("opencode") == {"state": "draining"}
+ refresh.side_effect = RuntimeError("application failed")
+ service.active = False
+ with pytest.raises(RuntimeError, match="application failed"):
+ await coordinator.wait("opencode")
+ assert coordinator.snapshot("opencode") == {"state": "failed", "error": "application failed"}
+ assert coordinator.snapshot("claude") == {"state": "applied"}
+
+ refresh.side_effect = None
+ assert await coordinator.request_restart("opencode") == "restarted"
+ assert coordinator.snapshot("opencode") == {"state": "applied"}
+ service.agents.pop("opencode")
+ assert coordinator.snapshot("opencode") == {"state": "unavailable"}
+
+ asyncio.run(run())
+
+
[email protected]("failure", [RuntimeError("prepare failed"), asyncio.CancelledError()])
+def test_application_projection_retains_prepare_failure_and_cancellation(failure):
+ async def run():
+ service = _AgentService()
+ service.agents = {"opencode": object()}
+ service.prepare_backend_restart = AsyncMock(side_effect=failure)
+ controller = _controller(service)
+ coordinator = BackendRestartCoordinator(controller, AsyncMock())
+ with pytest.raises(type(failure)):
+ await coordinator.request_restart("opencode")
+ assert coordinator.snapshot("opencode")["state"] == "failed"
+ assert not service.draining
+ controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=False)
+
+ asyncio.run(run())
+
+
+def test_cancelled_application_remains_failed_after_task_is_removed():
+ async def run():
+ service = _AgentService()
+ service.agents = {"opencode": object()}
+ service.active = True
+ coordinator = BackendRestartCoordinator(_controller(service), AsyncMock())
+ await coordinator.request_restart("opencode")
+ await asyncio.sleep(0)
+ task = coordinator._tasks["opencode"]
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert coordinator.snapshot("opencode") == {"state": "failed", "error": "cancelled"}
+ assert not service.draining
+
+ asyncio.run(run())
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index ba5536113..483bd0929 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -1208,3 +1208,38 @@ def test_show_access_apply_waits_for_a_definitive_controller_result(socket_path)
assert result["body"]["status"] == "no_change"
assert captured["timeout"].connect == 1.0
assert captured["timeout"].read is None
+
+
+def test_backend_application_uses_verified_socket_and_real_projection(socket_path):
+ from core.backend_restart import BackendRestartCoordinator
+ from core.internal_server import create_app
+ from tests.test_backend_restart import _AgentService, _controller
+ from unittest.mock import AsyncMock
+
+ service = _AgentService()
+ service.agents = {"claude": object()}
+ controller = _controller(service)
+ controller.backend_restart_coordinator = BackendRestartCoordinator(controller, AsyncMock())
+ app = create_app(controller)
+
+ async def run():
+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=httpx.ASGITransport(app=app)):
+ result = await internal_client.backend_application("claude", socket_path=socket_path)
+ assert result["status_code"] == 200
+ assert result["body"]["state"] == "applied"
+ assert result["body"]["controller_pid"] == os.getpid()
+ missing = await internal_client.backend_application("codex", socket_path=socket_path)
+ assert missing["body"]["state"] == "unavailable"
+ from config.v2_config import V2Config
+ from config.v2_compat import to_app_config
+
+ config = V2Config.default()
+ config.agents.codex.enabled = False
+ controller.config = to_app_config(config)
+ disabled = await internal_client.backend_application("codex", socket_path=socket_path)
+ assert disabled["body"]["state"] == "applied"
+ assert disabled["body"]["disabled"] is True
+ with pytest.raises(ValueError, match="unsupported_backend"):
+ await internal_client.backend_application("other", socket_path=socket_path)
+
+ asyncio.run(run())
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 185f70b81..e22f0e8ac 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -11,6 +11,7 @@ import contextlib
import json
import re
from pathlib import Path
+from unittest.mock import AsyncMock
import pytest
@@ -118,7 +119,11 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 291
+ assert len(endpoints) == 292
+ # Additive read-only backend projection inherits native backend-management
+ # authorization; it does not grant lower-tier credential-management access.
+ assert ("GET", "/api/backend/{name}/connection") in endpoints
+ assert http_authorization_policy("GET", "/api/backend/claude/connection").minimum_role == "member"
# Frozen from 1b191200c: independently protect all existing lower-tier grants.
baseline_read_roles = json.loads(
(Path(__file__).parent / "fixtures/member_management_existing_read_roles.json").read_text()
@@ -154,6 +159,30 @@ def test_complete_registered_api_management_inventory():
assert actual_read_roles == baseline_read_roles
[email protected]("role", ["owner", "member", "editor", "viewer", None])
+def test_backend_connection_native_route_preserves_management_roles(management_http, monkeypatch, role):
+ request = management_http(role or "viewer", authenticated=role is not None)
+ readiness = AsyncMock(return_value={"ok": True, "ready": True, "application": "applied"})
+ ipc = AsyncMock(side_effect=AssertionError("no live IPC"))
+ monkeypatch.setattr(api, "get_backend_connection", readiness)
+ monkeypatch.setattr(internal_client, "backend_application", ipc)
+ for name in ("claude", "codex", "opencode"):
+ response = request("GET", f"/api/backend/{name}/connection")
+ if role in {"owner", "member"}:
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json() == readiness.return_value
+ assert response.headers["Cache-Control"] == "private, no-store"
+ readiness.assert_awaited_with(name)
+ else:
+ assert response.status_code in {401, 403}, response.get_json()
+ readiness.assert_not_awaited()
+ previous_calls = readiness.await_count
+ unsupported = request("GET", "/api/backend/unknown/connection")
+ assert unsupported.status_code == (400 if role in {"owner", "member"} else 401 if role is None else 403)
+ assert readiness.await_count == previous_calls
+ ipc.assert_not_awaited()
+
+
@pytest.mark.parametrize("role", ["member", "owner"])
def test_manager_saves_config_credentials_and_reads_masked_result(management_http, role):
request = management_http(role)
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 879d17bc3..5f635cd54 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1694,6 +1694,8 @@ def test_normalize_backend_routing_payload_preserves_legacy_overrides_without_ba
def test_sync_start_oauth_web_keeps_background_tasks_on_persistent_loop(monkeypatch):
+ from core.agent_auth_service import WebAuthFlow
+
async def _start_web_setup(backend, *, force_reset=True, provider_id=None):
async def _mark_completed():
await asyncio.sleep(0.01)
@@ -1703,7 +1705,7 @@ def test_sync_start_oauth_web_keeps_background_tasks_on_persistent_loop(monkeypa
flow.waiter_task = task
return flow
- flow = SimpleNamespace(
+ flow = WebAuthFlow(
flow_id="flow-sync",
backend="codex",
state="awaiting_code",
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 12f5bb82e..a314b5d58 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -308,7 +308,7 @@ def test_post_web_success_hook_invocation_when_set(
monkeypatch.setattr(service, "_persist_backend_auth_mode", persist)
service._post_web_success_hook = hook
_run(service._invoke_post_web_success_hook("codex"))
- persist.assert_awaited_once_with("codex", "oauth")
+ persist.assert_awaited_once_with("codex", "oauth", strict=True)
assert calls == ["codex"]
@@ -438,19 +438,19 @@ def test_codex_oauth_after_official_key_transition_clears_stale_marker(
assert codex_cfg.oauth_relay_marker is None
-def test_post_web_success_hook_swallows_exceptions(
+def test_post_web_success_hook_propagates_apply_failure(
service: AgentAuthService,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """A misbehaving hook must not surface into the flow waiter."""
+ """The terminal flow must expose failure after credential persistence."""
def hook(_backend: str) -> None:
raise RuntimeError("boom")
monkeypatch.setattr(service, "_persist_backend_auth_mode", AsyncMock())
service._post_web_success_hook = hook
- # Should NOT raise.
- _run(service._invoke_post_web_success_hook("claude"))
+ with pytest.raises(RuntimeError, match="boom"):
+ _run(service._invoke_post_web_success_hook("claude"))
def test_claude_oauth_settings_cleanup_failure_fails_web_start(
@@ -1912,3 +1912,271 @@ def test_test_web_auth_api_key_mode_does_not_prompt_for_oauth_login(
assert result["ok"] is False
assert result["error"] == "invalid_credentials"
+
+
+def test_nonreset_claude_cancel_and_failed_start_restore_real_credential_files(service, monkeypatch, tmp_path):
+ """The existing attempt backup owns cancellation; no logout or second store."""
+ import core.agent_auth_service as auth_module
+ from config.v2_config import V2Config
+
+ home = tmp_path / "旧 用户/Claude 配置"
+ home.mkdir(parents=True)
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home))
+ monkeypatch.setattr(auth_module, "CLAUDE_SDK_AVAILABLE", True)
+ old = {"ANTHROPIC_API_KEY": "test-old-key", "ANTHROPIC_BASE_URL": "https://old.example"}
+ restore_claude_settings_env(old)
+ credentials = home / ".credentials.json"
+ credentials.write_text('{"claudeAiOauth":{"accessToken":"test-old-oauth"}}')
+ original = credentials.read_bytes()
+ V2Config.default().save()
+ logout = AsyncMock(side_effect=AssertionError("non-reset login must not log out"))
+ monkeypatch.setattr(service, "_run_utility_command", logout)
+ monkeypatch.setattr(service, "_create_claude_control_client", AsyncMock(return_value=SimpleNamespace()))
+ monkeypatch.setattr(service, "_disconnect_claude_client", AsyncMock())
+
+ async def run():
+ release = asyncio.Event()
+
+ async def request(_client, payload, **_kwargs):
+ if payload["subtype"] == "claude_authenticate":
+ return {"manualUrl": "https://claude.invalid/authorize"}
+ await release.wait()
+ return {}
+
+ monkeypatch.setattr(service, "_send_claude_control_request", request)
+ flow = await service.start_web_setup("claude", force_reset=False)
+ assert flow.state == "awaiting_code"
+ assert read_claude_settings_env() == {}
+ assert (await service.cancel_web_flow(flow.flow_id))["ok"]
+ assert read_claude_settings_env() == old
+ assert credentials.read_bytes() == original
+ assert read_claude_oauth_settings_backup() is None
+ monkeypatch.setattr(service, "_send_claude_control_request", AsyncMock(side_effect=RuntimeError("start failed")))
+ failed = await service.start_web_setup("claude", force_reset=False)
+ assert failed.state == "failed"
+ assert read_claude_settings_env() == old
+ assert credentials.read_bytes() == original
+ logout.assert_not_called()
+
+ asyncio.run(run())
+
+
+def test_claude_committed_credentials_survive_apply_failure_and_cancel(service, monkeypatch):
+ from config.v2_config import V2Config
+
+ V2Config.default().save()
+ old = {"ANTHROPIC_API_KEY": "old-test-key"}
+ restore_claude_settings_env(old)
+ monkeypatch.setattr(service, "_post_web_success_hook", lambda _backend: (_ for _ in ()).throw(RuntimeError("apply failed")))
+ refresh = AsyncMock()
+ monkeypatch.setattr(service, "_refresh_backend_runtime", refresh)
+
+ async def run():
+ attempt = await service._begin_claude_oauth_attempt()
+ 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 attempt.succeeded
+ assert V2Config.load().agents.claude.auth_mode == "oauth"
+ assert read_claude_settings_env() == {}
+ await service._terminate_web_flow(flow, final_state="cancelled")
+ assert read_claude_settings_env() == {}
+ assert read_claude_oauth_settings_backup() is None
+ refresh.assert_not_awaited()
+
+ asyncio.run(run())
+
+
+def test_cancel_waits_for_irreversible_commit_before_new_flow_can_start(service, monkeypatch):
+ from config.v2_config import V2Config
+
+ V2Config.default().save()
+ restore_claude_settings_env({"ANTHROPIC_API_KEY": "test-old"})
+
+ async def run():
+ committing = asyncio.Event()
+ release = asyncio.Event()
+ original = service._persist_backend_auth_mode
+
+ async def persist(*args, **kwargs):
+ committing.set()
+ await release.wait()
+ await original(*args, **kwargs)
+
+ monkeypatch.setattr(service, "_persist_backend_auth_mode", persist)
+ service._post_web_success_hook = lambda _: None
+ flow = WebAuthFlow(flow_id="pending-commit", backend="claude", claude_oauth_attempt=await service._begin_claude_oauth_attempt())
+ service._flow_registry.put(flow)
+ service._arm_flow_waiter(flow, service._commit_web_login(flow))
+ await committing.wait()
+ cancellation = asyncio.create_task(service.cancel_web_flow(flow.flow_id))
+ await asyncio.sleep(0)
+ assert not cancellation.done()
+ release.set()
+ assert (await cancellation)["ok"]
+ assert read_claude_settings_env() == {}
+ assert flow.claude_oauth_attempt.succeeded
+ assert flow.flow_id not in service._web_flows
+
+ asyncio.run(run())
+
+
[email protected]("terminal", ["cancel", "failure"])
+def test_manual_opencode_pending_callback_has_one_cancellable_owner(service, monkeypatch, terminal):
+ async def run():
+ pending = asyncio.Event()
+ provider = SimpleNamespace(
+ get_provider_auth=AsyncMock(return_value={"fixture": [{"type": "oauth"}]}),
+ start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
+ )
+
+ async def callback(*_args, **_kwargs):
+ pending.set()
+ if terminal == "failure":
+ raise RuntimeError("callback rejected")
+ await asyncio.Event().wait()
+
+ provider.wait_provider_oauth = callback
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ commit = AsyncMock()
+ monkeypatch.setattr(service, "_commit_web_login", commit)
+ flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ assert flow.waiter_task is not None
+ assert (await service.submit_web_code(flow.flow_id, "test-code"))["ok"]
+ await pending.wait()
+ if terminal == "cancel":
+ assert (await service.cancel_web_flow(flow.flow_id))["ok"]
+ assert flow.state == "cancelled"
+ assert not (await service.submit_web_code(flow.flow_id, "late-code"))["ok"]
+ else:
+ await flow.waiter_task
+ assert flow.state == "failed"
+ commit.assert_not_awaited()
+
+ asyncio.run(run())
+
+
+def test_manual_opencode_expires_without_browser_and_releases_provider_slot(service, monkeypatch):
+ """An abandoned manual-code tab must not retain the native-login admission."""
+ from vibe.opencode_config import get_opencode_auth_path
+
+ async def run():
+ service.setup_timeout_seconds = 0.02
+ auth_path = get_opencode_auth_path()
+ auth_path.parent.mkdir(parents=True, exist_ok=True)
+ previous = '{"fixture":{"type":"api","key":"old-test-key"}}'
+ auth_path.write_text(previous)
+ provider = SimpleNamespace(
+ get_provider_auth=AsyncMock(return_value={"fixture": [{"type": "oauth"}]}),
+ start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
+ wait_provider_oauth=AsyncMock(),
+ )
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ commit = AsyncMock()
+ monkeypatch.setattr(service, "_commit_web_login", commit)
+ flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ waiter = flow.waiter_task
+ # No status poll, submit or cancellation drives the timeout.
+ await asyncio.wait_for(asyncio.shield(waiter), 1)
+ assert flow.state == "failed" and flow.error == "timed_out"
+ assert not flow.awaiting_code
+ provider.wait_provider_oauth.assert_not_awaited()
+ commit.assert_not_awaited()
+ assert auth_path.read_text() == previous
+ assert not (await service.submit_web_code(flow.flow_id, "late-code"))["ok"]
+ reopened = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ assert reopened.flow_id != flow.flow_id and reopened.state == "awaiting_code"
+ await service.cancel_web_flow(flow.flow_id)
+ assert flow.state == "failed" and flow.error == "timed_out"
+ assert reopened.state == "awaiting_code"
+ await service.cancel_web_flow(reopened.flow_id)
+ assert reopened.state == "cancelled"
+ provider.wait_provider_oauth.assert_not_awaited()
+
+ asyncio.run(run())
+
+
+def test_manual_opencode_cancel_after_callback_completion_preserves_success(service, monkeypatch):
+ async def run():
+ provider = SimpleNamespace(
+ get_provider_auth=AsyncMock(return_value={"fixture": [{"type": "oauth"}]}),
+ start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
+ wait_provider_oauth=AsyncMock(),
+ )
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ commit = AsyncMock()
+ monkeypatch.setattr(service, "_commit_web_login", commit)
+ flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ assert (await service.submit_web_code(flow.flow_id, "fixture-code"))["ok"]
+ await flow.waiter_task
+ assert flow.state == "success"
+ await service.cancel_web_flow(flow.flow_id)
+ assert flow.state == "success"
+ commit.assert_awaited_once()
+ provider.wait_provider_oauth.assert_awaited_once()
+ assert flow.flow_id not in service._web_flows
+
+ asyncio.run(run())
+
+
+def test_manual_opencode_submission_does_not_extend_callback_deadline(service, monkeypatch):
+ async def run():
+ service.setup_timeout_seconds = 0.06
+ callback_started = asyncio.Event()
+
+ async def callback(*_args, **kwargs):
+ assert 0 < kwargs["timeout"] < service.setup_timeout_seconds
+ callback_started.set()
+ await asyncio.Event().wait()
+
+ provider = SimpleNamespace(
+ get_provider_auth=AsyncMock(return_value={"fixture": [{"type": "oauth"}]}),
+ start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
+ wait_provider_oauth=callback,
+ )
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ commit = AsyncMock()
+ monkeypatch.setattr(service, "_commit_web_login", commit)
+ flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ waiter, deadline = flow.waiter_task, flow.expires_at_iso
+ await asyncio.sleep(0.01)
+ assert (await service.submit_web_code(flow.flow_id, "fixture-code"))["ok"]
+ await asyncio.wait_for(callback_started.wait(), 1)
+ await asyncio.wait_for(asyncio.shield(waiter), 1)
+ assert flow.waiter_task is waiter and flow.expires_at_iso == deadline
+ assert flow.state == "failed" and flow.error == "timed_out"
+ commit.assert_not_awaited()
+ assert not (await service.submit_web_code(flow.flow_id, "late-code"))["ok"]
+ reopened = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ assert reopened.state == "awaiting_code"
+ await service.cancel_web_flow(reopened.flow_id)
+
+ asyncio.run(run())
+
+
+def test_manual_opencode_submit_keeps_start_waiter_and_cancel_before_dispatch_wins(service, monkeypatch):
+ async def run():
+ provider = SimpleNamespace(
+ get_provider_auth=AsyncMock(return_value={"fixture": [{"type": "oauth"}]}),
+ start_provider_oauth=AsyncMock(return_value={"method": "code", "url": "https://provider.invalid"}),
+ wait_provider_oauth=AsyncMock(),
+ )
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=provider))
+ commit = AsyncMock()
+ monkeypatch.setattr(service, "_commit_web_login", commit)
+ flow = await service.start_web_setup("opencode", provider_id="fixture", force_reset=False)
+ waiter, deadline = flow.waiter_task, flow.expires_at_iso
+ assert not (await service.submit_web_code(flow.flow_id, " "))["ok"]
+ assert (await service.submit_web_code(flow.flow_id, "fixture-code"))["ok"]
+ assert not (await service.submit_web_code(flow.flow_id, "duplicate"))["ok"]
+ assert flow.waiter_task is waiter and flow.expires_at_iso == deadline
+ # No yield between admission and cancellation: the queued waiter must
+ # not dispatch the callback afterward or mutate a reopened flow.
+ await service.cancel_web_flow(flow.flow_id)
+ assert flow.state == "cancelled"
+ assert waiter.done()
+ provider.wait_provider_oauth.assert_not_awaited()
+ commit.assert_not_awaited()
+ assert not (await service.submit_web_code(flow.flow_id, "stale"))["ok"]
+
+ asyncio.run(run())
diff --git a/tests/test_wechat_auth.py b/tests/test_wechat_auth.py
index 9e9cf41c6..a08606d1e 100644
--- a/tests/test_wechat_auth.py
+++ b/tests/test_wechat_auth.py
@@ -136,7 +136,13 @@ class WeChatAuthManagerTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("if (!autoStartLogin || !canManageAccessMembers) return;", source)
settings_source = Path("ui/src/components/settings/SettingsPlatformsPage.tsx").read_text(encoding="utf-8")
- self.assertIn("autoStartLogin={false}", settings_source)
+ self.assertIn("import { PlatformConfigEmbed } from './PlatformConfigEmbed'", settings_source)
+ self.assertIn("<PlatformConfigEmbed", settings_source)
+ embedded_source = Path("ui/src/components/settings/PlatformConfigEmbed.tsx").read_text(encoding="utf-8")
+ self.assertIn("<WeChatConfig", embedded_source)
+ self.assertIn("autoStartLogin={false}", embedded_source)
+ recovery_source = Path("ui/src/components/onboarding/SetupPlatformRecovery.tsx").read_text(encoding="utf-8")
+ self.assertIn("<PlatformConfigEmbed", recovery_source)
async def test_poll_status_refresh_preserves_local_token_list(self):
manager = WeChatAuthManager()
diff --git a/ui/e2e/badge-triggers/fixture.tsx b/ui/e2e/badge-triggers/fixture.tsx
index ce1ccf8aa..978c50ab0 100644
--- a/ui/e2e/badge-triggers/fixture.tsx
+++ b/ui/e2e/badge-triggers/fixture.tsx
@@ -21,7 +21,7 @@ export function Fixture() {
loaded: true, configError: false, enabled, cliPath,
cliStatus: state === 'error' ? 'missing' : state === 'loading' ? 'unknown' : 'ok',
detecting: false, installing: false, installResult: null, installOutputOpen: false,
- savingRuntime: false, runtimeDirty: false, setCliPath, setInstallOutputOpen: noop,
+ savingRuntime: false, runtimeDirty: false, connectionRevision: 0, setCliPath, setInstallOutputOpen: noop,
detect: asyncNoop, install: asyncNoop, onSaveRuntime: asyncNoop,
toggleEnabled: () => setEnabled((previous) => !previous), handleLifecycleChanged: asyncNoop,
};
diff --git a/ui/e2e/onboarding-fidelity/connections.spec.ts b/ui/e2e/onboarding-fidelity/connections.spec.ts
new file mode 100644
index 000000000..0f500ca98
--- /dev/null
+++ b/ui/e2e/onboarding-fidelity/connections.spec.ts
@@ -0,0 +1,265 @@
+import { writeFile } from 'node:fs/promises';
+import { expect, test, type Page } from '@playwright/test';
+import { openOnboarding, openSetup, serveProduct, settleEffects } from './support';
+
+async function authFixtures(page: Page) {
+ const cancellations: string[] = [];
+ await page.route('**/api/csrf-token', (route) => route.fulfill({ json: { csrf_token: 'fixture-token' } }));
+ await page.route('**/api/backend/*/auth', (route) => route.fulfill({ json: { ok: true, active_auth_mode: 'none', auth_mode: 'oauth', has_api_key: false, base_url: null } }));
+ await page.route('**/api/backend/opencode/providers', (route) => route.fulfill({ json: { ok: true, providers: [
+ { id: 'openai', name: 'OpenAI', description: 'ChatGPT subscription or API Key', oauth_available: true, configured: false, local: false, models: [] },
+ { id: 'github-copilot', name: 'GitHub Copilot', description: 'GitHub subscription', oauth_available: true, configured: false, local: false, models: [] },
+ { id: 'poe', name: 'Poe', description: 'Browser authorization', oauth_available: true, configured: false, local: false, models: [] },
+ ] } }));
+ await page.route('**/api/backend/*/auth/oauth/start', (route) => route.fulfill({ json: { ok: true, flow_id: 'fixture-flow', state: 'awaiting_code', url: 'https://auth.openai.com/codex/device', device_code: 'ABCD-1234' } }));
+ await page.route('**/api/backend/*/auth/oauth/status/*', (route) => route.fulfill({ json: { ok: true, flow_id: 'fixture-flow', state: 'awaiting_code', url: 'https://auth.openai.com/codex/device', device_code: 'ABCD-1234' } }));
+ await page.route('**/api/backend/*/auth/oauth/cancel', (route) => { cancellations.push(route.request().postData() || ''); return route.fulfill({ json: { ok: true } }); });
+ return cancellations;
+}
+
+for (const lang of ['en', 'zh']) for (const theme of ['dark', 'light']) {
+ test(`connection family ${lang} ${theme}: native desktop + narrow fields/device/focus`, async ({ page }, info) => {
+ const denied = await serveProduct(page);
+ const cancellations = await authFixtures(page);
+ await page.setViewportSize({ width: 1200, height: 800 });
+ await openOnboarding(page, { lang, theme });
+ await openSetup(page, lang);
+ const subscription = lang === 'zh' ? '添加订阅' : 'Add subscription';
+ const key = lang === 'zh' ? '添加 API Key' : 'Add API Key';
+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: subscription }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog.getByRole('button', { name: lang === 'zh' ? '使用 Claude 登录' : 'Sign in with Claude' })).toBeVisible();
+ await settleEffects(page);
+ const geometry = await dialog.evaluate((node) => { const rect = node.getBoundingClientRect(); const style = getComputedStyle(node); return { width: rect.width, padding: style.padding, gap: style.gap, radius: style.borderRadius }; });
+ expect(geometry).toEqual({ width: 568, padding: '24px', gap: '20px', radius: '16px' });
+ await settleEffects(page);
+ await dialog.screenshot({ path: info.outputPath(`claude-start-${lang}-${theme}-desktop.png`) });
+ await page.keyboard.press('Escape'); await expect(dialog).toHaveCount(0);
+
+ await page.setViewportSize({ width: 390, height: 640 });
+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: key }).click();
+ const save = dialog.getByRole('button', { name: lang === 'zh' ? '保存并连接' : 'Save and connect' });
+ await expect(save).toBeDisabled();
+ await save.scrollIntoViewIfNeeded(); await expect(save).toBeInViewport();
+ const overflow = await dialog.evaluate((node) => ({ width: node.getBoundingClientRect().width, extra: node.scrollWidth - node.clientWidth }));
+ expect(overflow.width).toBeLessThan(390); expect(overflow.extra).toBeLessThanOrEqual(1);
+ for (let index = 0; index < 12; index++) { await page.keyboard.press('Tab'); expect(await dialog.evaluate((node) => node.contains(document.activeElement))).toBe(true); }
+ await settleEffects(page);
+ await dialog.screenshot({ path: info.outputPath(`claude-key-${lang}-${theme}-narrow.png`) });
+ await page.keyboard.press('Escape'); await expect(dialog).toHaveCount(0);
+
+ await page.setViewportSize({ width: 1200, height: 800 });
+ await page.getByLabel('Codex', { exact: true }).getByRole('button', { name: subscription }).click();
+ await dialog.getByRole('button', { name: lang === 'zh' ? '使用 ChatGPT 登录' : 'Sign in with ChatGPT' }).click();
+ await expect(dialog.getByText('ABCD-1234')).toBeVisible();
+ await expect(dialog.getByRole('radio').first()).toBeDisabled();
+ await settleEffects(page);
+ await dialog.screenshot({ path: info.outputPath(`codex-device-${lang}-${theme}-desktop.png`) });
+ await page.keyboard.press('Escape'); await expect.poll(() => cancellations.length).toBe(1);
+
+ await page.setViewportSize({ width: 390, height: 640 });
+ await page.getByLabel('OpenCode', { exact: true }).getByRole('button', { name: key }).click();
+ await dialog.getByRole('button', { name: /OpenAI/ }).click();
+ await expect(dialog.getByLabel(lang === 'zh' ? 'Base URL(可选)' : 'Base URL (optional)')).toBeVisible();
+ await settleEffects(page);
+ await dialog.screenshot({ path: info.outputPath(`opencode-key-${lang}-${theme}-narrow.png`) });
+ await page.keyboard.press('Escape');
+ expect(denied).toEqual([]);
+ });
+}
+
+for (const lang of ['en', 'zh']) {
+ test(`corrected compact labels and Light action ${lang}`, async ({ page }, info) => {
+ const denied = await serveProduct(page); await authFixtures(page);
+ await page.setViewportSize({ width: 390, height: 640 });
+ await openOnboarding(page, { lang, theme: 'light' }); await openSetup(page, lang);
+ const addKey = lang === 'zh' ? '添加 API Key' : 'Add API Key';
+ await page.getByLabel('Claude Code', { exact: true }).getByRole('button', { name: addKey }).click();
+ const dialog = page.getByRole('dialog');
+ const credential = dialog.getByRole('radiogroup', { name: lang === 'zh' ? '凭据类型' : 'Credential type' });
+ await expect(credential.getByRole('radio', { name: 'API Key', exact: true })).toBeVisible();
+ await expect(credential.getByRole('radio', { name: 'Auth Token', exact: true })).toBeVisible();
+ const bounds = await credential.evaluate((node) => [...node.querySelectorAll('button')].map((button) => {
+ const range = document.createRange(); range.selectNodeContents(button);
+ const text = range.getBoundingClientRect(); const box = button.getBoundingClientRect();
+ return text.left >= box.left && text.right <= box.right && text.top >= box.top && text.bottom <= box.bottom;
+ }));
+ expect(bounds).toEqual([true, true]);
+ await page.keyboard.press('Tab');
+ await credential.getByRole('radio', { name: 'Auth Token' }).focus();
+ const focus = await credential.getByRole('radio', { name: 'Auth Token' }).evaluate((node) => {
+ const style = getComputedStyle(node); return { width: style.outlineWidth, style: style.outlineStyle, color: style.outlineColor };
+ });
+ expect(focus.width).toBe('2px'); expect(focus.style).toBe('solid');
+ const save = dialog.getByRole('button', { name: lang === 'zh' ? '保存并连接' : 'Save and connect' });
+ const disabled = await save.evaluate((node) => { const style = getComputedStyle(node); return { opacity: style.opacity, fill: style.backgroundColor, text: style.color }; });
+ expect(disabled.opacity).toBe('0.4'); expect(disabled.text).toBe('rgb(255, 255, 255)');
+ await settleEffects(page); await dialog.screenshot({ path: info.outputPath(`corrected-claude-key-${lang}-light-disabled.png`) });
+ await dialog.getByLabel('API Key', { exact: true }).fill('nonsecret-fixture-value');
+ await expect(save).toBeEnabled();
+ await settleEffects(page);
+ const enabled = await save.evaluate((node) => { const style = getComputedStyle(node); return { opacity: style.opacity, fill: style.backgroundColor, text: style.color }; });
+ expect(enabled).toEqual({ ...disabled, opacity: '1' });
+ await settleEffects(page); await dialog.screenshot({ path: info.outputPath(`corrected-claude-key-${lang}-light-enabled.png`) });
+ await page.keyboard.press('Escape');
+ await page.getByLabel('OpenCode', { exact: true }).getByRole('button', { name: addKey }).click();
+ await dialog.getByRole('button', { name: /OpenAI/ }).click();
+ await expect(dialog.getByLabel('API Key', { exact: true })).toBeVisible();
+ await expect(dialog.getByText(/ANTHROPIC_/)).toHaveCount(0);
+ await settleEffects(page); await dialog.screenshot({ path: info.outputPath(`corrected-opencode-key-${lang}-light-narrow.png`) });
+ await page.keyboard.press('Escape'); expect(denied).toEqual([]);
+ });
+}
+
+test('corrected locked Codex Light has one opacity layer and visible selected method', async ({ page }, info) => {
+ const denied = await serveProduct(page); await authFixtures(page);
+ await page.setViewportSize({ width: 1200, height: 800 });
+ await openOnboarding(page, { theme: 'light' }); await openSetup(page, 'en');
+ await page.getByLabel('Codex', { exact: true }).getByRole('button', { name: 'Add subscription' }).click();
+ const dialog = page.getByRole('dialog');
+ await dialog.getByRole('button', { name: 'Sign in with ChatGPT' }).click();
+ await expect(dialog.getByText('ABCD-1234')).toBeVisible();
+ const radio = dialog.getByRole('radio', { name: 'Sign in with ChatGPT' });
+ await expect(radio).toBeDisabled(); await expect(radio).toHaveAttribute('aria-checked', 'true');
+ const styles = await radio.evaluate((node) => {
+ const style = getComputedStyle(node); const parent = getComputedStyle(node.parentElement!);
+ return { opacity: style.opacity, parentOpacity: parent.opacity, color: style.color, fill: style.backgroundColor, border: style.borderColor };
+ });
+ expect(styles.opacity).toBe('1'); expect(styles.parentOpacity).toBe('0.6');
+ expect(styles.fill).not.toBe('rgba(0, 0, 0, 0)'); expect(styles.border).not.toBe('rgba(0, 0, 0, 0)');
+ await settleEffects(page); await dialog.screenshot({ path: info.outputPath('corrected-codex-locked-light.png') });
+ await page.keyboard.press('Escape'); expect(denied).toEqual([]);
+});
+
+for (const width of [1200, 390]) {
+ test(`OpenCode inline model recovery ${width}`, async ({ page }, info) => {
+ const denied = await serveProduct(page); await authFixtures(page);
+ let model = 'openai/gpt-5.6-sol'; let writes = 0;
+ const agent = () => ({ id: 'fixture-agent', name: 'opencode', display_name: 'OpenCode', backend: 'opencode', enabled: true, model, reasoning_effort: null, source: 'builtin', archived: false });
+ await page.route('**/api/backend/*/connection', (route) => { const backend = new URL(route.request().url()).pathname.split('/').at(-2); return route.fulfill({ json: { ok: true, backend, ready: backend === 'opencode', entry_eligible: backend === 'opencode', installed: true, enabled: true, auth: 'api_key', application: 'applied' } }); });
+ await page.route('**/api/agents', (route) => route.fulfill({ json: { ok: true, default_agent_name: 'opencode', agents: [agent()] } }));
+ await page.route('**/api/agents/opencode', (route) => { if (route.request().method() === 'PATCH') { model = route.request().postDataJSON().model; writes++; } return route.fulfill({ json: { ok: true, agent: agent() } }); });
+ await page.route('**/api/backend/opencode/providers', (route) => route.fulfill({ json: { ok: true, default_provider: 'openai', providers: [{ id: 'anthropic', name: 'Anthropic', description: '', local: false, oauth_available: false, active_auth_type: 'api', configured: true, models: ['chosen-model'] }] } }));
+ await page.route('**/api/models/agents/opencode/models', (route) => route.fulfill({ json: { ok: true, agent: { backend: 'opencode', mode: 'direct' } } }));
+ await page.route('**/api/opencode/options', (route) => route.fulfill({ json: { ok: true, data: { models: { providers: [{ id: 'anthropic', models: { 'chosen-model': {} } }] } } } }));
+ await page.setViewportSize({ width, height: 800 });
+ await openOnboarding(page); await openSetup(page, 'en');
+ await page.getByRole('button', { name: 'Enter workspace' }).click();
+ const recovery = page.getByRole('region', { name: 'Choose a model for this connection' });
+ await expect(recovery).toBeVisible(); expect(writes).toBe(0);
+ const picker = recovery.getByRole('combobox'); await expect(picker).toBeEnabled(); await picker.click();
+ await page.getByRole('option', { name: 'anthropic/chosen-model' }).click();
+ const apply = recovery.getByRole('button', { name: 'Apply model and enter' });
+ await apply.scrollIntoViewIfNeeded(); await expect(apply).toBeInViewport();
+ expect(await recovery.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);
+ await settleEffects(page); await recovery.screenshot({ path: info.outputPath(`model-recovery-${width}.png`) });
+ await recovery.getByRole('button', { name: 'Cancel' }).click(); expect(writes).toBe(0);
+ await expect(recovery).toHaveCount(0); expect(denied).toEqual([]);
+ });
+}
+
+test('saved Slack recovery narrow uses the existing form only after explicit repair', async ({ page }, info) => {
+ const denied = await serveProduct(page); await authFixtures(page);
+ let manifests = 0;
+ await page.route('**/api/config', (route) => route.fulfill({ json: { platforms: { enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token'] }], slack: { has_app_token: true, bot_token: '' }, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } } } }));
+ await page.route('**/api/backend/claude/connection', (route) => route.fulfill({ json: { ok: true, backend: 'claude', ready: true, entry_eligible: true, enabled: true, installed: true, application: 'applied', auth: 'api_key' } }));
+ await page.route('**/api/slack/manifest', (route) => { manifests++; return route.fulfill({ json: { ok: true, manifest: '{}' } }); });
+ await page.setViewportSize({ width: 390, height: 640 });
+ await openOnboarding(page); await openSetup(page, 'en');
+ await page.getByRole('button', { name: 'Enter workspace' }).click();
+ const recovery = page.getByRole('region', { name: 'Repair saved messaging configuration' });
+ await expect(recovery).toBeVisible(); expect(manifests).toBe(0);
+ await recovery.getByRole('button', { name: 'Repair saved messaging configuration' }).click();
+ await expect.poll(() => manifests).toBe(1);
+ await recovery.getByRole('button', { name: /Get Bot Token/ }).click();
+ await recovery.getByPlaceholder('xoxb-... (paste here)').fill('xoxb-fixture-only');
+ const apply = recovery.getByRole('button', { name: /Apply/ });
+ await expect(apply).toBeEnabled(); await apply.scrollIntoViewIfNeeded(); await expect(apply).toBeInViewport();
+ expect(await recovery.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);
+ await settleEffects(page); await recovery.screenshot({ path: info.outputPath('saved-slack-recovery-narrow.png') });
+ await recovery.getByRole('button', { name: 'Cancel' }).click();
+ expect(denied).toEqual([]);
+});
+
+for (const lang of ['en', 'zh']) {
+ test(`disabled Settings credentials stay saved without connection ${lang}`, async ({ page }, info) => {
+ const denied = await serveProduct(page);
+ let saves = 0;
+ let enabled = false;
+ await page.route('**/api/codex/models', (route) => route.fulfill({ json: { ok: true, models: [] } }));
+ await page.route('**/api/config', (route) => {
+ if (route.request().method() === 'POST') {
+ expect(route.request().postDataJSON()).toEqual({ agents: { codex: { enabled: true } } });
+ enabled = true;
+ }
+ return route.fulfill({ json: { agents: { codex: { enabled, cli_path: '/fixture/bin/codex' } }, platforms: { enabled: [] }, agent_backend_runtime: { hot_reconciled: true } } });
+ });
+ await page.route('**/api/csrf-token', (route) => route.fulfill({ json: { csrf_token: 'fixture-token' } }));
+ await page.route('**/api/backend/codex/auth', (route) => {
+ if (route.request().method() === 'POST') {
+ saves++;
+ return route.fulfill({ json: { ok: true, restart: { ok: true } } });
+ }
+ return route.fulfill({ json: { ok: true, active_auth_mode: 'api_key', auth_mode: 'api_key', has_api_key: true, api_key_masked: 'sk-••••test', base_url: 'https://fixture.invalid/v1', file_store_active: true } });
+ });
+ await page.route('**/api/backend/codex/connection', (route) => route.fulfill({ json: { ok: true, backend: 'codex', installed: true, enabled, auth: 'api_key', application: 'applied', ready: enabled, entry_eligible: enabled } }));
+ await page.setViewportSize({ width: 390, height: 640 });
+ await page.goto(`/e2e/onboarding-fidelity/fixture.html?surface=disabled-settings&lang=${lang}&theme=light`);
+ const saved = lang === 'zh' ? '凭据已保存。此助手当前未启用。' : 'Credentials saved. This assistant is currently disabled.';
+ await expect(page.getByText(saved)).toBeVisible();
+ await page.locator('.backend-connection-form').getByRole('button', { name: lang === 'zh' ? '保存' : 'Save', exact: true }).click();
+ await expect.poll(() => saves).toBe(1);
+ await expect(page.getByRole('alert')).toHaveCount(0);
+ await expect(page.getByText(lang === 'zh' ? '已连接' : 'Connected', { exact: true })).toHaveCount(0);
+ await page.reload(); await expect(page.getByText(saved)).toBeVisible();
+ const bounds = await page.getByText(saved).evaluate((node) => {
+ const range = document.createRange(); range.selectNodeContents(node);
+ const text = range.getBoundingClientRect(); const rect = node.getBoundingClientRect();
+ return text.left >= rect.left && text.right <= rect.right && text.bottom <= rect.bottom;
+ });
+ expect(bounds).toBe(true);
+ expect(await page.getByText(saved).evaluate((node) => node.classList.contains('text-muted'))).toBe(true);
+ await expect(page.getByRole('switch')).toHaveAttribute('aria-checked', 'false');
+ const save = page.locator('.backend-connection-form').getByRole('button', { name: lang === 'zh' ? '保存' : 'Save', exact: true });
+ const inspectActions = () => save.evaluate((button) => {
+ const ancestors = [];
+ for (let node: Element | null = button; node; node = node.parentElement) {
+ const style = getComputedStyle(node);
+ ancestors.push({ tag: node.tagName, class: node.className, rect: node.getBoundingClientRect().toJSON(), scrollTop: node.scrollTop, clientHeight: node.clientHeight, scrollHeight: node.scrollHeight, overflowY: style.overflowY, visibility: style.visibility, display: style.display, opacity: style.opacity });
+ }
+ const rect = button.getBoundingClientRect();
+ return { ancestors, hit: button.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2)) };
+ });
+ const before = await inspectActions();
+ await info.attach('pre-click-action-geometry', { body: JSON.stringify(before, null, 2), contentType: 'application/json' });
+ await save.click(); // real actionability and hit-target checks after reload
+ await expect.poll(() => saves).toBe(2);
+ await expect(page.getByText(saved)).toBeVisible();
+ await expect(save).toBeEnabled();
+ await page.getByLabel(lang === 'zh' ? 'Base URL(可选)' : 'Base URL (optional)').focus();
+ await page.keyboard.press('Tab'); // existing Remove key
+ await page.keyboard.press('Tab'); // Save
+ await expect(save).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect.poll(() => saves).toBe(3);
+ await expect(page.getByText(saved)).toBeVisible();
+ await save.scrollIntoViewIfNeeded();
+ await expect(save).toBeInViewport();
+ await expect(page.getByText(saved)).toBeInViewport();
+ const after = await inspectActions();
+ expect(after.hit).toBe(true);
+ const geometryPath = info.outputPath(`post-reload-action-geometry-${lang}.json`);
+ await writeFile(geometryPath, JSON.stringify({ before, after }, null, 2));
+ await info.attach('post-reload-action-geometry', { path: geometryPath, contentType: 'application/json' });
+ await page.screenshot({ path: info.outputPath(`post-reload-disabled-settings-${lang}-light-narrow.png`) });
+ const baseUrl = page.getByLabel(lang === 'zh' ? 'Base URL(可选)' : 'Base URL (optional)');
+ await baseUrl.fill('https://unsaved.invalid');
+ await page.getByRole('switch').click();
+ await expect(page.getByText(saved)).toHaveCount(0);
+ await expect(page.getByText(lang === 'zh' ? '已连接' : 'Connected', { exact: true })).toBeVisible();
+ await expect(baseUrl).toHaveValue('https://unsaved.invalid');
+ await expect(page.getByRole('alert')).toHaveCount(0);
+ expect(saves).toBe(3);
+ expect(denied).toEqual([]);
+ });
+}
diff --git a/ui/e2e/onboarding-fidelity/fixture.tsx b/ui/e2e/onboarding-fidelity/fixture.tsx
index ee169c8a5..0728455da 100644
--- a/ui/e2e/onboarding-fidelity/fixture.tsx
+++ b/ui/e2e/onboarding-fidelity/fixture.tsx
@@ -12,8 +12,15 @@ import '../../src/index.css';
import { ApiProvider } from '../../src/context/ApiContext';
import { ThemeProvider } from '../../src/context/ThemeProvider';
import { ToastProvider } from '../../src/context/ToastProvider';
+import { MemoryRouter } from 'react-router-dom';
+import { StatusProvider } from '../../src/context/StatusProvider';
+import { InstanceAuthorizationContext } from '../../src/context/InstanceAuthorizationContext';
+import { OWNER_INSTANCE_CAPABILITIES } from '../../src/lib/sessionInfo';
import { Wizard } from '../../src/components/Wizard';
+import { CodexProviderConfig } from '../../src/components/settings/providers/CodexProviderConfig';
+// Settings uses an internal scroll owner on mobile because global CSS locks the
+// document. The isolated provider fixture supplies that shell responsibility.
// The product's own ThemeProvider, reading the same `?theme=` it reads in the app:
// `dark` and `light` are explicit preferences, `system` follows the OS. Writing
// `data-theme` here instead would have been the fixture theming itself, which cannot
@@ -31,7 +38,9 @@ createRoot(document.getElementById('root')!).render(
<ThemeProvider>
<ToastProvider>
<ApiProvider>
- <Wizard />
+ <InstanceAuthorizationContext.Provider value={{ remote: false, instanceKind: null, instanceRole: 'owner', capabilities: OWNER_INSTANCE_CAPABILITIES }}><MemoryRouter><StatusProvider>{params.get('surface') === 'disabled-settings'
+ ? <main className="mx-auto h-dvh max-w-xl overflow-y-auto p-6"><CodexProviderConfig /></main>
+ : <Wizard />}</StatusProvider></MemoryRouter></InstanceAuthorizationContext.Provider>
</ApiProvider>
</ToastProvider>
</ThemeProvider>
diff --git a/ui/e2e/onboarding-fidelity/geometry.spec.ts b/ui/e2e/onboarding-fidelity/geometry.spec.ts
index 1ca914796..eb5a68597 100644
--- a/ui/e2e/onboarding-fidelity/geometry.spec.ts
+++ b/ui/e2e/onboarding-fidelity/geometry.spec.ts
@@ -30,8 +30,6 @@ const DESIGN_FRAME = { width: 1200, height: 756 };
*/
const CAPTURE_PHASE = 'codex-working';
const CAPTURE_STATES = ['complete', 'working', 'waiting'];
-/** 20px of shell padding plus the 45px language bar: the setup's authored top (IWQi6). */
-const SETUP_TOP = 65;
const box = async (page: Page, selector: string, index = 0) => {
const rect = await page.locator(selector).nth(index).boundingBox();
@@ -102,7 +100,7 @@ test.describe('desktop reference geometry', () => {
// The same type the design specifies: a 34/1.35 title, a 10 gap and a 14/1.57
// subtitle. The design reports 79 because it rounds each text box up on its own
// (46 + 10 + 23); the browser stacks the unrounded boxes to 77.9.
- expect(heading.height).toBeCloseTo(77.89, 1);
+ expect(heading.height).toBeCloseTo(78, 1);
const story = await box(page, '.onboarding-story');
const access = await box(page, '.onboarding-access');
@@ -116,48 +114,28 @@ test.describe('desktop reference geometry', () => {
expect(denied).toEqual([]);
});
- /**
- * The two steps are anchored differently because the design anchors them differently:
- * JuwcG and KIxnF centre the welcome inside their frame, IWQi6 tops the setup out at
- * its own 64.5 padding. So the welcome's y is a RESULT of the window height and the
- * setup's is a position — and a test that pinned the welcome to 65 was asserting the
- * one window height where those two happen to agree.
- */
- test('the welcome is centred by the window, and the setup is not', async ({ page }) => {
- await serveProduct(page);
- await openOnboarding(page);
- await freezeAt(page, PHASES['codex-working']);
-
- const centring = async () => {
- const content = await box(page, '.onboarding-shell-content');
- const welcome = await box(page, '.onboarding-welcome');
- return {
- above: welcome.y - content.y,
- below: (content.y + content.height) - (welcome.y + welcome.height),
- headingY: (await box(page, '.onboarding-heading')).y,
- };
- };
-
- await page.setViewportSize({ width: 1200, height: 1200 });
- const tall = await centring();
- expect(Math.abs(tall.above - tall.below)).toBeLessThanOrEqual(1);
- // Centred means it moved: a tall window puts the heading far below the setup's 65.
- expect(tall.headingY).toBeGreaterThan(SETUP_TOP + 100);
-
- // At the design's own content box the composition is taller than the window, so
- // there is no slack to share and the same rule lands it on the content edge — where
- // the frame draws it. The shell scrolls from there instead of clipping the top.
- await page.setViewportSize(DESIGN_FRAME);
- const short = await centring();
- expect(short.above).toBeLessThanOrEqual(1);
- expect(round(short.headingY)).toBe(SETUP_TOP);
-
- await openSetup(page, 'en');
- // The setup's top is the position itself, so it holds at both window heights.
- expect(round((await box(page, '.onboarding-heading')).y)).toBe(SETUP_TOP);
- await page.setViewportSize({ width: 1200, height: 1200 });
- expect(round((await box(page, '.onboarding-heading')).y)).toBe(SETUP_TOP);
- });
+ for (const lang of ['en', 'zh']) {
+ for (const viewport of [{ width: 1200, height: 800 }, { width: 1200, height: 1200 }, { width: 390, height: 844 }]) {
+ test(`Welcome → setup preserves title/subtitle anchors ${lang} ${size(viewport)}`, async ({ page }) => {
+ await page.setViewportSize(viewport);
+ const denied = await serveProduct(page);
+ await openOnboarding(page, { lang });
+ const title = await box(page, '.onboarding-heading h1');
+ const subtitle = await box(page, '.onboarding-heading p');
+ await expect(page.getByRole('img', { name: 'avibe', exact: true })).toBeVisible();
+ await openSetup(page, lang);
+ const nextTitle = await box(page, '.onboarding-heading h2');
+ const nextSubtitle = await box(page, '.onboarding-heading p');
+ expect(nextTitle.y).toBeCloseTo(title.y, 0);
+ expect(nextSubtitle.y).toBeCloseTo(subtitle.y, 0);
+ expect(nextTitle.height).toBeCloseTo(title.height, 0);
+ const action = page.locator('.onboarding-setup .onboarding-primary-action');
+ await action.scrollIntoViewIfNeeded();
+ await expect(action).toBeInViewport();
+ expect(denied).toEqual([]);
+ });
+ }
+ }
/**
* A short window used to buy about 30px by taking the step gaps from 24 to 16 and
diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.ts
index 0d3c45cf9..9e248f108 100644
--- a/ui/e2e/onboarding-fidelity/support.ts
+++ b/ui/e2e/onboarding-fidelity/support.ts
@@ -50,10 +50,12 @@ export async function serveProduct(page: Page) {
await page.route('**/*', async (route: Route) => {
const request = route.request();
const method = request.method();
- if (request.url().startsWith(ORIGIN) && (method === 'GET' || method === 'HEAD')) return route.fallback();
+ if (request.url().startsWith(ORIGIN) && (method === 'GET' || method === 'HEAD') && !new URL(request.url()).pathname.startsWith('/api/')) return route.fallback();
denied.push(`${method} ${request.url()}`);
return route.abort();
});
+ await page.route('**/status', (route) => route.fulfill({ json: { state: 'running' } }));
+ await page.route('**/api/backend/*/connection', (route) => route.fulfill({ json: { ok: true, backend: new URL(route.request().url()).pathname.split('/').at(-2), installed: true, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false } }));
await page.route('**/api/config', (route) => route.fulfill({ json: CONFIG }));
await page.route('**/api/platforms', (route) => route.fulfill({ json: CATALOG }));
await page.route('**/api/settings**', (route) => route.fulfill({ json: { channels: {} } }));
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 964246b50..f995b5bec 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -17,7 +17,7 @@
"react-hooks/set-state-in-effect": 1
},
"src/components/Wizard.tsx": {
- "@typescript-eslint/no-explicit-any": 8
+ "@typescript-eslint/no-explicit-any": 1
},
"src/components/settings/SettingsBackendsPage.tsx": {
"@typescript-eslint/no-explicit-any": 1
@@ -27,17 +27,11 @@
"react-hooks/set-state-in-effect": 1
},
"src/components/settings/SettingsPlatformsPage.tsx": {
- "@typescript-eslint/no-explicit-any": 9
+ "@typescript-eslint/no-explicit-any": 6
},
"src/components/settings/SettingsServicePage.tsx": {
"@typescript-eslint/no-explicit-any": 4
},
- "src/components/settings/providers/ClaudeProviderConfig.tsx": {
- "@typescript-eslint/no-explicit-any": 1
- },
- "src/components/settings/providers/CodexProviderConfig.tsx": {
- "@typescript-eslint/no-explicit-any": 1
- },
"src/components/settings/shared/useBackendRuntime.ts": {
"@typescript-eslint/no-explicit-any": 1
},
diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsx
index b5fbb4bee..ea791a6eb 100644
--- a/ui/src/components/Wizard.tsx
+++ b/ui/src/components/Wizard.tsx
@@ -1,303 +1,104 @@
-import React, { useEffect, useState } from 'react';
-import { motion, AnimatePresence, useReducedMotion } from 'framer-motion';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Welcome } from './steps/Welcome';
-import { PlatformSelection } from './steps/PlatformSelection';
import { AgentDetection } from './steps/AgentDetection';
-import { SlackConfig } from './steps/SlackConfig';
-import { DiscordConfig } from './steps/DiscordConfig';
-import { TelegramConfig } from './steps/TelegramConfig';
-import { LarkConfig } from './steps/LarkConfig';
-import { WeChatConfig } from './steps/WeChatConfig';
-import { ChannelList } from './steps/ChannelList';
-import { Summary } from './steps/Summary';
-import { useApi } from '../context/ApiContext';
-import clsx from 'clsx';
-import {
- getEnabledPlatforms,
- platformSupportsChannels,
-} from '../lib/platforms';
-import {
- buildWizardStepMutations,
- collectWizardEnabledPlatformDelta,
- type WizardEnabledPlatformDelta,
-} from '../lib/wizardConfigMutations';
-import { WizardChrome } from './visual';
+import { BrandLogo } from './visual';
import { LanguageSwitcher } from './LanguageSwitcher';
-
-export const Wizard: React.FC = () => {
- const { t } = useTranslation();
- const api = useApi();
- const reducedMotion = useReducedMotion();
- const [currentStep, setCurrentStep] = useState(0);
- const [data, setData] = useState<any>({
- show_duration: false,
- __wizardEnabledAdds: [],
- __wizardEnabledRemoves: [],
- });
- const [loaded, setLoaded] = useState(false);
-
- const steps = React.useMemo(() => {
- // ``platforms.enabled`` only ever contains real IM platforms — the
- // always-on workbench is stripped by PlatformsConfig.validate() before any
- // config reaches the UI — so these are the platforms that need credential +
- // channel steps. (The workbench has no credentials or channels to set up.)
- const enabledPlatforms = getEnabledPlatforms(data);
- const platformSteps = enabledPlatforms.map((platform) => {
- const component = platform === 'discord'
- ? DiscordConfig
- : platform === 'telegram'
- ? TelegramConfig
- : platform === 'lark'
- ? LarkConfig
- : platform === 'wechat'
- ? WeChatConfig
- : SlackConfig;
- return {
- id: `platform-${platform}`,
- title: platform,
- component,
- };
- });
-
- // Channel steps: merge into a single step with platform tabs (instead of one step per platform)
- const channelPlatforms = enabledPlatforms.filter((platform) => platformSupportsChannels(data, platform));
- const channelStep = channelPlatforms.length > 0
- ? [{ id: 'channels', title: t('nav.channels'), component: (props: any) => <ChannelList {...props} wizardPlatforms={channelPlatforms} /> }]
- : [];
-
- return [
- { id: 'welcome', title: 'Welcome', component: Welcome },
- // { id: 'mode', title: 'Mode', component: ModeSelection }, // temporarily hidden — SaaS mode not yet available
- { id: 'agents', title: 'Agents', component: AgentDetection },
- { id: 'platform', title: 'Platform', component: PlatformSelection },
- ...platformSteps,
- ...channelStep,
- { id: 'summary', title: 'Finish', component: Summary },
- ];
- }, [data, t]);
-
- useEffect(() => {
- const bootstrap = async () => {
- let platformCatalog: any[] = [];
- try {
- const catalog = await api.getPlatformCatalog();
- platformCatalog = catalog?.platforms || [];
- } catch {
- // Config payloads from newer backends also include the catalog.
+import { useApi, type VibeAgentBrief } from '../context/ApiContext';
+import { useStatus } from '../context/StatusContext';
+import { setConfigField } from '../lib/configMutations';
+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
+import { SetupPlatformRecovery, type SavedPlatformRecovery } from './onboarding/SetupPlatformRecovery';
+import { getEnabledPlatforms, getPlatformCatalog, platformHasRunnableConfig } from '../lib/platforms';
+import { SetupModelRecovery } from './onboarding/SetupModelRecovery';
+import { readOpencodeSetupRoutes } from './onboarding/opencodeSetupRoutes';
+import { ASSISTANT_ORDER } from './onboarding/collaborationTimeline';
+
+/** Owns explicit setup completion; credential and lifecycle writes stay with their owners. */
+export function Wizard() {
+ const api = useApi(); const { t } = useTranslation(); const navigate = useNavigate();
+ const { control } = useStatus();
+ const { capabilities } = useInstanceAuthorization();
+ const [platformRecovery, setPlatformRecovery] = useState<SavedPlatformRecovery | null>(null);
+ const [recovery, setRecovery] = useState<VibeAgentBrief | null>(null);
+ const [step, setStep] = useState<'welcome' | 'agents'>('welcome');
+ const [data, setData] = useState<Record<string, any> | null>(null);
+ const [error, setError] = useState('');
+ const completing = useRef(false);
+ const load = useCallback(async () => {
+ setError('');
+ try { setData(await api.getConfig()); }
+ catch (cause) { setError(String(cause)); }
+ }, [api]);
+ useEffect(() => { void load(); }, [load]);
+ const complete = async () => {
+ if (completing.current) return;
+ completing.current = true;
+ try {
+ const freshConfig = await api.getConfig();
+ const enabledPlatforms = getEnabledPlatforms(freshConfig);
+ const missing = getPlatformCatalog(freshConfig).find((platform) => enabledPlatforms.includes(platform.id) && !platformHasRunnableConfig(freshConfig, platform.id));
+ if (missing) {
+ setPlatformRecovery({ config: freshConfig, descriptor: missing });
+ return;
}
-
- try {
- const config = await api.getConfig();
- const configWithCatalog = {
- ...config,
- platform_catalog: config.platform_catalog || platformCatalog,
- };
- const enabledPlatforms = getEnabledPlatforms(configWithCatalog);
- const settingsEntries = await Promise.all(
- enabledPlatforms.map(async (platform) => [platform, await api.getSettings(platform)] as const)
- );
- const channelConfigsByPlatform = Object.fromEntries(
- settingsEntries.map(([platform, settings]) => [platform, settings.channels || {}])
- );
- const discordSettings = settingsEntries.find(([platform]) => platform === 'discord')?.[1];
- setData({
- ...configWithCatalog,
- discordGuildAllowlist: discordSettings?.guild_allowlist || [],
- channelConfigsByPlatform,
- // Baseline for deselection encoding: platforms enabled when
- // the wizard loaded. A user deselecting one of these must
- // produce a REMOVE operation on save — an add-only verb
- // would silently leave the adapter enabled and receiving
- // messages. Concurrent additions by other processes are NOT
- // in this baseline and are preserved.
- __wizardEnabledBaseline: enabledPlatforms,
- // Finish may reassert only list operations that this wizard has
- // actually submitted. These are intent records, not config fields.
- __wizardEnabledAdds: [],
- __wizardEnabledRemoves: [],
- agents: {
- opencode: config.agents?.opencode,
- claude: config.agents?.claude,
- codex: config.agents?.codex,
- },
- });
-
- } catch {
- setData((current: any) => ({
- ...current,
- platform_catalog: platformCatalog,
- }));
- } finally {
- setLoaded(true);
+ const readCandidates = async () => {
+ const results = await Promise.allSettled(ASSISTANT_ORDER.map((name) => api.getBackendConnection(name)));
+ return results.flatMap((result) => result.status === 'fulfilled' && result.value.ok ? [result.value] : []);
+ };
+ let connections = await readCandidates();
+ if (!connections.some((connection) => connection.entry_eligible)) throw new Error(t('onboarding.connection.entryFailed'));
+ if (!connections.some((connection) => connection.ready)) {
+ // Only confirmed stopped state allows this explicit start. Pending or
+ // unknown IPC never becomes a restart request from the browser.
+ if (!connections.some((connection) => connection.entry_eligible && connection.application === 'stopped')) throw new Error(t('onboarding.connection.applyPending'));
+ const started = await control('start');
+ if (started?.ok === false) throw new Error(started.message || t('onboarding.connection.entryFailed'));
+ connections = await readCandidates();
}
- };
- bootstrap();
- }, []);
-
- const next = async (stepData: any) => {
- const previousPlatforms = getEnabledPlatforms(data);
- const nextPlatforms = getEnabledPlatforms({ ...data, ...stepData });
- const platformsChanged = previousPlatforms.join(',') !== nextPlatforms.join(',');
-
- const nextData = {
- ...data,
- ...(platformsChanged ? { channelConfigsByPlatform: {} } : {}),
- // Keep a loaded WeChat value intact until the wizard-owned platform or
- // Finish mutation persists the required override. Normalizing it on
- // unrelated steps would erase the baseline and make Finish believe the
- // persisted value is already false.
- ...(nextPlatforms.includes('wechat') && !previousPlatforms.includes('wechat')
- ? { show_duration: false }
- : {}),
- ...stepData,
- };
- const submittedDelta = await persistStep(steps[currentStep].id, stepData, data, nextData);
- const previousAdds = Array.isArray(data.__wizardEnabledAdds)
- ? data.__wizardEnabledAdds.filter(
- (platform: unknown): platform is string => typeof platform === 'string',
- )
- : [];
- const previousRemoves = Array.isArray(data.__wizardEnabledRemoves)
- ? data.__wizardEnabledRemoves.filter(
- (platform: unknown): platform is string => typeof platform === 'string',
- )
- : [];
- const wizardAdds = new Set(previousAdds);
- const wizardRemoves = new Set(previousRemoves);
- for (const platform of submittedDelta.remove) {
- wizardAdds.delete(platform);
- wizardRemoves.add(platform);
- }
- for (const platform of submittedDelta.add) {
- wizardRemoves.delete(platform);
- wizardAdds.add(platform);
- }
- nextData.__wizardEnabledAdds = [...wizardAdds];
- nextData.__wizardEnabledRemoves = [...wizardRemoves];
- setData(nextData);
- if (currentStep < steps.length - 1) {
- setCurrentStep(currentStep + 1);
- }
- };
-
- const back = (stepData?: { agents: Record<string, unknown> }) => {
- if (stepData?.agents) setData((current: Record<string, unknown>) => ({ ...current, agents: stepData.agents }));
- if (currentStep > 0) {
- setCurrentStep(currentStep - 1);
- }
- };
-
- const persistStep = async (
- stepId: string,
- stepData: any,
- before: any,
- mergedData: any,
- ): Promise<WizardEnabledPlatformDelta> => {
- const mutations = buildWizardStepMutations({ stepId, before, stepData, after: mergedData });
- if (mutations.length > 0) await api.mutateConfig(mutations);
-
- const discordGuildAllowlist = stepData?.discordGuildAllowlist;
- if (
- Array.isArray(discordGuildAllowlist) &&
- (discordGuildAllowlist.length > 0 || stepData?.discordGuildAllowlistTouched === true)
- ) {
- await api.saveSettings({
- guilds: Object.fromEntries(
- discordGuildAllowlist.map((guildId: string) => [guildId, { enabled: true }])
- ),
- }, 'discord');
- }
- if (stepData?.channelConfigsByPlatform) {
- const platforms = Object.keys(stepData.channelConfigsByPlatform);
- for (const p of platforms) {
- const channelConfigs = stepData.channelConfigsByPlatform[p];
- if (channelConfigs && Object.keys(channelConfigs).length > 0) {
- await api.saveSettings({ channels: channelConfigs }, p);
+ const ready = new Set(connections.filter((connection) => connection.ready).map((connection) => connection.backend));
+ if (!ready.size) throw new Error(t('onboarding.connection.entryFailed'));
+ const agents = await api.listVibeAgents({ cache: false });
+ const candidates = agents.agents.filter((agent) => agent.enabled && !agent.archived && ready.has(agent.backend as typeof ASSISTANT_ORDER[number]));
+ if (!agents.ok || !candidates.length) throw new Error(t('onboarding.connection.entryFailed'));
+ let available = candidates.filter((agent) => agent.backend !== 'opencode');
+ const opencode = candidates.filter((agent) => agent.backend === 'opencode');
+ if (opencode.length) {
+ try {
+ const routes = await readOpencodeSetupRoutes(api);
+ available = [...available, ...opencode.filter((agent) => routes.accepts(agent.model))];
+ if (!available.length && routes.mode === 'direct' && capabilities.can_manage_agents) {
+ setPlatformRecovery(null);
+ setRecovery(opencode.find((agent) => agent.name === agents.default_agent_name) || opencode[0]);
+ return;
+ }
+ } catch (cause) {
+ // An unused OpenCode failure cannot block another usable backend.
+ if (!available.length) throw cause;
}
}
- }
- return collectWizardEnabledPlatformDelta(mutations);
+ if (!available.length) throw new Error(t('onboarding.connection.modelUnavailable'));
+ // Preserve a usable selected Agent. First setup may have auto-seeded a
+ // default for a missing backend; choose a real enabled Agent in that case.
+ if (!available.some((agent) => agent.name === agents.default_agent_name)) {
+ const selected = await api.setDefaultVibeAgent(available[0].name);
+ if (!selected.ok) throw new Error(t('onboarding.connection.entryFailed'));
+ }
+ // Persist completion last: failed start/readiness leaves AuthGuard's
+ // existing setup gate intact. The locked config API validates existing IM.
+ await api.mutateConfig([setConfigField(['setup_completed'], true)]);
+ navigate('/', { state: { onboardingCompleted: true } });
+ } finally { completing.current = false; }
};
-
- const CurrentComponent = steps[currentStep].component;
- const stepId = steps[currentStep].id;
- const wizardGlowClass =
- stepId === 'welcome' ? 'page-glow-wizard-welcome'
- : stepId === 'agents' ? 'page-glow-wizard-backends'
- : stepId === 'platform' ? 'page-glow-wizard-platforms'
- : stepId === 'platform-slack' ? 'page-glow-wizard-slack'
- : stepId === 'summary' ? 'page-glow-wizard-summary'
- : 'page-glow-wizard-platforms';
-
- if (!loaded) return <div className="min-h-screen flex items-center justify-center bg-background text-muted">{t('common.loading')}</div>;
-
- // Welcome step omits the segmented progress and the skip button (matches design.pen Kebr6).
- // Summary step keeps the rail but disables skip (already at the end).
- const isWelcome = stepId === 'welcome';
- const isSummary = stepId === 'summary';
- // Include welcome in the count so the counter ("Step X / N") matches the
- // step eyebrows (03 — PLATFORMS, etc.). The progress bar itself still
- // skips welcome via showProgress to keep the welcome screen clean.
- const progressTotal = steps.length;
- const progressIndex = steps.findIndex((step) => step.id === stepId);
-
- if (isWelcome || stepId === 'agents') {
- return (
- <div className="onboarding-shell">
- {/* The 2026-09-17 design drops the brand mark from the guidance screens
- ("这些引导页的logo都去掉"); the language switcher keeps the bar. */}
- <header>
- <LanguageSwitcher />
- </header>
- <main className="onboarding-shell-content">
- <CurrentComponent data={data} onNext={next} onBack={back} isFirst={currentStep === 0} isLast={currentStep === steps.length - 1} />
- </main>
- </div>
- );
- }
-
- return (
- <div
- className={clsx(
- // The mobile body is scroll-locked (index.css @media max-width:767px:
- // html/body overflow-hidden) for the iOS keyboard fix. The wizard
- // bypasses AppShell, so — like AppShell's <main> — it must be its own
- // internal scroll container on phones, or tall steps strand the footer
- // button below the fold. Desktop keeps normal document flow.
- 'h-[var(--app-shell-h)] overflow-y-auto px-5 py-7 text-foreground md:h-auto md:min-h-screen md:overflow-visible md:px-10 md:py-10',
- wizardGlowClass
- )}
- >
- <div className="mx-auto flex min-h-full max-w-[1280px] flex-col gap-8 md:min-h-[calc(100vh-4rem)]">
- <WizardChrome
- current={Math.max(0, progressIndex)}
- total={Math.max(progressTotal, 1)}
- showProgress={!isWelcome}
- onSkip={!isWelcome && !isSummary ? () => setCurrentStep(steps.length - 1) : undefined}
- />
-
- <div className="flex flex-1 flex-col items-center justify-start">
- <AnimatePresence mode="wait">
- <motion.div
- key={currentStep}
- initial={reducedMotion ? false : { opacity: 0, y: 12 }}
- animate={{ opacity: 1, y: 0 }}
- exit={reducedMotion ? undefined : { opacity: 0, y: -8 }}
- transition={{ duration: reducedMotion ? 0 : 0.18 }}
- className="w-full"
- >
- <CurrentComponent
- data={data}
- onNext={next}
- onBack={back}
- isFirst={currentStep === 0}
- isLast={currentStep === steps.length - 1}
- />
- </motion.div>
- </AnimatePresence>
- </div>
- </div>
- </div>
- );
-};
+ if (!data) return <div className="min-h-screen flex flex-col items-center justify-center bg-background text-muted">
+ {error ? <><p role="alert">{error}</p><button onClick={() => void load()}>{t('common.retry')}</button></> : t('common.loading')}
+ </div>;
+ return <div className="onboarding-shell">
+ <header><BrandLogo size={36} /><LanguageSwitcher /></header>
+ <main className="onboarding-shell-content">
+ {step === 'welcome' ? <Welcome data={data} onNext={(next) => { setData({ ...data, ...Object(next) }); setStep('agents'); window.scrollTo({ top: 0, behavior: 'instant' }); }} />
+ : <AgentDetection data={data} completionRecovery={platformRecovery ? <SetupPlatformRecovery key={platformRecovery.descriptor.id} saved={platformRecovery} onRepaired={complete} onCancel={() => setPlatformRecovery(null)} /> : recovery ? <SetupModelRecovery key={recovery.id} agent={recovery} onComplete={complete} onCancel={() => setRecovery(null)} /> : undefined} onNext={complete} onBack={(next) => { setData({ ...data, ...next }); setStep('welcome'); window.scrollTo({ top: 0, behavior: 'instant' }); }} />}
+ </main>
+ </div>;
+}
diff --git a/ui/src/components/onboarding/AssistantRow.tsx b/ui/src/components/onboarding/AssistantRow.tsx
index d3e36244d..3844a60c2 100644
--- a/ui/src/components/onboarding/AssistantRow.tsx
+++ b/ui/src/components/onboarding/AssistantRow.tsx
@@ -19,19 +19,23 @@ export interface AssistantRowProps {
onInstall: () => void;
onDetect: () => void;
onConfigure: () => void;
+ onAddKey?: () => void;
+ onRefreshConnection?: () => void;
+ connectionPending?: boolean;
+ connectionError?: string;
configuringDisabled?: boolean;
/** Presentation only. The connection owner must supply confirmed state. */
connection?: 'subscription' | 'api_key';
}
export function AssistantRow({ backend, status, installing, detecting, error, lifecycle, enabledControl,
- onInstall, onDetect, onConfigure, configuringDisabled = false, connection }: AssistantRowProps) {
+ onInstall, onDetect, onConfigure, configuringDisabled = false, connection, onAddKey, onRefreshConnection, connectionPending, connectionError }: AssistantRowProps) {
const { t } = useTranslation();
const label = getBackendUiMeta(backend).label;
return (
<Card className="onboarding-assistant" aria-label={label}>
<div className="onboarding-assistant-main">
- <div className="onboarding-assistant-logo"><BackendIcon backend={backend} variant="glyph" size={28} aria-hidden="true" /></div>
+ <div className="onboarding-assistant-logo"><BackendIcon backend={backend} variant="brand" brandFit="mark" size={28} aria-hidden="true" /></div>
<div className="onboarding-assistant-identity">
<h3>{label}</h3>
<p title={t(`onboarding.setup.${backend}Description`)}>{t(connection ? `onboarding.setup.${connection}` : `onboarding.setup.${backend}Description`)}</p>
@@ -55,11 +59,16 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
{status === 'unknown' && !detecting && <Button variant="secondary" size="sm" onClick={onDetect}><RefreshCw size={14} />{t('common.retry')}</Button>}
<Button variant="secondary" size="sm" className="h-[34px]" onClick={onConfigure} disabled={configuringDisabled || installing || detecting}>
{connection ? <Check size={14} className="text-mint-ink" /> : <Sliders size={14} />}
- {t(connection ? `onboarding.setup.${connection}Connected` : 'agentDetection.configureProvider')}
+ {t(connection ? `onboarding.setup.${connection}Connected` : 'onboarding.connection.addSubscription')}
</Button>
+ {!connection && onAddKey && <Button variant="secondary" size="sm" className="h-[34px]" onClick={onAddKey} disabled={configuringDisabled || installing || detecting}>{t('onboarding.connection.addKey')}</Button>}
{enabledControl}
</div>
</div>
+ {(connectionError || connectionPending) && <div className="onboarding-assistant-error" role={connectionError ? 'alert' : 'status'}>
+ {connectionPending ? t('common.loading') : connectionError}
+ {!connectionPending && onRefreshConnection && <Button variant="link" size="xs" onClick={onRefreshConnection}>{t('common.retry')}</Button>}
+ </div>}
{error && <div className="onboarding-assistant-error" role="alert">
<p>{error.message}</p>
{error.output && <details><summary>{t('onboarding.details')}</summary><pre>{error.output}</pre></details>}
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index 053a894f6..e7e7a6fe3 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -7,9 +7,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentDetection } from '../steps/AgentDetection';
import { AssistantRow } from './AssistantRow';
import en from '../../i18n/en.json';
+import type { BackendConnectionState } from '../../context/ApiContext';
const mock = vi.hoisted(() => ({ api: {
- detectCli: vi.fn(), installAgent: vi.fn(), getConfig: vi.fn(), getBackendRuntime: vi.fn(),
+ detectCli: vi.fn(), installAgent: vi.fn(), getConfig: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(), mutateConfig: vi.fn(), getClaudeAuth: vi.fn(), getCodexAuth: vi.fn(), getOpencodeProviders: vi.fn(),
} }));
vi.mock('../../context/ApiContext', () => ({ useApi: () => mock.api }));
vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
@@ -24,6 +25,11 @@ const row = (name: string) => within(screen.getByLabelText(name));
beforeEach(() => {
vi.resetAllMocks();
mock.api.getConfig.mockResolvedValue(data());
+ mock.api.mutateConfig.mockResolvedValue({});
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true }));
+ mock.api.getClaudeAuth.mockResolvedValue({ ok: true, active_auth_mode: 'none' });
+ mock.api.getCodexAuth.mockResolvedValue({ ok: true, active_auth_mode: 'none' });
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [] });
mock.api.detectCli.mockResolvedValue({ found: true, path: '/isolated/bin/assistant' });
mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: false });
});
@@ -51,13 +57,24 @@ describe('assistant installation presentation', () => {
expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/bin/claude');
expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();
});
+ it('a failed install settlement refreshes connection state without admitting stale readiness', async () => {
+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({ ok: true, backend, installed: false, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false }));
+ render(wrap(<AgentDetection data={data()} onNext={vi.fn()} />));
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(3));
+ mock.api.installAgent.mockResolvedValue({ ok: false, path: '/fixture/new-cli', message: 'fixture apply failed' });
+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({ ok: true, backend, installed: true, enabled: true, auth: 'api_key', application: 'failed', ready: false, entry_eligible: false }));
+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(4));
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ expect(mock.api.installAgent).toHaveBeenCalledOnce(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ });
it('keeps existing configure entry and does not claim connection from installation', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
expect(screen.queryByText('Subscription connected')).toBeNull();
expect(screen.queryByText('API Key connected')).toBeNull();
- fireEvent.click(row('Claude Code').getByRole('button', { name: en.agentDetection.configureProvider }));
- expect(await screen.findByText('Existing provider: claude')).toBeTruthy();
+ fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }));
+ expect(await screen.findByRole('dialog')).toBeTruthy();
});
it('an available update keeps Continue and configuration usable', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
@@ -65,9 +82,9 @@ describe('assistant installation presentation', () => {
const next = vi.fn();
render(wrap(<AgentDetection data={saved} onNext={next} />));
await screen.findByRole('button', { name: en.backendLifecycle.statusUpdateAvailable });
- expect(row('Claude Code').getByRole('button', { name: en.agentDetection.configureProvider }).hasAttribute('disabled')).toBe(false);
- fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
- expect(next).toHaveBeenCalledWith({ agents: saved.agents });
+ expect(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Enter workspace' }));
+ await waitFor(() => expect(next).toHaveBeenCalled());
expect(mock.api.installAgent).not.toHaveBeenCalled();
});
it('retains a detection error separately from missing installation', async () => {
@@ -90,59 +107,23 @@ describe('assistant installation presentation', () => {
codex: expect.objectContaining({ enabled: false }),
}) });
});
- it.each(['Back', 'Continue'])('serializes provider reconciliation and returns final live rows via %s', async (navigation) => {
+ it('reconciles saved non-ASCII CLI paths before navigation resumes', async () => {
let finishConfig!: (value: unknown) => void;
let finishDetection!: (value: unknown) => void;
mock.api.getConfig.mockImplementation(() => new Promise((resolve) => { finishConfig = resolve; }));
mock.api.detectCli.mockImplementation(() => new Promise((resolve) => { finishDetection = resolve; }));
+ const saved = data(); saved.agents.claude.status = 'ok';
const back = vi.fn();
- const next = vi.fn();
- render(wrap(<AgentDetection data={data()} onNext={next} onBack={back} />));
- const assertSyncGates = () => {
- for (const backend of ['Claude Code', 'Codex', 'OpenCode']) {
- const configure = row(backend).getByRole('button', { name: en.agentDetection.configureProvider });
- expect(configure.hasAttribute('disabled')).toBe(true);
- fireEvent.click(configure);
- expect(screen.queryByRole('dialog')).toBeNull();
- }
- for (const name of ['Back', 'Continue']) {
- const button = screen.getByRole('button', { name });
- expect(button.hasAttribute('disabled')).toBe(true);
- fireEvent.click(button);
- }
- expect(back).not.toHaveBeenCalled();
- expect(next).not.toHaveBeenCalled();
- };
- const finalAgents = { ...data().agents };
- for (const [index, [backend, label]] of [['claude', 'Claude Code'], ['codex', 'Codex']].entries()) {
- fireEvent.click(row(label).getByRole('button', { name: en.agentDetection.configureProvider }));
- expect(screen.getByText(`Existing provider: ${backend}`)).toBeTruthy();
- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
- assertSyncGates();
- expect(mock.api.getConfig).toHaveBeenCalledTimes(index + 1);
- expect(mock.api.detectCli).toHaveBeenCalledTimes(index);
- // Local enablement remains editable while persisted provider fields reload.
- fireEvent.click(row(label).getByRole('checkbox'));
- const savedPath = `/isolated/新的路径/${backend}`;
- const canonicalPath = `/isolated/真实路径/${backend}`;
- const provider = { default_provider: `provider-${backend}`, cli_path: savedPath, enabled: true };
- await act(async () => finishConfig({ agents: { [backend]: provider } }));
- expect(mock.api.detectCli).toHaveBeenLastCalledWith(savedPath);
- assertSyncGates();
- expect(mock.api.getConfig).toHaveBeenCalledTimes(index + 1);
- await act(async () => finishDetection({ found: true, path: canonicalPath }));
- expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(false);
- expect(screen.getByRole('button', { name: 'Continue' }).hasAttribute('disabled')).toBe(false);
- for (const name of ['Claude Code', 'Codex', 'OpenCode']) {
- expect(row(name).getByRole('button', { name: en.agentDetection.configureProvider }).hasAttribute('disabled')).toBe(false);
- }
- finalAgents[backend] = { ...provider, enabled: false, status: 'ok', cli_path: canonicalPath };
- // Consume after each cycle: a settled pre-detection snapshot must not be replayed.
- fireEvent.click(screen.getByRole('button', { name: navigation }));
- await waitFor(() => expect(navigation === 'Back' ? back : next).toHaveBeenCalledWith({ agents: finalAgents }));
- back.mockClear();
- next.mockClear();
- }
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} onBack={back} />));
+ fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected/ }));
+ fireEvent.keyDown(await screen.findByRole('dialog'), { key: 'Escape' });
+ expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(true);
+ await act(async () => finishConfig({ agents: { claude: { enabled: true, cli_path: '/isolated/新的路径/claude' } } }));
+ expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/新的路径/claude');
+ expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(true);
+ await act(async () => finishDetection({ found: true, path: '/isolated/真实路径/claude' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Back' }));
+ expect(back).toHaveBeenCalledWith({ agents: expect.objectContaining({ claude: expect.objectContaining({ cli_path: '/isolated/真实路径/claude', status: 'ok' }) }) });
});
it('clears only obsolete install failures after a successful external rescan', async () => {
mock.api.installAgent.mockImplementation((name) => Promise.resolve({ ok: false, message: `Failed ${name}`, output: `Details ${name}` }));
@@ -174,44 +155,30 @@ describe('assistant installation presentation', () => {
let finishInstall!: (value: unknown) => void;
mock.api.getConfig.mockImplementation(() => new Promise((resolve) => { finishConfig = resolve; }));
mock.api.installAgent.mockImplementation(() => new Promise((resolve) => { finishInstall = resolve; }));
- render(wrap(<AgentDetection data={data()} onNext={vi.fn()} />));
- fireEvent.click(row('Claude Code').getByRole('button', { name: en.agentDetection.configureProvider }));
+ const saved = data(); saved.agents.claude.status = 'ok';
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }));
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
fireEvent.click(row('Codex').getByRole('button', { name: 'Install' }));
expect(mock.api.installAgent).toHaveBeenCalledWith('codex');
await act(async () => finishInstall({ ok: true, path: '/isolated/bin/codex' }));
expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();
- expect(row('Codex').getByRole('button', { name: en.agentDetection.configureProvider }).hasAttribute('disabled')).toBe(true);
- expect(screen.getByRole('button', { name: 'Continue' }).hasAttribute('disabled')).toBe(true);
+ expect(row('Codex').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }).hasAttribute('disabled')).toBe(true);
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
await act(async () => finishConfig(data()));
- expect(screen.getByRole('button', { name: 'Continue' }).hasAttribute('disabled')).toBe(false);
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);
expect(row('Codex').getByRole('button', { name: 'Installed' })).toBeTruthy();
});
- it('ignores an obsolete successful probe when a newer provider-path probe reports missing', async () => {
- let finishConfig!: (value: unknown) => void;
- let finishOldProbe!: (value: unknown) => void;
- mock.api.installAgent.mockResolvedValue({ ok: false, message: 'Install failed', output: 'Failure details' });
- mock.api.getConfig.mockImplementation(() => new Promise((resolve) => { finishConfig = resolve; }));
- mock.api.detectCli.mockImplementation((path) => path === 'claude'
- ? new Promise((resolve) => { finishOldProbe = resolve; }) : Promise.resolve({ found: false }));
- const back = vi.fn();
- render(wrap(<AgentDetection data={data()} onNext={vi.fn()} onBack={back} />));
- fireEvent.click(row('Claude Code').getByRole('button', { name: 'Install' }));
- await screen.findByText('Install failed');
- fireEvent.click(row('Claude Code').getByRole('button', { name: en.agentDetection.configureProvider }));
- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
- fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
- expect(mock.api.detectCli).toHaveBeenCalledWith('claude');
- await act(async () => finishConfig({ agents: { claude: { cli_path: '/isolated/new/claude' } } }));
- expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/new/claude');
- await act(async () => finishOldProbe({ found: true, path: '/isolated/old/claude' }));
- expect(row('Claude Code').getByText('Install failed')).toBeTruthy();
- expect(row('Claude Code').getByText('Failure details')).toBeTruthy();
- expect(row('Claude Code').queryByRole('button', { name: 'Installed' })).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'Back' }));
- expect(back).toHaveBeenCalledWith({ agents: expect.objectContaining({ claude: expect.objectContaining({
- cli_path: '/isolated/new/claude', status: 'missing',
- }) }) });
+ it('does not enable entry from installed, draining, failed or unknown states', async () => {
+ for (const application of ['draining', 'failed', 'unknown']) {
+ mock.api.getBackendConnection.mockResolvedValue({ ok: true, auth: 'api_key', application, ready: false, entry_eligible: false });
+ const saved = data(); saved.agents.claude.status = 'ok';
+ const { unmount } = render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ await act(async () => {});
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ expect(screen.queryByText('API Key connected')).toBeNull();
+ unmount();
+ }
});
it('renders connected controls only from explicit presentation state', () => {
const configure = vi.fn();
@@ -225,3 +192,67 @@ describe('assistant installation presentation', () => {
expect(configure).toHaveBeenCalledOnce();
});
});
+
+const pending = <T,>() => { let resolve!: (value: T) => void; let reject!: (reason: Error) => void; const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; };
+const stateFor = (backend: string, enabled = true, application: BackendConnectionState['application'] = 'applied') => ({ ok: true, backend, enabled, installed: true, auth: 'api_key', application, ready: backend === 'claude' && enabled && application === 'applied', entry_eligible: backend === 'claude' && enabled && application === 'applied' });
+describe('settled wizard enablement follows persistence and latest intent', () => {
+ function mountReady() {
+ const saved = data(); saved.agents.claude.status = 'ok';
+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ return row('Claude Code').getByRole('checkbox') as HTMLInputElement;
+ }
+ it.each(['rejected', 'committed-failed', 'unreadable'] as const)('reconciles a single toggle (%s) and Retry repairs enabled without another write', async (outcome) => {
+ const checkbox = mountReady();
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false));
+ if (outcome === 'committed-failed') {
+ mock.api.mutateConfig.mockResolvedValue({ agents: { claude: { enabled: false } }, agent_backend_runtime: { hot_reconciled: false, restart_error: 'fixture apply failure' } });
+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name, false, 'failed'));
+ } else {
+ mock.api.mutateConfig.mockRejectedValue(new Error('fixture persist failure'));
+ if (outcome === 'unreadable') mock.api.getBackendConnection.mockRejectedValue(new Error('fixture read failure'));
+ }
+ fireEvent.click(checkbox);
+ await row('Claude Code').findByRole('alert');
+ expect(checkbox.checked).toBe(outcome === 'rejected');
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(checkbox.checked).toBe(true));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false));
+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
+ });
+ it('an older rejected off cannot replace queued on intent or accept a read started before the toggle', async () => {
+ const checkbox = mountReady(); await row('Claude Code').findByRole('button', { name: 'API Key connected' });
+ const oldRead = pending<ReturnType<typeof stateFor>>();
+ mock.api.getBackendConnection.mockImplementation((name) => name === 'claude' ? oldRead.promise : Promise.resolve(stateFor(name)));
+ fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
+ await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude'));
+ const off = pending<unknown>(); const on = pending<unknown>();
+ mock.api.mutateConfig.mockReturnValueOnce(off.promise).mockReturnValueOnce(on.promise);
+ fireEvent.click(checkbox); fireEvent.click(checkbox);
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
+ await act(async () => oldRead.resolve(stateFor('claude', false)));
+ expect(checkbox.checked).toBe(true);
+ await act(async () => off.reject(new Error('old off rejected')));
+ expect(checkbox.checked).toBe(true);
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
+ await act(async () => on.resolve({ agents: { claude: { enabled: true } } }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false));
+ expect(checkbox.checked).toBe(true); expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2);
+ });
+ it('delayed modal config cannot undo a newer authoritative enablement result', async () => {
+ const checkbox = mountReady(); await row('Claude Code').findByRole('button', { name: 'API Key connected' });
+ const config = pending<unknown>(); mock.api.getConfig.mockReturnValue(config.promise);
+ fireEvent.click(row('Claude Code').getByRole('button', { name: 'API Key connected' }));
+ fireEvent.keyDown(await screen.findByRole('dialog'), { key: 'Escape' });
+ mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name, false));
+ mock.api.mutateConfig.mockResolvedValue({ agents: { claude: { enabled: false } } });
+ fireEvent.click(checkbox);
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
+ await act(async () => config.resolve(data()));
+ expect(checkbox.checked).toBe(false);
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ });
+});
diff --git a/ui/src/components/onboarding/BackendConnection.test.tsx b/ui/src/components/onboarding/BackendConnection.test.tsx
new file mode 100644
index 000000000..38628f279
--- /dev/null
+++ b/ui/src/components/onboarding/BackendConnection.test.tsx
@@ -0,0 +1,541 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ClaudeProviderConfig } from '../settings/providers/ClaudeProviderConfig';
+import { OpencodeProviderConfig } from '../settings/providers/OpencodeProviderConfig';
+import { CodexProviderConfig } from '../settings/providers/CodexProviderConfig';
+import { BackendConnectionForm } from '../settings/providers/BackendConnectionForm';
+import { BackendConnectionDialog } from './BackendConnectionDialog';
+import en from '../../i18n/en.json';
+import type { BackendConnectionState, ClaudeAuthState, CodexAuthState } from '../../context/ApiContext';
+
+const mock = vi.hoisted(() => ({ toast: vi.fn(), api: {
+ getConfig: vi.fn(), detectCli: vi.fn(), mutateConfig: vi.fn(), getBackendRuntime: vi.fn(), restartBackend: vi.fn(), claudeModels: vi.fn(), codexModels: vi.fn(),
+ getClaudeAuth: vi.fn(), getCodexAuth: vi.fn(), getOpencodeProviders: vi.fn(),
+ setOpencodeProviderAuth: vi.fn(), getBackendConnection: vi.fn(), saveClaudeAuth: vi.fn(), saveCodexAuth: vi.fn(),
+ startOAuthWeb: vi.fn(), startOAuthWebForOpencodeProvider: vi.fn(),
+ getOAuthWebStatus: vi.fn(), submitOAuthWebCode: vi.fn(), cancelOAuthWeb: vi.fn(),
+ removeClaudeOAuthCredentials: vi.fn(), removeBackendAuth: vi.fn(), removeBackendApiKey: vi.fn(), deleteOpencodeProviderAuth: vi.fn(),
+} }));
+vi.mock('../../context/ApiContext', () => ({ useApi: () => mock.api }));
+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mock.toast }) }));
+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 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 }; };
+beforeEach(() => {
+ vi.resetAllMocks();
+ mock.api.getClaudeAuth.mockResolvedValue(native());
+ mock.api.getCodexAuth.mockResolvedValue(codexNative());
+ mock.api.getBackendConnection.mockImplementation(async (backend) => connection({ backend }));
+ mock.api.saveClaudeAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.cancelOAuthWeb.mockResolvedValue({ ok: true });
+ mock.api.getConfig.mockResolvedValue({ agents: { claude: { enabled: false, cli_path: 'claude' }, codex: { enabled: false, cli_path: 'codex' } } });
+ mock.api.detectCli.mockImplementation(async (binary) => ({ found: true, path: binary }));
+ mock.api.getBackendRuntime.mockImplementation(async (backend) => ({ ok: true, name: backend, enabled: true, installed: true, process_status: 'running' }));
+ mock.api.claudeModels.mockResolvedValue({ ok: true, models: [] });
+ mock.api.codexModels.mockResolvedValue({ ok: true, models: [] });
+});
+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.useRealTimers(); });
+
+describe('shared Settings and onboarding connection owner', () => {
+ it.each(['claude', 'codex', 'opencode'] as const)('saves disabled %s credentials and keeps saved-not-connected after reopen', async (backend) => {
+ const provider = { id: 'fixture', name: 'Fixture', description: '', configured: true, oauth_available: false, local: false, models: [], active_auth_type: 'api', api_key_masked: 'sk-•••old' };
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider] });
+ mock.api.saveCodexAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.setOpencodeProviderAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend, enabled: false, ready: false, entry_eligible: false }));
+ const refreshed = vi.fn();
+ const props = { backend, provider: backend === 'opencode' ? provider : undefined, initialMethod: 'api_key' as const, onConnected: refreshed };
+ const first = render(wrap(<BackendConnectionForm {...props} />));
+ await screen.findByText(en.onboarding.connection.savedDisabled);
+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));
+ await waitFor(() => expect(refreshed).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ first.unmount(); render(wrap(<BackendConnectionForm {...props} />));
+ await screen.findByText(en.onboarding.connection.savedDisabled);
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ expect(refreshed).toHaveBeenCalledOnce();
+ });
+ it.each(['unknown', 'failed', 'draining'] as const)('disabled backend does not mask %s application', async (application) => {
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', enabled: false, ready: false, entry_eligible: false, application }));
+ mock.api.saveCodexAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ const refreshed = vi.fn();
+ render(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" onConnected={refreshed} />));
+ fireEvent.click(await screen.findByRole('button', { name: en.common.save }));
+ await screen.findByRole('alert');
+ expect(screen.queryByText(en.onboarding.connection.savedDisabled)).toBeNull();
+ expect(refreshed).not.toHaveBeenCalled();
+ });
+ it('disabled backend preserves explicit failed receipt and uncertain auth', async () => {
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ auth_mode_uncertain: true }));
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', enabled: false, auth: 'unknown', ready: false, entry_eligible: false }));
+ mock.api.saveCodexAuth.mockResolvedValue({ ok: true, restart: { ok: false, message: 'apply failed' } });
+ const refreshed = vi.fn();
+ render(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" onConnected={refreshed} />));
+ fireEvent.click(await screen.findByRole('button', { name: en.common.save }));
+ await screen.findByText(/apply failed/);
+ expect(screen.queryByText(en.onboarding.connection.savedDisabled)).toBeNull();
+ expect(refreshed).not.toHaveBeenCalled();
+ });
+ for (const backend of ['claude', 'codex'] as const) {
+ it.each(['applied', 'draining', 'failed', 'unreadable'] as const)(`${backend} Settings refreshes after toggle settlement (%s), preserving unsaved drafts`, async (outcome) => {
+ const mutation = deferred<{ agent_backend_runtime: { hot_reconciled: boolean; restart_error?: string } }>();
+ mock.api.mutateConfig.mockReturnValue(mutation.promise);
+ mock.api.saveCodexAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend, enabled: false, ready: false, entry_eligible: false }));
+ render(wrap(backend === 'claude' ? <ClaudeProviderConfig /> : <CodexProviderConfig />));
+ await screen.findByText(en.onboarding.connection.savedDisabled);
+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(2));
+ await screen.findByText(en.onboarding.connection.savedDisabled);
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Replace' }));
+ const keyInput = document.getElementById(`${backend}-connection-key`) as HTMLInputElement;
+ fireEvent.change(keyInput, { target: { value: 'unsaved-fixture-key' } });
+ fireEvent.change(screen.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://unsaved.invalid' } });
+ const toggle = screen.getByRole('switch');
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ fireEvent.click(toggle);
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledWith([{ kind: 'set', path: ['agents', backend, 'enabled'], value: true }]));
+ expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(2); // optimistic enabled is not settlement
+ if (outcome === 'unreadable') mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC unavailable'));
+ else mock.api.getBackendConnection.mockResolvedValue(connection({ backend, application: outcome, ready: outcome === 'applied', entry_eligible: outcome === 'applied', message: outcome === 'failed' ? 'fixture apply failed' : undefined }));
+ 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(); }
+ 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');
+ });
+ }
+ const providerFixture = () => ({ id: 'fixture', name: 'Fixture', description: '', configured: true, oauth_available: false, local: false, models: ['model'], active_auth_type: 'api', api_key_masked: 'sk-•••old' });
+ for (const backend of ['claude', 'codex', 'opencode'] as const) {
+ it.each(['failed', 'unreadable'] as const)(`${backend} committed removal publishes auth despite %s application; Retry does not mutate`, async (outcome) => {
+ vi.spyOn(window, 'confirm').mockReturnValue(true);
+ const provider = providerFixture();
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider] });
+ render(wrap(<BackendConnectionForm backend={backend} provider={backend === 'opencode' ? provider : undefined} initialMethod="api_key" />));
+ await screen.findByText('sk-•••old');
+ const removedNative = { ...native(), active_auth_mode: 'oauth', has_api_key: false, api_key_masked: null, base_url: null };
+ mock.api.getClaudeAuth.mockResolvedValue(removedNative); mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'oauth', has_api_key: false, api_key_masked: null, base_url: null }));
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [{ ...provider, configured: false, active_auth_type: null, api_key_masked: null }] });
+ mock.api.removeBackendApiKey.mockResolvedValue({ ok: true, restart: { ok: false, message: 'fixture refresh failed' } });
+ mock.api.deleteOpencodeProviderAuth.mockResolvedValue({ ok: true, restart: { ok: false, message: 'fixture refresh failed' } });
+ if (outcome === 'unreadable') mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC unreadable'));
+ else mock.api.getBackendConnection.mockResolvedValue(connection({ backend, application: 'failed', ready: false, entry_eligible: false }));
+ fireEvent.click(screen.getByRole('button', { name: en.settings.backends.claudeApiKeyRemove }));
+ await waitFor(() => expect(screen.queryByText('sk-•••old')).toBeNull());
+ expect(screen.queryByRole('button', { name: en.settings.backends.claudeApiKeyRemove })).toBeNull();
+ expect((await screen.findByRole('alert')).textContent).toContain('fixture refresh failed');
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend, auth: backend === 'opencode' ? 'none' : 'subscription', ready: backend !== 'opencode', entry_eligible: backend !== 'opencode' }));
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.refresh }));
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ expect(backend === 'opencode' ? mock.api.deleteOpencodeProviderAuth : mock.api.removeBackendApiKey).toHaveBeenCalledOnce();
+ expect(mock.api.saveClaudeAuth).not.toHaveBeenCalled(); expect(mock.api.saveCodexAuth).not.toHaveBeenCalled(); expect(mock.api.setOpencodeProviderAuth).not.toHaveBeenCalled();
+ });
+ it(`${backend} committed save publishes new mask while preserving replacement draft on failed apply`, async () => {
+ const provider = providerFixture();
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider] });
+ const done = vi.fn();
+ render(wrap(<BackendConnectionForm backend={backend} provider={backend === 'opencode' ? provider : undefined} compact initialMethod="api_key" onConnected={done} />));
+ fireEvent.click(await screen.findByRole('button', { name: 'Replace' }));
+ const input = document.getElementById(`${backend}-connection-key`) as HTMLInputElement;
+ fireEvent.change(input, { target: { value: 'fixture-new-key' } });
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), api_key_masked: 'new-mask' });
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ api_key_masked: 'new-mask' }));
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [{ ...provider, api_key_masked: 'new-mask' }] });
+ for (const save of [mock.api.saveClaudeAuth, mock.api.saveCodexAuth, mock.api.setOpencodeProviderAuth]) save.mockResolvedValue({ ok: true, restart: { ok: false, message: 'fixture apply receipt' } });
+ mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC'));
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));
+ expect((await screen.findByRole('alert')).textContent).toContain('fixture apply receipt');
+ expect(input.value).toBe('fixture-new-key'); expect(done).not.toHaveBeenCalled();
+ fireEvent.click(screen.getAllByRole('button', { name: 'Cancel' })[0]);
+ await screen.findByText('new-mask');
+ expect(screen.queryByText('sk-•••old')).toBeNull();
+ });
+ }
+ it('an unreadable post-removal native store is unknown rather than the old confirmed mask', async () => {
+ vi.spyOn(window, 'confirm').mockReturnValue(true);
+ render(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" />)); await screen.findByText('sk-•••old');
+ mock.api.removeBackendApiKey.mockResolvedValue({ ok: true, restart: { ok: false, message: 'apply failed' } });
+ mock.api.getCodexAuth.mockRejectedValue(new Error('native read unavailable'));
+ fireEvent.click(screen.getByRole('button', { name: en.settings.backends.claudeApiKeyRemove }));
+ expect((await screen.findByRole('alert')).textContent).toContain('native read unavailable');
+ expect(screen.queryByText('sk-•••old')).toBeNull(); expect(screen.queryByRole('button', { name: en.settings.backends.claudeApiKeyRemove })).toBeNull();
+ 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.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 });
+ 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());
+ 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);
+ });
+ it.each(['applied', 'draining', 'failed', 'unreadable'] as const)('expanded OpenCode parent consumes runtime CLI settlement (%s)', async (outcome) => {
+ mock.api.getConfig.mockResolvedValue({ agents: { opencode: { enabled: true, cli_path: 'opencode' } } });
+ const provider = providerFixture();
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider], permission_allowed: true });
+ render(wrap(<OpencodeProviderConfig />));
+ fireEvent.click(await screen.findByText('Fixture', { exact: true }));
+ await screen.findByText(en.onboarding.connection.connected);
+ const form = within(document.querySelector('.backend-connection-form') as HTMLElement);
+ fireEvent.change(form.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://draft.invalid' } });
+ fireEvent.change(screen.getByLabelText(en.agentDetection.cliPath), { target: { value: '/fixture/new-opencode' } });
+ if (outcome === 'unreadable') mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC'));
+ else mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', application: outcome, ready: outcome === 'applied', entry_eligible: outcome === 'applied' }));
+ mock.api.mutateConfig.mockResolvedValue({ agents: { opencode: { enabled: true, cli_path: '/fixture/new-opencode' } }, agent_backend_runtime: { hot_reconciled: outcome !== 'failed', restart_error: 'fixture apply failed' } });
+ const runtimeSave = screen.getAllByRole('button', { name: en.common.save }).find((button) => !document.querySelector('.backend-connection-form')?.contains(button))!;
+ fireEvent.click(runtimeSave);
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(2));
+ expect(mock.api.mutateConfig).toHaveBeenCalledWith([{ kind: 'set', path: ['agents', 'opencode', 'cli_path'], value: '/fixture/new-opencode' }]);
+ if (outcome === 'applied') await screen.findByText(en.onboarding.connection.connected);
+ else { await screen.findByRole('alert'); expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull(); }
+ expect((form.getByLabelText(en.onboarding.connection.baseUrl) as HTMLInputElement).value).toBe('https://draft.invalid');
+ expect(runtimeSave.isConnected).toBe(false); // committed CLI is not an unsaved draft after apply failure
+ });
+ const parents = { claude: ClaudeProviderConfig, codex: CodexProviderConfig, opencode: OpencodeProviderConfig };
+ for (const backend of Object.keys(parents) as Array<keyof typeof parents>) {
+ const Parent = parents[backend];
+ const mountParent = async () => {
+ mock.api.getConfig.mockResolvedValue({ agents: { [backend]: { enabled: true, cli_path: backend } } });
+ 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);
+ };
+ it(`${backend} Settings preserves queued on after an older off persistence rejection`, async () => {
+ let rejectOff!: (error: Error) => void;
+ const rejection = new Promise((_, reject) => { rejectOff = reject; });
+ mock.api.mutateConfig.mockReturnValueOnce(rejection).mockResolvedValueOnce({ agents: { [backend]: { enabled: true } }, agent_backend_runtime: { hot_reconciled: true } });
+ await mountParent();
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
+ fireEvent.click(screen.getByRole('switch'));
+ await act(async () => rejectOff(new Error('old off rejected')));
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledTimes(2));
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
+ expect(mock.api.mutateConfig.mock.calls.map(([ops]) => ops[0].value)).toEqual([false, true]);
+ expect(mock.toast).not.toHaveBeenCalledWith('old off rejected', 'error');
+ });
+ it(`${backend} Settings reconciles rejected toggle from uncached persisted enabled`, async () => {
+ await mountParent();
+ const configReads = mock.api.getConfig.mock.calls.length;
+ mock.api.mutateConfig.mockRejectedValue(new Error('write rejected'));
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(mock.toast).toHaveBeenCalledWith('write rejected', 'error'));
+ await waitFor(() => expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true'));
+ expect(mock.api.getConfig).toHaveBeenCalledTimes(configReads);
+ expect(mock.api.getBackendConnection).toHaveBeenCalledWith(backend);
+ });
+ it.each(['applied', 'failed', 'unreadable'] as const)(`${backend} Settings restart settlement reads fresh auth/application (%s)`, async (outcome) => {
+ mock.api.getBackendRuntime.mockResolvedValue({ ok: true, name: backend, enabled: true, installed: true, supports_restart: true, process_status: 'running' });
+ await mountParent();
+ const form = within(document.querySelector('.backend-connection-form') as HTMLElement);
+ fireEvent.change(form.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://draft.invalid' } });
+ fireEvent.click(screen.getByRole('button', { name: en.backendLifecycle.statusReady }));
+ const restart = await screen.findByRole('button', { name: en.backendLifecycle.restart });
+ await waitFor(() => expect(restart.hasAttribute('disabled')).toBe(false));
+ if (outcome === 'unreadable') mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC'));
+ else mock.api.getBackendConnection.mockResolvedValue(connection({ backend, application: outcome, ready: outcome === 'applied', entry_eligible: outcome === 'applied' }));
+ mock.api.restartBackend.mockResolvedValue({ ok: outcome === 'applied', message: 'fixture restart' });
+ 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(); }
+ 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();
+ });
+ }
+ it.each(['success', 'failed'] as const)('OAuth terminal %s observes committed auth despite failed application and Refresh never rewrites it', async (state) => {
+ 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 }));
+ const done = vi.fn();
+ render(wrap(<BackendConnectionForm backend="codex" compact onConnected={done} />));
+ const start = await screen.findByRole('button', { name: en.onboarding.connection.codexSignIn });
+ mock.api.startOAuthWeb.mockResolvedValue({ ok: true, flow_id: 'settled', state, error: state === 'failed' ? 'fixture committed apply failure' : undefined });
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'oauth', has_api_key: false }));
+ mock.api.getBackendConnection.mockRejectedValue(new Error('fixture IPC'));
+ fireEvent.click(start);
+ await screen.findByText(en.onboarding.connection.savedSubscription);
+ await waitFor(() => expect(screen.getAllByRole('alert').some((node) => node.textContent?.includes('fixture IPC'))).toBe(true));
+ if (state === 'failed') expect(screen.getAllByRole('alert').some((node) => node.textContent?.includes('fixture committed apply failure'))).toBe(true);
+ expect(done).not.toHaveBeenCalled(); expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', auth: 'subscription' }));
+ const refresh = screen.getByRole('button', { name: en.onboarding.connection.refresh });
+ await waitFor(() => expect(refresh.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(refresh);
+ await waitFor(() => expect(done).toHaveBeenCalledOnce());
+ expect(mock.api.startOAuthWeb).toHaveBeenCalledOnce(); expect(mock.api.saveCodexAuth).not.toHaveBeenCalled();
+ });
+ 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 }));
+ const done = vi.fn();
+ render(wrap(<BackendConnectionForm backend="codex" onConnected={done} />));
+ const start = await screen.findByRole('button', { name: en.settings.backends.codexSignInButton });
+ const auth = deferred<CodexAuthState>();
+ mock.api.getCodexAuth.mockReturnValue(auth.promise);
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', auth: 'subscription' }));
+ mock.api.startOAuthWeb.mockResolvedValue({ ok: true, flow_id: 'cancel-confirm', state: 'success' });
+ fireEvent.click(start);
+ await waitFor(() => expect(mock.api.getCodexAuth).toHaveBeenCalledTimes(2));
+ fireEvent.click(screen.getByRole('button', { name: en.common.cancel }));
+ await act(async () => auth.resolve(codexNative({ active_auth_mode: 'oauth', has_api_key: false })));
+ expect(done).not.toHaveBeenCalled(); expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ expect(screen.queryByText(en.settings.backends.codexOauthSignedIn)).toBeNull();
+ expect(mock.api.cancelOAuthWeb).toHaveBeenCalledWith('codex', 'cancel-confirm');
+ });
+ it('a newer runtime revision wins over an older native read without erasing drafts', async () => {
+ const view = render(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" />));
+ await screen.findByText('sk-•••old');
+ const stale = deferred<CodexAuthState>();
+ mock.api.getCodexAuth.mockReturnValueOnce(stale.promise);
+ view.rerender(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" connectionRevision={1} />));
+ fireEvent.change(screen.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://draft.invalid' } });
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'none', has_api_key: false, has_chatgpt_tokens: false }));
+ view.rerender(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" connectionRevision={2} />));
+ await waitFor(() => expect(screen.queryByText('sk-•••old')).toBeNull());
+ await act(async () => stale.resolve(codexNative()));
+ expect(screen.queryByText('sk-•••old')).toBeNull();
+ expect((screen.getByLabelText(en.onboarding.connection.baseUrl) as HTMLInputElement).value).toBe('https://draft.invalid');
+ });
+ it('a late CLI detection cannot overwrite a newer Settings path draft', async () => {
+ mock.api.getConfig.mockResolvedValue({ agents: { codex: { enabled: true, cli_path: 'codex' } } });
+ render(wrap(<CodexProviderConfig />));
+ await screen.findByText(en.onboarding.connection.connected);
+ const detected = deferred<{ found: boolean; path: string }>();
+ mock.api.detectCli.mockReturnValue(detected.promise);
+ fireEvent.click(screen.getByRole('button', { name: en.common.detect }));
+ const input = screen.getByLabelText(en.agentDetection.cliPath) as HTMLInputElement;
+ fireEvent.change(input, { target: { value: '/fixture/newer-path' } });
+ await act(async () => detected.resolve({ found: true, path: '/fixture/older-probe' }));
+ expect(input.value).toBe('/fixture/newer-path');
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ });
+ it('a committed CLI save with failed apply keeps a newer path draft independent', async () => {
+ mock.api.getConfig.mockResolvedValue({ agents: { codex: { enabled: true, cli_path: 'codex' } } });
+ render(wrap(<CodexProviderConfig />));
+ await screen.findByText(en.onboarding.connection.connected);
+ const path = screen.getByLabelText(en.agentDetection.cliPath) as HTMLInputElement;
+ fireEvent.change(path, { target: { value: '/fixture/saved-codex' } });
+ const saved = deferred<{ agent_backend_runtime: { hot_reconciled: boolean; restart_error: string } }>();
+ mock.api.mutateConfig.mockReturnValue(saved.promise);
+ const runtimeSave = () => screen.getAllByRole('button', { name: en.common.save }).find((node) => !document.querySelector('.backend-connection-form')?.contains(node));
+ fireEvent.click(runtimeSave()!);
+ await waitFor(() => expect(mock.api.mutateConfig).toHaveBeenCalledOnce());
+ fireEvent.change(path, { target: { value: '/fixture/newer-draft' } });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', application: 'failed', ready: false, entry_eligible: false }));
+ await act(async () => saved.resolve({ agent_backend_runtime: { hot_reconciled: false, restart_error: 'fixture failed apply' } }));
+ await screen.findByRole('alert');
+ expect(path.value).toBe('/fixture/newer-draft'); expect(runtimeSave()).toBeTruthy();
+ fireEvent.change(path, { target: { value: '/fixture/saved-codex' } });
+ expect(runtimeSave()).toBeUndefined();
+ });
+ 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 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 });
+ const application = deferred<BackendConnectionState>();
+ mock.api.getBackendConnection.mockReturnValue(application.promise);
+ fireEvent.click(cleanupButton);
+ await screen.findByText('sk-•••old');
+ await act(async () => application.resolve(connection({ application: 'failed', ready: false, entry_eligible: false, message: 'fixture apply failed' })));
+ expect((await screen.findByRole('alert')).textContent).toContain('fixture apply failed');
+ expect(screen.queryByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials })).toBeNull();
+ 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);
+ });
+ it('a lost signout response reads committed token absence and keeps retry observational', async () => {
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'oauth', has_api_key: false }));
+ render(wrap(<BackendConnectionForm backend="codex" />));
+ const remove = await screen.findByRole('button', { name: en.settings.backends.oauthRemove });
+ mock.api.removeBackendAuth.mockRejectedValue(new Error('fixture signout response lost'));
+ 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 }));
+ fireEvent.click(remove);
+ expect((await screen.findByRole('alert')).textContent).toContain('fixture signout response lost');
+ expect(screen.queryByRole('button', { name: en.settings.backends.oauthRemove })).toBeNull();
+ const refresh = screen.getByRole('button', { name: en.onboarding.connection.refresh });
+ await waitFor(() => expect(refresh.hasAttribute('disabled')).toBe(false)); fireEvent.click(refresh);
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ expect(mock.api.removeBackendAuth).toHaveBeenCalledOnce(); expect(mock.api.saveCodexAuth).not.toHaveBeenCalled();
+ });
+ it('a lost save response still observes persisted credentials and retains its failure receipt', async () => {
+ render(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" />));
+ await screen.findByText('sk-•••old');
+ mock.api.saveCodexAuth.mockRejectedValue(new Error('fixture lost response'));
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ api_key_masked: 'new-mask' }));
+ fireEvent.click(screen.getByRole('button', { name: en.common.save }));
+ await screen.findByText('new-mask');
+ expect((await screen.findByRole('alert')).textContent).toContain('fixture lost response');
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ });
+ it.each([true, false])('preserves masked credentials, saves once, confirms effective application (compact=%s)', async (compact) => {
+ const saved = deferred<{ ok: boolean; restart: { ok: boolean } }>();
+ mock.api.saveClaudeAuth.mockReturnValue(saved.promise);
+ const connected = vi.fn();
+ render(wrap(<BackendConnectionForm backend="claude" compact={compact} initialMethod="api_key" onConnected={connected} />));
+ await screen.findByText('sk-•••old');
+ fireEvent.change(screen.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://新的.example/v1' } });
+ const button = screen.getByRole('button', { name: compact ? en.onboarding.connection.saveConnect : en.common.save });
+ fireEvent.click(button); fireEvent.click(button);
+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();
+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', credential_type: 'api_key', api_key: undefined, base_url: 'https://新的.example/v1' });
+ expect(connected).not.toHaveBeenCalled();
+ await act(async () => saved.resolve({ ok: true, restart: { ok: true } }));
+ expect(connected).toHaveBeenCalledOnce();
+ expect(mock.api.getBackendConnection).toHaveBeenCalledWith('claude');
+ });
+ it('keeps replacement input and dialog open on runtime apply failure', async () => {
+ mock.api.saveClaudeAuth.mockResolvedValue({ ok: true, restart: { ok: false, message: 'apply failed' } });
+ const close = vi.fn();
+ render(wrap(<BackendConnectionDialog backend="claude" method="api_key" onConnected={vi.fn()} onClose={close} onWriteState={vi.fn()} />));
+ fireEvent.click(await screen.findByRole('button', { name: 'Replace' }));
+ fireEvent.change(screen.getByLabelText(en.onboarding.connection.apiKeyLabel), { target: { value: 'new-test-key' } });
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));
+ expect(await screen.findByText('apply failed')).toBeTruthy();
+ expect((screen.getByLabelText(en.onboarding.connection.apiKeyLabel) as HTMLInputElement).value).toBe('new-test-key');
+ expect(close).not.toHaveBeenCalled();
+ });
+ it('does not claim connection for accepted draining; readback can finish without another save', async () => {
+ mock.api.getBackendConnection.mockResolvedValue(connection({ ok: true, application: 'draining', ready: false, entry_eligible: false }));
+ const connected = vi.fn();
+ render(wrap(<BackendConnectionForm backend="claude" compact initialMethod="api_key" onConnected={connected} />));
+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.saveConnect }));
+ await screen.findByText(en.onboarding.connection.applyPending);
+ expect(connected).not.toHaveBeenCalled();
+ mock.api.getBackendConnection.mockResolvedValue(connection({ ok: true, application: 'applied', ready: true }));
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.refresh }));
+ await waitFor(() => expect(connected).toHaveBeenCalledOnce());
+ expect(mock.api.saveClaudeAuth).toHaveBeenCalledOnce();
+ });
+ it('reports pending write settlement after close while ignoring late success presentation', async () => {
+ const saved = deferred<{ ok: boolean }>(); mock.api.saveClaudeAuth.mockReturnValue(saved.promise);
+ const connected = vi.fn(); const writes = vi.fn();
+ const { unmount } = render(wrap(<BackendConnectionForm backend="claude" compact initialMethod="api_key" onConnected={connected} onWriteState={writes} />));
+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.saveConnect }));
+ expect(writes).toHaveBeenCalledWith(true); unmount();
+ await act(async () => saved.resolve({ ok: true }));
+ expect(writes).toHaveBeenLastCalledWith(false); expect(connected).not.toHaveBeenCalled();
+ });
+ it('cancels a late start with force_reset=false and never accepts its result after close', async () => {
+ const started = deferred<{ ok: boolean; flow_id: string; state: 'awaiting_code'; url: string }>();
+ mock.api.startOAuthWeb.mockReturnValue(started.promise);
+ const connected = vi.fn();
+ const { unmount } = render(wrap(<BackendConnectionForm backend="claude" compact onConnected={connected} />));
+ const start = await screen.findByRole('button', { name: en.onboarding.connection.claudeSignIn });
+ fireEvent.click(start); fireEvent.click(start);
+ expect(mock.api.startOAuthWeb).toHaveBeenCalledOnce();
+ expect(mock.api.startOAuthWeb).toHaveBeenCalledWith('claude', false);
+ unmount();
+ await act(async () => started.resolve({ ok: true, flow_id: 'late-flow', state: 'awaiting_code', url: 'https://example.invalid' }));
+ expect(mock.api.cancelOAuthWeb).toHaveBeenCalledWith('claude', 'late-flow');
+ expect(connected).not.toHaveBeenCalled(); expect(mock.api.getOAuthWebStatus).not.toHaveBeenCalled();
+ });
+ it('retains Settings stale Claude credential cleanup', async () => {
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), active_auth_mode: 'none' });
+ mock.api.removeClaudeOAuthCredentials.mockResolvedValue({ ok: true });
+ render(wrap(<BackendConnectionForm backend="claude" />));
+ fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials }));
+ await waitFor(() => expect(mock.api.removeClaudeOAuthCredentials).toHaveBeenCalledOnce());
+ expect(mock.api.getBackendConnection).toHaveBeenCalledWith('claude');
+ });
+ it('ignores late poll and submit results after cancelling the dialog', async () => {
+ const status = deferred<{ ok: boolean; state: 'success' }>();
+ const submit = deferred<{ ok: boolean }>();
+ mock.api.startOAuthWeb.mockResolvedValue({ ok: true, flow_id: 'poll-flow', state: 'awaiting_code', url: 'https://fixture.invalid' });
+ mock.api.getOAuthWebStatus.mockReturnValue(status.promise);
+ mock.api.submitOAuthWebCode.mockReturnValue(submit.promise);
+ const connected = vi.fn(); const writes = vi.fn();
+ const { unmount } = render(wrap(<BackendConnectionForm backend="claude" compact onConnected={connected} onWriteState={writes} />));
+ const start = await screen.findByRole('button', { name: en.onboarding.connection.claudeSignIn });
+ vi.useFakeTimers(); await act(async () => fireEvent.click(start));
+ const input = screen.getByLabelText(en.settings.backends.claudeCallbackCodeLabel);
+ fireEvent.change(input, { target: { value: 'fixture-code#state' } });
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.finishConnect }));
+ await act(async () => vi.advanceTimersByTimeAsync(2000));
+ expect(mock.api.getOAuthWebStatus).toHaveBeenCalledOnce();
+ unmount();
+ await act(async () => { status.resolve({ ok: true, state: 'success' }); submit.resolve({ ok: true }); });
+ expect(mock.api.cancelOAuthWeb).toHaveBeenCalledWith('claude', 'poll-flow');
+ expect(connected).not.toHaveBeenCalled(); expect(writes).toHaveBeenLastCalledWith(false);
+ });
+ it('preserves keyless custom-provider URL editing in Settings without claiming a credential connection', async () => {
+ const provider = { id: 'local-test', name: 'Local', description: '', configured: true, custom: true, oauth_available: false, local: true, models: [], base_url: 'http://localhost:4567/v1' };
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider] });
+ mock.api.setOpencodeProviderAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', ok: true, application: 'applied', ready: false, entry_eligible: false, auth: 'none' }));
+ render(wrap(<BackendConnectionForm backend="opencode" provider={provider} />));
+ const button = await screen.findByRole('button', { name: en.common.save });
+ expect(button.hasAttribute('disabled')).toBe(false); fireEvent.click(button);
+ await waitFor(() => expect(mock.api.setOpencodeProviderAuth).toHaveBeenCalledWith('local-test', undefined, 'http://localhost:4567/v1'));
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('does not label an unconnected provider ready because another OpenCode provider is connected', async () => {
+ const provider = { id: 'new-provider', name: 'New provider', description: '', configured: false, oauth_available: false, local: false, models: [] };
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider] });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', ok: true, application: 'applied', ready: true, auth: 'api_key' }));
+ render(wrap(<BackendConnectionForm backend="opencode" compact provider={provider} />));
+ await screen.findByLabelText('API Key');
+ expect(screen.queryByText(en.onboarding.connection.connected)).toBeNull();
+ });
+
+ it('keeps Claude Auth Token payload distinct from the compact API Key label', async () => {
+ mock.api.getClaudeAuth.mockResolvedValue({ ...native(), credential_type: 'auth_token' });
+ render(wrap(<BackendConnectionForm backend="claude" compact initialMethod="api_key" />));
+ fireEvent.click(await screen.findByRole('button', { name: 'Replace' }));
+ fireEvent.change(screen.getByLabelText('Auth Token', { exact: true }), { target: { value: 'fixture-token' } });
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.saveConnect }));
+ await waitFor(() => expect(mock.api.saveClaudeAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', credential_type: 'auth_token', api_key: 'fixture-token', base_url: 'https://old.example' }));
+ });
+ it('Codex saves through its native owner and refuses uncertain keychain readback', async () => {
+ mock.api.getCodexAuth.mockResolvedValue(codexNative({ auth_mode_uncertain: true }));
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'codex', ok: true, application: 'applied', ready: false, entry_eligible: false, auth: 'unknown' }));
+ mock.api.saveCodexAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ const connected = vi.fn();
+ render(wrap(<BackendConnectionForm backend="codex" compact initialMethod="api_key" onConnected={connected} />));
+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.saveConnect }));
+ expect(await screen.findByText(en.onboarding.connection.unconfirmed)).toBeTruthy();
+ expect(mock.api.saveCodexAuth).toHaveBeenCalledWith({ auth_mode: 'api_key', api_key: undefined, base_url: 'https://old.example' });
+ expect(mock.api.saveClaudeAuth).not.toHaveBeenCalled(); expect(connected).not.toHaveBeenCalled();
+ });
+ it('OpenCode runtime-declared manual code uses the existing submit owner and blocks duplicate submit', async () => {
+ const provider = { id: 'poe', name: 'Poe', description: '', configured: false, oauth_available: true, local: false, models: [] };
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [provider] });
+ mock.api.getBackendConnection.mockResolvedValue(connection({ backend: 'opencode', ok: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false }));
+ mock.api.startOAuthWebForOpencodeProvider.mockResolvedValue({ ok: true, flow_id: 'manual-flow', state: 'awaiting_code', callback_kind: 'code', url: 'https://fixture.invalid' });
+ const pending = deferred<{ ok: boolean }>(); mock.api.submitOAuthWebCode.mockReturnValue(pending.promise);
+ render(wrap(<BackendConnectionForm backend="opencode" compact provider={provider} />));
+ fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.opencodeProviderSignIn }));
+ fireEvent.change(await screen.findByLabelText(en.onboarding.connection.manualCode), { target: { value: 'fixture-code' } });
+ const submit = screen.getByRole('button', { name: en.onboarding.connection.finishConnect }); fireEvent.click(submit); fireEvent.click(submit);
+ expect(mock.api.submitOAuthWebCode).toHaveBeenCalledExactlyOnceWith('opencode', 'manual-flow', 'fixture-code');
+ expect(mock.api.setOpencodeProviderAuth).not.toHaveBeenCalled();
+ await act(async () => pending.resolve({ ok: true }));
+ });
+
+});
diff --git a/ui/src/components/onboarding/BackendConnectionDialog.tsx b/ui/src/components/onboarding/BackendConnectionDialog.tsx
new file mode 100644
index 000000000..754e7eade
--- /dev/null
+++ b/ui/src/components/onboarding/BackendConnectionDialog.tsx
@@ -0,0 +1,75 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { ChevronRight, Search } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useApi, type OpencodeProvider } from '@/context/ApiContext';
+import { errorMessage } from '@/lib/errorMessage';
+import { getBackendUiMeta } from '@/lib/agentBackends';
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog';
+import { Button } from '../ui/button';
+import { Input } from '../ui/input';
+import { BackendIcon } from '../visual';
+import { BackendConnectionForm, type ConnectionHeading } from '../settings/providers/BackendConnectionForm';
+import type { BackendId } from '../settings/shared/useBackendRuntime';
+
+export function BackendConnectionDialog({ backend, method, onClose, onConnected, onWriteState }: {
+ backend: BackendId;
+ method: 'oauth' | 'api_key';
+ onClose: () => void;
+ onConnected: () => Promise<void>;
+ onWriteState: (pending: boolean) => void;
+}) {
+ const api = useApi(); const { t } = useTranslation();
+ const [heading, setHeading] = useState<ConnectionHeading>({ method, active: false, credential: 'api_key' });
+ const [providers, setProviders] = useState<OpencodeProvider[]>([]);
+ const [provider, setProvider] = useState<OpencodeProvider>();
+ const [loading, setLoading] = useState(backend === 'opencode');
+ const [error, setError] = useState('');
+ const [query, setQuery] = useState('');
+ const [busy, setBusy] = useState(false);
+ const readToken = useRef(0);
+ const mounted = useRef(true);
+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
+ const load = useCallback(async () => {
+ const token = ++readToken.current;
+ setLoading(true); setError('');
+ try {
+ const result = await api.getOpencodeProviders();
+ if (token !== readToken.current) return;
+ if (!result.ok) throw new Error(result.message || t('onboarding.connection.readFailed'));
+ setProviders(result.providers || []);
+ } catch (err) { if (token === readToken.current) setError(errorMessage(err) || t('onboarding.connection.readFailed')); }
+ finally { if (token === readToken.current) setLoading(false); }
+ }, [api, t]);
+ useEffect(() => { if (backend === 'opencode') void load(); return () => { readToken.current++; }; }, [backend, load]);
+ const isKey = heading.method === 'api_key';
+ const title = backend === 'claude' ? t(heading.active ? 'onboarding.connection.claudeComplete' : isKey ? heading.credential === 'auth_token' ? 'onboarding.connection.claudeTokenTitle' : 'onboarding.connection.claudeKeyTitle' : 'onboarding.connection.claudeTitle')
+ : backend === 'codex' ? t(isKey ? 'onboarding.connection.codexKeyTitle' : heading.active ? 'onboarding.connection.codexComplete' : 'onboarding.connection.codexTitle')
+ : provider ? t(isKey ? 'onboarding.connection.providerKeyTitle' : 'onboarding.connection.providerTitle', { name: provider.name })
+ : t(isKey ? 'onboarding.connection.opencodeKeyTitle' : 'onboarding.connection.opencodeTitle');
+ const intro = backend === 'claude' ? t(heading.active ? 'onboarding.connection.claudeCompleteIntro' : isKey ? 'onboarding.connection.claudeKeyIntro' : 'onboarding.connection.claudeIntro')
+ : backend === 'codex' ? t(isKey ? 'onboarding.connection.codexKeyIntro' : heading.active ? 'onboarding.connection.codexCompleteIntro' : 'onboarding.connection.codexIntro')
+ : provider ? t('onboarding.connection.providerIntro', { name: provider.name }) : t(isKey ? 'onboarding.connection.pickKey' : 'onboarding.connection.pickSubscription');
+ const filtered = providers.filter((entry) => (method === 'api_key' ? !entry.local : entry.oauth_available)
+ && `${entry.name} ${entry.id}`.toLowerCase().includes(query.toLowerCase()));
+ return <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}><DialogContent className="connection-dialog" closeLabel={t('common.close')}>
+ <div className="connection-heading"><div className="connection-logo"><BackendIcon backend={backend} variant="brand" brandFit="mark" size={28} aria-hidden="true" /></div>
+ <div><DialogTitle>{title}</DialogTitle><p>{t('onboarding.connection.target', { name: getBackendUiMeta(backend).label })}</p></div>
+ </div>
+ <DialogDescription className="connection-intro">{intro}</DialogDescription>
+ {backend === 'opencode' && !provider ? <>
+ {loading && <p role="status">{t('common.loading')}</p>}
+ {error && <div className="connection-error" role="alert">{error}<Button variant="secondary" onClick={() => void load()}>{t('common.retry')}</Button></div>}
+ {method === 'api_key' && <div className="relative"><Search size={15} className="absolute left-3 top-3 text-muted" /><Input className="h-[38px] pl-9" aria-label={t('settings.backends.opencodeSearchPlaceholder')} placeholder={t('settings.backends.opencodeSearchPlaceholder')} value={query} onChange={(event) => setQuery(event.target.value)} /></div>}
+ <div className="connection-provider-list">{filtered.map((entry) => <button type="button" key={entry.id} className="connection-provider focus-visible:outline-2 focus-visible:outline-ring" onClick={() => setProvider(entry)}>
+ <span><strong>{entry.name}</strong><small>{entry.description || entry.id}</small></span><ChevronRight size={16} /></button>)}</div>
+ {!loading && !error && filtered.length === 0 && <p className="connection-intro">{t('onboarding.connection.noProviders')}</p>}
+ <p className="connection-intro">{t('onboarding.connection.catalogHint')}</p>
+ <div className="connection-actions"><Button variant="secondary" onClick={onClose}>{t('common.cancel')}</Button></div>
+ </> : <>
+ {provider && <div className="connection-provider"><span><strong>{provider.name}</strong><small>{t('onboarding.connection.providerDescription')}</small></span><Button variant="ghost" size="xs" disabled={busy} onClick={() => setProvider(undefined)}>{t('onboarding.connection.changeProvider')}</Button></div>}
+ <BackendConnectionForm key={provider?.id || backend} backend={backend} provider={provider} initialMethod={method} compact
+ onHeading={setHeading} onBusyChange={setBusy} onWriteState={onWriteState} onCancel={onClose}
+ onConnected={async () => { await onConnected(); if (mounted.current) onClose(); }} />
+ </>}
+ </DialogContent></Dialog>;
+}
diff --git a/ui/src/components/onboarding/CollaborationStory.tsx b/ui/src/components/onboarding/CollaborationStory.tsx
index e297170d9..516420810 100644
--- a/ui/src/components/onboarding/CollaborationStory.tsx
+++ b/ui/src/components/onboarding/CollaborationStory.tsx
@@ -174,7 +174,7 @@ export function CollaborationStory() {
</div>
<Skeleton backend={backend} done={done} written={reducedMotion ? WORK_LINES : frame.written[index]} />
<div className="onboarding-story-identity">
- <BackendIcon backend={backend} size={28} variant="glyph" aria-hidden="true" />
+ <BackendIcon backend={backend} size={28} variant="brand" aria-hidden="true" />
<strong>{t(`onboarding.story.${backend}.name`)}</strong>
<span>{t(`onboarding.story.${backend}.role`)}</span>
</div>
diff --git a/ui/src/components/onboarding/SetupModelRecovery.tsx b/ui/src/components/onboarding/SetupModelRecovery.tsx
new file mode 100644
index 000000000..e66d8a325
--- /dev/null
+++ b/ui/src/components/onboarding/SetupModelRecovery.tsx
@@ -0,0 +1,71 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useApi, type VibeAgentBrief, type VibeAgentUpdatePayload } from '@/context/ApiContext';
+import { fetchBackendModels, modelOptionLabel, type BackendModels } from '@/lib/backendModels';
+import { resolveEffortOptions } from '@/lib/effortOptions';
+import { errorMessage } from '@/lib/errorMessage';
+import { Button } from '../ui/button';
+import { Combobox } from '../ui/combobox';
+import { readOpencodeSetupRoutes } from './opencodeSetupRoutes';
+
+/** An explicit model repair, scoped to the named Agent and existing catalog. */
+export function SetupModelRecovery({ agent, onComplete, onCancel }: {
+ agent: VibeAgentBrief; onComplete: () => Promise<void>; onCancel: () => void;
+}) {
+ const api = useApi(); const { t } = useTranslation();
+ const [catalog, setCatalog] = useState<BackendModels>({ models: [] });
+ const [model, setModel] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const [attempt, setAttempt] = useState(0);
+ const busy = useRef(false);
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true); setError('');
+ void Promise.all([readOpencodeSetupRoutes(api), fetchBackendModels(api, 'opencode')]).then(([routes, models]) => {
+ if (cancelled) return;
+ if (routes.mode !== 'direct') throw new Error(t('onboarding.connection.modelChanged'));
+ setCatalog({ ...models, models: models.models.filter(routes.accepts) });
+ }).catch((cause) => { if (!cancelled) setError(errorMessage(cause) || t('onboarding.connection.modelUnavailable')); })
+ .finally(() => { if (!cancelled) setLoading(false); });
+ return () => { cancelled = true; };
+ }, [api, attempt, t]);
+ const apply = async () => {
+ if (busy.current || !catalog.models.includes(model)) return;
+ busy.current = true; setSaving(true); setError('');
+ try {
+ const [routes, fresh] = await Promise.all([readOpencodeSetupRoutes(api), api.getVibeAgent(agent.name, { cache: false })]);
+ if (!fresh.ok || !fresh.agent.enabled || fresh.agent.archived || fresh.agent.backend !== 'opencode' || routes.mode !== 'direct' || !routes.accepts(model)) throw new Error(t('onboarding.connection.modelChanged'));
+ if (fresh.agent.model !== agent.model && fresh.agent.model !== model) throw new Error(t('onboarding.connection.modelChanged'));
+ const patch: VibeAgentUpdatePayload = { model };
+ // Only an explicit catalog statement justifies changing existing effort.
+ const effort = fresh.agent.reasoning_effort;
+ if (effort && catalog.reasoningOptions && Object.prototype.hasOwnProperty.call(catalog.reasoningOptions, model)) {
+ const options = resolveEffortOptions('opencode', model, catalog.reasoningOptions);
+ if (!options.includes(effort)) patch.reasoning_effort = options.includes('medium') ? 'medium' : options[0] ?? null;
+ }
+ if (fresh.agent.model !== model) {
+ const result = await api.updateVibeAgent(agent.name, patch);
+ if (!result.ok) throw new Error(t('onboarding.connection.saveFailed'));
+ }
+ await onComplete();
+ } catch (cause) { setError(errorMessage(cause) || t('onboarding.connection.modelUnavailable')); }
+ finally { busy.current = false; setSaving(false); }
+ };
+ return <section className="onboarding-model-recovery" aria-label={t('onboarding.connection.modelTitle')}>
+ <h3>{t('onboarding.connection.modelTitle')}</h3>
+ <p>{t('onboarding.connection.modelHint', { agent: agent.display_name || agent.name, model: agent.model || '—' })}</p>
+ {error && <p role="alert" className="connection-error">{error}</p>}
+ {!loading && !catalog.models.length && <p role="status">{t('onboarding.connection.modelEmpty')}</p>}
+ <Combobox options={catalog.models.map((value) => ({ value, label: modelOptionLabel(value, catalog.modelLabels) }))}
+ value={model} onValueChange={setModel} disabled={loading || saving} allowCustomValue={false}
+ searchPlaceholder={t('onboarding.connection.modelSelect')} emptyText={t('onboarding.connection.modelEmpty')}
+ ariaLabel={t('onboarding.connection.modelSelect')} placeholder={t('onboarding.connection.modelSelect')} />
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button variant="ghost" disabled={saving} onClick={onCancel}>{t('common.cancel')}</Button>
+ <Button variant="secondary" disabled={loading || saving} onClick={() => setAttempt((value) => value + 1)}>{t('common.retry')}</Button>
+ <Button variant="brand" disabled={loading || saving || !catalog.models.includes(model)} onClick={() => void apply()}>{t('onboarding.connection.modelApply')}</Button>
+ </div>
+ </section>;
+}
diff --git a/ui/src/components/onboarding/SetupPlatformRecovery.tsx b/ui/src/components/onboarding/SetupPlatformRecovery.tsx
new file mode 100644
index 000000000..33609d031
--- /dev/null
+++ b/ui/src/components/onboarding/SetupPlatformRecovery.tsx
@@ -0,0 +1,42 @@
+import { useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useApi } from '@/context/ApiContext';
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
+import { configChanges } from '@/lib/configMutations';
+import { errorMessage } from '@/lib/errorMessage';
+import { platformText, type PlatformDescriptor } from '@/lib/platforms';
+import { PlatformConfigEmbed } from '../settings/PlatformConfigEmbed';
+import { savePlatformSettings } from '../settings/shared/savePlatformSettings';
+import { Button } from '../ui/button';
+
+export type SavedPlatformRecovery = { config: Record<string, unknown>; descriptor: PlatformDescriptor };
+
+export function SetupPlatformRecovery({ saved, onRepaired, onCancel }: {
+ saved: SavedPlatformRecovery; onRepaired: () => Promise<void>; onCancel: () => void;
+}) {
+ const api = useApi(); const { t } = useTranslation();
+ const { capabilities } = useInstanceAuthorization();
+ const [editing, setEditing] = useState(false);
+ const [error, setError] = useState('');
+ const busy = useRef(false);
+ const { config, descriptor } = saved;
+ const key = descriptor.config_key || descriptor.id;
+ const apply = async (next: Record<string, unknown>) => {
+ if (busy.current) return;
+ busy.current = true; setError('');
+ try {
+ const result = await api.mutateConfig(configChanges(config[key], next[key], [key]));
+ const runtime = result?.platform_runtime;
+ if (runtime?.hot_reconciled === false && !runtime.restart_scheduled) throw new Error(runtime.restart_error || runtime.error || t('platform.restartFailed'));
+ await savePlatformSettings(api, descriptor.id, next, capabilities.can_manage_access_members);
+ await onRepaired();
+ } catch (cause) { setError(errorMessage(cause) || t('common.saveFailed')); }
+ finally { busy.current = false; }
+ };
+ return <section className="onboarding-model-recovery" aria-label={t('onboarding.connection.platformRepair')}>
+ <p role="alert">{t('onboarding.connection.platformRepairHint', { platform: platformText(t, descriptor.id, 'title', descriptor.title_key) })}</p>
+ {error && <p role="alert" className="connection-error">{error}</p>}
+ {editing ? <PlatformConfigEmbed platform={descriptor.id} config={config} onApply={apply} onCancel={onCancel} />
+ : <div className="flex flex-wrap gap-2"><Button variant="secondary" onClick={() => setEditing(true)}>{t('onboarding.connection.platformRepair')}</Button><Button variant="ghost" onClick={onCancel}>{t('common.cancel')}</Button></div>}
+ </section>;
+}
diff --git a/ui/src/components/onboarding/WizardCompletion.test.tsx b/ui/src/components/onboarding/WizardCompletion.test.tsx
new file mode 100644
index 000000000..0a1f422c3
--- /dev/null
+++ b/ui/src/components/onboarding/WizardCompletion.test.tsx
@@ -0,0 +1,311 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { Wizard } from '../Wizard';
+import en from '../../i18n/en.json';
+
+const mock = vi.hoisted(() => ({ supply: vi.fn(), control: vi.fn(), toast: vi.fn(), permission: vi.fn(), manageAccess: true, api: {
+ saveSettings: vi.fn(), discordAuthTest: vi.fn(), discordGuilds: vi.fn(), slackManifest: vi.fn(), slackAuthTest: vi.fn(), getConfig: vi.fn(), detectCli: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(),
+ getOpencodeProviders: vi.fn(), readOpencodeOptionsForModelPicker: vi.fn(), readModelHubAgentCatalogForModelPicker: vi.fn(), updateVibeAgent: vi.fn(), getVibeAgent: vi.fn(), listVibeAgents: vi.fn(), setDefaultVibeAgent: vi.fn(), mutateConfig: vi.fn(),
+} }));
+vi.mock('../../context/ApiContext', async (importOriginal) => ({ ...await importOriginal<typeof import('../../context/ApiContext')>(), useApi: () => mock.api }));
+vi.mock('../settings/models/modelsApi', () => ({ modelsApi: { getAgentSources: mock.supply } }));
+vi.mock('../../context/InstanceAuthorizationContext', () => ({ useInstanceAuthorization: () => ({ capabilities: { can_manage_agents: true, can_manage_access_members: mock.manageAccess } }) }));
+vi.mock('../../context/StatusContext', () => ({ useStatus: () => ({ control: mock.control }) }));
+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mock.toast }) }));
+vi.mock('../settings/models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));
+vi.mock('../settings/shared/useOpencodePermission', () => ({ useOpencodePermission: () => ({ permissionAllowed: false, statusLoaded: true, setupPermission: mock.permission }) }));
+const i18n = createInstance();
+await i18n.init({ lng: 'en', resources: { en: { translation: en } } });
+function Destination() { const location = useLocation(); return <div data-testid="destination">{JSON.stringify(location.state)}</div>; }
+function mount() { return render(<MemoryRouter initialEntries={['/setup']}><I18nextProvider i18n={i18n}><Routes><Route path="/setup" element={<Wizard />} /><Route path="/" element={<Destination />} /></Routes></I18nextProvider></MemoryRouter>); }
+let running: boolean;
+beforeEach(() => {
+ vi.resetAllMocks(); running = true; mock.manageAccess = true;
+ mock.api.saveSettings.mockResolvedValue({ guild_allowlist: [] });
+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
+ Element.prototype.scrollIntoView = vi.fn();
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+ mock.api.readModelHubAgentCatalogForModelPicker.mockResolvedValue(null);
+ mock.api.getConfig.mockResolvedValue({ setup_completed: false, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } }, platforms: { enabled: [] } });
+ mock.api.detectCli.mockResolvedValue({ found: true, path: '/测试/bin/assistant' });
+ mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: false });
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: backend === 'claude' ? 'api_key' : 'none', application: running ? 'applied' : 'stopped', ready: backend === 'claude' && running, entry_eligible: backend === 'claude', permission_required: backend === 'opencode' }));
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'missing-codex', agents: [{ name: 'claude-agent', backend: 'claude', enabled: true }] });
+ mock.api.setDefaultVibeAgent.mockResolvedValue({ ok: true });
+ mock.api.mutateConfig.mockResolvedValue({ setup_completed: true });
+ mock.control.mockImplementation(async () => { running = true; return { ok: true }; });
+});
+afterEach(cleanup);
+async function setup() {
+ mount(); fireEvent.click(await screen.findByRole('button', { name: 'Get started' }));
+ const enter = await screen.findByRole('button', { name: 'Enter workspace' });
+ await waitFor(() => expect(enter.hasAttribute('disabled')).toBe(false));
+ return enter;
+}
+describe('explicit any-one-ready completion', () => {
+ it('keeps setup until explicit Enter, scopes OpenCode permission, chooses an available Agent, writes only completion', async () => {
+ const enter = await setup();
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('destination')).toBeNull();
+ fireEvent.click(enter); fireEvent.click(enter);
+ expect(await screen.findByTestId('destination')).toBeTruthy();
+ expect(screen.getByTestId('destination').textContent).toBe('{"onboardingCompleted":true}');
+ expect(mock.api.mutateConfig).toHaveBeenCalledExactlyOnceWith([{ kind: 'set', path: ['setup_completed'], value: true }]);
+ expect(mock.api.setDefaultVibeAgent).toHaveBeenCalledExactlyOnceWith('claude-agent');
+ expect(mock.permission).not.toHaveBeenCalled(); expect(mock.control).not.toHaveBeenCalled();
+ });
+ it('allows stopped entry and confirms start before committing setup', async () => {
+ running = false;
+ const enter = await setup(); fireEvent.click(enter);
+ await screen.findByTestId('destination');
+ expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
+ expect(mock.control.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[0]);
+ });
+ it('preserves an existing usable default', async () => {
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'mine', agents: [{ name: 'mine', backend: 'claude', enabled: true }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
+ });
+ it.each(['start', 'legacy IM'])('keeps failed completion recoverable (%s)', async (failure) => {
+ if (failure === 'start') { running = false; mock.control.mockRejectedValue(new Error('Start unavailable')); }
+ else mock.api.mutateConfig.mockRejectedValue(new Error("Config 'slack.bot_token' must be provided"));
+ fireEvent.click(await setup());
+ await screen.findByRole('alert');
+ expect(screen.queryByTestId('destination')).toBeNull();
+ if (failure === 'start') expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();
+ mock.control.mockImplementation(async () => { running = true; return { ok: true }; });
+ mock.api.mutateConfig.mockResolvedValue({ setup_completed: true });
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Enter workspace' })));
+ await screen.findByTestId('destination');
+ });
+ it('rechecks effective readiness at explicit entry instead of trusting a stale badge', async () => {
+ const enter = await setup();
+ mock.api.getBackendConnection.mockResolvedValue({ ok: true, ready: false, entry_eligible: false, application: 'failed' });
+ fireEvent.click(enter); await screen.findByRole('alert');
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.control).not.toHaveBeenCalled();
+ });
+});
+
+const opencodeAgent = { id: 'oc-1', name: 'opencode', display_name: 'OpenCode', backend: 'opencode', model: 'openai/gpt-5.6-sol', enabled: true, archived: false, source: 'builtin', reasoning_effort: 'high' };
+function directConnection(provider: string) {
+ let agent = { ...opencodeAgent };
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: 'api_key', application: 'applied', ready: backend === 'opencode', entry_eligible: backend === 'opencode' }));
+ mock.api.listVibeAgents.mockImplementation(async () => ({ ok: true, default_agent_name: 'opencode', agents: [agent] }));
+ mock.api.getVibeAgent.mockImplementation(async () => ({ ok: true, agent }));
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, default_provider: 'openai', providers: [{ id: 'openai', configured: true, active_auth_type: null, models: ['gpt-5.6-sol'] }, { id: provider, configured: true, active_auth_type: 'oauth', models: ['selected-model', 'my-model'] }] });
+ mock.api.readOpencodeOptionsForModelPicker.mockResolvedValue({ ok: true, data: { models: { providers: [{ id: provider, models: { 'selected-model': {} } }, { id: 'openai', models: { 'gpt-5.6-sol': {} } }] }, reasoning_options: { [`${provider}/selected-model`]: [] } } });
+ mock.api.updateVibeAgent.mockImplementation(async (_name, patch) => { agent = { ...agent, ...patch }; return { ok: true, agent }; });
+}
+// AUTH-SETUP-121: the actual Wizard consumes route eligibility and explicit repair.
+describe('OpenCode model recovery', () => {
+ it.each(['anthropic', 'poe'])('requires explicit compatible model selection for %s-only auth', async (provider) => {
+ directConnection(provider);
+ fireEvent.click(await setup());
+ await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ const picker = screen.getByRole('combobox', { name: en.onboarding.connection.modelSelect });
+ await waitFor(() => expect(picker.hasAttribute('disabled')).toBe(false));
+ fireEvent.click(picker);
+ fireEvent.click(await screen.findByText(`${provider}/selected-model`, { exact: true }));
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply }));
+ await screen.findByTestId('destination');
+ expect(mock.api.updateVibeAgent).toHaveBeenCalledExactlyOnceWith('opencode', { model: `${provider}/selected-model`, reasoning_effort: null });
+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
+ });
+ it('cancel leaves the Agent and completion untouched', async () => {
+ directConnection('anthropic'); fireEvent.click(await setup());
+ await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ });
+ it('keeps selected input after a failed save and permits retry', async () => {
+ directConnection('poe'); mock.api.updateVibeAgent.mockRejectedValueOnce(new Error('Agent save failed'));
+ fireEvent.click(await setup());
+ const picker = await screen.findByRole('combobox', { name: en.onboarding.connection.modelSelect });
+ await waitFor(() => expect(picker.hasAttribute('disabled')).toBe(false)); fireEvent.click(picker);
+ fireEvent.click(await screen.findByText('poe/selected-model', { exact: true }));
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply }));
+ expect((await screen.findByRole('alert')).textContent).toContain('Agent save failed');
+ expect(picker.textContent).toContain('poe/selected-model'); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.modelApply })); await screen.findByTestId('destination');
+ });
+ it('preserves a custom compatible default without opening the catalog', async () => {
+ directConnection('anthropic');
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model: 'anthropic/my-model' }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.readOpencodeOptionsForModelPicker).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
+ });
+ it.each(['anthropic/removed', 'anthropic/typo', 'anthropic/'] as const)('rejects unregistered Direct model %s without editing Agent or auth', async (model) => {
+ directConnection('anthropic');
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model }] });
+ fireEvent.click(await setup()); await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
+ expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ });
+ it.each([[], undefined])('keeps an Agent route unverified with absent model list (%s)', async (models) => {
+ directConnection('anthropic');
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [{ id: 'anthropic', active_auth_type: 'api', models }] });
+ fireEvent.click(await setup()); await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
+ expect(screen.queryByTestId('destination')).toBeNull(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ });
+ it.each(['anthropic/family/custom-model', 'family-model'] as const)('preserves registered slash or explicit-default Direct model %s', async (model) => {
+ directConnection('anthropic');
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, default_provider: 'anthropic', providers: [{ id: 'anthropic', active_auth_type: 'api', models: ['family/custom-model', 'family-model'] }] });
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.updateVibeAgent).not.toHaveBeenCalled(); expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled();
+ });
+ it('does not infer a default provider for a bare model and retries unreadable catalog without auth mutation', async () => {
+ directConnection('anthropic');
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'custom', agents: [{ ...opencodeAgent, name: 'custom', source: 'user', model: 'my-model' }] });
+ mock.api.getOpencodeProviders.mockRejectedValue(new Error('provider catalog unreadable'));
+ fireEvent.click(await setup());
+ expect((await screen.findByRole('alert')).textContent).toContain('provider catalog unreadable');
+ expect(screen.queryByTestId('destination')).toBeNull();
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [{ id: 'anthropic', active_auth_type: 'api', models: ['my-model'] }] });
+ fireEvent.click(screen.getByRole('button', { name: en.common.retry }));
+ await screen.findByRole('region', { name: en.onboarding.connection.modelTitle });
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ });
+ it('an unreadable OpenCode catalog cannot block an existing usable Claude default', async () => {
+ directConnection('anthropic');
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true }));
+ mock.api.getOpencodeProviders.mockRejectedValue(new Error('provider catalog unreadable'));
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'mine', agents: [opencodeAgent, { name: 'mine', backend: 'claude', enabled: true }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ });
+ it('allows another ready backend despite OpenCode mismatch', async () => {
+ directConnection('anthropic');
+ mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true }));
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'mine', agents: [opencodeAgent, { name: 'mine', backend: 'claude', enabled: true }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.readOpencodeOptionsForModelPicker).not.toHaveBeenCalled(); expect(mock.api.setDefaultVibeAgent).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ });
+});
+
+it('uses canonical Hub supply instead of treating canonical slash IDs as Direct providers', async () => {
+ directConnection('anthropic');
+ const config = await mock.api.getConfig();
+ mock.api.getConfig.mockResolvedValue({ ...config, capabilities: { model_hub: { enabled: true } } });
+ mock.api.listVibeAgents.mockResolvedValue({ ok: true, default_agent_name: 'opencode', agents: [{ ...opencodeAgent, model: 'canonical/model' }] });
+ mock.supply.mockResolvedValue({ backend: 'opencode', mode: 'hub', catalog_models: [{ id: 'canonical/model', routeable: true }], model_supply: [{ model_id: 'canonical/model', has_runnable_hop: true }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.getOpencodeProviders).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+});
+it('keeps incomplete setup when catalog retrieval fails and allows cancellation', async () => {
+ directConnection('anthropic'); mock.api.readOpencodeOptionsForModelPicker.mockRejectedValue(new Error('Catalog unavailable'));
+ fireEvent.click(await setup());
+ expect((await screen.findByRole('alert')).textContent).toContain('Catalog unavailable');
+ expect(mock.api.mutateConfig).not.toHaveBeenCalled(); expect(mock.api.updateVibeAgent).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByRole('region', { name: en.onboarding.connection.modelTitle })).toBeNull();
+});
+
+// AUTH-SETUP-120: the actual Wizard consumes legacy-IM recovery and narrow mutations.
+describe('saved messaging recovery', () => {
+ function incompleteSlack() {
+ const config = { setup_completed: false, agents: { claude: { enabled: true }, codex: { enabled: true }, opencode: { enabled: true } }, platforms: { enabled: ['slack'] }, platform_catalog: [{ id: 'slack', config_key: 'slack', credential_fields: ['bot_token', 'app_token'] }], slack: { bot_token: '', app_token: '', has_bot_token: false, has_app_token: true, proxy_url: '' }, agent: { default_cwd: '/original' } };
+ mock.api.getConfig.mockResolvedValue(config);
+ mock.api.slackManifest.mockResolvedValue({ ok: true, manifest: '{}' });
+ return config;
+ }
+ it('mounts only after explicit repair, saves changed credentials only, then rechecks and completes', async () => {
+ const config = incompleteSlack(); running = false;
+ fireEvent.click(await setup());
+ await screen.findByRole('region', { name: en.onboarding.connection.platformRepair });
+ expect(mock.control).not.toHaveBeenCalled(); expect(mock.api.slackManifest).not.toHaveBeenCalled();
+ mock.api.mutateConfig.mockImplementation(async (mutations) => {
+ if (mutations[0].path[0] === 'slack') mock.api.getConfig.mockResolvedValue({ ...config, slack: { ...config.slack, has_bot_token: true }, agent: { default_cwd: '/concurrent' } });
+ return {};
+ });
+ fireEvent.click(screen.getByRole('button', { name: en.onboarding.connection.platformRepair }));
+ fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));
+ fireEvent.change(await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder), { target: { value: 'xoxb-fixture-only' } });
+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));
+ await screen.findByTestId('destination');
+ expect(mock.api.mutateConfig.mock.calls[0][0]).toEqual([{ kind: 'set', path: ['slack', 'bot_token'], value: 'xoxb-fixture-only' }]);
+ expect(mock.api.mutateConfig.mock.calls[1][0]).toEqual([{ kind: 'set', path: ['setup_completed'], value: true }]);
+ expect(mock.api.slackAuthTest).not.toHaveBeenCalled(); expect(mock.control).toHaveBeenCalledExactlyOnceWith('start');
+ });
+ it('keeps failed repair drafts editable and cancel preserves credentials', async () => {
+ incompleteSlack(); mock.api.mutateConfig.mockRejectedValue(new Error('Platform apply failed'));
+ fireEvent.click(await setup()); fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));
+ fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.slackConfig.step2Title) }));
+ const input = await screen.findByPlaceholderText(en.slackConfig.botTokenPlaceholder);
+ fireEvent.change(input, { target: { value: 'xoxb-retained-draft' } });
+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));
+ await screen.findByText('Platform apply failed');
+ expect((input as HTMLInputElement).value).toBe('xoxb-retained-draft'); expect(screen.queryByTestId('destination')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
+ });
+ it('honors redacted credential markers and the WeChat runnable exception', async () => {
+ const config = incompleteSlack();
+ mock.api.getConfig.mockResolvedValue({ ...config, platforms: { enabled: ['slack', 'wechat'] }, slack: { has_bot_token: true, has_app_token: true }, wechat: {}, platform_catalog: [...config.platform_catalog, { id: 'wechat', credential_fields: ['bot_token'] }] });
+ fireEvent.click(await setup()); await screen.findByTestId('destination');
+ expect(mock.api.slackManifest).not.toHaveBeenCalled(); expect(mock.api.slackAuthTest).not.toHaveBeenCalled();
+ });
+});
+
+
+// AUTH-SETUP-120: Discord's existing form emits credential and auxiliary settings.
+describe('saved Discord recovery', () => {
+ async function repairDiscord() {
+ const config = { setup_completed: false, agents: { claude: { enabled: true } }, platforms: { enabled: ['discord'] }, platform_catalog: [{ id: 'discord', config_key: 'discord', credential_fields: ['bot_token'] }], discord: { bot_token: '', has_bot_token: false } };
+ mock.api.getConfig.mockResolvedValue(config);
+ mock.api.discordAuthTest.mockResolvedValue({ ok: true });
+ mock.api.discordGuilds.mockResolvedValue({ ok: true, guilds: [{ id: 'g-one', name: 'Guild One' }, { id: 'g-two', name: 'Guild Two' }] });
+ mock.api.mutateConfig.mockImplementation(async (changes) => {
+ if (changes[0].path[0] === 'discord') mock.api.getConfig.mockResolvedValue({ ...config, discord: { bot_token: '', has_bot_token: true } });
+ return {};
+ });
+ fireEvent.click(await setup());
+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.platformRepair }));
+ fireEvent.click(await screen.findByRole('button', { name: new RegExp(en.discordConfig.step4Title) }));
+ const input = await screen.findByPlaceholderText(en.discordConfig.botTokenPlaceholder);
+ fireEvent.change(input, { target: { value: 'fixture-discord-token' } });
+ fireEvent.click(screen.getByRole('button', { name: en.discordConfig.validateToken }));
+ await screen.findByRole('checkbox', { name: 'Guild One' });
+ return input;
+ }
+ it.each(['selected', 'cleared', 'unchanged', 'excluded'] as const)('persists only the intended guild selection (%s)', async (mode) => {
+ mock.manageAccess = mode !== 'excluded';
+ await repairDiscord();
+ if (mode === 'selected' || mode === 'cleared') fireEvent.click(screen.getByRole('checkbox', { name: 'Guild One' }));
+ if (mode === 'cleared') fireEvent.click(screen.getByRole('button', { name: en.discordConfig.clearGuilds }));
+ if (mode === 'excluded') expect(screen.getByRole('checkbox', { name: 'Guild One' }).hasAttribute('disabled')).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));
+ await screen.findByTestId('destination');
+ if (mode === 'selected' || mode === 'cleared') {
+ expect(mock.api.saveSettings).toHaveBeenCalledExactlyOnceWith({ guilds: mode === 'selected' ? { 'g-one': { enabled: true } } : {} }, 'discord');
+ expect(mock.api.saveSettings.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[1]);
+ } else expect(mock.api.saveSettings).not.toHaveBeenCalled();
+ expect(mock.api.mutateConfig.mock.calls[0][0]).toEqual([{ kind: 'set', path: ['discord', 'bot_token'], value: 'fixture-discord-token' }]);
+ });
+ it('retains selected guild and credential draft after partial save failure, then retries before completion', async () => {
+ const input = await repairDiscord();
+ fireEvent.click(screen.getByRole('checkbox', { name: 'Guild Two' }));
+ mock.api.saveSettings.mockRejectedValueOnce(new Error('Guild settings failed'));
+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));
+ await screen.findByText('Guild settings failed');
+ expect(screen.queryByTestId('destination')).toBeNull();
+ expect((screen.getByRole('checkbox', { name: 'Guild Two' }) as HTMLInputElement).checked).toBe(true);
+ expect((input as HTMLInputElement).value).toBe('fixture-discord-token');
+ expect(mock.api.mutateConfig).toHaveBeenCalledOnce();
+ fireEvent.click(screen.getByRole('button', { name: en.platform.apply }));
+ await screen.findByTestId('destination');
+ expect(mock.api.saveSettings).toHaveBeenCalledTimes(2);
+ expect(mock.api.saveSettings).toHaveBeenLastCalledWith({ guilds: { 'g-two': { enabled: true } } }, 'discord');
+ });
+ it('cancelled selection writes neither credentials nor settings', async () => {
+ await repairDiscord(); fireEvent.click(screen.getByRole('checkbox', { name: 'Guild One' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(mock.api.saveSettings).not.toHaveBeenCalled(); expect(mock.api.mutateConfig).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('destination')).toBeNull();
+ });
+});
diff --git a/ui/src/components/onboarding/onboarding.css b/ui/src/components/onboarding/onboarding.css
index 388b221bd..8b4117574 100644
--- a/ui/src/components/onboarding/onboarding.css
+++ b/ui/src/components/onboarding/onboarding.css
@@ -135,7 +135,7 @@
.onboarding-shell > header {
display: flex;
align-items: center;
- justify-content: flex-end;
+ justify-content: space-between;
flex-shrink: 0;
height: var(--ob-header-h);
max-width: var(--ob-content-w);
@@ -151,12 +151,8 @@
align-items: flex-start;
justify-content: center;
}
-/* The two steps are anchored differently because the design anchors them differently.
- JuwcG and KIxnF centre the welcome in their frame; IWQi6 tops the setup out at its
- own 64.5 padding. So the welcome's y is a RESULT of the window height — it is 65 at
- the design's own 756 content box and lower in a taller one — while the setup's is the
- position itself. Whichever is taller than the window scrolls from its top edge. */
-.onboarding-welcome { align-self: center; }
+/* Owner amendment, 2026-09-18: both steps share the same top anchor.
+ Normal flow scrolls on short windows; only the lower composition changes. */
.onboarding-welcome, .onboarding-setup {
display: flex;
flex-direction: column;
@@ -167,6 +163,8 @@
gap: 24px;
}
.onboarding-heading { text-align: center; width: 100%; }
+.onboarding-heading h1, .onboarding-heading h2 { min-height: 46px; }
+.onboarding-heading p { min-height: 22px; }
/* The live design's headline: 34/1.35/600 at -1.6 tracking (nodes XKQOx, Igagh and
hv9DA all agree), shared by the welcome and the setup title. */
.onboarding-heading h1, .onboarding-heading h2 {
@@ -541,7 +539,8 @@
/* Phones loosen rather than follow the proportion: -1.2 would be the 34/-1.6 ratio at
this size, and tight tracking is exactly what costs legibility on a small screen. */
.onboarding-heading h1, .onboarding-heading h2 { font-size: 25px; line-height: 1.4; letter-spacing: -0.8px; }
- .onboarding-heading p { font-size: 12px; line-height: 20px; }
+ .onboarding-heading h1, .onboarding-heading h2 { min-height: 70px; display: flex; align-items: flex-start; justify-content: center; }
+ .onboarding-heading p { min-height: 40px; font-size: 12px; line-height: 20px; }
.onboarding-welcome, .onboarding-setup { gap: 20px; }
.onboarding-collaboration-card { padding: 10px 8px; border-radius: 10px; }
/* The kind glyph stays: it is the one mark that says which of the three kinds of work
@@ -639,3 +638,7 @@
.onboarding-access-icon { transform: none !important; }
.onboarding-pulse-core, .onboarding-pulse-halo { stroke-dasharray: none; }
}
+
+.onboarding-model-recovery { width: 100%; padding: 20px; border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; gap: 16px; background: var(--surface); min-width: 0; }
+.onboarding-model-recovery h3 { font-size: 16px; font-weight: 600; }
+.onboarding-model-recovery p { font-size: 13px; color: var(--muted); overflow-wrap: anywhere; }
diff --git a/ui/src/components/onboarding/opencodeSetupRoutes.ts b/ui/src/components/onboarding/opencodeSetupRoutes.ts
new file mode 100644
index 000000000..b0cdbee16
--- /dev/null
+++ b/ui/src/components/onboarding/opencodeSetupRoutes.ts
@@ -0,0 +1,32 @@
+import type { ApiContextType } from '@/context/ApiContext';
+import { modelsApi } from '../settings/models/modelsApi';
+import { modelHubEnabledFromConfig } from '../settings/models/featureFlags';
+import { catalogModelIds } from '../settings/models/backendCatalog';
+
+/** Routing eligibility is separate from backend credential/application readiness. */
+export async function readOpencodeSetupRoutes(api: ApiContextType) {
+ const config = await api.getConfig();
+ if (modelHubEnabledFromConfig(config)) {
+ // Unlike a best-effort picker read, an unreadable active supply cannot
+ // silently become Direct mode during explicit setup completion.
+ const supply = await modelsApi.getAgentSources('opencode');
+ if (supply.mode === 'hub') {
+ const catalog = new Set(catalogModelIds(supply));
+ const supplied = new Set(supply.model_supply?.filter((row) => row.has_runnable_hop).map((row) => row.model_id));
+ return { mode: 'hub' as const, accepts: (model: string | null) => Boolean(model && catalog.has(model) && supplied.has(model)) };
+ }
+ }
+ const result = await api.getOpencodeProviders();
+ if (!result.ok) throw new Error(result.message);
+ const connected = new Map(result.providers?.filter((provider) => provider.active_auth_type === 'api' || provider.active_auth_type === 'oauth').map((provider) => [provider.id, new Set(provider.models || [])]));
+ return {
+ mode: 'direct' as const,
+ accepts: (model: string | null) => {
+ if (!model) return false;
+ const slash = model.indexOf('/');
+ const provider = slash >= 0 ? model.slice(0, slash) : result.default_provider;
+ const modelId = slash < 0 ? model : model.slice(slash + 1);
+ return Boolean(provider && modelId && connected.get(provider)?.has(modelId));
+ },
+ };
+}
diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsx
index abf831785..d3a642b3a 100644
--- a/ui/src/components/settings/BackendLifecycleChip.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.tsx
@@ -33,6 +33,7 @@ interface BackendLifecycleChipProps {
/** Setup describes executable availability separately from connection readiness. */
readyLabel?: string;
onChanged?: (info?: BackendChipChange) => void | Promise<void>;
+ onOperationChange?: (pending: boolean) => void;
}
// Map lifecycle visual states to canonical Badge variants from the design
@@ -96,6 +97,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
enabled,
cliStatus,
onChanged,
+ onOperationChange,
readyLabel,
}) => {
const { t } = useTranslation();
@@ -173,6 +175,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
const handleUpgrade = async () => {
setOperation('upgrading');
+ onOperationChange?.(true);
try {
const result = await api.installAgent(name);
if (result.ok) {
@@ -186,12 +189,14 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
} catch (e) {
showToast(String(e), 'error');
} finally {
+ onOperationChange?.(false);
if (isMountedRef.current) setOperation('idle');
}
};
const handleRestart = async () => {
setOperation('restarting');
+ onOperationChange?.(true);
try {
const result = await api.restartBackend(name);
showToast(
@@ -202,6 +207,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
} catch (e) {
showToast(String(e), 'error');
} finally {
+ onOperationChange?.(false);
if (isMountedRef.current) setOperation('idle');
}
};
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index b3c789d7c..f1c00ad4c 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -1,26 +1,18 @@
import React, { useEffect, useRef, useState } from 'react';
+import { useBackendOAuth } from './oauth/useBackendOAuth';
import { useTranslation } from 'react-i18next';
import { AlertTriangle, CheckCircle2, LogIn, Trash2, X } from 'lucide-react';
import { Button } from '../ui/button';
import { Label } from '../ui/label';
import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from './oauth/OAuthFlowParts';
-import { useApi } from '@/context/ApiContext';
-import type { OAuthWebState } from '@/context/ApiContext';
+import { useApi, type OAuthWebMutationResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
+import { surfaceBackendNotices } from './shared/surfaceBackendNotices';
import { errorMessage } from '@/lib/errorMessage';
type Backend = 'claude' | 'codex' | 'opencode';
-type LocalState = 'idle' | OAuthWebState;
-
-const POLL_INTERVAL_MS = 2000;
-// Stop polling 16 minutes in (matches AgentAuthService.setup_timeout_seconds
-// which gives the user 15 minutes to complete login). Anything still
-// polling past that has been abandoned and just burns the UI server's
-// background OAuth loop.
-const POLL_DEADLINE_MS = 16 * 60 * 1000;
-
export type BackendOAuthPanelProps = {
backend: Backend;
/** Required when ``backend === "opencode"``; the OpenCode daemon needs
@@ -49,7 +41,10 @@ export type BackendOAuthPanelProps = {
/** 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;
+ onSuccess?: () => void | Promise<void>;
+ onRemoved?: (result: OAuthWebMutationResult) => boolean | void | Promise<boolean | void>;
+ onFailure?: (error: string) => void | Promise<void>;
+ onCancel?: () => void;
/** Fires whenever the panel's internal flow is mid-handshake
* (``state`` ∈ {starting, awaiting_code, verifying}). The parent
* uses this to disable auth-mode switching: on iOS Safari the
@@ -83,179 +78,25 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
signedInDetail,
hideRemove,
onSuccess,
+ onRemoved,
+ onFailure,
+ onCancel,
onActiveChange,
}) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const [state, setState] = useState<LocalState>('idle');
- const [flowId, setFlowId] = useState<string | null>(null);
- const [url, setUrl] = useState<string | null>(null);
- const [deviceCode, setDeviceCode] = useState<string | null>(null);
- const [code, setCode] = useState('');
- const [submitting, setSubmitting] = useState(false);
- const [starting, setStarting] = useState(false);
+ const { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,
+ startFlow, cancelFlow, submitCallback, resetToIdle, copyUrl, copyDeviceCode, isActive } =
+ useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailure, onCancel, onActiveChange });
const [removing, setRemoving] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const pollTimer = useRef<number | null>(null);
- const pollDeadlineRef = useRef<number | null>(null);
- const onSuccessRef = useRef(onSuccess);
- onSuccessRef.current = onSuccess;
-
- const stopPolling = () => {
- if (pollTimer.current !== null) {
- window.clearTimeout(pollTimer.current);
- pollTimer.current = null;
- }
- pollDeadlineRef.current = null;
- };
-
- const resetToIdle = () => {
- stopPolling();
- setState('idle');
- setFlowId(null);
- setUrl(null);
- setDeviceCode(null);
- setCode('');
- setError(null);
- };
-
- // Broadcast in-progress flow state to the parent so it can lock the
- // auth-mode segmented radio. On iOS Safari the device-code "Copy" tap
- // was bouncing that radio mid-flow — we can't reproduce the exact
- // event path in code, but freezing the radio while in-flight makes
- // the bug impossible to trigger regardless of how the rogue event
- // gets there.
- const onActiveChangeRef = useRef(onActiveChange);
- onActiveChangeRef.current = onActiveChange;
+ const removalOwner = useRef({ mounted: true, busy: false });
useEffect(() => {
- const active = state === 'starting' || state === 'awaiting_code' || state === 'verifying';
- onActiveChangeRef.current?.(active);
- }, [state]);
-
- // Poll the status endpoint until the flow lands on a terminal state.
- // The server holds the flow alive across requests on its own event loop,
- // so dropping the timer on success/failure is safe — we'll never miss a
- // transition by stopping early.
- useEffect(() => {
- return () => stopPolling();
+ const owner = removalOwner.current; owner.mounted = true;
+ return () => { owner.mounted = false; };
}, []);
- const scheduleNextPoll = (currentFlowId: string) => {
- if (pollDeadlineRef.current !== null && Date.now() > pollDeadlineRef.current) {
- setError(t('settings.backends.oauthPollTimedOut') as string);
- setState('failed');
- stopPolling();
- return;
- }
- pollTimer.current = window.setTimeout(() => {
- void pollOnce(currentFlowId);
- }, POLL_INTERVAL_MS);
- };
-
- const pollOnce = async (currentFlowId: string) => {
- try {
- const data = await api.getOAuthWebStatus(backend, currentFlowId);
- if (!data.ok) {
- setError(data.error || 'flow_not_found');
- setState('failed');
- stopPolling();
- return;
- }
- if (data.url) setUrl(data.url);
- if (data.device_code) setDeviceCode(data.device_code);
- if (data.state) setState(data.state);
- if (data.state === 'success') {
- stopPolling();
- showToast(t('settings.backends.oauthSuccess'), 'success');
- onSuccessRef.current?.();
- return;
- }
- if (data.state === 'failed' || data.state === 'cancelled') {
- setError(data.error || (data.state === 'cancelled' ? 'cancelled' : 'unknown_failure'));
- stopPolling();
- return;
- }
- scheduleNextPoll(currentFlowId);
- } catch (err) {
- setError(errorMessage(err) || 'poll_failed');
- setState('failed');
- stopPolling();
- }
- };
-
- const startFlow = async () => {
- setStarting(true);
- setError(null);
- setCode('');
- try {
- const result =
- backend === 'opencode'
- ? await api.startOAuthWebForOpencodeProvider(opencodeProviderId || '', true)
- : await api.startOAuthWeb(backend, true);
- if (!result.ok || !result.flow_id) {
- setError(result.detail || result.error || 'start_failed');
- setState('failed');
- return;
- }
- setFlowId(result.flow_id);
- setUrl(result.url || null);
- setDeviceCode(result.device_code || null);
- setState(result.state || 'starting');
- pollDeadlineRef.current = Date.now() + POLL_DEADLINE_MS;
- scheduleNextPoll(result.flow_id);
- } catch (err) {
- setError(errorMessage(err) || 'start_failed');
- setState('failed');
- } finally {
- setStarting(false);
- }
- };
-
- const cancelFlow = async () => {
- if (!flowId) {
- resetToIdle();
- return;
- }
- stopPolling();
- try {
- await api.cancelOAuthWeb(backend, flowId);
- } catch {
- // Swallow — even if the cancel rountrip failed, the UI should still
- // return to the idle state so the user can retry without a stuck
- // panel. The server-side flow times out on its own at 900s.
- }
- resetToIdle();
- };
-
- const submitCallback = async () => {
- if (!flowId) return;
- const trimmed = code.trim();
- if (!trimmed) return;
- setSubmitting(true);
- setError(null);
- try {
- // Claude → ``code#state`` (Anthropic's callback fragment).
- // OpenCode browser-redirect → ``http://127.0.0.1:<port>/callback?...``
- // (the URL the provider redirected to). Both flow through the
- // same endpoint; the server side dispatches by backend type.
- const result = await api.submitOAuthWebCode(backend, flowId, trimmed);
- if (!result.ok) {
- setError(result.error || result.detail || 'submit_failed');
- return;
- }
- // Server transitioned the flow to "verifying"; reflect that locally
- // so the UI hides the code input immediately rather than waiting for
- // the next poll tick.
- setState('verifying');
- } catch (err) {
- setError(errorMessage(err) || 'submit_failed');
- } finally {
- setSubmitting(false);
- }
- };
-
const removeAuth = async () => {
if (backend === 'opencode') {
// OpenCode providers expose their own Remove-key affordance inline
@@ -263,13 +104,17 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
// the OAuth panel just shouldn't render this button there.
return;
}
+ if (removalOwner.current.busy) return;
+ removalOwner.current.busy = true;
setRemoving(true);
+ onActiveChange?.(true);
setError(null);
try {
const result =
backend === 'claude' && canRemoveAuth && !signedIn
? await api.removeClaudeOAuthCredentials()
: await api.removeBackendAuth(backend);
+ if (!removalOwner.current.mounted) return;
if (!result.ok) {
showToast(
t('settings.backends.oauthRemoveFailed', {
@@ -277,68 +122,39 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
}),
'error',
);
+ await onRemoved?.(result);
return;
}
resetToIdle();
+ onActiveChange?.(true);
+ if (result.notices) surfaceBackendNotices(result.notices, showToast, t);
+ // Report partial persistence before readback can change the effective mode
+ // and unmount this panel. The parent owns subsequent application errors.
if (result.partial) {
- // V2Config got cleared, but the CLI logout subprocess failed —
- // credentials may still live on disk. Surface a warning toast
- // with the detail so the user knows to investigate (e.g.
- // ``codex logout`` returning "Not logged in" is harmless;
- // a real failure means the user has to run logout manually).
- showToast(
- t('settings.backends.oauthRemovePartial', {
- detail: result.detail || result.warning || 'logout_failed',
- }),
- 'warning',
- );
- } else {
+ showToast(t('settings.backends.oauthRemovePartial', {
+ detail: result.detail || result.warning || 'logout_failed',
+ }), 'warning');
+ }
+ const observed = onRemoved ? await onRemoved(result) : await onSuccess?.();
+ if (!removalOwner.current.mounted) return;
+ if (result.restart?.ok === false) {
+ setError(result.restart.message || t('onboarding.connection.applyFailed'));
+ } else if (!result.partial && observed !== false) {
showToast(t('settings.backends.oauthRemoved'), 'success');
}
- onSuccessRef.current?.();
} catch (err) {
+ if (!removalOwner.current.mounted) return;
showToast(
t('settings.backends.oauthRemoveFailed', { detail: errorMessage(err) || 'unknown' }),
'error',
);
+ await onRemoved?.({ ok: false, error: errorMessage(err) || 'unknown' });
} finally {
- setRemoving(false);
- }
- };
-
- const copyUrl = async (e?: React.MouseEvent) => {
- // Defensively stop the click from bubbling. If a parent had an
- // accidental form / radio handler, copying the URL must never
- // also trigger a tab switch or a save.
- e?.preventDefault();
- e?.stopPropagation();
- if (!url) return;
- try {
- await navigator.clipboard.writeText(url);
- showToast(t('settings.backends.oauthUrlCopied'), 'success');
- } catch {
- showToast(t('common.copyFailed'), 'error');
- }
- };
-
- const copyDeviceCode = async (e?: React.MouseEvent) => {
- // Same defensive bubble-stop as copyUrl. Reported symptom: clicking
- // "Copy" on the Codex device code in Settings was bouncing the auth-
- // mode segmented radio from OAuth to API Key, interrupting the
- // login flow. Without seeing a repro path in code, guard the
- // click here so the side effect can't survive in any browser.
- e?.preventDefault();
- e?.stopPropagation();
- if (!deviceCode) return;
- try {
- await navigator.clipboard.writeText(deviceCode);
- showToast(t('settings.backends.oauthDeviceCodeCopied'), 'success');
- } catch {
- showToast(t('common.copyFailed'), 'error');
+ removalOwner.current.busy = false;
+ if (removalOwner.current.mounted) { setRemoving(false); onActiveChange?.(false); }
}
};
- const isActive = state !== 'idle' && state !== 'success' && state !== 'failed' && state !== 'cancelled';
const showStartButton = state === 'idle' || state === 'success' || state === 'failed' || state === 'cancelled';
const claudeAwaitingCode = backend === 'claude' && state === 'awaiting_code';
// OpenCode browser-redirect providers (poe, gitlab, openai-browser)
@@ -348,7 +164,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
// their browser landed on; the backend replays it from inside the
// container so OpenCode's listener consumes it.
const opencodeAwaitingCallback =
- backend === 'opencode' && state === 'awaiting_code' && url && !deviceCode;
+ backend === 'opencode' && state === 'awaiting_code' && (callbackKind === 'code' || callbackKind === 'redirect' || (!callbackKind && url && !deviceCode));
// OpenCode device flows (openai headless, github-copilot) carry the
// user-facing code in the same payload as Codex; reuse the same UI
// affordance. Browser-redirect flows (gitlab, poe, openai browser)
@@ -364,7 +180,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
if (backend === 'codex') return t('settings.backends.codexSignInButton');
return t('settings.backends.opencodeProviderSignIn');
})();
- const showRemoveAuth = (canRemoveAuth ?? signedIn) || state === 'success';
+ const showRemoveAuth = canRemoveAuth ?? (signedIn || state === 'success');
const removeLabel =
backend === 'claude' && canRemoveAuth && !signedIn
? t('settings.backends.oauthCleanStoredCredentials')
@@ -395,7 +211,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
</div>
)}
- {state === 'success' && (
+ {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>
@@ -472,7 +288,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
{opencodeAwaitingCallback && (
<div className="flex flex-col gap-2">
<Label htmlFor={`oauth-code-${backend}`} className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.opencodeCallbackUrlLabel')}
+ {t(callbackKind === 'code' ? 'onboarding.connection.manualCode' : 'settings.backends.opencodeCallbackUrlLabel')}
</Label>
<OAuthSubmitRow
id={`oauth-code-${backend}`}
@@ -480,12 +296,12 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
onChange={setCode}
onSubmit={() => void submitCallback()}
submitting={submitting}
- placeholder="http://127.0.0.1:..../callback?code=..."
+ placeholder={callbackKind === 'code' ? t('onboarding.connection.manualCodePlaceholder') : 'http://127.0.0.1:..../callback?code=...'}
submitLabel={t('common.submit') as string}
submittingLabel={t('common.submitting') as string}
/>
<p className="text-[12px] leading-relaxed text-muted">
- {t('settings.backends.opencodeCallbackUrlHint')}
+ {t(callbackKind === 'code' ? 'onboarding.connection.manualCodeHint' : 'settings.backends.opencodeCallbackUrlHint')}
</p>
</div>
)}
diff --git a/ui/src/components/settings/PlatformConfigEmbed.tsx b/ui/src/components/settings/PlatformConfigEmbed.tsx
new file mode 100644
index 000000000..a0eb84bf2
--- /dev/null
+++ b/ui/src/components/settings/PlatformConfigEmbed.tsx
@@ -0,0 +1,40 @@
+import type React from 'react';
+import { SlackConfig } from '@/components/steps/SlackConfig';
+import { DiscordConfig } from '@/components/steps/DiscordConfig';
+import { TelegramConfig } from '@/components/steps/TelegramConfig';
+import { LarkConfig } from '@/components/steps/LarkConfig';
+import { WeChatConfig } from '@/components/steps/WeChatConfig';
+
+export const PlatformConfigEmbed: React.FC<{
+ platform: string;
+ config: Record<string, unknown>;
+ onApply: (data: Record<string, unknown>) => Promise<void>;
+ onCancel: () => void;
+}> = ({ platform, config, onApply, onCancel }) => {
+ const noopNext = () => {};
+ if (platform === 'slack') {
+ return <SlackConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
+ }
+ if (platform === 'discord') {
+ return <DiscordConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
+ }
+ if (platform === 'telegram') {
+ return <TelegramConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
+ }
+ if (platform === 'lark') {
+ return <LarkConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
+ }
+ if (platform === 'wechat') {
+ return (
+ <WeChatConfig
+ data={config}
+ onNext={noopNext}
+ embedded
+ onApply={onApply}
+ onCancel={onCancel}
+ autoStartLogin={false}
+ />
+ );
+ }
+ return null;
+};
diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsx
index 971ec8a7c..6ba89d39d 100644
--- a/ui/src/components/settings/SettingsPlatformsPage.tsx
+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx
@@ -19,11 +19,8 @@ import {
platformHasRunnableConfig,
} from '@/lib/platforms';
import { PlatformIcon } from '@/components/visual';
-import { SlackConfig } from '@/components/steps/SlackConfig';
-import { DiscordConfig } from '@/components/steps/DiscordConfig';
-import { TelegramConfig } from '@/components/steps/TelegramConfig';
-import { LarkConfig } from '@/components/steps/LarkConfig';
-import { WeChatConfig } from '@/components/steps/WeChatConfig';
+import { PlatformConfigEmbed } from './PlatformConfigEmbed';
+import { savePlatformSettings } from './shared/savePlatformSettings';
import { SettingsPageShell } from './SettingsPageShell';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
@@ -97,21 +94,6 @@ export const SettingsPlatformsPage: React.FC = () => {
return savedConfig;
};
- const savePlatformSettings = async (platform: string, nextData: any) => {
- const discordGuildAllowlist = nextData?.discordGuildAllowlist;
- if (
- canManageAccessMembers && platform === 'discord' &&
- Array.isArray(discordGuildAllowlist) &&
- (discordGuildAllowlist.length > 0 || nextData?.discordGuildAllowlistTouched === true)
- ) {
- await api.saveSettings({
- guilds: Object.fromEntries(
- discordGuildAllowlist.map((guildId: string) => [guildId, { enabled: true }])
- ),
- }, 'discord');
- }
- };
-
// Persist the enabled set. ``primary`` is intentionally omitted:
// the backend normalizes it from ``enabled`` (first enabled, or the workbench
// when empty), so the UI never chooses or sends one.
@@ -224,7 +206,7 @@ export const SettingsPlatformsPage: React.FC = () => {
showToast(t('common.saveFailed'), 'error');
return;
}
- await savePlatformSettings(platform, nextData);
+ await savePlatformSettings(api, platform, nextData, canManageAccessMembers);
const runnable = platformHasRunnableConfig(savedConfig, platform);
if (!wasEnabled && !runnable) {
// Saved credentials but they are incomplete — keep the card open so the
@@ -492,37 +474,3 @@ const PlatformCard: React.FC<{
</section>
);
};
-
-const PlatformConfigEmbed: React.FC<{
- platform: string;
- config: any;
- onApply: (data: any) => Promise<void>;
- onCancel: () => void;
-}> = ({ platform, config, onApply, onCancel }) => {
- const noopNext = () => {};
- if (platform === 'slack') {
- return <SlackConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
- }
- if (platform === 'discord') {
- return <DiscordConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
- }
- if (platform === 'telegram') {
- return <TelegramConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
- }
- if (platform === 'lark') {
- return <LarkConfig data={config} onNext={noopNext} embedded onApply={onApply} onCancel={onCancel} />;
- }
- if (platform === 'wechat') {
- return (
- <WeChatConfig
- data={config}
- onNext={noopNext}
- embedded
- onApply={onApply}
- onCancel={onCancel}
- autoStartLogin={false}
- />
- );
- }
- return null;
-};
diff --git a/ui/src/components/settings/oauth/useBackendOAuth.ts b/ui/src/components/settings/oauth/useBackendOAuth.ts
new file mode 100644
index 000000000..131b6fa07
--- /dev/null
+++ b/ui/src/components/settings/oauth/useBackendOAuth.ts
@@ -0,0 +1,200 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useApi, type OAuthWebStartResult, type OAuthWebState } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
+import { errorMessage } from '@/lib/errorMessage';
+
+export type OAuthBackend = 'claude' | 'codex' | 'opencode';
+const POLL_INTERVAL_MS = 2000;
+const POLL_DEADLINE_MS = 16 * 60 * 1000;
+
+/** One owner for Settings and onboarding: invalidation precedes cancellation. */
+export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailure, onCancel, onActiveChange, onPendingChange }: {
+ backend: OAuthBackend;
+ opencodeProviderId?: string;
+ onSuccess?: () => 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. */
+ onCancel?: () => void;
+ onActiveChange?: (active: boolean) => void;
+ onPendingChange?: (pending: boolean) => void;
+}) {
+ const api = useApi();
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const [state, setState] = useState<'idle' | OAuthWebState>('idle');
+ const [url, setUrl] = useState<string | null>(null);
+ const [deviceCode, setDeviceCode] = useState<string | null>(null);
+ const [callbackKind, setCallbackKind] = useState<OAuthWebStartResult['callback_kind']>(null);
+ const [code, setCode] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+ const [starting, setStarting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const owner = useRef({ generation: 0, mounted: true, flowId: '', busy: false, submitting: false, deadline: 0 });
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const callbacks = useRef({ onSuccess, onFailure, onCancel, onActiveChange, onPendingChange });
+ callbacks.current = { onSuccess, onFailure, onCancel, onActiveChange, onPendingChange };
+ const pending = useRef(new Set<number>());
+ const settled = useCallback((generation: number) => {
+ if (pending.current.delete(generation)) {
+ const remaining = pending.current.size > 0;
+ callbacks.current.onPendingChange?.(remaining);
+ if (!remaining && owner.current.mounted) {
+ owner.current.busy = false;
+ setStarting(false);
+ callbacks.current.onActiveChange?.(false);
+ }
+ }
+ }, []);
+ const current = (generation: number) => owner.current.mounted && owner.current.generation === generation;
+ const stopPolling = () => { clearTimeout(timer.current); timer.current = undefined; };
+ const cancelRemote = useCallback(async (id: string) => {
+ try {
+ const result = await api.cancelOAuthWeb(backend, id);
+ if (!result.ok && result.error !== 'flow_not_found') throw new Error(result.detail || result.error);
+ } catch (err) {
+ // Keep a cancellation failure observable, including after the dialog closes.
+ showToast(errorMessage(err) || t('settings.backends.oauthFailed', { detail: 'cancel_failed' }), 'warning');
+ }
+ }, [api, backend, showToast, t]);
+ useEffect(() => {
+ owner.current.mounted = true;
+ const lifetime = owner.current;
+ return () => {
+ lifetime.mounted = false;
+ const generation = lifetime.generation++;
+ clearTimeout(timer.current);
+ if (lifetime.flowId) void cancelRemote(lifetime.flowId).finally(() => settled(generation));
+ // A pending start owns its settlement until its returned flow is cancelled.
+ lifetime.flowId = '';
+ lifetime.busy = false;
+ callbacks.current.onActiveChange?.(false);
+ };
+ }, [cancelRemote, opencodeProviderId, settled]);
+
+ const resetToIdle = () => {
+ stopPolling();
+ owner.current.generation += 1;
+ owner.current.flowId = '';
+ owner.current.busy = false;
+ owner.current.submitting = false;
+ setState('idle'); setUrl(null); setDeviceCode(null); setCode(''); setError(null);
+ setStarting(false); setSubmitting(false);
+ callbacks.current.onActiveChange?.(false);
+ };
+ const accept = async (data: OAuthWebStartResult, generation: number) => {
+ if (!current(generation)) return;
+ if (!data.ok) 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') {
+ stopPolling();
+ // The success consumer must re-read effective auth/application before the
+ // presentation can claim success. It may reject while application fails.
+ setState('verifying');
+ await callbacks.current.onSuccess?.();
+ if (!current(generation)) return;
+ owner.current.flowId = '';
+ owner.current.busy = false;
+ settled(generation);
+ setState('success');
+ callbacks.current.onActiveChange?.(false);
+ return;
+ }
+ if (data.state === 'failed' || data.state === 'cancelled') {
+ if (data.state === 'failed') await callbacks.current.onFailure?.(data.error || data.state);
+ if (!current(generation)) return;
+ throw new Error(data.error || data.state);
+ }
+ setState(data.state || 'starting');
+ if (Date.now() > owner.current.deadline) throw new Error(t('settings.backends.oauthPollTimedOut'));
+ timer.current = setTimeout(() => { void poll(generation); }, POLL_INTERVAL_MS);
+ };
+ const fail = (err: unknown, generation: number) => {
+ if (!current(generation)) return;
+ stopPolling();
+ setError(errorMessage(err) || 'auth_failed'); setState('failed');
+ // Cancel a failed local polling attempt as well; it must not finish later
+ // behind a newly selected method. Server cancellation never logs out.
+ const id = owner.current.flowId;
+ owner.current.flowId = '';
+ // Keep method/key writes locked until server cancellation settles.
+ if (id) void cancelRemote(id).finally(() => settled(generation));
+ else settled(generation);
+ };
+ const poll = async (generation: number) => {
+ if (!current(generation)) return;
+ try {
+ const result = await api.getOAuthWebStatus(backend, owner.current.flowId);
+ await accept({ ...result, error: result.error || undefined }, generation);
+ } catch (err) { fail(err, generation); }
+ };
+ const startFlow = async () => {
+ if (owner.current.busy || pending.current.size > 0) return;
+ const generation = ++owner.current.generation;
+ pending.current.add(generation);
+ callbacks.current.onPendingChange?.(true);
+ owner.current.busy = true;
+ owner.current.deadline = Date.now() + POLL_DEADLINE_MS;
+ setStarting(true); setState('starting'); setError(null); setCode(''); setUrl(null); setDeviceCode(null); setCallbackKind(null);
+ callbacks.current.onActiveChange?.(true);
+ try {
+ const result = backend === 'opencode'
+ ? await api.startOAuthWebForOpencodeProvider(opencodeProviderId || '', false)
+ : await api.startOAuthWeb(backend, false);
+ if (!current(generation)) {
+ if (result.flow_id) await cancelRemote(result.flow_id);
+ settled(generation);
+ return;
+ }
+ owner.current.flowId = result.flow_id || '';
+ if (!result.flow_id) throw new Error(result.detail || result.error || 'start_failed');
+ await accept(result, generation);
+ } catch (err) { if (current(generation)) fail(err, generation); else settled(generation); }
+ finally { if (current(generation)) setStarting(false); }
+ };
+ const cancelFlow = async () => {
+ callbacks.current.onCancel?.();
+ const id = owner.current.flowId;
+ const generation = owner.current.generation;
+ resetToIdle();
+ if (pending.current.size > 0) {
+ owner.current.busy = true; setStarting(true);
+ callbacks.current.onActiveChange?.(true);
+ }
+ if (id) {
+ owner.current.busy = true;
+ setStarting(true);
+ await cancelRemote(id);
+ settled(generation);
+ owner.current.busy = false;
+ if (owner.current.mounted) setStarting(false);
+ }
+ };
+ const submitCallback = async () => {
+ if (!owner.current.flowId || owner.current.submitting || !code.trim()) return;
+ const generation = owner.current.generation;
+ owner.current.submitting = true; setSubmitting(true); setError(null);
+ try {
+ const result = await api.submitOAuthWebCode(backend, owner.current.flowId, code.trim());
+ if (!current(generation)) return;
+ if (!result.ok) throw new Error(result.detail || result.error || 'submit_failed');
+ setState('verifying');
+ } catch (err) { if (current(generation)) setError(errorMessage(err) || 'submit_failed'); }
+ finally {
+ if (current(generation)) { owner.current.submitting = false; setSubmitting(false); }
+ }
+ };
+ const copy = async (text: string | null, event?: React.MouseEvent) => {
+ event?.preventDefault(); event?.stopPropagation();
+ if (!text) return;
+ try { await navigator.clipboard.writeText(text); showToast(t('common.copied'), 'success'); }
+ catch { showToast(t('common.copyFailed'), 'error'); }
+ };
+ const isActive = state === 'starting' || state === 'awaiting_code' || state === 'verifying';
+ return { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,
+ isActive, startFlow, cancelFlow, submitCallback, resetToIdle,
+ copyUrl: (e?: React.MouseEvent) => copy(url, e), copyDeviceCode: (e?: React.MouseEvent) => copy(deviceCode, e) };
+}
diff --git a/ui/src/components/settings/providers/BackendConnectionForm.tsx b/ui/src/components/settings/providers/BackendConnectionForm.tsx
new file mode 100644
index 000000000..ed90384b5
--- /dev/null
+++ b/ui/src/components/settings/providers/BackendConnectionForm.tsx
@@ -0,0 +1,282 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { CheckCircle2, ExternalLink, Eye, EyeOff, KeyRound, LoaderCircle, Pencil } from 'lucide-react';
+import { useApi, type ClaudeAuthState, type CodexAuthState, type OpencodeProvider, type OAuthWebMutationResult } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
+import { errorMessage } from '@/lib/errorMessage';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { SegmentedRadio } from '../shared/SegmentedRadio';
+import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';
+import { useBackendOAuth, type OAuthBackend } from '../oauth/useBackendOAuth';
+import { BackendOAuthPanel } from '../BackendOAuthPanel';
+import { OAuthDeviceCodeRow, OAuthLinkRow } from '../oauth/OAuthFlowParts';
+import './connection.css';
+
+type Method = 'oauth' | 'api_key';
+type NativeState = ClaudeAuthState | CodexAuthState;
+export type ConnectionHeading = { method: Method; active: boolean; credential: 'api_key' | 'auth_token' };
+
+/** Settings and onboarding share persistence, validation, effective readback and cancellation. */
+export function BackendConnectionForm({ backend, provider, initialMethod = 'oauth', compact = false,
+ onConnected, onCancel, onHeading, onBusyChange, onWriteState, connectionRevision = 0 }: {
+ backend: OAuthBackend;
+ provider?: OpencodeProvider;
+ initialMethod?: Method;
+ compact?: boolean;
+ /** Runtime mutation settlement: refresh observations without replacing input drafts. */
+ connectionRevision?: number;
+ onConnected?: () => void | Promise<void>;
+ onCancel?: () => void;
+ onHeading?: (heading: ConnectionHeading) => void;
+ onBusyChange?: (busy: boolean) => void;
+ onWriteState?: (pending: boolean) => void;
+}) {
+ const api = useApi();
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+ const [native, setNative] = useState<NativeState | null>(null);
+ const [currentProvider, setCurrentProvider] = useState(provider);
+ const [method, setMethod] = useState<Method>(backend === 'opencode' && !provider?.oauth_available ? 'api_key' : initialMethod);
+ const [credential, setCredential] = useState<'api_key' | 'auth_token'>('api_key');
+ const [key, setKey] = useState('');
+ const [editing, setEditing] = useState(false);
+ const [reveal, setReveal] = useState(false);
+ const [baseUrl, setBaseUrl] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const [connected, setConnected] = useState(false);
+ const [savedDisabled, setSavedDisabled] = useState(false);
+ const [active, setActive] = useState(false);
+ const [applyPending, setApplyPending] = useState(false);
+ const [authReadable, setAuthReadable] = useState(false);
+ const observation = useRef(0);
+ const draftTouched = useRef(false);
+ const pendingConfirmation = useRef<Method | null>(null);
+ const writeState = useRef(onWriteState); writeState.current = onWriteState;
+ const lifetime = useRef({ mounted: true, busy: false });
+ const onConnectedRef = useRef(onConnected); onConnectedRef.current = onConnected;
+ useEffect(() => {
+ const owner = lifetime.current; owner.mounted = true;
+ return () => { owner.mounted = false; observation.current += 1; };
+ }, []);
+ const read = useCallback(async () => {
+ if (backend === 'opencode') {
+ const result = await api.getOpencodeProviders();
+ if (!result.ok) throw new Error(result.message || t('onboarding.connection.readFailed'));
+ const fresh = result.providers?.find((entry) => entry.id === provider?.id);
+ if (!fresh) throw new Error(t('onboarding.connection.readFailed'));
+ return { provider: fresh, native: null };
+ }
+ const fresh = await (backend === 'claude' ? api.getClaudeAuth() : api.getCodexAuth());
+ if (!fresh.ok) throw new Error(fresh.message || t('onboarding.connection.readFailed'));
+ return { native: fresh, provider: undefined };
+ }, [api, backend, provider?.id, t]);
+ // Native persistence and controller application are independent observations.
+ // A failed IPC read must not discard a successful post-commit credential read.
+ const observe = useCallback(async ({ expectedMethod, receiptError = '' }: {
+ expectedMethod?: Method; receiptError?: string;
+ } = {}) => {
+ const token = ++observation.current;
+ const current = () => lifetime.current.mounted && token === observation.current;
+ setConnected(false); setSavedDisabled(false); setError(receiptError);
+ const nativeRead = read().then((fresh) => {
+ if (current()) {
+ setNative(fresh.native); setCurrentProvider(fresh.provider); setAuthReadable(true);
+ if (!draftTouched.current) {
+ setBaseUrl(fresh.native?.base_url || fresh.provider?.base_url || '');
+ if (fresh.native && 'credential_type' in fresh.native) setCredential(fresh.native.credential_type || 'api_key');
+ }
+ if (!compact && !draftTouched.current) {
+ const effective = 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);
+ }
+ }
+ return fresh;
+ }, (cause: unknown) => {
+ if (current()) setAuthReadable(false);
+ throw cause;
+ });
+ const [auth, application] = await Promise.allSettled([nativeRead, api.getBackendConnection(backend)]);
+ if (!current()) return false;
+ setLoading(false);
+ const messages = receiptError ? [receiptError] : [];
+ const connection = application.status === 'fulfilled' ? application.value : null;
+ const applied = connection?.ok && ['applied', 'stopped'].includes(connection.application);
+ if (!applied) messages.push(application.status === 'rejected' ? errorMessage(application.reason) || t('onboarding.connection.readFailed') : connection?.message || t('onboarding.connection.applyPending'));
+ let hasAuth = false;
+ let keylessSettings = false;
+ if (auth.status === 'rejected') messages.push(errorMessage(auth.reason) || t('onboarding.connection.readFailed'));
+ 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;
+ keylessSettings = !compact && Boolean(fresh.provider?.custom && fresh.provider.configured && effective === 'none');
+ if (expectedMethod && ((!keylessSettings && effective !== expectedMethod) || uncertain)) 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));
+ setSavedDisabled(confirmed && hasAuth && connection?.enabled === false && !keylessSettings);
+ return confirmed;
+ }, [read, api, backend, compact, provider?.oauth_available, initialMethod, t]);
+ useEffect(() => {
+ void observe();
+ return () => { observation.current += 1; };
+ }, [observe]);
+ const observedRevision = useRef(connectionRevision);
+ useEffect(() => {
+ if (observedRevision.current === connectionRevision) return;
+ observedRevision.current = connectionRevision;
+ void observe();
+ return () => { observation.current += 1; };
+ }, [connectionRevision, observe]);
+
+ const confirm = async (expectedMethod: Method = method, receiptError = '') => {
+ pendingConfirmation.current = expectedMethod;
+ if (!await observe({ expectedMethod, receiptError })) return false;
+ pendingConfirmation.current = null;
+ setKey(''); setEditing(false); draftTouched.current = false;
+ await onConnectedRef.current?.();
+ return true;
+ };
+ const confirmOAuth = async () => {
+ if (!await confirm('oauth')) throw new Error(t('onboarding.connection.applyPending'));
+ };
+ const observeOAuthFailure = async (receiptError: string) => {
+ pendingConfirmation.current = 'oauth';
+ await observe({ receiptError });
+ };
+ const oauth = useBackendOAuth({ backend, opencodeProviderId: provider?.id, onSuccess: confirmOAuth,
+ onFailure: observeOAuthFailure, onCancel: () => { pendingConfirmation.current = null; observation.current += 1; }, onActiveChange: setActive, onPendingChange: onWriteState });
+ const refresh = async () => {
+ const expected = pendingConfirmation.current;
+ if (expected) await confirm(expected);
+ else await observe();
+ };
+ const removed = async (result: OAuthWebMutationResult) => {
+ pendingConfirmation.current = null;
+ return observe({ receiptError: !result.ok ? result.error || result.detail || t('onboarding.connection.saveFailed')
+ : result.restart?.ok === false ? result.restart.message || t('onboarding.connection.applyFailed') : '' });
+ };
+ const busy = saving || active;
+ useEffect(() => { onBusyChange?.(busy); }, [busy, onBusyChange]);
+ useEffect(() => { onHeading?.({ method, active, credential }); }, [method, active, credential, onHeading]);
+ const hasKey = authReadable && (backend === 'opencode' ? Boolean(currentProvider?.api_key_masked) : Boolean(native?.has_api_key));
+ 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 urlValid = (() => {
+ if (!baseUrl.trim()) return !provider?.custom;
+ try { const url = new URL(baseUrl.trim()); return ['http:', 'https:'].includes(url.protocol) && Boolean(url.hostname); }
+ catch { return false; }
+ })();
+ const canSave = !loading && authReadable && !busy && urlValid && Boolean(key.trim() || (hasKey && !editing) || (!compact && currentProvider?.custom && currentProvider.configured && !editing));
+ const save = async () => {
+ if (!canSave || lifetime.current.busy) return;
+ lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false);
+ try {
+ const payload = { auth_mode: 'api_key' as const, api_key: key.trim() || undefined, base_url: baseUrl.trim() || null };
+ const result = backend === 'claude' ? await api.saveClaudeAuth({ ...payload, credential_type: credential })
+ : backend === 'codex' ? await api.saveCodexAuth(payload)
+ : await api.setOpencodeProviderAuth(provider!.id, payload.api_key, payload.base_url);
+ if (!lifetime.current.mounted) return;
+ if (!result.ok) throw new Error(result.message || t('onboarding.connection.saveFailed'));
+ if ('notices' in result) surfaceBackendNotices(result.notices, showToast, t);
+ if ('partial' in result && result.partial) showToast(result.detail || result.warning || t('onboarding.connection.partial'), 'warning');
+ await confirm('api_key', result.restart?.ok === false ? result.restart.message || t('onboarding.connection.applyFailed') : '');
+ } catch (err) {
+ if (lifetime.current.mounted) {
+ pendingConfirmation.current = 'api_key';
+ await observe({ receiptError: errorMessage(err) || t('onboarding.connection.saveFailed') });
+ }
+ }
+ finally { lifetime.current.busy = false; writeState.current?.(false); if (lifetime.current.mounted) setSaving(false); }
+ };
+ const remove = async (onlyKey: boolean) => {
+ if (lifetime.current.busy || !window.confirm(t('onboarding.connection.removeConfirm'))) return;
+ lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false);
+ try {
+ const result = backend === 'opencode' ? await api.deleteOpencodeProviderAuth(provider!.id)
+ : onlyKey ? await api.removeBackendApiKey(backend) : await api.removeBackendAuth(backend);
+ if (!lifetime.current.mounted) return;
+ if (!result.ok) throw new Error(('message' in result ? result.message : 'detail' in result ? result.detail : undefined) || t('onboarding.connection.saveFailed'));
+ if ('notices' in result) surfaceBackendNotices(result.notices, showToast, t);
+ await removed(result);
+ } catch (err) {
+ if (lifetime.current.mounted) {
+ pendingConfirmation.current = null;
+ await observe({ receiptError: errorMessage(err) || t('onboarding.connection.readFailed') });
+ }
+ }
+ finally { lifetime.current.busy = false; writeState.current?.(false); if (lifetime.current.mounted) setSaving(false); }
+ };
+ const prefix = backend === 'claude' ? 'claude' : backend === 'codex' ? 'codex' : 'opencode';
+ const title = backend === 'claude' ? t('onboarding.connection.claudeAccount') : backend === 'codex' ? t('onboarding.connection.codexAccount') : provider?.name || '';
+ const hint = backend === 'claude' ? t('onboarding.connection.claudeHint') : t('onboarding.connection.deviceHint');
+ const needsCode = oauth.state === 'awaiting_code' && (backend === 'claude' || (backend === 'opencode' && (oauth.callbackKind === 'code' || oauth.callbackKind === 'redirect' || (!oauth.callbackKind && Boolean(oauth.url) && !oauth.deviceCode))));
+ const apiKeyLabel = t(compact || backend !== 'claude' ? 'onboarding.connection.apiKeyLabel' : 'settings.backends.claudeCredentialTypeApiKey');
+ const tokenLabel = t(compact ? 'onboarding.connection.authTokenLabel' : 'settings.backends.claudeCredentialTypeAuthToken');
+ const credentialLabel = t(compact ? 'onboarding.connection.credentialType' : 'settings.backends.claudeCredentialTypeLabel');
+ const secretLabel = credential === 'auth_token' && backend === 'claude' ? tokenLabel : apiKeyLabel;
+ const startLabel = backend === 'claude' ? t('onboarding.connection.claudeSignIn') : backend === 'codex' ? t('onboarding.connection.codexSignIn') : t('settings.backends.opencodeProviderSignIn');
+ if (loading) return <div className="connection-loading" role="status"><LoaderCircle className="animate-spin" size={16} />{t('common.loading')}</div>;
+ return <div className="backend-connection-form">
+ {!(compact && active && backend !== 'codex') && (backend !== 'opencode' || (!compact && provider?.oauth_available)) && <SegmentedRadio
+ value={method} onChange={(value) => { if (!busy) { pendingConfirmation.current = null; draftTouched.current = true; setMethod(value); setError(''); setConnected(false); } }} disabled={busy}
+ 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 }]} />}
+ {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>}
+ {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))}
+ 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.error && <p className="connection-error" role="alert">{oauth.error}</p>}
+ {!oauth.isActive ? <div className="connection-account"><h3>{title}</h3><p>{hint}</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">
+ {oauth.deviceCode && <><Label>{t('onboarding.connection.copyDevice')}</Label><OAuthDeviceCodeRow code={oauth.deviceCode} onCopy={(event) => void oauth.copyDeviceCode(event)} copyLabel={t('common.copy')} /></>}
+ {oauth.url && <><Label>{t(oauth.deviceCode ? 'onboarding.connection.openDevice' : 'onboarding.connection.authorizeBrowser')}</Label><OAuthLinkRow url={oauth.url} onCopy={(event) => void oauth.copyUrl(event)} copyLabel={t('common.copy')} /></>}
+ {oauth.deviceCode && oauth.url && <div><Button variant="brand" asChild><a href={oauth.url} target="_blank" rel="noopener noreferrer"><ExternalLink size={15} />{t(backend === 'codex' ? 'onboarding.connection.openChatGPT' : 'onboarding.connection.openProvider')}</a></Button></div>}
+ {needsCode && <div className="connection-field"><Label htmlFor="connection-code">{t(backend === 'claude' ? 'settings.backends.claudeCallbackCodeLabel' : oauth.callbackKind === 'code' ? 'onboarding.connection.manualCode' : 'settings.backends.opencodeCallbackUrlLabel')}</Label>
+ <Input id="connection-code" value={oauth.code} onChange={(event) => oauth.setCode(event.target.value)} disabled={oauth.submitting} placeholder={backend === 'claude' ? 'code#state' : oauth.callbackKind === 'code' ? t('onboarding.connection.manualCodePlaceholder') : 'http://127.0.0.1:…/callback?code=…'} autoComplete="off" />
+ <p>{t(backend === 'claude' ? 'onboarding.connection.codeHint' : oauth.callbackKind === 'code' ? 'onboarding.connection.manualCodeHint' : 'settings.backends.opencodeCallbackUrlHint')}</p></div>}
+ <p className="connection-waiting" role="status"><LoaderCircle size={15} className="motion-safe:animate-spin" />{t(oauth.state === 'starting' ? 'settings.backends.oauthStarting' : oauth.state === 'verifying' ? 'settings.backends.oauthVerifying' : 'onboarding.connection.waiting')}</p>
+ </div>}
+ </>)}
+ {method === 'api_key' && <>
+ {backend === 'claude' && <div className="connection-field"><Label>{credentialLabel}</Label><SegmentedRadio value={credential} onChange={(value) => { draftTouched.current = true; setCredential(value); }} disabled={busy} ariaLabel={credentialLabel}
+ options={[{ id: 'api_key', label: apiKeyLabel }, { id: 'auth_token', label: tokenLabel }]} /></div>}
+ <div className="connection-field"><Label htmlFor={`${prefix}-connection-key`}>{secretLabel}</Label>
+ {hasKey && !editing ? <div className="connection-secret"><KeyRound size={15} /><code>{mask}</code><Button variant="ghost" size="xs" disabled={busy} onClick={() => { draftTouched.current = true; setEditing(true); setKey(''); }}><Pencil size={14} />{t('settings.backends.replaceApiKey')}</Button></div>
+ : <div className="connection-secret"><KeyRound size={15} /><Input id={`${prefix}-connection-key`} type={reveal ? 'text' : 'password'} value={key} onChange={(event) => { draftTouched.current = true; setKey(event.target.value); }} disabled={busy} autoComplete="off" spellCheck={false} placeholder={credential === 'auth_token' ? t('settings.backends.claudeAuthTokenPlaceholder') : backend === 'claude' ? 'sk-ant-…' : 'sk-…'} />
+ <Button variant="ghost" size="icon" aria-label={t(reveal ? 'onboarding.connection.hideKey' : 'onboarding.connection.showKey')} onClick={() => setReveal(!reveal)}>{reveal ? <EyeOff size={15} /> : <Eye size={15} />}</Button></div>}
+ <p>{backend === 'opencode' ? t('onboarding.connection.providerCredentialHint', { name: provider?.name }) : t(backend === 'claude' && credential === 'auth_token' ? 'onboarding.connection.tokenHint' : 'onboarding.connection.keyHint')}</p>
+ {editing && hasKey && <Button variant="link" size="xs" onClick={() => { setEditing(false); setKey(''); }}>{t('common.cancel')}</Button>}
+ </div>
+ <div className="connection-field"><Label htmlFor={`${prefix}-connection-url`}>{t('onboarding.connection.baseUrl')}</Label>
+ <Input id={`${prefix}-connection-url`} type="url" value={baseUrl} onChange={(event) => { draftTouched.current = true; setBaseUrl(event.target.value); }} disabled={busy} autoComplete="off" placeholder={backend === 'claude' ? 'https://api.anthropic.com' : backend === 'codex' ? 'https://api.openai.com/v1' : t('onboarding.connection.providerDefault')} />
+ <p>{t(backend === 'claude' ? 'onboarding.connection.claudeUrlHint' : 'onboarding.connection.urlHint')}</p>
+ {!urlValid && <p className="connection-error">{t('onboarding.connection.invalidUrl')}</p>}
+ </div>
+ </>}
+ {(compact || method === 'api_key') && <div className="connection-actions">
+ {compact && <Button variant="secondary" onClick={onCancel}>{t('common.cancel')}</Button>}
+ {!compact && hasKey && method === 'api_key' && <Button variant="ghost" disabled={busy} onClick={() => void remove(true)}>{t('settings.backends.claudeApiKeyRemove')}</Button>}
+ {method === 'api_key' && <Button variant="brand" disabled={!canSave} onClick={() => void save()}>{saving ? t(compact ? 'onboarding.connection.connecting' : 'common.saving') : t(compact ? 'onboarding.connection.saveConnect' : 'common.save')}</Button>}
+ {compact && needsCode && <Button variant="brand" disabled={!oauth.code.trim() || oauth.submitting} onClick={() => void oauth.submitCallback()}>{oauth.submitting ? t('onboarding.connection.connecting') : t('onboarding.connection.finishConnect')}</Button>}
+ </div>}
+ </div>;
+}
diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
index 036402495..7fb02c948 100644
--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
@@ -1,538 +1,23 @@
-import React, { useEffect, useMemo, useState } from 'react';
+import { Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import {
- AlertTriangle,
- CheckCircle2,
- Info,
- KeyRound,
- Pencil,
- RotateCcw,
- Save,
- Sparkles,
- Trash2,
-} from 'lucide-react';
-
-import { Badge } from '../../ui/badge';
-import { Button } from '../../ui/button';
-import { Card, CardContent } from '../../ui/card';
-import { Input } from '../../ui/input';
-import { Label } from '../../ui/label';
-import { BackendOAuthPanel } from '../BackendOAuthPanel';
-import { BackendTestPanel } from '../BackendTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
import { useModelHubCapability } from '../models/useModelHubCapability';
-import { SegmentedRadio } from '../shared/SegmentedRadio';
-import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';
import { useBackendRuntime } from '../shared/useBackendRuntime';
-import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';
-import { useApi } from '@/context/ApiContext';
-import type {
- ClaudeAuthMode,
- ClaudeAuthState,
- ClaudeCredentialType,
-} from '@/context/ApiContext';
-import { useToast } from '@/context/ToastContext';
-import { errorMessage } from '@/lib/errorMessage';
-
-const BACKEND_ID = 'claude';
-const DEFAULT_CLI = 'claude';
+import { BackendTestPanel } from '../BackendTestPanel';
+import { BackendConnectionForm } from './BackendConnectionForm';
+import { Card, CardContent } from '@/components/ui/card';
-export const ClaudeProviderConfig: React.FC<{
- hideEnableToggle?: boolean;
-}> = ({ hideEnableToggle } = {}) => {
+export function ClaudeProviderConfig({ hideEnableToggle }: { hideEnableToggle?: boolean } = {}) {
const { t } = useTranslation();
- const api = useApi();
+ const runtime = useBackendRuntime({ backend: 'claude', defaultCli: 'claude' });
const modelHubEnabled = useModelHubCapability();
- const { showToast } = useToast();
-
- // Runtime state — CLI detection + lifecycle. Shared with Codex /
- // OpenCode pages via the ``useBackendRuntime`` hook.
- const runtime = useBackendRuntime({
- backend: BACKEND_ID,
- defaultCli: DEFAULT_CLI,
- });
-
- // Auth state — OAuth vs API-key.
- const [authState, setAuthState] = useState<ClaudeAuthState | null>(null);
- const [authLoading, setAuthLoading] = useState(true);
- const [authSaving, setAuthSaving] = useState(false);
- const [removingKey, setRemovingKey] = useState(false);
- const [authMode, setAuthMode] = useState<ClaudeAuthMode>('oauth');
- const [apiKey, setApiKey] = useState('');
- // ``editingKey`` mirrors the Codex page convention: false = show the
- // saved key as a read-only mask (``sk-ant-•••cd34``) with a pencil to
- // replace it; true = empty editable input ready for a fresh secret.
- const [editingKey, setEditingKey] = useState(false);
- const [credentialType, setCredentialType] = useState<ClaudeCredentialType>('api_key');
- const [baseUrl, setBaseUrl] = useState('');
- // Snapshot the last loaded/saved auth-mode + base_url so we can hide
- // the Save button when nothing has changed (page feedback: no-op
- // Save buttons are noise).
- const [savedAuthMode, setSavedAuthMode] = useState<ClaudeAuthMode>('oauth');
- const [savedCredentialType, setSavedCredentialType] =
- useState<ClaudeCredentialType>('api_key');
- const [savedBaseUrl, setSavedBaseUrl] = useState('');
- // Freeze the auth-mode segmented radio while the OAuth panel is mid-
- // handshake. Shared with Codex / OpenCode via ``useOAuthFlowLock``.
- const { oauthFlowActive, setOauthFlowActive, guardedSetAuthMode } =
- useOAuthFlowLock<ClaudeAuthMode>({
- setAuthMode,
- warnTag: 'claude-auth-mode',
- });
-
- useEffect(() => {
- // Runtime config (enabled + cli_path + initial detect) is owned by
- // ``useBackendRuntime``. This effect only loads auth state.
- let cancelled = false;
- api
- .getClaudeAuth()
- .then((data) => {
- if (cancelled) return;
- setAuthState(data);
- // Prefer the live-effective tab. V2Config defaults to ``"oauth"``
- // even when settings.json carries the actual key, so reading
- // ``auth_mode`` alone would land the user on the wrong tab. Fall
- // back to V2Config only when nothing on disk is configured.
- const initialMode =
- data.active_auth_mode !== 'none' ? data.active_auth_mode : data.auth_mode;
- const initialBase = data.base_url || '';
- const initialCredentialType = data.credential_type || 'api_key';
- setAuthMode(initialMode);
- setCredentialType(initialCredentialType);
- setBaseUrl(initialBase);
- setSavedAuthMode(initialMode);
- setSavedCredentialType(initialCredentialType);
- setSavedBaseUrl(initialBase);
- // The masked preview lives in ``authState.api_key_masked``;
- // ``apiKey`` stays empty until the user clicks "Replace".
- setApiKey('');
- setEditingKey(false);
- })
- .catch(() => {
- // ApiContext already toasted; leave the page on its defaults.
- })
- .finally(() => {
- if (!cancelled) setAuthLoading(false);
- });
-
- return () => {
- cancelled = true;
- };
- }, [api]);
-
- const modeOptions = useMemo(
- () =>
- [
- { id: 'oauth' as const, label: t('settings.backends.claudeAuthModeOauth') },
- { id: 'api_key' as const, label: t('settings.backends.claudeAuthModeApiKey') },
- ] as const,
- [t]
- );
-
- const credentialTypeOptions = useMemo(
- () =>
- [
- { id: 'api_key' as const, label: t('settings.backends.claudeCredentialTypeApiKey') },
- { id: 'auth_token' as const, label: t('settings.backends.claudeCredentialTypeAuthToken') },
- ] as const,
- [t]
- );
-
- const apiKeyStatus = authState?.has_api_key
- ? t('settings.backends.claudeApiKeyConfigured', { length: authState.api_key_length })
- : t('settings.backends.claudeApiKeyMissing');
-
- const onRemoveApiKey = async () => {
- // Drop just the API key from Claude Code settings; leave its OAuth token
- // store alone. Lets the user clear a stale key without redoing OAuth.
- const confirmed = window.confirm(
- t('settings.backends.claudeApiKeyRemoveConfirm') as string,
- );
- if (!confirmed) return;
- setRemovingKey(true);
- try {
- const result = await api.removeBackendApiKey('claude');
- if (!result.ok) {
- showToast(
- t('settings.backends.claudeApiKeyRemoveFailed', {
- detail: result.error || result.detail || 'unknown',
- }),
- 'error',
- );
- return;
- }
- const fresh = await api.getClaudeAuth();
- setAuthState(fresh);
- const freshCredentialType = fresh.credential_type || 'api_key';
- setCredentialType(freshCredentialType);
- setSavedCredentialType(freshCredentialType);
- setBaseUrl(fresh.base_url || '');
- setSavedBaseUrl(fresh.base_url || '');
- setApiKey('');
- setEditingKey(false);
- if (result.restart?.ok === false) {
- showToast(
- result.restart.message || t('settings.backends.claudeApiKeyRemoveFailed', {
- detail: 'runtime refresh failed',
- }),
- 'warning',
- );
- } else {
- showToast(t('settings.backends.claudeApiKeyRemoved'), 'success');
- }
- surfaceBackendNotices(result.notices, showToast, t);
- } catch (err) {
- showToast(
- t('settings.backends.claudeApiKeyRemoveFailed', { detail: errorMessage(err) || 'unknown' }),
- 'error',
- );
- } finally {
- setRemovingKey(false);
- }
- };
-
- const onSaveAuth = async () => {
- setAuthSaving(true);
- try {
- const payload: Record<string, unknown> = {
- auth_mode: authMode,
- api_key: authMode === 'api_key' ? (apiKey || undefined) : null,
- };
- if (authMode === 'api_key') {
- payload.credential_type = credentialType;
- payload.base_url = baseUrl.trim() || null;
- }
- const result = await api.saveClaudeAuth(payload as any);
- if (result.ok === false) {
- showToast(result.message || t('settings.backends.claudeSaveFailed'), 'error');
- return;
- }
- setAuthState(result);
- const nextMode =
- result.active_auth_mode !== 'none' ? result.active_auth_mode : result.auth_mode;
- const nextBase = result.base_url || '';
- const nextCredentialType = result.credential_type || credentialType;
- setAuthMode(nextMode);
- setCredentialType(nextCredentialType);
- setBaseUrl(nextBase);
- setSavedAuthMode(nextMode);
- setSavedCredentialType(nextCredentialType);
- setSavedBaseUrl(nextBase);
- setApiKey('');
- setEditingKey(false);
- if (result.restart?.ok === false) {
- showToast(result.restart.message || t('settings.backends.claudeSaveSuccess'), 'warning');
- } else if (result.partial) {
- showToast(
- t('settings.backends.claudeSavePartial', {
- detail: result.detail || result.warning || 'oauth_cleanup_failed',
- }),
- 'warning',
- );
- } else {
- showToast(t('settings.backends.claudeSaveSuccess'), 'success');
- }
- } catch (err) {
- showToast(errorMessage(err) || t('settings.backends.claudeSaveFailed'), 'error');
- } finally {
- setAuthSaving(false);
- }
- };
-
- if (!runtime.loaded) {
- return <div className="text-sm text-muted">{t('common.loading')}</div>;
- }
-
- return (
- <div className="flex flex-col gap-4">
- <BackendRuntimeCard
- backend={BACKEND_ID}
- label="Claude Code"
- description={t('settings.backends.claudeDescription')}
- Icon={Sparkles}
- iconTileClassName="bg-cyan-soft"
- iconClassName="text-cyan-ink"
- runtime={runtime}
- hideEnableToggle={hideEnableToggle}
- />
-
- {/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
- {modelHubEnabled === true && <BackendSupplyModeCard backend="claude" />}
-
- {authLoading ? (
- <div className="text-sm text-muted">{t('common.loading')}</div>
- ) : (
- <Card>
- <CardContent className="flex flex-col gap-5 p-6">
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between gap-3">
- <Label className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.claudeAuthModeLabel')}
- </Label>
- {authState?.active_auth_mode && authState.active_auth_mode !== 'none' && (
- <Badge
- variant={authState.active_auth_mode === 'oauth' ? 'success' : 'info'}
- className="font-mono uppercase tracking-[0.06em]"
- >
- <CheckCircle2 className="size-3" />
- {authState.active_auth_mode === 'oauth'
- ? t('settings.backends.activeAuthOauth')
- : t('settings.backends.claudeActiveAuthCredential')}
- </Badge>
- )}
- {authState?.active_auth_mode === 'none' && (
- <Badge variant="secondary" className="font-mono uppercase tracking-[0.06em]">
- {t('settings.backends.activeAuthNone')}
- </Badge>
- )}
- </div>
- <SegmentedRadio
- value={authMode}
- onChange={guardedSetAuthMode}
- options={modeOptions}
- ariaLabel={t('settings.backends.claudeAuthModeLabel') as string}
- disabled={oauthFlowActive}
- />
- <p className="text-[12px] leading-relaxed text-muted">
- {authMode === 'api_key'
- ? t('settings.backends.claudeAuthModeApiKeyHint')
- : t('settings.backends.claudeAuthModeOauthHint')}
- </p>
- </div>
-
- {authMode === 'oauth' && (
- <BackendOAuthPanel
- backend={BACKEND_ID}
- // Claude Code may still have account tokens in its own
- // store after the user switches Avibe to API-key mode.
- // The Settings UI should show OAuth as signed in only when
- // OAuth is the currently effective Avibe auth source.
- signedIn={authState?.active_auth_mode === 'oauth'}
- canRemoveAuth={!!authState?.has_oauth_credentials}
- title={t('settings.backends.claudeOauthPanelTitle')}
- subtitle={t('settings.backends.claudeOauthPanelSubtitle')}
- onActiveChange={setOauthFlowActive}
- onSuccess={() => {
- // Re-fetch the auth state so the "Signed in" pill and
- // any masked-key indicators reflect the fresh login
- // immediately rather than waiting for a page reload.
- void api
- .getClaudeAuth()
- .then((data) => {
- // Refresh the underlying state (active badge,
- // masked key, settings.json conflict warning)
- // but DO NOT clobber ``authMode``. The radio
- // tab is a *user-controlled* affordance after
- // first load — re-syncing it from the server
- // here would force a tab change every time
- // OAuth completes / Sign out fires, even when
- // the user wants to stay on the OAuth tab to
- // re-authenticate.
- setAuthState(data);
- setBaseUrl(data.base_url || '');
- })
- .catch(() => {
- // Already toasted upstream; leave UI on previous state.
- });
- }}
- />
- )}
-
- {authMode === 'api_key' && (
- <>
- <div className="flex flex-col gap-2">
- <Label className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.claudeCredentialTypeLabel')}
- </Label>
- <SegmentedRadio
- value={credentialType}
- onChange={setCredentialType}
- options={credentialTypeOptions}
- ariaLabel={t('settings.backends.claudeCredentialTypeLabel') as string}
- disabled={authSaving}
- />
- <p className="text-[12px] leading-relaxed text-muted">
- {credentialType === 'api_key'
- ? t('settings.backends.claudeCredentialTypeApiKeyHint')
- : t('settings.backends.claudeCredentialTypeAuthTokenHint')}
- </p>
- </div>
-
- <div className="flex flex-col gap-2">
- <Label htmlFor="claude-api-key" className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.claudeCredentialValueLabel')}
- </Label>
- {authState?.has_api_key && !editingKey ? (
- // Same masked-preview affordance the Codex page uses;
- // keeps the user from re-typing the secret when they
- // are only changing the Base URL.
- <div className="flex items-center gap-2 rounded-md border border-border bg-foreground/[0.04] px-3 py-2">
- <KeyRound className="size-4 shrink-0 text-muted" />
- <code className="flex-1 truncate font-mono text-[13px] text-foreground">
- {authState.api_key_masked || '••••••••'}
- </code>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={() => {
- setEditingKey(true);
- setApiKey('');
- }}
- disabled={removingKey}
- >
- <Pencil className="size-3" />
- {t('settings.backends.replaceApiKey')}
- </Button>
- {/* Symmetric to OpenCode's Remove affordance:
- clear the saved API key while leaving OAuth
- token store intact. Without this, a stuck key
- keeps forcing the env-var path even after the
- user signed in via OAuth. */}
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={() => void onRemoveApiKey()}
- disabled={removingKey || editingKey}
- className="text-destructive-ink hover:bg-destructive/10 hover:text-destructive-ink"
- >
- <Trash2 className="size-3" />
- {removingKey
- ? t('common.removing')
- : t('settings.backends.claudeApiKeyRemove')}
- </Button>
- </div>
- ) : (
- <div className="relative">
- <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
- <Input
- id="claude-api-key"
- type="password"
- autoComplete="off"
- spellCheck={false}
- placeholder={t(
- credentialType === 'api_key'
- ? 'settings.backends.claudeApiKeyPlaceholder'
- : 'settings.backends.claudeAuthTokenPlaceholder'
- ) as string}
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- className="pl-9 font-mono"
- disabled={authSaving}
- autoFocus={editingKey}
- />
- </div>
- )}
- <div className="flex items-center justify-between gap-2">
- <p className="text-[12px] text-muted">{apiKeyStatus}</p>
- {authState?.has_api_key && editingKey && (
- <button
- type="button"
- className="text-[12px] text-muted underline-offset-2 transition hover:text-foreground hover:underline"
- onClick={() => {
- setEditingKey(false);
- setApiKey('');
- }}
- >
- {t('common.cancel')}
- </button>
- )}
- </div>
- </div>
-
- <div className="flex flex-col gap-2">
- <Label htmlFor="claude-base-url" className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.claudeBaseUrlLabel')}
- </Label>
- <div className="flex gap-2">
- <Input
- id="claude-base-url"
- type="url"
- autoComplete="off"
- spellCheck={false}
- placeholder={t('settings.backends.claudeBaseUrlPlaceholder') as string}
- value={baseUrl}
- onChange={(e) => setBaseUrl(e.target.value)}
- className="font-mono"
- disabled={authSaving}
- />
- <Button
- type="button"
- variant="secondary"
- size="sm"
- onClick={() => setBaseUrl('')}
- disabled={!baseUrl || authSaving}
- >
- <RotateCcw className="size-3.5" />
- {t('settings.backends.claudeBaseUrlReset')}
- </Button>
- </div>
- <p className="text-[12px] text-muted">{t('settings.backends.claudeBaseUrlHint')}</p>
- </div>
- </>
- )}
-
- {/* Kept defensively for legacy states where V2Config still
- carries a key before the next save migrates it. New saves
- overwrite Claude's own settings.json directly. */}
- {authMode === 'api_key' && authState?.settings_conflict && (
- <div className="flex items-start gap-2 rounded-lg border border-gold/30 bg-gold/[0.08] px-3 py-2.5">
- <AlertTriangle className="mt-0.5 size-3.5 shrink-0 text-gold-ink" />
- <div className="flex flex-col gap-1">
- <p className="text-[12px] font-medium text-gold-ink">
- {t('settings.backends.claudeSettingsConflictTitle')}
- </p>
- <p className="text-[12px] leading-relaxed text-muted">
- {t('settings.backends.claudeSettingsConflictBody', {
- var: authState.settings_env_key_var || 'ANTHROPIC_API_KEY',
- path: authState.settings_path || '~/.claude/settings.json',
- })}
- </p>
- </div>
- </div>
- )}
-
- {authMode === 'api_key' && (
- <div className="flex items-start gap-2 rounded-lg border border-border bg-surface-2/60 px-3 py-2.5">
- <Info className="mt-0.5 size-3.5 shrink-0 text-muted" />
- <p className="text-[12px] leading-relaxed text-muted">
- {t('settings.backends.claudeInfoHint')}
- </p>
- </div>
- )}
-
- {/* OAuth mode persists ``auth_mode=oauth`` automatically on
- successful sign-in (see ``_invoke_post_web_success_hook``),
- so the Save button only needs to surface in API-key mode
- where the user still has to commit the key / Base URL —
- and even there, only when something has actually changed. */}
- {authMode === 'api_key' && (() => {
- const dirty =
- authMode !== savedAuthMode ||
- credentialType !== savedCredentialType ||
- apiKey.trim().length > 0 ||
- baseUrl.trim() !== savedBaseUrl.trim();
- if (!dirty) return null;
- return (
- <div className="flex justify-end">
- <Button variant="brand" size="default" onClick={onSaveAuth} disabled={authSaving}>
- <Save className="size-3.5" />
- {authSaving ? t('settings.backends.claudeSaving') : t('settings.backends.claudeSave')}
- </Button>
- </div>
- );
- })()}
- </CardContent>
- </Card>
- )}
-
- {/* Connectivity probe — matches design.pen cdTest2 panel.
- Works in both OAuth and API-key modes because the underlying
- ``claude -p "Hi"`` subprocess inherits whichever auth source
- Claude Code reads at launch. */}
- {!authLoading && <BackendTestPanel backend={BACKEND_ID} />}
- </div>
- );
-};
+ if (!runtime.loaded) return <p>{t('common.loading')}</p>;
+ return <div className="flex flex-col gap-4">
+ <BackendRuntimeCard backend="claude" label="Claude Code" description={t('settings.backends.claudeDescription')}
+ Icon={Sparkles} iconTileClassName="bg-cyan-soft" iconClassName="text-cyan-ink" runtime={runtime} hideEnableToggle={hideEnableToggle} />
+ {modelHubEnabled === true && <BackendSupplyModeCard backend="claude" />}
+ <Card><CardContent className="p-6"><BackendConnectionForm backend="claude" connectionRevision={runtime.connectionRevision} /></CardContent></Card>
+ <BackendTestPanel backend="claude" />
+ </div>;
+}
diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsx
index f7bf97084..63caa2597 100644
--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx
+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx
@@ -1,490 +1,23 @@
-import React, { useEffect, useMemo, useState } from 'react';
-import { Bot, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save, Trash2 } from 'lucide-react';
+import { Bot } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-
-import { Badge } from '../../ui/badge';
-import { Button } from '../../ui/button';
-import { Card, CardContent } from '../../ui/card';
-import { Input } from '../../ui/input';
-import { Label } from '../../ui/label';
-import { useApi } from '@/context/ApiContext';
-import type { CodexAuthMode, CodexAuthState } from '@/context/ApiContext';
-import { useToast } from '@/context/ToastContext';
-import { BackendOAuthPanel } from '../BackendOAuthPanel';
-import { BackendTestPanel } from '../BackendTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
import { useModelHubCapability } from '../models/useModelHubCapability';
-import { SegmentedRadio } from '../shared/SegmentedRadio';
-import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';
import { useBackendRuntime } from '../shared/useBackendRuntime';
-import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';
-import { errorMessage } from '@/lib/errorMessage';
-
-const BACKEND_ID = 'codex';
-const DEFAULT_CLI = 'codex';
+import { BackendTestPanel } from '../BackendTestPanel';
+import { BackendConnectionForm } from './BackendConnectionForm';
+import { Card, CardContent } from '@/components/ui/card';
-export const CodexProviderConfig: React.FC<{
- hideEnableToggle?: boolean;
-}> = ({ hideEnableToggle } = {}) => {
+export function CodexProviderConfig({ hideEnableToggle }: { hideEnableToggle?: boolean } = {}) {
const { t } = useTranslation();
- const api = useApi();
+ const runtime = useBackendRuntime({ backend: 'codex', defaultCli: 'codex' });
const modelHubEnabled = useModelHubCapability();
- const { showToast } = useToast();
-
- // Runtime state — shared across all backend pages via the hook. Adds
- // the Runtime card affordances (lifecycle chip / toggle / CLI path
- // detect / install) that #282 omitted from the Codex page.
- const runtime = useBackendRuntime({
- backend: BACKEND_ID,
- defaultCli: DEFAULT_CLI,
- });
-
- const [state, setState] = useState<CodexAuthState | null>(null);
- const [loading, setLoading] = useState(true);
- const [saving, setSaving] = useState(false);
- const [removingKey, setRemovingKey] = useState(false);
- const [authMode, setAuthMode] = useState<CodexAuthMode>('oauth');
- const [apiKey, setApiKey] = useState('');
- // ``editingKey`` distinguishes "showing the saved masked key" (false,
- // input is read-only and pre-filled with ``api_key_masked``) from "user
- // is typing a fresh secret" (true, input is editable + empty). The
- // pencil button flips it on; saving or reloading flips it back off.
- const [editingKey, setEditingKey] = useState(false);
- const [baseUrl, setBaseUrl] = useState('');
- // ``savedAuthMode`` / ``savedBaseUrl`` snapshot the last successfully
- // loaded (or saved) values so we can show the Save button only when
- // the user has actually changed something. Page feedback: a Save
- // button that never has a no-op state is noisy and confusing.
- const [savedAuthMode, setSavedAuthMode] = useState<CodexAuthMode>('oauth');
- const [savedBaseUrl, setSavedBaseUrl] = useState('');
- // Freeze the auth-mode segmented radio while the OAuth panel is mid-
- // handshake. Shared with Claude / OpenCode via ``useOAuthFlowLock``.
- const { oauthFlowActive, setOauthFlowActive, guardedSetAuthMode } =
- useOAuthFlowLock<CodexAuthMode>({
- setAuthMode,
- warnTag: 'codex-auth-mode',
- });
-
- useEffect(() => {
- let cancelled = false;
- api
- .getCodexAuth()
- .then((data) => {
- if (cancelled) return;
- setState(data);
- // Default the radio to whichever auth source the running CLI is
- // *actually* using (``active_auth_mode``). V2Config's
- // ``auth_mode`` defaults to ``"oauth"`` on fresh installs, which
- // would otherwise force the OAuth tab even when the user has a
- // working API key on disk (e.g. they pre-configured ``auth.json``
- // by hand, or a prior Sign out wiped V2Config but the relay
- // config in ``config.toml`` still points at a custom endpoint).
- // ``active_auth_mode === "none"`` means we have nothing on disk
- // either, so honour V2Config's saved intent in that fallback case.
- const initialMode =
- data.active_auth_mode !== 'none' ? data.active_auth_mode : data.auth_mode;
- const initialBase = data.base_url || '';
- setAuthMode(initialMode);
- setBaseUrl(initialBase);
- setSavedAuthMode(initialMode);
- setSavedBaseUrl(initialBase);
- // Empty + read-only input + masked preview rendered separately
- // (see below) reflects the saved state without leaking plaintext.
- setApiKey('');
- setEditingKey(false);
- })
- .catch(() => {
- // Errors are already surfaced via ToastContext by ApiContext;
- // leave the page on the default oauth state so the user can still
- // make a choice rather than seeing a broken UI.
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [api]);
-
- const modeOptions = useMemo(
- () =>
- [
- { id: 'oauth' as const, label: t('settings.backends.codexAuthModeOauth') },
- { id: 'api_key' as const, label: t('settings.backends.codexAuthModeApiKey') },
- ] as const,
- [t]
- );
-
- const apiKeyStatus = state?.has_api_key
- ? t('settings.backends.codexApiKeyConfigured', { length: state.api_key_length })
- : t('settings.backends.codexApiKeyMissing');
-
- const onRemoveApiKey = async () => {
- // Drop just the API key (V2Config + auth.json's OPENAI_API_KEY),
- // leave OAuth tokens intact. Codex's CLI prefers the API key when
- // both are present — without this affordance a stale/invalid key
- // keeps forcing 401s even after the user signed in via OAuth.
- const confirmed = window.confirm(
- t('settings.backends.codexApiKeyRemoveConfirm') as string,
- );
- if (!confirmed) return;
- setRemovingKey(true);
- try {
- const result = await api.removeBackendApiKey('codex');
- if (!result.ok) {
- showToast(
- t('settings.backends.codexApiKeyRemoveFailed', {
- detail: result.error || result.detail || 'unknown',
- }),
- 'error',
- );
- return;
- }
- const fresh = await api.getCodexAuth();
- setState(fresh);
- setBaseUrl(fresh.base_url || '');
- setSavedBaseUrl(fresh.base_url || '');
- setApiKey('');
- setEditingKey(false);
- showToast(t('settings.backends.codexApiKeyRemoved'), 'success');
- surfaceBackendNotices(result.notices, showToast, t);
- } catch (err) {
- showToast(
- t('settings.backends.codexApiKeyRemoveFailed', { detail: errorMessage(err) || 'unknown' }),
- 'error',
- );
- } finally {
- setRemovingKey(false);
- }
- };
-
- const onSave = async () => {
- setSaving(true);
- try {
- // In OAuth mode base_url does not apply, so omit it entirely — the
- // backend's three-state payload semantics preserve whatever is
- // already stored. This keeps a relay URL the user had configured in
- // api_key mode intact when they toggle to OAuth and back.
- const payload: Record<string, unknown> = {
- auth_mode: authMode,
- // Send a fresh key only when the user typed one; an empty string
- // lets the server reuse the stored key (useful when the user is
- // just updating the base URL).
- api_key: authMode === 'api_key' ? (apiKey || undefined) : null,
- };
- if (authMode === 'api_key') {
- payload.base_url = baseUrl.trim() || null;
- }
- const result = await api.saveCodexAuth(payload as any);
- if (result.ok === false) {
- // The server returns ok:false for validation/persist failures
- // (e.g. missing api_key when auth_mode is "api_key") with HTTP 200,
- // so we must not advance into the success branch here — applying
- // ``result`` into state would overwrite the user's in-progress
- // edits with a malformed response that omits auth_mode / base_url.
- showToast(result.message || t('settings.backends.codexSaveFailed'), 'error');
- return;
- }
- setState(result);
- const nextMode =
- result.active_auth_mode !== 'none' ? result.active_auth_mode : result.auth_mode;
- const nextBase = result.base_url || '';
- setAuthMode(nextMode);
- setBaseUrl(nextBase);
- setSavedAuthMode(nextMode);
- setSavedBaseUrl(nextBase);
- setApiKey('');
- setEditingKey(false);
- if (result.restart?.ok === false) {
- // Config saved, restart failed — make the partial success visible.
- showToast(result.restart.message || result.message || t('settings.backends.codexSaveSuccess'), 'warning');
- } else {
- showToast(t('settings.backends.codexSaveSuccess'), 'success');
- }
- surfaceBackendNotices(result.notices, showToast, t);
- } catch (err) {
- showToast(errorMessage(err) || t('settings.backends.codexSaveFailed'), 'error');
- } finally {
- setSaving(false);
- }
- };
-
- if (loading || !runtime.loaded) {
- return <div className="text-sm text-muted">{t('common.loading')}</div>;
- }
-
- return (
- <div className="flex flex-col gap-4">
- <BackendRuntimeCard
- backend={BACKEND_ID}
- label="Codex"
- description={t('settings.backends.codexDescription')}
- Icon={Bot}
- iconTileClassName="bg-gold"
- iconClassName="text-gold-foreground"
- runtime={runtime}
- hideEnableToggle={hideEnableToggle}
- />
-
- {/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
- {modelHubEnabled === true && <BackendSupplyModeCard backend="codex" />}
-
- <Card>
- <CardContent className="flex flex-col gap-5 p-6">
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between gap-3">
- <Label className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.codexAuthModeLabel')}
- </Label>
- {state?.active_auth_mode && state.active_auth_mode !== 'none' && (
- <Badge
- variant={state.active_auth_mode === 'oauth' ? 'success' : 'info'}
- className="font-mono uppercase tracking-[0.06em]"
- >
- <CheckCircle2 className="size-3" />
- {state.active_auth_mode === 'oauth'
- ? t('settings.backends.activeAuthOauth')
- : t('settings.backends.activeAuthApiKey')}
- </Badge>
- )}
- {state?.active_auth_mode === 'none' && (
- <Badge variant="secondary" className="font-mono uppercase tracking-[0.06em]">
- {t('settings.backends.activeAuthNone')}
- </Badge>
- )}
- </div>
- <SegmentedRadio
- value={authMode}
- onChange={guardedSetAuthMode}
- options={modeOptions}
- ariaLabel={t('settings.backends.codexAuthModeLabel') as string}
- disabled={oauthFlowActive}
- />
- <p className="text-[12px] leading-relaxed text-muted">
- {authMode === 'api_key'
- ? t('settings.backends.codexAuthModeApiKeyHint')
- : t('settings.backends.codexAuthModeOauthHint')}
- </p>
- {state?.auth_mode_uncertain && (
- // Codex stores credentials in the OS keychain by default
- // (``cli_auth_credentials_store=auto``). When there's no
- // disk key/tokens we cannot tell whether the user is
- // signed in via keychain or not — say so honestly rather
- // than rendering "no key configured" with an oauth toggle.
- <p className="text-[12px] text-gold-ink">
- {t('settings.backends.codexAuthModeUncertain', { store: state.credentials_store })}
- </p>
- )}
- {authMode === 'api_key' && state && !state.file_store_active && !state.auth_mode_uncertain && (
- // Codex's documented default is ``auto`` (keyring-preferred), so
- // the API-key UX is honest about what saving will do: we pin
- // ``cli_auth_credentials_store = "file"`` on save, otherwise
- // Codex would ignore ``auth.json`` and keep reading the keychain.
- <p className="text-[12px] text-gold-ink">
- {t('settings.backends.codexCredentialsStoreKeyringWarn', { store: state.credentials_store })}
- </p>
- )}
- </div>
-
- {authMode === 'oauth' && (
- <BackendOAuthPanel
- backend="codex"
- signedIn={state?.active_auth_mode === 'oauth'}
- signedInDetail={(() => {
- // Compose a single-line identity (``email · plan ·
- // org``) from the JWT-decoded ``chatgpt_account``
- // bundle. We render only the pieces present so a
- // partial JWT still surfaces something useful.
- const acct = state?.chatgpt_account;
- if (!acct) return null;
- const parts: string[] = [];
- if (acct.email) parts.push(acct.email);
- if (acct.plan_type) parts.push(acct.plan_type);
- const defaultOrg = acct.organizations?.find((o) => o.is_default)
- || acct.organizations?.[0];
- if (defaultOrg?.title) parts.push(defaultOrg.title);
- return parts.length ? parts.join(' · ') : null;
- })()}
- title={t('settings.backends.codexOauthPanelTitle')}
- subtitle={t('settings.backends.codexOauthPanelSubtitle')}
- onActiveChange={setOauthFlowActive}
- onSuccess={() => {
- // Re-read Codex auth state so the "ChatGPT tokens detected"
- // line and any keychain hints catch up with the freshly
- // minted credential without a manual page reload.
- void api
- .getCodexAuth()
- .then((data) => {
- // Refresh underlying state but DO NOT clobber the
- // radio tab — that's a user-controlled affordance
- // after first load. Forcing a re-sync here would
- // bounce the user back to whatever
- // ``active_auth_mode`` reports every time OAuth
- // completes / Sign out runs.
- setState(data);
- setBaseUrl(data.base_url || '');
- })
- .catch(() => {
- /* ApiContext already toasted; leave existing state. */
- });
- }}
- />
- )}
-
- {authMode === 'api_key' && (
- <>
- <div className="flex flex-col gap-2">
- <Label htmlFor="codex-api-key" className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.codexApiKeyLabel')}
- </Label>
- {state?.has_api_key && !editingKey ? (
- // Saved-key preview: render the server-masked value
- // (``sk-proj-•••H8mN``) read-only with a pencil to swap
- // in a fresh key. Same affordance shown in design.pen
- // ``cxApiVal`` — saves the user from typing the secret
- // again when they only want to change the Base URL.
- <div className="flex items-center gap-2 rounded-md border border-border bg-foreground/[0.04] px-3 py-2">
- <KeyRound className="size-4 shrink-0 text-muted" />
- <code className="flex-1 truncate font-mono text-[13px] text-foreground">
- {state.api_key_masked || '••••••••'}
- </code>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={() => {
- setEditingKey(true);
- setApiKey('');
- }}
- disabled={removingKey}
- >
- <Pencil className="size-3" />
- {t('settings.backends.replaceApiKey')}
- </Button>
- {/* Symmetric to OpenCode's Remove affordance: lets
- the user drop a stale / invalid key without
- re-signing in. Important for Codex specifically
- because the CLI prefers ``OPENAI_API_KEY`` when
- both api_key and OAuth tokens live in
- ``auth.json`` — a stuck key keeps forcing 401s
- even after a successful OAuth sign-in. */}
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={() => void onRemoveApiKey()}
- disabled={removingKey || editingKey}
- className="text-destructive-ink hover:bg-destructive/10 hover:text-destructive-ink"
- >
- <Trash2 className="size-3" />
- {removingKey
- ? t('common.removing')
- : t('settings.backends.codexApiKeyRemove')}
- </Button>
- </div>
- ) : (
- <div className="relative">
- <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
- <Input
- id="codex-api-key"
- type="password"
- autoComplete="off"
- spellCheck={false}
- placeholder={t('settings.backends.codexApiKeyPlaceholder') as string}
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- className="pl-9 font-mono"
- autoFocus={editingKey}
- />
- </div>
- )}
- <div className="flex items-center justify-between gap-2">
- <p className="text-[12px] text-muted">{apiKeyStatus}</p>
- {state?.has_api_key && editingKey && (
- <button
- type="button"
- className="text-[12px] text-muted underline-offset-2 transition hover:text-foreground hover:underline"
- onClick={() => {
- setEditingKey(false);
- setApiKey('');
- }}
- >
- {t('common.cancel')}
- </button>
- )}
- </div>
- </div>
-
- <div className="flex flex-col gap-2">
- <Label htmlFor="codex-base-url" className="text-xs font-medium uppercase text-muted">
- {t('settings.backends.codexBaseUrlLabel')}
- </Label>
- <div className="flex gap-2">
- <Input
- id="codex-base-url"
- type="url"
- autoComplete="off"
- spellCheck={false}
- placeholder={t('settings.backends.codexBaseUrlPlaceholder') as string}
- value={baseUrl}
- onChange={(e) => setBaseUrl(e.target.value)}
- className="font-mono"
- />
- <Button
- type="button"
- variant="secondary"
- size="sm"
- onClick={() => setBaseUrl('')}
- disabled={!baseUrl}
- >
- <RotateCcw className="size-3.5" />
- {t('settings.backends.codexBaseUrlReset')}
- </Button>
- </div>
- <p className="text-[12px] text-muted">{t('settings.backends.codexBaseUrlHint')}</p>
- </div>
- </>
- )}
-
- {/* Info hint describes ``~/.codex/{auth.json,config.toml}``
- writes that only happen on api_key saves. Skip it under
- OAuth so the panel doesn't carry irrelevant copy. */}
- {authMode === 'api_key' && (
- <div className="flex items-start gap-2 rounded-lg border border-border bg-surface-2/60 px-3 py-2.5">
- <Info className="mt-0.5 size-3.5 shrink-0 text-muted" />
- <p className="text-[12px] leading-relaxed text-muted">
- {t('settings.backends.codexInfoHint')}
- </p>
- </div>
- )}
-
- {/* OAuth mode persists ``auth_mode=oauth`` automatically on
- successful sign-in, so the Save button only surfaces for
- api_key mode — and even then only when something has
- actually changed (page feedback: a permanent Save button
- with no dirty signal is noisy). ``dirty`` watches the
- three things this card mutates against their saved
- snapshot. */}
- {authMode === 'api_key' && (() => {
- const dirty =
- authMode !== savedAuthMode ||
- apiKey.trim().length > 0 ||
- baseUrl.trim() !== savedBaseUrl.trim();
- if (!dirty) return null;
- return (
- <div className="flex justify-end">
- <Button variant="brand" size="default" onClick={onSave} disabled={saving}>
- <Save className="size-3.5" />
- {saving ? t('settings.backends.codexSaving') : t('settings.backends.codexSave')}
- </Button>
- </div>
- );
- })()}
- </CardContent>
- </Card>
-
- <BackendTestPanel backend="codex" />
- </div>
- );
-};
+ if (!runtime.loaded) return <p>{t('common.loading')}</p>;
+ return <div className="flex flex-col gap-4">
+ <BackendRuntimeCard backend="codex" label="Codex" description={t('settings.backends.codexDescription')}
+ Icon={Bot} iconTileClassName="bg-gold" iconClassName="text-gold-foreground" runtime={runtime} hideEnableToggle={hideEnableToggle} />
+ {modelHubEnabled === true && <BackendSupplyModeCard backend="codex" />}
+ <Card><CardContent className="p-6"><BackendConnectionForm backend="codex" connectionRevision={runtime.connectionRevision} /></CardContent></Card>
+ <BackendTestPanel backend="codex" />
+ </div>;
+}
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index a07ace0f7..878b94a54 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -8,10 +8,7 @@ import {
Cpu,
Plus,
Info,
- KeyRound,
- Pencil,
RefreshCw,
- RotateCcw,
Save,
Search,
Server,
@@ -29,7 +26,7 @@ import { Checkbox } from '../../ui/checkbox';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';
-import { BackendOAuthPanel } from '../BackendOAuthPanel';
+import { BackendConnectionForm } from './BackendConnectionForm';
import { OpencodeProviderTestPanel } from '../OpencodeProviderTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
@@ -37,7 +34,6 @@ import { useModelHubCapability } from '../models/useModelHubCapability';
import { OpencodePermissionSetup } from '../shared/OpencodePermissionSetup';
import { useBackendRuntime } from '../shared/useBackendRuntime';
import { useOpencodePermission } from '../shared/useOpencodePermission';
-import { providerOauthSignedIn } from './opencodeProviderAuth';
import { useApi } from '@/context/ApiContext';
import type {
OpencodeMutationResult,
@@ -476,63 +472,6 @@ export const OpencodeProviderConfig: React.FC<{
}
};
- const onSaveProviderAuth = async (provider: OpencodeProvider) => {
- const state = editByProvider[provider.id] || emptyEdit();
- const key = state.apiKey.trim();
- // Reject an empty key only when the provider has no saved
- // credentials. For already-configured providers the UI hides the
- // plaintext key behind a "Replace" pencil; the backend save
- // endpoint reuses the on-disk key in that case so a base-URL-only
- // edit can land without re-typing the secret. Without this branch
- // a user with a saved key can never persist a relay-URL fix.
- if (!key && !provider.configured) {
- updateEdit(provider.id, {
- error: t('settings.backends.opencodeProviderApiKeyRequired') as string,
- });
- return;
- }
- // The Base URL field is the only signal the form sends for the
- // ``provider.<id>.options.baseURL`` override in ``opencode.json``.
- // Forwarding the trimmed value verbatim — including the empty
- // string for "clear" — is critical: if we dropped to ``undefined``
- // for blanks, the server would interpret it as "leave unchanged"
- // and a user who removed the value in the form would silently keep
- // the old override on disk.
- const baseUrl = state.baseUrl.trim();
- if (provider.custom && !baseUrl) {
- updateEdit(provider.id, {
- error: t('settings.backends.opencodeProviderBaseUrlRequired') as string,
- });
- return;
- }
- updateEdit(provider.id, { saving: true, error: null });
- try {
- const result = await api.setOpencodeProviderAuth(provider.id, key, baseUrl);
- if (!result.ok) {
- updateEdit(provider.id, {
- saving: false,
- error: result.message || (t('settings.backends.opencodeProviderSaveFailed') as string),
- });
- return;
- }
- updateEdit(provider.id, {
- saving: false,
- apiKey: '',
- editingKey: false,
- error: null,
- });
- showToast(t('settings.backends.opencodeProviderSaved'), 'success');
- notifyOpenCodeModelOptionsChanged();
- if (!applyMutationCatalogRefresh(result)) {
- await loadProviders();
- }
- } catch (e) {
- updateEdit(provider.id, {
- saving: false,
- error: errorMessage(e) || (t('settings.backends.opencodeProviderSaveFailed') as string),
- });
- }
- };
const onRemoveProviderAuth = async (provider: OpencodeProvider) => {
// Confirm copy matches what's actually about to be removed.
@@ -1350,204 +1289,8 @@ export const OpencodeProviderConfig: React.FC<{
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="flex flex-col gap-3">
- {provider.oauth_available && (
- // In-card OAuth panel: reuses the
- // same component Claude / Codex use,
- // configured for OpenCode's
- // per-provider HTTP flow. Drives the
- // ``/api/backend/opencode/provider/<id>/auth/oauth/start``
- // endpoint and polls for completion
- // — no terminal commands required.
- <BackendOAuthPanel
- backend="opencode"
- opencodeProviderId={provider.id}
- signedIn={providerOauthSignedIn(provider)}
- title={t('settings.backends.opencodeProviderOauthPanelTitle', {
- name: provider.name,
- })}
- subtitle={t('settings.backends.opencodeProviderOauthPanelSubtitle')}
- hideRemove
- onSuccess={() => {
- notifyOpenCodeModelOptionsChanged();
- // Refresh the providers list so
- // the just-authorised provider
- // flips to "configured" and the
- // masked-key block (if any)
- // appears.
- void loadProviders();
- }}
- />
- )}
-
- <div className="flex flex-col gap-1.5">
- <Label
- htmlFor={`opencode-key-${provider.id}`}
- className="text-[11px] font-medium uppercase text-muted"
- >
- {t('settings.backends.opencodeProviderApiKey')}
- </Label>
- {providerHasAuth(provider) && provider.api_key_masked && !edit.editingKey ? (
- // Masked-preview affordance ported from
- // the Claude / Codex pages: show the
- // saved key as a read-only mono-typed
- // value with a pencil to swap in a
- // fresh one. Saves the user from
- // re-typing the secret on baseURL-only
- // edits.
- <div className="flex items-center gap-2 rounded-md border border-border bg-foreground/[0.04] px-3 py-2">
- <KeyRound className="size-4 shrink-0 text-muted" />
- <code className="flex-1 truncate font-mono text-[12px] text-foreground">
- {provider.api_key_masked}
- </code>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- onClick={() =>
- updateEdit(provider.id, {
- editingKey: true,
- apiKey: '',
- })
- }
- disabled={edit.saving || edit.removing}
- >
- <Pencil className="size-3" />
- {t('settings.backends.replaceApiKey')}
- </Button>
- </div>
- ) : (
- <div className="relative">
- <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
- <Input
- id={`opencode-key-${provider.id}`}
- type="password"
- autoComplete="off"
- spellCheck={false}
- placeholder={
- providerHasAuth(provider)
- ? (t(
- 'settings.backends.opencodeProviderApiKeyPlaceholderStored'
- ) as string)
- : (t(
- 'settings.backends.opencodeProviderApiKeyPlaceholder'
- ) as string)
- }
- value={edit.apiKey}
- onChange={(e) =>
- updateEdit(provider.id, { apiKey: e.target.value })
- }
- className="pl-9 font-mono"
- disabled={edit.saving}
- autoFocus={edit.editingKey}
- />
- </div>
- )}
- <div className="flex items-center justify-between gap-2">
- <p className="text-[11px] text-muted">
- {providerHasAuth(provider)
- ? t('settings.backends.opencodeProviderApiKeyStored')
- : t('settings.backends.opencodeProviderApiKeyMissing')}
- </p>
- {providerHasAuth(provider) && edit.editingKey && (
- <Button
- type="button"
- variant="link"
- size="xs"
- className="h-auto px-0 text-[11px] text-muted"
- onClick={() =>
- updateEdit(provider.id, {
- editingKey: false,
- apiKey: '',
- })
- }
- >
- {t('common.cancel')}
- </Button>
- )}
- </div>
- </div>
-
- <div className="flex flex-col gap-1.5">
- <Label
- htmlFor={`opencode-base-url-${provider.id}`}
- className="text-[11px] font-medium uppercase text-muted"
- >
- {t('settings.backends.opencodeProviderBaseUrl')}
- </Label>
- <div className="flex gap-2">
- <Input
- id={`opencode-base-url-${provider.id}`}
- type="url"
- autoComplete="off"
- spellCheck={false}
- placeholder={
- t(
- 'settings.backends.opencodeProviderBaseUrlPlaceholder'
- ) as string
- }
- value={edit.baseUrl}
- onChange={(e) =>
- updateEdit(provider.id, { baseUrl: e.target.value })
- }
- className="font-mono"
- disabled={edit.saving}
- />
- <Button
- type="button"
- variant="secondary"
- size="sm"
- onClick={() => updateEdit(provider.id, { baseUrl: '' })}
- disabled={!edit.baseUrl || edit.saving}
- >
- <RotateCcw className="size-3.5" />
- </Button>
- </div>
- <p className="text-[11px] text-muted">
- {t('settings.backends.opencodeProviderBaseUrlHint')}
- </p>
- </div>
-
- {edit.error && (
- <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-[12px] text-destructive-ink">
- {edit.error}
- </div>
- )}
-
- {(() => {
- // Save button only renders when the
- // user has something to commit:
- // typed a fresh key, or modified
- // the Base URL relative to what's
- // saved on the provider. Mirrors
- // the Claude / Codex dirty-state
- // pattern — a permanent Save button
- // is noisy and confusing.
- const keyDirty = edit.apiKey.trim().length > 0;
- const savedBase = (provider.base_url || '').trim();
- const baseDirty = edit.baseUrl.trim() !== savedBase;
- const dirty = keyDirty || baseDirty;
- if (!dirty) return null;
- return (
- <div className="flex flex-wrap items-center justify-end gap-2">
- <Button
- type="button"
- variant="brand"
- size="sm"
- onClick={() => void onSaveProviderAuth(provider)}
- disabled={edit.saving}
- >
- {edit.saving ? (
- <RefreshCw className="size-3.5 animate-spin" />
- ) : (
- <Save className="size-3.5" />
- )}
- {edit.saving
- ? t('common.saving')
- : t('settings.backends.opencodeProviderSave')}
- </Button>
- </div>
- );
- })()}
+ <BackendConnectionForm backend="opencode" provider={provider} connectionRevision={runtime.connectionRevision}
+ onConnected={async () => { notifyOpenCodeModelOptionsChanged(); await loadProviders(); }} />
{/* Per-provider connectivity probe.
Gated on ``configured`` because
diff --git a/ui/src/components/settings/providers/connection.css b/ui/src/components/settings/providers/connection.css
new file mode 100644
index 000000000..9ba541749
--- /dev/null
+++ b/ui/src/components/settings/providers/connection.css
@@ -0,0 +1,65 @@
+/* Native dialogs eKlyp/Q0wFN/DZesH/JEkvL and their Light variants. */
+.connection-dialog {
+ --connection-overlay-shadow: #00000088;
+ --connection-selected-border: #5bffa059;
+ --connection-logo-well: #ffffff04;
+ width: min(568px, calc(100vw - 32px)); max-width: 568px;
+ padding: 24px; gap: 20px; border-radius: 16px;
+ border-color: var(--border-strong); background: var(--surface-2);
+ box-shadow: 0 18px 48px var(--desktop-overlay-shadow, var(--connection-overlay-shadow));
+}
+[data-theme='light'] .connection-dialog { --connection-overlay-shadow: #0a0a1424; --connection-selected-border: #10b98160; --connection-logo-well: #eef1f780; }
+@media (prefers-color-scheme: light) {
+ :root:not([data-theme='dark']) .connection-dialog { --connection-overlay-shadow: #0a0a1424; --connection-selected-border: #10b98160; --connection-logo-well: #eef1f780; }
+}
+.connection-heading { display: flex; gap: 12px; align-items: center; padding-right: 20px; }
+.connection-logo { width: 40px; height: 40px; flex: none; border: 1px solid var(--border); border-radius: 10px; display: grid; place-items: center; background: var(--logo-well-background, var(--connection-logo-well)); }
+.connection-heading h2 { font-size: 20px; line-height: 24px; font-weight: 600; }
+.connection-heading p { line-height: 15px; font-size: 12px; color: var(--muted); margin-top: 4px; }
+.connection-intro { font-size: 13px; line-height: 1.55; color: var(--muted); }
+.backend-connection-form { display: flex; flex-direction: column; gap: 20px; min-width: 0; }
+.connection-dialog [role='radiogroup'] { height: 40px; padding: 3px; gap: 4px; border-radius: 9px; background: var(--background); border: 1px solid var(--border); }
+.connection-dialog [role='radio'] { min-width: 0; border-radius: 6px; font-size: 12px; line-height: 1.2; font-weight: 500; white-space: normal; flex: 1; }
+.connection-dialog [role='radio'][aria-checked='true'] { background: var(--mint-soft); color: var(--mint); border: 1px solid var(--nav-selected-border, var(--connection-selected-border)); font-weight: 600; }
+.connection-dialog button:disabled:not([role='radio']) { opacity: .4; }
+.backend-connection-form [role='radio']:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
+.connection-dialog [role='radiogroup']:has(button:disabled) { opacity: .6; }
+.connection-account { display: flex; flex-direction: column; gap: 12px; padding: 18px; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; }
+.connection-account h3 { line-height: 17px; font-size: 14px; font-weight: 600; }
+.connection-account p { font-size: 13px; line-height: 1.6; color: var(--muted); }
+.connection-field { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
+.connection-field label, .connection-auth-steps label { font-size: 12px; font-weight: 500; }
+.connection-field p { font-size: 12px; line-height: 1.55; color: var(--muted); }
+.connection-field input { height: 42px; border-radius: 8px; background: var(--background); border-color: var(--border-strong); font-family: var(--font-mono); font-size: 12px; }
+.connection-secret { display: flex; align-items: center; gap: 9px; min-height: 42px; padding: 0 12px; border: 1px solid var(--border-strong); border-radius: 8px; background: var(--background); color: var(--muted); }
+.connection-secret input { border: none; background: transparent; padding: 0; box-shadow: none; min-width: 0; }
+.connection-secret code { flex: 1; min-width: 0; overflow-wrap: anywhere; font-size: 12px; }
+.connection-secret > svg { flex: none; }
+.connection-secret > button { flex: none; }
+.connection-actions { display: flex; align-items: center; justify-content: flex-end; gap: 10px; padding-top: 18px; border-top: 1px solid var(--border); }
+.connection-dialog .connection-actions button, .connection-dialog .connection-account button { height: 38px; border-radius: 8px; padding: 0 14px; font-size: 13px; font-weight: 600; }
+.connection-auth-steps { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
+.connection-auth-steps > div:has(> a + button) { border-radius: 8px; background: var(--cyan-soft); padding: 0 12px; min-height: 40px; gap: 8px; flex-wrap: nowrap; }
+.connection-auth-steps > div:has(> a + button) a { background: transparent; padding: 0; min-width: 0; flex: 1; }
+.connection-auth-steps > div:has(> a + button) a span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
+.connection-auth-steps > div:has(> code) { min-height: 54px; background: var(--background); border: 1px solid var(--border); padding: 8px 12px; border-radius: 8px; justify-content: space-between; }
+.connection-auth-steps code { background: transparent; font-size: 19px; letter-spacing: 2px; padding: 0; }
+.connection-waiting, .connection-loading, .connection-confirmed { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); }
+.connection-waiting svg, .connection-confirmed { color: var(--mint-ink); }
+.connection-error, .connection-field .connection-error { color: var(--destructive-ink); font-size: 12px; overflow-wrap: anywhere; }
+.connection-notice { font-size: 12px; color: var(--gold-ink); }
+.connection-provider-list { display: flex; flex-direction: column; gap: 10px; max-height: 300px; overflow-y: auto; }
+.connection-provider { width: 100%; min-height: 64px; border-radius: 10px; padding: 10px 14px; gap: 12px; border: 1px solid var(--border); background: var(--surface); display: flex; align-items: center; justify-content: space-between; text-align: left; }
+.connection-provider strong { display: block; font-size: 13px; font-weight: 600; }
+.connection-provider small { display: block; font-size: 11px; color: var(--muted); margin-top: 3px; overflow-wrap: anywhere; }
+.connection-provider svg { flex: none; }
+/* No narrow native frames exist: preserve a centered, scrollable dialog, type,
+ focus and reachable actions rather than inheriting the management sheet. */
+@media (max-width: 767px) {
+ .connection-dialog { left: 50%; right: auto; top: 50%; bottom: auto; transform: translate(-50%, -50%); max-width: 568px; width: calc(100vw - 24px); padding: 20px; max-height: calc(100dvh - 24px); border-radius: 16px; }
+ .connection-dialog > div[aria-hidden='true']:first-child { display: none; }
+ .connection-heading h2 { font-size: 19px; }
+}
+
+.connection-auth-steps > div > a[data-slot="button"] { height: 38px; border-radius: 8px; padding: 0 14px; font-size: 13px; font-weight: 600; }
+.connection-dialog .connection-auth-steps > div > a:not(:has(+ button)) { height: 38px; border-radius: 8px; padding: 0 14px; font-size: 13px; font-weight: 600; }
diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
index e8261a129..c0b2d7c15 100644
--- a/ui/src/components/settings/shared/BackendRuntimeCard.tsx
+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
@@ -107,6 +107,7 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
enabled={runtime.enabled}
cliStatus={runtime.cliStatus}
onChanged={runtime.handleLifecycleChanged}
+ onOperationChange={(busy) => { if (!busy) void runtime.handleLifecycleChanged(null); }}
/>
{!hideEnableToggle && (
<ToggleSwitch enabled={runtime.enabled} onClick={runtime.toggleEnabled} />
diff --git a/ui/src/components/settings/shared/savePlatformSettings.ts b/ui/src/components/settings/shared/savePlatformSettings.ts
new file mode 100644
index 000000000..85421cbb2
--- /dev/null
+++ b/ui/src/components/settings/shared/savePlatformSettings.ts
@@ -0,0 +1,17 @@
+import type { ApiContextType } from '@/context/ApiContext';
+
+/** Persist the platform editor's auxiliary settings through the Settings owner. */
+export async function savePlatformSettings(
+ api: Pick<ApiContextType, 'saveSettings'>,
+ platform: string,
+ data: Record<string, unknown>,
+ canManageAccessMembers: boolean,
+): Promise<void> {
+ const guilds = data.discordGuildAllowlist;
+ if (canManageAccessMembers && platform === 'discord' && Array.isArray(guilds)
+ && (guilds.length > 0 || data.discordGuildAllowlistTouched === true)) {
+ await api.saveSettings({
+ guilds: Object.fromEntries(guilds.map((id: string) => [id, { enabled: true }])),
+ }, 'discord');
+ }
+}
diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.ts
index 139a56dad..de61a5dd5 100644
--- a/ui/src/components/settings/shared/useBackendRuntime.ts
+++ b/ui/src/components/settings/shared/useBackendRuntime.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useApi } from '@/context/ApiContext';
@@ -45,6 +45,8 @@ export interface BackendRuntimeState {
savingRuntime: boolean;
/** True once the user has typed a path different from the saved one. */
runtimeDirty: boolean;
+ /** Changes after a runtime mutation settles; consumers must read fresh state. */
+ connectionRevision: number;
setCliPath: (next: string) => void;
setInstallOutputOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
@@ -52,13 +54,15 @@ export interface BackendRuntimeState {
detect: (binary?: string) => Promise<void>;
/** Calls ``installAgent`` then re-runs detect with the resolved path. */
install: () => Promise<void>;
- /** Persists ``enabled`` + ``cliPath`` into V2Config. */
+ /** Persists this backend's CLI path; enablement has its own mutation. */
onSaveRuntime: () => Promise<void>;
- /** Optimistically flip ``enabled`` + persist; rolls back on save failure. */
+ /** Optimistically flip enabled, then reconcile the latest persisted intent. */
toggleEnabled: () => void;
/**
* Pass to ``BackendLifecycleChip.onChanged``. Updates ``cliPath`` when
- * the chip reports a fresh install path and re-runs detect.
+ * the chip reports a fresh install path and re-runs detect. A null
+ * notification from onOperationChange(false) observes every settlement,
+ * including rejected restart/upgrade, without modifying a path draft.
*/
handleLifecycleChanged: (info: { installedPath?: string | null } | undefined | null) => Promise<void>;
}
@@ -114,20 +118,36 @@ export function useBackendRuntime({
const [installResult, setInstallResult] = useState<InstallResult | null>(null);
const [installOutputOpen, setInstallOutputOpen] = useState(false);
const [savingRuntime, setSavingRuntime] = useState(false);
+ const [connectionRevision, setConnectionRevision] = useState(0);
+ const mutationQueue = useRef(Promise.resolve());
+ const enabledIntent = useRef(0);
+ const pathIntent = useRef(0);
+ const detectionToken = useRef(0);
+ const pathState = useRef({ cliPath, savedCliPath });
+ pathState.current = { cliPath, savedCliPath };
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; enabledIntent.current += 1; detectionToken.current += 1; };
+ }, []);
const detect = useCallback(
async (binary?: string) => {
+ const token = ++detectionToken.current;
+ const intent = pathIntent.current;
setDetecting(true);
try {
const result = await api.detectCli(binary || cliPath || defaultCli);
+ if (!mounted.current || detectionToken.current !== token || pathIntent.current !== intent) return;
const nextPath = result.path || cliPath || defaultCli;
setCliPath(nextPath);
setCliStatus(result.found ? 'ok' : 'missing');
} catch (e) {
+ if (!mounted.current || detectionToken.current !== token || pathIntent.current !== intent) return;
setCliStatus('missing');
showToast(errorMessage(e) || t('common.saveFailed'), 'error');
} finally {
- setDetecting(false);
+ if (mounted.current && detectionToken.current === token) setDetecting(false);
}
},
[api, cliPath, defaultCli, showToast, t],
@@ -171,85 +191,113 @@ export function useBackendRuntime({
}, [api, backend, defaultCli]);
const install = useCallback(async () => {
+ const intent = pathIntent.current;
setInstalling(true);
setInstallResult(null);
setInstallOutputOpen(false);
try {
const result = await api.installAgent(backend);
+ if (!mounted.current) return;
const installedPath =
typeof result.path === 'string' && result.path ? result.path : null;
setInstallResult({ ok: result.ok, message: result.message, output: result.output });
if (result.ok) {
- if (installedPath) setCliPath(installedPath);
- await detect(installedPath || cliPath);
+ if (installedPath) setSavedCliPath(installedPath);
+ if (pathIntent.current === intent) {
+ if (installedPath) setCliPath(installedPath);
+ await detect(installedPath || cliPath);
+ }
showToast(result.message || t('agentDetection.installAgent'), 'success');
} else {
showToast(result.message || t('common.saveFailed'), 'error');
}
} catch (e) {
+ if (!mounted.current) return;
setInstallResult({ ok: false, message: String(e), output: null });
showToast(errorMessage(e) || String(e), 'error');
} finally {
- setInstalling(false);
+ if (mounted.current) {
+ setConnectionRevision((revision) => revision + 1);
+ setInstalling(false);
+ }
}
}, [api, backend, cliPath, detect, showToast, t]);
const onSaveRuntime = useCallback(async () => {
setSavingRuntime(true);
- try {
- // Patch-write shape: only THIS backend's fields. Rebuilding the
- // whole agents section from a pre-save GET would overwrite a
- // concurrent cross-process write (e.g. an installer updating
- // another backend's cli_path) inside the locked merge, and the
- // subsequent rolling refresh could switch the live backend to the
- // obsolete path.
- const saved = await api.mutateConfig([
- setConfigField(['agents', backend, 'enabled'], enabled),
- setConfigField(['agents', backend, 'cli_path'], cliPath || defaultCli),
- ]);
- // The config boundary owns both persistence and live runtime
- // reconciliation. A second route-level restart would refresh the backend
- // twice and could interrupt a transport that was just rebuilt.
- assertBackendRuntimeApplied(saved, t('common.saveFailed'));
- setSavedCliPath(cliPath);
- showToast(t('common.saved'), 'success');
- } catch (e) {
- showToast(errorMessage(e) || t('common.saveFailed'), 'error');
- } finally {
- setSavingRuntime(false);
- }
- }, [api, backend, cliPath, defaultCli, enabled, showToast, t]);
+ const path = cliPath || defaultCli;
+ // Save edits only the CLI field. Enablement has its own serialized toggle;
+ // including it here could overwrite a newer optimistic on/off intent.
+ const operation = mutationQueue.current.then(async () => {
+ try {
+ const saved = await api.mutateConfig([setConfigField(['agents', backend, 'cli_path'], path)]);
+ if (!mounted.current) return;
+ setSavedCliPath(path); // persistence succeeded even if application failed
+ assertBackendRuntimeApplied(saved, t('common.saveFailed'));
+ showToast(t('common.saved'), 'success');
+ } catch (e) {
+ if (mounted.current) showToast(errorMessage(e) || t('common.saveFailed'), 'error');
+ } finally {
+ if (mounted.current) {
+ setSavingRuntime(false);
+ setConnectionRevision((revision) => revision + 1);
+ }
+ }
+ });
+ mutationQueue.current = operation;
+ await operation;
+ }, [api, backend, cliPath, defaultCli, showToast, t]);
const toggleEnabled = useCallback(() => {
const next = !enabled;
+ const intent = ++enabledIntent.current;
setEnabled(next);
- // Persist immediately so the routing layer picks up the flip
- // without forcing the user to also click Save (the Save button
- // is reserved for cli_path edits). Roll back only if the config write
- // itself fails; after a successful save the UI should reflect persisted state.
- void (async () => {
+ mutationQueue.current = mutationQueue.current.then(async () => {
let saved = false;
try {
- // Patch-write shape: only this backend's enabled flag.
- const savedConfig = await api.mutateConfig([
- setConfigField(['agents', backend, 'enabled'], next),
- ]);
+ const savedConfig = await api.mutateConfig([setConfigField(['agents', backend, 'enabled'], next)]);
saved = true;
+ if (!mounted.current || enabledIntent.current !== intent) return;
+ const persisted = savedConfig?.agents?.[backend]?.enabled;
+ setEnabled(typeof persisted === 'boolean' ? persisted : next);
assertBackendRuntimeApplied(savedConfig, t('common.saveFailed'));
} catch (e) {
+ if (!mounted.current || enabledIntent.current !== intent) return;
showToast(errorMessage(e) || t('common.saveFailed'), 'error');
- if (!saved) setEnabled(!next);
+ if (!saved) {
+ // A rejected request may have lost its response after persistence.
+ // Reconcile the uncached config projection instead of guessing rollback.
+ try {
+ const fresh = await api.getBackendConnection(backend);
+ if (!fresh.ok) throw new Error(fresh.message || t('common.saveFailed'));
+ if (mounted.current && enabledIntent.current === intent) setEnabled(fresh.enabled);
+ } catch (cause) {
+ if (mounted.current && enabledIntent.current === intent) showToast(errorMessage(cause) || t('common.saveFailed'), 'error');
+ }
+ }
+ } finally {
+ if (mounted.current && enabledIntent.current === intent) setConnectionRevision((revision) => revision + 1);
}
- })();
+ });
}, [api, backend, enabled, showToast, t]);
const handleLifecycleChanged = useCallback(
async (info: { installedPath?: string | null } | undefined | null) => {
+ if (!mounted.current) return;
+ if (!info) {
+ if (mounted.current) setConnectionRevision((revision) => revision + 1);
+ return;
+ }
const installedPath = info?.installedPath || null;
- if (installedPath) setCliPath(installedPath);
- await detect(installedPath || cliPath);
+ if (installedPath) setSavedCliPath(installedPath);
+ // The lifecycle chip may still hold the callback from before a user edit.
+ // Read the current draft before accepting its installed path.
+ if (pathState.current.cliPath === pathState.current.savedCliPath) {
+ if (installedPath) setCliPath(installedPath);
+ await detect(installedPath || pathState.current.cliPath);
+ }
},
- [cliPath, detect],
+ [detect],
);
const runtimeDirty = cliPath !== savedCliPath;
@@ -266,7 +314,8 @@ export function useBackendRuntime({
installOutputOpen,
savingRuntime,
runtimeDirty,
- setCliPath,
+ connectionRevision,
+ setCliPath: (next) => { pathIntent.current += 1; setCliPath(next); },
setInstallOutputOpen,
detect,
install,
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index ab868325b..902adbbd9 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
ArrowLeft,
ArrowRight,
@@ -20,21 +20,23 @@ import '../onboarding/onboarding.css';
import type { BackendId } from '../visual';
import { BackendLifecycleChip } from '../settings/BackendLifecycleChip';
import { ToggleSwitch } from '../settings/SettingsPrimitives';
-import { BackendProviderConfig } from '../settings/providers/BackendProviderConfig';
+import { BackendConnectionDialog } from '../onboarding/BackendConnectionDialog';
+import type { BackendConnectionState } from '@/context/ApiContext';
+import { setConfigField } from '@/lib/configMutations';
import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';
import { MigrationBanner } from '../settings/models/MigrationBanner';
import { useModelHubCapability } from '../settings/models/useModelHubCapability';
import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';
import { useOpencodePermission } from '../settings/shared/useOpencodePermission';
import { Button } from '../ui/button';
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';
import { DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';
interface AgentDetectionProps {
data: any;
- onNext: (data: any) => void;
+ onNext: (data: any) => void | Promise<void>;
onBack?: (data?: { agents: Record<string, AgentState> }) => void;
isPage?: boolean;
+ completionRecovery?: React.ReactNode;
onSave?: (data: { agents: Record<string, AgentState> }) => Promise<void> | void;
}
@@ -73,7 +75,7 @@ const normalizeAgents = (source: any): Record<string, AgentState> => {
// description, status pill, enable switch) and an action row (configure
// provider / set up Allow / install). Detection runs automatically on mount —
// the user enables what they have and installs anything missing.
-export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave }) => {
+export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave, completionRecovery }) => {
const { t } = useTranslation();
const api = useApi();
const modelHubEnabled = useModelHubCapability();
@@ -85,7 +87,17 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
>({});
const [expandedOutputs, setExpandedOutputs] = useState<Record<string, boolean>>({});
// Which backend's "Configure provider" modal is open (wizard mode only).
- const [providerModal, setProviderModal] = useState<string | null>(null);
+ const [providerModal, setProviderModal] = useState<{ backend: RuntimeBackendId; method: 'oauth' | 'api_key' } | null>(null);
+ const [connections, setConnections] = useState<Partial<Record<RuntimeBackendId, BackendConnectionState>>>({});
+ const [connectionPending, setConnectionPending] = useState<Partial<Record<RuntimeBackendId, boolean>>>({});
+ const [connectionErrors, setConnectionErrors] = useState<Partial<Record<RuntimeBackendId, string>>>({});
+ const [pendingWrites, setPendingWrites] = useState<Partial<Record<RuntimeBackendId, boolean>>>({});
+ const [entering, setEntering] = useState(false);
+ const [entryError, setEntryError] = useState('');
+ const connectionTokens = useRef<Partial<Record<RuntimeBackendId, number>>>({});
+ const enableQueue = useRef(Promise.resolve());
+ const enableIntent = useRef<Partial<Record<RuntimeBackendId, number>>>({});
+ const pendingEnable = useRef<Partial<Record<RuntimeBackendId, number>>>({});
// One provider modal/reconciliation at a time; Configure and navigation stay
// disabled until persisted fields and the subsequent detection reach agents.
const [syncing, setSyncing] = useState(false);
@@ -95,6 +107,35 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const detectionTokens = useRef<Record<string, number>>({});
const isMissing = (agent: AgentState) => agent.status === 'missing';
+ const refreshConnection = useCallback(async (name: RuntimeBackendId, receiptError = '') => {
+ if (pendingEnable.current[name] !== undefined) return;
+ const intent = enableIntent.current[name];
+ const token = (connectionTokens.current[name] || 0) + 1;
+ connectionTokens.current[name] = token;
+ setConnectionPending((current) => ({ ...current, [name]: true }));
+ setConnectionErrors((current) => ({ ...current, [name]: receiptError }));
+ try {
+ const result = await api.getBackendConnection(name);
+ if (connectionTokens.current[name] !== token || enableIntent.current[name] !== intent) return;
+ if (!result.ok) throw new Error(result.message || t('onboarding.connection.readFailed'));
+ setConnections((current) => ({ ...current, [name]: result }));
+ setAgents((current) => ({ ...current, [name]: { ...current[name], enabled: result.enabled } }));
+ } catch (error) {
+ if (connectionTokens.current[name] !== token || enableIntent.current[name] !== intent) return;
+ setConnections((current) => ({ ...current, [name]: undefined }));
+ setConnectionErrors((current) => ({ ...current, [name]: String(error) }));
+ } finally {
+ if (connectionTokens.current[name] === token) setConnectionPending((current) => ({ ...current, [name]: false }));
+ }
+ }, [api, t]);
+ useEffect(() => {
+ if (!isPage) for (const name of ASSISTANT_ORDER) void refreshConnection(name);
+ return () => { for (const name of ASSISTANT_ORDER) {
+ connectionTokens.current[name] = (connectionTokens.current[name] || 0) + 1;
+ enableIntent.current[name] = (enableIntent.current[name] || 0) + 1;
+ } };
+ }, [refreshConnection, isPage]);
+
const isAnyInstalling = Object.values(installingAgents).some(Boolean);
useEffect(() => {
@@ -118,6 +159,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
return next;
});
}
+ if (!isPage) void refreshConnection(name as RuntimeBackendId);
setAgents((prev) => ({
...prev,
[name]: {
@@ -180,10 +222,31 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
};
const toggle = (name: string, enabled: boolean) => {
- setAgents((prev) => ({
- ...prev,
- [name]: { ...prev[name], enabled },
- }));
+ setAgents((prev) => ({ ...prev, [name]: { ...prev[name], enabled } }));
+ if (isPage) return;
+ const backend = name as RuntimeBackendId;
+ const intent = (enableIntent.current[backend] || 0) + 1;
+ enableIntent.current[backend] = intent;
+ pendingEnable.current[backend] = intent;
+ connectionTokens.current[backend] = (connectionTokens.current[backend] || 0) + 1;
+ setConnectionPending((current) => ({ ...current, [backend]: true }));
+ setConnections((current) => ({ ...current, [backend]: undefined }));
+ // Persist each queued intent, but only the latest intent may publish state.
+ enableQueue.current = enableQueue.current.then(async () => {
+ let receiptError = '';
+ try {
+ const saved = await api.mutateConfig([setConfigField(['agents', backend, 'enabled'], enabled)]);
+ const applied = saved?.agent_backend_runtime;
+ if (applied && !applied.hot_reconciled && !applied.restart_scheduled && !applied.apply_on_next_start) {
+ receiptError = applied.restart_error || applied.error || t('onboarding.connection.applyFailed');
+ }
+ } catch (error) { receiptError = String(error); }
+ if (enableIntent.current[backend] !== intent) return;
+ delete pendingEnable.current[backend];
+ // This uncached projection reads persisted enabled even after a rejected
+ // write. Apply failure cannot roll back config that was already committed.
+ await refreshConnection(backend, receiptError);
+ });
};
const installAgent = async (name: string) => {
@@ -218,6 +281,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
} finally {
pendingInstalls.current.delete(name);
setInstallingAgents((prev) => ({ ...prev, [name]: false }));
+ if (!isPage) void refreshConnection(name as RuntimeBackendId);
}
};
@@ -225,29 +289,20 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
setExpandedOutputs((prev) => ({ ...prev, [name]: !prev[name] }));
};
- // Gate the wizard's Continue when OpenCode is enabled and ready but hasn't
- // been granted ``permission: "allow"`` yet — without it every tool call
- // silently waits for an approval prompt avibe can't answer, so the
- // user must write it before proceeding. Fails open while the status is still
- // unknown (statusLoaded false) so a transient probe error can't trap the
- // user, and never gates the Settings page (isPage).
const opencodeAgent = agents['opencode'];
- const opencodeNeedsPermission =
- !isPage &&
- !!opencodeAgent?.enabled &&
- opencodeAgent?.status === 'ok' &&
- permission.statusLoaded &&
- !permission.permissionAllowed;
- const canContinue =
- Object.values(agents).some((agent) => agent.enabled) && !opencodeNeedsPermission;
-
+ const readyBackends = ASSISTANT_ORDER.filter((name) => agents[name].enabled && agents[name].status === 'ok'
+ && !installingAgents[name] && !detectingAgents[name] && !connectionPending[name]
+ && !pendingWrites[name] && !connectionErrors[name] && connections[name]?.entry_eligible);
+ const canContinue = isPage ? Object.values(agents).some((agent) => agent.enabled) : readyBackends.length > 0;
const handlePrimaryAction = async () => {
- const nextData = { agents };
- if (isPage && onSave) {
- await onSave(nextData);
- return;
- }
- onNext(nextData);
+ if (entering) return;
+ if (isPage && onSave) { await onSave({ agents }); return; }
+ setEntering(true); setEntryError('');
+ try {
+ await enableQueue.current;
+ await onNext({ agents, readyBackends });
+ } catch (error) { setEntryError(String(error)); }
+ finally { setEntering(false); }
};
@@ -342,7 +397,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
type="button"
variant="secondary"
size="sm"
- onClick={() => setProviderModal(name)}
+ onClick={() => setProviderModal({ backend: name as RuntimeBackendId, method: 'oauth' })}
disabled={syncing}
>
<Sliders className="size-3.5" />
@@ -414,46 +469,20 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</>
) : null;
- const providerDialog = (<>
- {/* Wizard-mode provider config modal — reuses the same component tree as
- the Settings route. Page mode navigates to the route instead (see the
- Link above), so the dialog is wizard-only. */}
- {!isPage && (
- <Dialog
- open={providerModal !== null}
- onOpenChange={(open) => {
- if (!open) {
- const name = providerModal;
- setProviderModal(null);
- // Re-read config + re-detect so runtime edits (enabled / cli_path /
- // provider defaults) and the status pill reflect whatever changed
- // inside the modal before Configure or navigation is available.
- if (name) void syncBackendFromConfig(name);
- // The Configure-provider modal embeds its OWN useOpencodePermission
- // instance, so a permission write inside it doesn't touch this
- // wizard's gate/callout state. Re-read opencode.json so the gate
- // clears and the callout hides once allow was granted in the modal.
- if (name === 'opencode') void permission.refreshStatus();
- }
- }}
- >
- <DialogContent className="max-w-3xl">
- <DialogHeader>
- <DialogTitle>
- {providerModal
- ? t('agentDetection.configureProviderTitle', { name: getBackendUiMeta(providerModal).label })
- : ''}
- </DialogTitle>
- </DialogHeader>
- {providerModal && (
- // Config saves reconcile a live controller at the shared API
- // boundary and defer naturally when the controller is stopped.
- <BackendProviderConfig backend={providerModal as RuntimeBackendId} hideEnableToggle />
- )}
- </DialogContent>
- </Dialog>
- )}
- </>);
+ const providerDialog = !isPage && providerModal && <BackendConnectionDialog
+ key={`${providerModal.backend}:${providerModal.method}`} backend={providerModal.backend} method={providerModal.method}
+ onClose={() => {
+ const name = providerModal.backend;
+ setProviderModal(null);
+ void syncBackendFromConfig(name);
+ void refreshConnection(name);
+ }}
+ onWriteState={(pending) => {
+ const name = providerModal.backend;
+ setPendingWrites((current) => ({ ...current, [name]: pending }));
+ if (!pending) void refreshConnection(name);
+ }}
+ onConnected={async () => { await refreshConnection(providerModal.backend); }} />;
if (isPage) {
return (
@@ -493,8 +522,13 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
return <AssistantRow key={name} backend={name} status={agent.status || 'unknown'}
installing={!!installingAgents[name]} detecting={!!detectingAgents[name]} error={error}
onInstall={() => void installAgent(name)} onDetect={() => void detect(name, agent.cli_path)}
- onConfigure={() => setProviderModal(name)}
- configuringDisabled={syncing}
+ onConfigure={() => setProviderModal({ backend: name, method: 'oauth' })}
+ onAddKey={() => setProviderModal({ backend: name, method: 'api_key' })}
+ connection={!connectionErrors[name] && connections[name]?.ready ? (connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key') : undefined}
+ connectionPending={connectionPending[name]}
+ connectionError={connectionErrors[name] || connections[name]?.message}
+ onRefreshConnection={() => void refreshConnection(name)}
+ configuringDisabled={syncing || pendingWrites[name] || !agent.enabled || agent.status !== 'ok'}
enabledControl={<label className="flex items-center gap-2 text-xs text-muted">
<input type="checkbox" className="size-3.5 accent-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
checked={agent.enabled} onChange={(event) => toggle(name, event.target.checked)} />
@@ -502,6 +536,10 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</label>}
lifecycle={<BackendLifecycleChip name={name} enabled={agent.enabled} cliStatus={agent.status || 'unknown'}
readyLabel={t('onboarding.setup.installed')}
+ onOperationChange={(pending) => {
+ setPendingWrites((current) => ({ ...current, [name]: pending }));
+ if (!pending) void refreshConnection(name);
+ }}
onChanged={async (info) => {
const installedPath = info?.installedPath || agent.cli_path;
setAgents((previous) => ({ ...previous, [name]: { ...previous[name], cli_path: installedPath } }));
@@ -512,16 +550,18 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</div>
<OpencodePermissionSetup cliReady={opencodeAgent?.status === 'ok'}
permissionAllowed={permission.permissionAllowed} state={permission.state} message={permission.message}
- onSetup={() => void permission.setupPermission()} className="w-full" />
+ onSetup={() => void permission.setupPermission().then(() => refreshConnection('opencode'))} className="w-full" />
{providerDialog}
+ {completionRecovery}
<div className="onboarding-setup-footer">
<Button type="button" variant="brand" className="group onboarding-primary-action" onClick={() => void handlePrimaryAction()}
- disabled={!canContinue || syncing}>
- {t('common.continue')}
+ disabled={!canContinue || syncing || entering || Boolean(completionRecovery)}>
+ {t(entering ? 'onboarding.connection.connecting' : 'onboarding.connection.enter')}
<ArrowRight size={16} className="motion-safe:transition-transform motion-safe:duration-180 motion-safe:group-hover:translate-x-1" />
</Button>
- {opencodeNeedsPermission && <p className="text-center text-xs text-gold-ink">{t('agentDetection.permissionGateHint')}</p>}
- {onBack && <Button type="button" variant="ghost" size="sm" disabled={syncing} onClick={() => onBack({ agents })}><ArrowLeft size={14} />{t('common.back')}</Button>}
+ <p className="text-center text-xs text-muted">{t(readyBackends.some((name) => connections[name]?.ready) ? 'onboarding.connection.entryReady' : canContinue ? 'onboarding.connection.entryStopped' : 'onboarding.connection.entryHint')}</p>
+ {entryError && <div role="alert" className="connection-error">{entryError} <Button variant="link" size="sm" disabled={entering} onClick={() => void handlePrimaryAction()}>{t('common.retry')}</Button></div>}
+ {onBack && <Button type="button" variant="ghost" size="sm" disabled={syncing || entering || Boolean(completionRecovery)} onClick={() => onBack({ agents })}><ArrowLeft size={14} />{t('common.back')}</Button>}
</div>
</div>
);
diff --git a/ui/src/components/visual/BackendIcon.tsx b/ui/src/components/visual/BackendIcon.tsx
index 5621f6351..833491059 100644
--- a/ui/src/components/visual/BackendIcon.tsx
+++ b/ui/src/components/visual/BackendIcon.tsx
@@ -1,6 +1,7 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
import { getBackendUiMeta, type BackendId } from '@/lib/agentBackends';
+import { BACKEND_BRAND_MARKS } from './backendBrandMarks';
export type { BackendId } from '@/lib/agentBackends';
@@ -10,20 +11,42 @@ interface BackendIconProps extends React.HTMLAttributes<HTMLSpanElement> {
/**
* `block` (default) renders a square tile with mono initials, tinted per-backend.
* `glyph` renders just the lucide icon in the brand color (no tile, no border).
+ * `brand` opts into the authored brand mark, without changing other surfaces.
*/
- variant?: 'block' | 'glyph';
+ variant?: 'block' | 'glyph' | 'brand';
+ /** Canvas keeps authored whitespace; mark fits OpenCode's 4:5 bounds in logo wells. */
+ brandFit?: 'canvas' | 'mark';
}
export const BackendIcon: React.FC<BackendIconProps> = ({
backend,
size = 40,
variant = 'block',
+ brandFit = 'canvas',
className,
...props
}) => {
const meta = getBackendUiMeta(backend);
- if (variant === 'glyph') {
+ if (variant === 'brand' && Object.prototype.hasOwnProperty.call(BACKEND_BRAND_MARKS, backend)) {
+ const mark = BACKEND_BRAND_MARKS[backend as keyof typeof BACKEND_BRAND_MARKS];
+ const fittedOpenCode = backend === 'opencode' && brandFit === 'mark';
+ return (
+ <span
+ className={cn('inline-flex shrink-0 items-center justify-center text-foreground', className)}
+ style={{ width: size, height: size }}
+ {...props}
+ >
+ <svg width={fittedOpenCode ? '80%' : '100%'} height="100%"
+ viewBox={fittedOpenCode ? '4 2 16 20' : '0 0 24 24'}
+ aria-hidden="true" focusable="false">
+ <path d={mark.path} fill={mark.fill} fillRule={mark.fillRule} />
+ </svg>
+ </span>
+ );
+ }
+
+ if (variant === 'glyph' || variant === 'brand') {
const Icon = meta.Icon;
return (
<span
diff --git a/ui/src/components/visual/backendBrandMarks.ts b/ui/src/components/visual/backendBrandMarks.ts
new file mode 100644
index 000000000..966b17455
--- /dev/null
+++ b/ui/src/components/visual/backendBrandMarks.ts
@@ -0,0 +1,20 @@
+// Exact authored vectors from avibe-docs/design_desktop.pen.
+// Source SHA256: 115c69604b50e32823bcead4bd6c9269c8178b58d66a73b2e00db4a06d2caeb3.
+// Welcome: dAO38 / o2x2l0 / Rxw0c; inset OpenCode: VE60T (also dialog v9S8Li).
+export const BACKEND_BRAND_MARKS = {
+ claude: {
+ path: "M4.709 15.955l4.72-2.647 0.08-0.23-0.08-0.128h-0.229l-0.79-0.048-2.698-0.073-2.339-0.097-2.266-0.122-0.571-0.121-0.536-0.705 0.055-0.352 0.48-0.321 0.686 0.06 1.52 0.103 2.278 0.158 1.652 0.097 2.449 0.255h0.389l0.055-0.157-0.134-0.098-0.103-0.097-2.358-1.596-2.552-1.688-1.336-0.972-0.724-0.491-0.364-0.462-0.158-1.008 0.656-0.722 0.881 0.06 0.225 0.061 0.893 0.686 1.908 1.476 2.491 1.833 0.365 0.304 0.145-0.103 0.019-0.073-0.164-0.274-1.355-2.446-1.446-2.49-0.644-1.032-0.17-0.619a2.97 2.97 0 0 1-0.104-0.729l0.748-1.013 0.413-0.134 0.996 0.134 0.42 0.364 0.62 1.414 1.002 2.229 1.555 3.03 0.456 0.898 0.243 0.832 0.091 0.255h0.158v-0.146l0.128-1.706 0.237-2.095 0.23-2.695 0.08-0.76 0.376-0.91 0.747-0.492 0.584 0.28 0.48 0.685-0.067 0.444-0.286 1.851-0.559 2.903-0.364 1.942h0.212l0.243-0.242 0.985-1.306 1.652-2.064 0.73-0.82 0.85-0.904 0.547-0.431h1.033l0.76 1.129-0.34 1.166-1.064 1.347-0.881 1.142-1.264 1.7-0.79 1.36 0.073 0.11 0.188-0.02 2.856-0.606 1.543-0.28 1.841-0.315 0.833 0.388 0.091 0.395-0.328 0.807-1.969 0.486-2.309 0.462-3.439 0.813-0.042 0.03 0.049 0.061 1.549 0.146 0.662 0.036h1.622l3.02 0.225 0.79 0.522 0.474 0.638-0.079 0.485-1.215 0.62-1.64-0.389-3.829-0.91-1.312-0.329h-0.182v0.11l1.093 1.068 2.006 1.81 2.509 2.33 0.127 0.578-0.322 0.455-0.34-0.049-2.205-1.657-0.851-0.747-1.926-1.62h-0.128v0.17l0.444 0.649 2.345 3.521 0.122 1.08-0.17 0.353-0.608 0.213-0.668-0.122-1.374-1.925-1.415-2.167-1.143-1.943-0.14 0.08-0.674 7.254-0.316 0.37-0.729 0.28-0.607-0.461-0.322-0.747 0.322-1.476 0.389-1.924 0.315-1.53 0.286-1.9 0.17-0.632-0.012-0.042-0.14 0.018-1.434 1.967-2.18 2.945-1.726 1.845-0.414 0.164-0.717-0.37 0.067-0.662 0.401-0.589 2.388-3.036 1.44-1.882 0.93-1.086-0.006-0.158h-0.055l-6.343 4.116-1.13 0.146-0.487-0.456 0.061-0.746 0.231-0.243 1.908-1.312-0.006 0.006z",
+ fill: "#D97757",
+ fillRule: "nonzero",
+ },
+ codex: {
+ path: "M9.205 8.658v-2.26c0-0.19 0.072-0.333 0.238-0.428l4.543-2.616c0.619-0.357 1.356-0.523 2.117-0.523 2.854 0 4.662 2.212 4.662 4.566 0 0.167 0 0.357-0.024 0.547l-4.71-2.759a0.797 0.797 0 0 0-0.856 0l-5.97 3.473z m10.609 8.8v-5.398c0-0.333-0.143-0.57-0.429-0.737l-5.97-3.473 1.95-1.118a0.433 0.433 0 0 1 0.476 0l4.543 2.617c1.309 0.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163z m-12.012-4.755l-1.95-1.142c-0.167-0.095-0.239-0.238-0.239-0.428v-5.234c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927 0.333 2.712 0.928l-4.686 2.712c-0.285 0.166-0.428 0.404-0.428 0.737v6.898z m4.198 2.425l-2.795-1.57v-3.33l2.795-1.57 2.795 1.57v3.33l-2.795 1.57z m1.796 7.23c-1 0-1.927-0.332-2.712-0.927l4.686-2.712c0.285-0.166 0.428-0.404 0.428-0.737v-6.898l1.974 1.142c0.167 0.095 0.238 0.238 0.238 0.428v5.233c0 2.545-1.974 4.472-4.614 4.472z m-5.637-5.303l-4.544-2.617c-1.308-0.761-2.188-2.378-2.188-3.948a4.482 4.482 0 0 1 2.783-4.163v5.423c0 0.333 0.143 0.571 0.428 0.738l5.947 3.449-1.95 1.118a0.432 0.432 0 0 1-0.476 0z m-0.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-0.19 0.024-0.38 0.047-0.57l4.686 2.71c0.286 0.167 0.571 0.167 0.856 0l5.97-3.448v2.26c0 0.19-0.07 0.333-0.237 0.428l-4.543 2.616c-0.619 0.357-1.356 0.523-2.117 0.523z m5.899 2.83a5.947 5.947 0 0 0 5.827-4.756c2.664-0.69 4.377-3.189 4.377-5.733 0-1.665-0.713-3.282-1.998-4.448 0.119-0.5 0.19-0.999 0.19-1.498 0-3.401-2.759-5.947-5.946-5.947-0.642 0-1.26 0.095-1.88 0.31a5.962 5.962 0 0 0-4.161-1.713 5.947 5.947 0 0 0-5.827 4.757c-2.665 0.69-4.378 3.188-4.378 5.733 0 1.666 0.713 3.283 1.998 4.448-0.119 0.5-0.19 1-0.19 1.499 0 3.401 2.759 5.946 5.946 5.946 0.642 0 1.26-0.095 1.88-0.309a5.96 5.96 0 0 0 4.162 1.713z",
+ fill: "currentColor",
+ fillRule: "evenodd",
+ },
+ opencode: {
+ path: "M16 6h-8v12h8v-12z m4 16h-16v-20h16v20z",
+ fill: "currentColor",
+ fillRule: "evenodd",
+ },
+} as const;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 0fa37795f..fc8712d2d 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -599,6 +599,7 @@ export type ApiContextType = {
deleteMemoryData: (confirmLoss: true) => Promise<MemoryDataOperationResult>;
wakeMemory: () => Promise<MemoryWakeResult>;
repairMemory: (confirmLoss: true) => Promise<MemoryDataOperationResult>;
+ getBackendConnection: (name: 'claude' | 'codex' | 'opencode') => Promise<BackendConnectionState>;
getBackendRuntime: (name: string) => Promise<BackendRuntimeInfo>;
restartBackend: (name: string) => Promise<BackendRestartResult>;
getCodexAuth: () => Promise<CodexAuthState>;
@@ -646,8 +647,8 @@ export type ApiContextType = {
deleteOpencodeCustomProvider: (providerId: string) => Promise<OpencodeMutationResult>;
setOpencodeProviderAuth: (
providerId: string,
- apiKey: string,
- baseUrl?: string,
+ apiKey?: string,
+ baseUrl?: string | null,
) => Promise<OpencodeMutationResult>;
deleteOpencodeProviderAuth: (providerId: string) => Promise<OpencodeMutationResult>;
setOpencodeDefaultProvider: (providerId: string) => Promise<OpencodeMutationResult>;
@@ -2244,6 +2245,19 @@ export type MemoryDataOperationResult = {
}>;
};
+export type BackendConnectionState = {
+ ok: boolean;
+ backend: 'claude' | 'codex' | 'opencode';
+ installed: boolean;
+ enabled: boolean;
+ auth: 'subscription' | 'api_key' | 'none' | 'unknown';
+ application: 'applied' | 'draining' | 'failed' | 'stopped' | 'unknown';
+ ready: boolean;
+ entry_eligible: boolean;
+ permission_required?: boolean;
+ message?: string;
+};
+
export type BackendRuntimeInfo = {
ok: boolean;
name?: string;
@@ -2406,11 +2420,12 @@ export type OAuthWebState =
export type OAuthWebStartResult = {
ok: boolean;
flow_id?: string;
- backend?: 'claude' | 'codex';
+ backend?: 'claude' | 'codex' | 'opencode';
state?: OAuthWebState;
url?: string | null;
device_code?: string | null;
awaiting_code?: boolean;
+ callback_kind?: 'code' | 'device' | 'redirect' | null;
error?: string;
detail?: string;
};
@@ -2418,11 +2433,12 @@ export type OAuthWebStartResult = {
export type OAuthWebStatus = {
ok: boolean;
flow_id?: string;
- backend?: 'claude' | 'codex';
+ backend?: 'claude' | 'codex' | 'opencode';
state?: OAuthWebState;
url?: string | null;
device_code?: string | null;
awaiting_code?: boolean;
+ callback_kind?: 'code' | 'device' | 'redirect' | null;
error?: string | null;
};
@@ -2520,6 +2536,7 @@ export type OpencodeOptionsResult = {
export type OpencodeMutationResult = {
ok: boolean;
+ restart?: BackendRestartResult;
message?: string;
default_provider?: string;
provider_id?: string;
@@ -3822,6 +3839,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
deleteMemoryData: (confirmLoss) => postJson('/api/memory/delete-data', { confirm_loss: confirmLoss }, { handleError: false }),
wakeMemory: () => postJson('/api/memory/runtime/wake', {}, { handleError: false }),
repairMemory: (confirmLoss) => postJson('/api/memory/repair', { confirm_loss: confirmLoss }, { handleError: false }),
+ getBackendConnection: (name) => getJson(`/api/backend/${encodeURIComponent(name)}/connection`),
getBackendRuntime: (name) => getJson(`/api/backend/${encodeURIComponent(name)}/runtime`),
restartBackend: (name) => postJson(`/api/backend/${encodeURIComponent(name)}/restart`, {}),
getCodexAuth: () => getJson('/api/backend/codex/auth'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 3a5353c34..d40238b4d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -5255,6 +5255,100 @@
"api_key": "API Key",
"subscriptionConnected": "Subscription connected",
"api_keyConnected": "API Key connected"
+ },
+ "connection": {
+ "method": "Connection method",
+ "subscription": "Subscription",
+ "claudeLogin": "Claude account",
+ "claudeCredentials": "API credentials",
+ "claudeSignIn": "Sign in with Claude",
+ "codexSignIn": "Sign in with ChatGPT",
+ "openaiKey": "OpenAI API Key",
+ "claudeAccount": "Sign in with Anthropic",
+ "codexAccount": "Sign in with your ChatGPT account",
+ "claudeHint": "Approve access in your browser, then paste the authorization code here",
+ "deviceHint": "Get a device code, sign in and authorize in your browser. The connection completes automatically.",
+ "codeHint": "Paste the full code, including everything after #.",
+ "keyHint": "Use the API Key supplied by your provider.",
+ "tokenHint": "For relay services that require a Bearer Token.",
+ "baseUrl": "Base URL (optional)",
+ "providerDefault": "Use provider default URL",
+ "claudeUrlHint": "Leave empty for Anthropic. The URL does not change the credential type.",
+ "urlHint": "Leave empty to use the provider’s default URL.",
+ "invalidUrl": "Enter a valid http:// or https:// URL.",
+ "saveConnect": "Save and connect",
+ "finishConnect": "Complete connection",
+ "connecting": "Connecting…",
+ "waiting": "Waiting for authorization",
+ "authorizeBrowser": "Complete authorization in your browser",
+ "showKey": "Show credential",
+ "hideKey": "Hide credential",
+ "connected": "Connected",
+ "savedSubscription": "Subscription credentials detected",
+ "savedDisabled": "Credentials saved. This assistant is currently disabled.",
+ "readFailed": "Unable to read connection state. Try again.",
+ "saveFailed": "Unable to save the connection. Try again.",
+ "applyFailed": "Credentials saved, but runtime application failed. Retry the save.",
+ "applyPending": "Runtime application is not confirmed yet. Refresh the connection state.",
+ "unconfirmed": "The effective connection could not be confirmed. Try again.",
+ "uncertain": "Credentials may be in the system keychain. Their effective state could not be confirmed. You can sign in or save a key here.",
+ "partial": "Saved with a warning. Review the connection state.",
+ "removeConfirm": "Remove this saved credential?",
+ "claudeTitle": "Add Claude subscription",
+ "claudeComplete": "Complete Claude authorization",
+ "claudeKeyTitle": "Add Anthropic API Key",
+ "claudeTokenTitle": "Add Claude Auth Token",
+ "codexTitle": "Add ChatGPT subscription",
+ "codexKeyTitle": "Add OpenAI API Key",
+ "opencodeTitle": "Add a subscription for OpenCode",
+ "opencodeKeyTitle": "Add an API Key for OpenCode",
+ "providerTitle": "Connect {{name}}",
+ "providerKeyTitle": "Add {{name}} API Key",
+ "target": "For {{name}}",
+ "claudeIntro": "Authorize Claude Code with your Anthropic account",
+ "claudeCompleteIntro": "Approve access in your browser, then paste the returned authorization code",
+ "claudeKeyIntro": "Connect Anthropic or a compatible provider to Claude Code",
+ "codexIntro": "Authorize Codex with your OpenAI account",
+ "codexKeyIntro": "Connect OpenAI or a compatible provider to Codex",
+ "pickKey": "Choose an API Key provider",
+ "pickSubscription": "Choose a subscription provider to connect",
+ "catalogHint": "Providers come from your installed OpenCode runtime.",
+ "noProviders": "No matching providers. Try an API Key or refresh the catalog.",
+ "changeProvider": "Change",
+ "enter": "Enter workspace",
+ "entryHint": "Connect any one subscription or API Key to enter the workspace",
+ "entryReady": "Connected. You can start working.",
+ "entryStopped": "Connection saved. Enter workspace to start the service.",
+ "entryFailed": "A ready assistant could not be confirmed. Refresh and try again.",
+ "addSubscription": "Add subscription",
+ "addKey": "Add API Key",
+ "refresh": "Refresh connection",
+ "enableFirst": "Enable this assistant to connect it.",
+ "checkSettings": "Review settings",
+ "manualCode": "Authorization code",
+ "manualCodePlaceholder": "Paste the code from your browser",
+ "manualCodeHint": "Complete authorization in your browser, then paste the code here.",
+ "copyDevice": "1 Copy the device code",
+ "openDevice": "2 Open the sign-in page and enter the code",
+ "openChatGPT": "Open ChatGPT sign-in",
+ "openProvider": "Open authorization page",
+ "codexComplete": "Connect your ChatGPT subscription",
+ "codexCompleteIntro": "Sign in through your browser. Codex will connect automatically",
+ "providerIntro": "Connect {{name}} to OpenCode",
+ "providerCredentialHint": "This credential is only used for {{name}} in OpenCode",
+ "providerDescription": "Provider · For OpenCode",
+ "modelTitle": "Choose a model for this connection",
+ "modelHint": "{{agent}} currently uses {{model}}. Select a model from a connected provider to finish setup.",
+ "modelSelect": "Model from a connected provider",
+ "modelApply": "Apply model and enter",
+ "modelEmpty": "No compatible models are available. Check the connection above, then retry the catalog.",
+ "modelChanged": "The connection or Agent changed. Refresh the catalog and try again.",
+ "modelUnavailable": "No available Agent has a usable model route. Check your connections and try again.",
+ "credentialType": "Credential type",
+ "apiKeyLabel": "API Key",
+ "authTokenLabel": "Auth Token",
+ "platformRepair": "Repair saved messaging configuration",
+ "platformRepairHint": "Your saved {{platform}} configuration is incomplete. Repair its required credentials before entering the workspace."
}
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 18ce89777..c0fcf6c26 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -5255,6 +5255,100 @@
"api_key": "API Key",
"subscriptionConnected": "订阅已连接",
"api_keyConnected": "API Key 已连接"
+ },
+ "connection": {
+ "method": "连接方式",
+ "subscription": "订阅",
+ "claudeLogin": "Claude 账号登录",
+ "claudeCredentials": "Claude Code 凭据",
+ "claudeSignIn": "使用 Claude 登录",
+ "codexSignIn": "使用 ChatGPT 登录",
+ "openaiKey": "OpenAI API Key",
+ "claudeAccount": "使用 Anthropic 账号登录",
+ "codexAccount": "使用 ChatGPT 账号登录",
+ "claudeHint": "打开授权页面并批准访问,再将返回的授权码粘贴到这里",
+ "deviceHint": "获取设备码,在浏览器中登录并授权,完成后自动连接",
+ "codeHint": "请完整粘贴,包含 # 后的内容",
+ "keyHint": "使用服务商提供的 API Key",
+ "tokenHint": "适用于要求 Bearer Token 的中转服务",
+ "baseUrl": "Base URL(可选)",
+ "providerDefault": "使用服务商默认地址",
+ "claudeUrlHint": "留空使用 Anthropic 默认地址;地址不改变凭据类型",
+ "urlHint": "留空使用服务商默认地址",
+ "invalidUrl": "请输入有效的 http:// 或 https:// 地址",
+ "saveConnect": "保存并连接",
+ "finishConnect": "完成连接",
+ "connecting": "连接中…",
+ "waiting": "等待授权完成",
+ "authorizeBrowser": "在浏览器中完成授权",
+ "showKey": "显示凭据",
+ "hideKey": "隐藏凭据",
+ "connected": "已连接",
+ "savedSubscription": "已检测到订阅凭据",
+ "savedDisabled": "凭据已保存。此助手当前未启用。",
+ "readFailed": "无法读取连接状态,请重试",
+ "saveFailed": "无法保存连接,请重试",
+ "applyFailed": "凭据已保存,但运行时应用失败,请重试保存",
+ "applyPending": "运行时尚未确认生效,请刷新连接状态",
+ "unconfirmed": "无法确认当前生效的连接,请重试",
+ "uncertain": "凭据可能保存在系统钥匙串,暂时无法确认其生效状态。可以在此登录或保存密钥",
+ "partial": "已保存,但有警告,请检查连接状态",
+ "removeConfirm": "移除此已保存凭据?",
+ "claudeTitle": "添加 Claude 订阅",
+ "claudeComplete": "完成 Claude 授权",
+ "claudeKeyTitle": "添加 Anthropic API Key",
+ "claudeTokenTitle": "添加 Claude Auth Token",
+ "codexTitle": "添加 ChatGPT 订阅",
+ "codexKeyTitle": "添加 OpenAI API Key",
+ "opencodeTitle": "为 OpenCode 添加订阅",
+ "opencodeKeyTitle": "为 OpenCode 添加 API Key",
+ "providerTitle": "连接 {{name}}",
+ "providerKeyTitle": "添加 {{name}} API Key",
+ "target": "用于 {{name}}",
+ "claudeIntro": "使用 Anthropic 账号授权 Claude Code",
+ "claudeCompleteIntro": "在浏览器中批准访问,然后粘贴返回的授权码",
+ "claudeKeyIntro": "为 Claude Code 连接 Anthropic 或兼容服务商",
+ "codexIntro": "使用 OpenAI 账号授权 Codex",
+ "codexKeyIntro": "为 Codex 连接 OpenAI 或兼容服务商",
+ "pickKey": "选择 API Key 服务商",
+ "pickSubscription": "选择要连接的订阅服务商",
+ "catalogHint": "服务商来自当前安装的 OpenCode",
+ "noProviders": "没有匹配的服务商,请尝试 API Key 或刷新列表",
+ "changeProvider": "更换",
+ "enter": "进入工作台",
+ "entryHint": "添加任意一个订阅或 API Key,即可进入工作台",
+ "entryReady": "已连接,可以开始工作",
+ "entryStopped": "连接已保存,进入工作台即可启动服务",
+ "entryFailed": "无法确认可用助手,请刷新后重试",
+ "addSubscription": "添加订阅",
+ "addKey": "添加 API Key",
+ "refresh": "刷新连接",
+ "enableFirst": "请先启用此助手以连接",
+ "checkSettings": "检查设置",
+ "manualCode": "授权码",
+ "manualCodePlaceholder": "粘贴浏览器显示的授权码",
+ "manualCodeHint": "在浏览器中完成授权后,将授权码粘贴到这里。",
+ "copyDevice": "1 复制设备码",
+ "openDevice": "2 打开授权页并输入设备码",
+ "openChatGPT": "打开 ChatGPT 授权页",
+ "openProvider": "打开授权页",
+ "codexComplete": "连接 ChatGPT 订阅",
+ "codexCompleteIntro": "在浏览器中登录,授权完成后 Codex 将自动连接",
+ "providerIntro": "将 {{name}} 连接到 OpenCode",
+ "providerCredentialHint": "此凭据只用于 OpenCode 中的 {{name}} 服务商",
+ "providerDescription": "服务商 · 用于 OpenCode",
+ "modelTitle": "为此连接选择模型",
+ "modelHint": "{{agent}} 当前使用 {{model}}。请选择已连接提供商的模型以完成设置。",
+ "modelSelect": "已连接提供商的模型",
+ "modelApply": "应用模型并进入",
+ "modelEmpty": "暂无兼容模型。请检查上方连接,再重试获取模型列表。",
+ "modelChanged": "连接或 Agent 已发生变化。请刷新模型列表后重试。",
+ "modelUnavailable": "没有可用 Agent 的模型路由。请检查连接后重试。",
+ "credentialType": "凭据类型",
+ "apiKeyLabel": "API Key",
+ "authTokenLabel": "Auth Token",
+ "platformRepair": "修复已保存的消息配置",
+ "platformRepairHint": "已保存的 {{platform}} 配置不完整。请修复必填凭据后进入工作区。"
}
}
}
diff --git a/vibe/api.py b/vibe/api.py
index ca1caa548..b5537bfa8 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -7124,7 +7124,7 @@ def _prune_agent_install_jobs(now: float | None = None) -> None:
def _agent_install_job_succeeded(result: dict, name: str) -> bool:
if not bool(result.get("ok")):
return False
- if name == "claude" or not supports_runtime_refresh(name):
+ if not supports_runtime_refresh(name):
return True
restart = result.get("restart")
return isinstance(restart, dict) and bool(restart.get("ok"))
@@ -7167,7 +7167,7 @@ def start_agent_install_job(name: str) -> dict:
def _worker() -> None:
try:
result = install_agent(name)
- if result.get("ok") and name != "claude" and supports_runtime_refresh(name):
+ if result.get("ok") and supports_runtime_refresh(name):
try:
result["restart"] = restart_backend(
name,
@@ -10671,6 +10671,79 @@ def _codex_process_status(resolved_binary: str | None) -> str:
return "running" if _codex_processes(resolved_binary) else "stopped"
+async def get_backend_connection(name: str) -> dict:
+ """Observe native launch auth and controller application, without a model call."""
+ from vibe import internal_client, runtime
+
+ if not is_agent_backend(name):
+ return {"ok": False, "error": "unsupported_backend"}
+ config = await asyncio.to_thread(load_config)
+ backend_config = getattr(config.agents, name)
+ enabled = bool(backend_config.enabled)
+ installed = await asyncio.to_thread(resolve_cli_path, backend_config.cli_path or name) is not None
+ result = {
+ "ok": True, "backend": name, "installed": installed, "enabled": enabled,
+ "auth": "unknown", "application": "unknown", "ready": False,
+ "entry_eligible": False,
+ }
+ body = {}
+ try:
+ application = await internal_client.backend_application(name)
+ body = application.get("body") or {}
+ if application.get("status_code") == 200 and body.get("ok"):
+ result["application"] = body.get("state") if body.get("state") in {"applied", "draining", "failed"} else "unknown"
+ if enabled and body.get("disabled") is True and result["application"] == "applied":
+ result["application"] = "unknown"
+ if body.get("error"):
+ result["message"] = body["error"]
+ except internal_client.InternalServerUnavailable:
+ if not await asyncio.to_thread(runtime.service_process_running):
+ result["application"] = "stopped"
+ with _backend_apply_receipts_lock:
+ receipt = _backend_apply_receipts.get(name)
+ # A confirmed new controller has applied persisted startup config.
+ # Browser refresh or a recovered socket to the same owner cannot clear
+ # an undelivered request. PID is existing runtime identity, not an epoch.
+ if (receipt and receipt.get("controller_pid") and body.get("controller_pid")
+ and receipt["controller_pid"] != body["controller_pid"]
+ and result["application"] == "applied"):
+ _backend_apply_receipts.pop(name, None)
+ receipt = None
+ if receipt and not receipt.get("ok") and result["application"] != "stopped":
+ result["application"] = "failed"
+ result["message"] = receipt.get("message") or receipt.get("error")
+ if not installed:
+ return result
+ try:
+ if name == "opencode":
+ if not enabled:
+ return result
+ # Read the same persisted launch sources as the provider catalog.
+ # Readiness must not start an OpenCode daemon just to inspect auth.
+ from vibe.opencode_config import read_opencode_provider_auth_entries
+
+ key_ids = await _read_opencode_config_api_key_provider_ids()
+ entries = await asyncio.to_thread(read_opencode_provider_auth_entries, logger_instance=logger)
+ modes = {pid: entry.get("type") for pid, entry in entries.items() if isinstance(entry, 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")
+ permission = await asyncio.to_thread(opencode_permission_status)
+ result["permission_required"] = bool(permission.get("ok")) and not permission.get("permission_allowed", False)
+ else:
+ auth = await asyncio.to_thread(get_claude_auth if name == "claude" else 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")
+ except Exception as exc:
+ result["message"] = str(exc)
+ return result
+ credential_ready = enabled and result["auth"] in {"subscription", "api_key"} 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
+
+
def get_backend_runtime(name: str) -> dict:
"""Return live lifecycle info for one backend.
@@ -10739,7 +10812,7 @@ def _wait_for_controller_ack(marker: Path, timeout: float) -> tuple[bool, str |
the handler raised; the controller wrote the message to a companion
``<marker>.err`` file before deleting the request marker.
- ``handled=False, error=None`` — timed out; the controller never
- consumed the marker. Caller should fall back to a direct kill.
+ consumed the marker. Caller must preserve the failed application.
The companion ``.err`` file is consumed (unlinked) before returning so
later requests start clean.
@@ -10776,9 +10849,9 @@ def _request_controller_restart(
state. Killing those processes from the UI server would leave that cache
stale, so the cleanest path is to ask the controller to call its existing
``_refresh_backend_runtime(backend)`` for us. We drop a marker file and
- wait briefly for the controller to delete it; the caller falls back to a
- direct process kill when the controller is unreachable (e.g. running
- detached, not yet started).
+ wait briefly for the controller to delete it. An unreachable running
+ controller remains an unconfirmed apply; no child-process kill can prove
+ that its in-memory state accepted the saved configuration.
Each request gets its own marker filename (``restart-<backend>.<reqid>.cmd``)
so we can correlate failures back to *this* request. Without the reqid,
@@ -10825,15 +10898,40 @@ def _request_controller_restart(
return False, None
+# Bounded to the supported backends; survives modal/HTTP lifetimes. This records
+# undelivered apply requests which the controller cannot itself observe.
+_backend_apply_receipts: dict[str, dict] = {}
+_backend_apply_receipts_lock = threading.Lock()
+
+
+def record_backend_apply_receipt(backend: str, result: dict) -> None:
+ if not is_agent_backend(backend):
+ return
+ from vibe import runtime
+
+ receipt = dict(result)
+ receipt["controller_pid"] = runtime.resolve_service_owner_pid(include_starting=False)
+ with _backend_apply_receipts_lock:
+ _backend_apply_receipts[backend] = receipt
+
+
def restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) -> dict:
+ try:
+ result = _restart_backend(name, metadata=metadata)
+ except Exception as exc:
+ result = {"ok": False, "message": str(exc)}
+ record_backend_apply_receipt(name, result)
+ return result
+
+
+def _restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) -> dict:
"""Refresh the backend so the next request picks up new config/env.
Preferred path: drop a runtime-command marker that the controller
observes and reacts to via ``_refresh_backend_runtime``. This keeps the
- controller's in-memory transport/session state consistent. If the
- controller isn't running (e.g. service not yet started), backends with a
- separate runtime can fall back to killing their OS process directly — the
- controller's recovery logic will rebuild state when it next starts.
+ controller's in-memory transport/session state consistent. A confirmed
+ stopped controller applies persisted configuration on its next explicit
+ start; a running controller with unavailable IPC remains a failed apply.
Claude has no separate daemon, but the controller keeps SDK sessions
and a loaded compat config; the marker path refreshes those in memory.
@@ -10841,6 +10939,15 @@ def restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) ->
if not supports_runtime_refresh(name):
return {"ok": False, "message": f"Restart is not supported for backend: {name}"}
+ from vibe import runtime
+
+ try:
+ language = load_config().language
+ except FileNotFoundError:
+ language = "en"
+ if not runtime.service_process_running():
+ return {"ok": True, "apply_on_next_start": True, "message": backend_t("backendConnection.applyOnStart", lang=language)}
+
controller_handled, controller_error = _request_controller_restart(name, metadata=metadata)
_invalidate_version_cache(name)
@@ -10856,59 +10963,9 @@ def restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) ->
}
return {"ok": True, "message": runtime_refresh_success_message(name)}
- if name == "opencode":
- from vibe import runtime
- from vibe.cli import _stop_opencode_server
-
- stopped = _stop_opencode_server()
- if stopped:
- return {"ok": True, "message": "OpenCode server stopped; it will respawn on next request."}
- pid = _opencode_server_pid()
- if not pid or not runtime.pid_alive(pid):
- return {"ok": True, "message": "OpenCode server is not running; next request will start a fresh one."}
- return {"ok": False, "message": "Failed to stop OpenCode server."}
-
- if name == "claude":
- return {
- "ok": False,
- "message": "Claude runtime refresh was not acknowledged by the controller; retry after the service is running.",
- }
-
- # codex fallback: kill app-server processes; controller recovery rebuilds.
- try:
- import psutil
- except ImportError:
- return {"ok": False, "message": "psutil unavailable; cannot manage Codex processes."}
-
- try:
- config = V2Config.load()
- backend_cfg = getattr(getattr(config, "agents", None), "codex", None)
- configured = getattr(backend_cfg, "cli_path", "") or "codex"
- except Exception:
- configured = "codex"
- resolved = resolve_cli_path(configured)
-
- pids = _codex_processes(resolved)
- if not pids:
- return {"ok": True, "message": "Codex app-server is not running; next request will start a fresh one."}
-
- failed: list[int] = []
- for pid in pids:
- try:
- proc = psutil.Process(pid)
- proc.terminate()
- try:
- proc.wait(timeout=5)
- except psutil.TimeoutExpired:
- proc.kill()
- except (psutil.NoSuchProcess, psutil.AccessDenied) as exc:
- logger.debug("Codex restart skip pid=%s: %s", pid, exc)
- except Exception as exc:
- logger.warning("Failed to stop codex pid=%s: %s", pid, exc)
- failed.append(pid)
- if failed:
- return {"ok": False, "message": f"Failed to stop Codex process(es): {failed}"}
- return {"ok": True, "message": f"Stopped {len(pids)} Codex process(es); they will respawn on next request."}
+ # A running service with broken IPC is not a stopped backend. Killing its
+ # child process here would hide stale controller state and split ownership.
+ return {"ok": False, "message": backend_t("backendConnection.applyUnacknowledged", lang=language)}
_VALID_AUTH_MODES = {"oauth", "api_key"}
@@ -11087,19 +11144,12 @@ def _start_oauth_event_loop() -> tuple[asyncio.AbstractEventLoop, threading.Thre
def _on_web_auth_success(backend: str) -> None:
- """Tell the live controller to refresh its agent after web OAuth success."""
- try:
- handled, err = _request_controller_restart(
- backend,
- timeout=4.0,
- metadata={"reason": "web_auth_success", "source": "oauth_callback"},
- )
- if handled and err:
- logger.warning("Controller refresh after web auth reported error: %s", err)
- elif not handled:
- logger.info("Controller did not pick up web-auth refresh marker for %s", backend)
- except Exception as exc: # noqa: BLE001
- logger.warning("Failed to notify controller after web auth: %s", exc)
+ """Surface persistence/application separately from successful consent."""
+ result = restart_backend(
+ backend, metadata={"reason": "web_auth_success", "source": "oauth_callback"},
+ )
+ if not result.get("ok"):
+ raise RuntimeError(result.get("message") or "backend_apply_failed")
def _get_oauth_service() -> Any:
@@ -11205,6 +11255,7 @@ async def start_oauth_web_async(
"url": flow.url,
"device_code": flow.device_code,
"awaiting_code": flow.awaiting_code,
+ "callback_kind": flow.callback_kind,
"provider": flow.provider,
}
@@ -11570,13 +11621,8 @@ def get_codex_auth() -> dict:
# Surface "we can't read your key — it may live in the OS
# keychain" so the UI doesn't claim "no key configured" when
# Codex is in keyring-preferred mode and we have no disk
- # evidence. We suppress the flag when V2Config has a stored
- # ``auth_mode`` (the user already saved through our flow), since
- # we then know the mode and the next save will pin file storage.
- "auth_mode_uncertain": (
- bool(disk_state.get("auth_mode_uncertain"))
- and configured_mode not in _VALID_AUTH_MODES
- ),
+ # evidence. Saved intent cannot resolve an unreadable native store.
+ "auth_mode_uncertain": bool(disk_state.get("auth_mode_uncertain")),
}
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 58b0d8435..e0e4ba181 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -512,6 +512,7 @@ _MEMBER_HTTP_RULES = tuple(
("POST", r"^/api/agent/[^/]+/install$"),
("GET", r"^/api/agent/[^/]+/install/[^/]+$"),
("GET", r"^/api/backend/[^/]+/runtime$"),
+ ("GET", r"^/api/backend/[^/]+/connection$"),
("POST", r"^/api/backend/[^/]+/restart$"),
("GET", r"^/api/dependencies$"),
("POST", r"^/api/dependencies/[^/]+/install$"),
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index e19c12863..1f71999f5 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1,4 +1,8 @@
{
+ "backendConnection": {
+ "applyOnStart": "Configuration will apply on next start.",
+ "applyUnacknowledged": "Backend refresh was not acknowledged by the controller."
+ },
"errors": {
"agentModelRequired": "Select a model for the {backend} Agent or Session in Avibe before running it.",
"opencodeModelProviderRequired": "Select an OpenCode model with a provider in Avibe, or configure its Model Hub route."
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 511d74387..5b52b0053 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1,4 +1,8 @@
{
+ "backendConnection": {
+ "applyOnStart": "配置将在下次启动时应用。",
+ "applyUnacknowledged": "控制器未确认后端刷新请求。"
+ },
"errors": {
"agentModelRequired": "请先在 Avibe 中为 {backend} Agent 或会话选择模型。",
"opencodeModelProviderRequired": "请在 Avibe 中选择带供应商的 OpenCode 模型,或配置它的 Model Hub 路由。"
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index e4ad39d5e..734e0df14 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -395,6 +395,25 @@ async def invalidate_activity_streaming(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def backend_application(
+ backend: str, *, socket_path: Optional[Path] = None, timeout: float = 5.0,
+) -> dict[str, Any]:
+ from modules.agents.catalog import AGENT_BACKENDS
+
+ if backend not in AGENT_BACKENDS:
+ raise ValueError("unsupported_backend")
+ target = await _verified_socket_path_async(socket_path)
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport, base_url="http://localhost", timeout=timeout,
+ ) as client:
+ response = await client.get(f"/internal/backend-application/{backend}")
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": response.status_code, "body": response.json() if response.content else {}}
+
+
async def reconcile_agent_backends(
backends: list[str],
*,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index cfd8ba29b..879c93c6c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6853,6 +6853,14 @@ async def config_post():
agent_backend_runtime["restart_code"] = restart_result.get("code")
else:
agent_backend_runtime["apply_on_next_start"] = True
+ if agent_backend_runtime is not None:
+ from vibe import api
+
+ for backend in changed_agent_backends:
+ api.record_backend_apply_receipt(backend, {
+ "ok": bool(agent_backend_runtime.get("hot_reconciled") or agent_backend_runtime.get("apply_on_next_start")),
+ "message": agent_backend_runtime.get("restart_error") or agent_backend_runtime.get("error"),
+ })
authorization_context = getattr(g, "authorization_context", None)
response_payload = _config_api_payload_for_context(config, authorization_context)
if remote_access_runtime is not None:
@@ -7904,6 +7912,20 @@ def agent_install_status(name, job_id):
_ALLOWED_BACKENDS = set(AGENT_BACKENDS)
[email protected]("/api/backend/{name}/connection", include_in_schema=False)
+async def backend_connection(name: str, starlette_request: FastAPIRequest):
+ async def handler():
+ if name not in _ALLOWED_BACKENDS:
+ return jsonify({"ok": False, "error": "unsupported_backend"}), 400
+ from vibe import api
+
+ response = jsonify(await api.get_backend_connection(name))
+ response.headers["Cache-Control"] = "private, no-store"
+ return response
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.route("/api/backend/<name>/runtime")
def backend_runtime(name):
"""Return lifecycle info (version, update, process status) for a backend."""