Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): setup wizard revamp + 100% reuse of backend provider config (#453)
Call Whiteb88160d80b57
diff --git a/config/platform_registry.py b/config/platform_registry.pyindex cd8d8a590..207bc58fd 100644--- a/config/platform_registry.py+++ b/config/platform_registry.py@@ -38,6 +38,12 @@ class PlatformDescriptor:formatter_class: strcredential_fields: tuple[str, ...]capabilities: PlatformCapabilities+ # Structural distinction between real IM transports ("im") and the+ # always-on in-process Avibe Workbench ("workbench"), which lives in the+ # same registry but is never a configurable IM platform. IM-only code paths+ # should select via ``im_platform_descriptors()`` / ``im_platform_ids()``+ # rather than re-deriving an ad-hoc workbench exclude.+ kind: str = "im"@propertydef title_key(self) -> str:@@ -90,6 +96,7 @@ class PlatformDescriptor:"description_key": self.description_key,"credential_fields": list(self.credential_fields),"capabilities": asdict(self.capabilities),+ "kind": self.kind,}@@ -98,6 +105,17 @@ def _load_attr(module_name: str, attr_name: str) -> Any:return getattr(module, attr_name)+# The in-process Avibe Workbench (Web UI), surfaced as a peer platform so it+# shares scopes/agent_sessions/routing with Slack/Discord/etc. It has no remote+# credentials and is wired by the controller, never built as an IM transport.+# Single source of truth, mirrored by the frontend (ui/src/lib/platforms.ts).+WORKBENCH_PLATFORM_ID = "avibe"+++def is_workbench_platform(platform: str) -> bool:+ return platform == WORKBENCH_PLATFORM_ID++PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {"slack": PlatformDescriptor(id="slack",@@ -223,6 +241,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {client_class="AvibeBot",formatter_module="modules.im.formatters",formatter_class="AvibeFormatter",+ kind="workbench",credential_fields=(),capabilities=PlatformCapabilities(supports_channels=True,@@ -242,6 +261,16 @@ def platform_descriptors() -> list[PlatformDescriptor]:return list(PLATFORM_REGISTRY.values())+def im_platform_descriptors() -> list[PlatformDescriptor]:+ """Descriptors for real IM transports only (excludes the workbench)."""+ return [descriptor for descriptor in PLATFORM_REGISTRY.values() if descriptor.kind == "im"]+++def im_platform_ids() -> list[str]:+ """Ids of real IM transports only (excludes the workbench)."""+ return [descriptor.id for descriptor in im_platform_descriptors()]++def supported_platform_ids() -> list[str]:return list(PLATFORM_REGISTRY.keys())diff --git a/config/v2_compat.py b/config/v2_compat.pyindex 25f3aa215..eef0d4772 100644--- a/config/v2_compat.py+++ b/config/v2_compat.py@@ -83,7 +83,13 @@ class AppCompatConfig:def enabled_platforms(self) -> list[str]:enabled = self.platforms.get("enabled") if isinstance(self.platforms, dict) else None- if isinstance(enabled, list) and enabled:+ # An explicit empty list is the workbench-only signal: no external IM+ # platform is enabled and the in-process Avibe surface is wired by the+ # controller (never by the IM factory, which has no AppCompatConfig for+ # "avibe"). Mirror ``V2Config.enabled_platforms`` and return ``[]`` so+ # ``create_clients`` produces no clients. Fall back to ``[self.platform]``+ # only for legacy configs that never populated ``enabled`` at all.+ if isinstance(enabled, list):return [str(platform) for platform in enabled]return [self.platform]diff --git a/config/v2_config.py b/config/v2_config.pyindex 99cc55118..bfac09534 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -9,7 +9,9 @@ from typing import List, Literal, Optional, Unionfrom config import pathsfrom config.platform_registry import (+ WORKBENCH_PLATFORM_ID,get_platform_descriptor,+ is_workbench_platform,platform_catalog_payload,platform_descriptors,supported_platform_ids,@@ -296,14 +298,32 @@ class PlatformsConfig:for platform in self.enabled:if platform not in supported:raise ValueError(f"Unsupported enabled platform: {platform}")+ # The in-process workbench is never an enabled IM transport — the+ # controller wires it directly. Strip it from ``enabled`` so a+ # legacy/hand-edited config can't crash the IM factory or strand the+ # primary when a real IM is also enabled.+ if is_workbench_platform(platform):+ continueif platform not in normalized:normalized.append(platform)if not normalized:- raise ValueError("Config 'platforms.enabled' must contain at least one platform")- if self.primary not in supported:+ # Workbench-only install: no external IM platform is enabled. The+ # Avibe Workbench (in-process Web UI) is the sole inbound surface,+ # so anchor ``primary`` to it instead of force-inserting a real IM.+ # ``avibe`` is a registered platform but is intentionally NOT added+ # to ``enabled`` — it has no remote runtime and the controller wires+ # it as the in-process client directly (see ``_init_modules``).+ self.primary = WORKBENCH_PLATFORM_ID+ self.enabled = []+ return+ if is_workbench_platform(self.primary):+ # Real IM platforms are enabled, so the workbench can't be the+ # primary transport — retarget to the first real platform.+ self.primary = normalized[0]+ elif self.primary not in supported:supported_text = "', '".join(supported_platform_ids())raise ValueError(f"Config 'platforms.primary' must be one of: '{supported_text}'")- if self.primary not in normalized:+ elif self.primary not in normalized:normalized.insert(0, self.primary)self.enabled = normalized@@ -337,6 +357,13 @@ class V2Config:reply_enhancements: bool = True # Enable quick-reply buttonsshow_pages_prompt: bool = True # Inject Show Pages capability guidance into agent promptslanguage: str = "en" # Global language setting (see vibe/i18n)+ # True once the user has finished the setup wizard. This is the explicit+ # gate for ``setup_state().needs_setup`` — it replaces the old heuristic+ # that inferred "setup done" from having a mode plus configured platform+ # credentials (which forced credential-less / workbench-only installs back+ # into the wizard). Legacy configs that predate the flag have it derived in+ # ``from_payload`` from the old condition.+ setup_completed: bool = False@classmethoddef load(cls, config_path: Optional[Path] = None) -> "V2Config":@@ -537,7 +564,14 @@ class V2Config:language = normalize_language(payload.get("language"), default="en")- return cls(+ # ``setup_completed`` is the explicit setup gate. Read the stored value+ # when present; otherwise leave it ``None`` here and derive it below+ # from the legacy "setup done" heuristic so installs configured before+ # this flag existed are not bounced back into the wizard.+ setup_completed_raw = payload.get("setup_completed")+ setup_completed = setup_completed_raw if isinstance(setup_completed_raw, bool) else None++ config = cls(platform=platform,platforms=platforms,mode=mode,@@ -567,6 +601,16 @@ class V2Config:language=language,)+ # Migration: when the payload predates ``setup_completed``, derive it+ # from the legacy heuristic (a mode plus at least one configured+ # platform). Only derive when the key is absent; an explicitly stored+ # value always wins.+ if setup_completed is None:+ setup_completed = bool(config.mode) and bool(config.configured_platforms())+ config.setup_completed = setup_completed++ return config+def save(self, config_path: Optional[Path] = None) -> None:paths.ensure_data_dirs()path = config_path or paths.get_config_path()@@ -615,6 +659,7 @@ class V2Config:"reply_enhancements": self.reply_enhancements,"show_pages_prompt": self.show_pages_prompt,"language": self.language,+ "setup_completed": self.setup_completed,}content = json.dumps(payload, indent=2)path.parent.mkdir(parents=True, exist_ok=True)@@ -648,7 +693,7 @@ class V2Config:configured = self.configured_platforms()missing = self.missing_platform_credentials()return {- "needs_setup": not bool(self.mode) or not bool(configured),+ "needs_setup": not self.setup_completed,"configured_platforms": configured,"missing_credentials": missing,}diff --git a/core/controller.py b/core/controller.pyindex 237b425d9..d9340f80b 100644--- a/core/controller.py+++ b/core/controller.py@@ -144,6 +144,22 @@ class Controller:def _init_modules(self):"""Initialize core modules"""self.im_clients: Dict[str, BaseIMClient] = IMFactory.create_clients(self.config)++ # Workbench-only install: no external IM platform is enabled, so+ # ``create_clients`` returns an empty map. Register the in-process+ # Avibe (Web UI) client as the SOLE client BEFORE the snapshot/primary+ # access below so ``self.im_client`` resolves to it, ``self.im_clients+ # [self.primary_platform]`` (== "avibe") works, and avibe joins the+ # single-client run loop (its ``run()`` fires on_ready + blocks to keep+ # the service alive — see ``modules/im/avibe.py``). The has-IM path is+ # unaffected: avibe is added there AFTER the snapshot (further below) and+ # stays OUT of the MultiIMClient run loop.+ if not self.im_clients:+ from modules.im.avibe import AvibeBot, AvibeConfig++ self.primary_platform = "avibe"+ self.im_clients["avibe"] = AvibeBot(AvibeConfig())+for platform, client in self.im_clients.items():client.formatter = self._create_formatter(platform)@@ -163,7 +179,16 @@ class Controller:# Initialize managersself.session_manager = SessionManager()- self.settings_manager = MultiSettingsManager(self.enabled_platforms, primary_platform=self.primary_platform)+ # The settings manager must own a per-platform manager for the primary+ # so ``get_settings_manager_for_context`` (and its primary fallback) can+ # always resolve one. For has-IM the primary is already in+ # ``enabled_platforms`` so this is a no-op; for workbench-only it adds+ # the "avibe" manager that empty ``enabled_platforms`` would otherwise+ # omit (which would KeyError on the very first settings lookup).+ settings_platforms = list(self.enabled_platforms)+ if self.primary_platform not in settings_platforms:+ settings_platforms.append(self.primary_platform)+ self.settings_manager = MultiSettingsManager(settings_platforms, primary_platform=self.primary_platform)self.platform_settings_managers = self.settings_manager.managersself.sessions = self.settings_manager.sessionsself.native_session_service = Nonediff --git a/core/services/settings.py b/core/services/settings.pyindex c5042aa93..c3e68856c 100644--- a/core/services/settings.py+++ b/core/services/settings.py@@ -26,11 +26,62 @@ from pathlib import Pathfrom typing import Callable, Optionalfrom config import SettingsStore, paths-from config.v2_config import V2Config+from config.platform_registry import WORKBENCH_PLATFORM_ID+from config.v2_config import (+ AgentsConfig,+ ClaudeConfig,+ CodexConfig,+ OpenCodeConfig,+ PlatformsConfig,+ RuntimeConfig,+ SlackConfig,+ V2Config,+)DefaultConfigFactory = Callable[[], V2Config]+def default_config() -> V2Config:+ """Build a fresh, un-completed default ``V2Config`` (never persisted here).++ Single source of truth for the "first run" config shape, shared by:++ * the CLI's seed-on-first-use path (``vibe.cli._ensure_config`` →+ ``load_config(default_factory=default_config)``), which persists the+ result, and+ * the read-side default for the Web UI's ``GET /api/config``+ (``load_config_or_default``), which keeps it in memory so a brand-new+ user can open the setup wizard — including the reused provider-config+ modal that calls ``getConfig()`` — before any config file exists.++ ``setup_completed`` stays ``False`` and no platform carries credentials,+ so ``setup_state()['needs_setup']`` is ``True``: a fresh default is never+ mistaken for a finished setup, and the wizard still shows. ``platforms``+ starts workbench-only (no external IM enabled) — see below.+ """++ return V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token="", app_token=""),+ # Workbench-only first-run state. The always-on Avibe Workbench is the+ # sole inbound surface and no external IM is enabled yet, so ``enabled``+ # MUST start empty — overriding the PlatformsConfig ``["slack"]``+ # dataclass default. Otherwise a fresh install (or the wizard's "skip+ # chat platforms" path) would persist a setup-completed config with+ # Slack enabled and empty credentials — a phantom transport. ``primary``+ # anchors to the workbench; the user adds real IMs explicitly later.+ platforms=PlatformsConfig(enabled=[], primary=WORKBENCH_PLATFORM_ID),+ runtime=RuntimeConfig(default_cwd=str(Path.home() / "work")),+ agents=AgentsConfig(+ default_backend="opencode",+ opencode=OpenCodeConfig(enabled=True, cli_path="opencode"),+ claude=ClaudeConfig(enabled=True, cli_path="claude"),+ codex=CodexConfig(enabled=False, cli_path="codex"),+ ),+ )++def load_config(config_path: Optional[Path] = None,*,@@ -64,6 +115,27 @@ def load_config(return V2Config.load(target)+def load_config_or_default(config_path: Optional[Path] = None) -> V2Config:+ """Load the V2 config, returning an in-memory default when it is missing.++ Unlike ``load_config(default_factory=...)``, this never writes the file:+ it is the read-side default for surfaces (notably the Web UI's+ ``GET /api/config``) that must serve a usable config to a brand-new user+ before any config has been persisted, without turning a read into a+ write or pre-empting the wizard's own first save.++ The default comes from :func:`default_config`, so ``setup_completed`` is+ ``False`` and ``setup_state()['needs_setup']`` is ``True`` — a fresh+ install is never reported as a completed setup. Once a config file+ exists, the on-disk value is returned unchanged.+ """++ target = config_path or paths.get_config_path()+ if not target.exists():+ return default_config()+ return V2Config.load(target)++def get_settings_store(settings_path: Optional[Path] = None) -> SettingsStore:"""Return the process-wide ``SettingsStore`` singleton.@@ -103,7 +175,9 @@ def reset_settings_store() -> None:__all__ = [+ "default_config","load_config",+ "load_config_or_default","get_settings_store","reload_settings_store","reset_settings_store",diff --git a/docs/plans/setup-wizard-revamp.md b/docs/plans/setup-wizard-revamp.mdnew file mode 100644index 000000000..b308a0614--- /dev/null+++ b/docs/plans/setup-wizard-revamp.md@@ -0,0 +1,70 @@+# Setup Wizard Revamp + Provider-Config Reuse++## Background+User feedback on `/setup` (the first-run Wizard). Two steps redesigned + a new+provider-config modal. Design proposals were built in `design.pen` (Platforms+`jXiOv`, Backends `JHgjz`, modal scene `yKgt1`) and approved in direction. The+modal must NOT be a mock: it must render the **real** `/admin/settings/backends/<backend>`+provider config (UI + request logic), shared 100% with the settings pages — no+copy-paste.++## Architecture (verified)+The provider config bodies are already route-clean. The prior refactor extracted+`settings/shared/useBackendRuntime`, `BackendRuntimeCard`, `BackendOAuthPanel`,+`BackendTestPanel`, `OpencodeProviderTestPanel`, `useOAuthFlowLock`,+`surfaceBackendNotices`. The only route-bound wrapper is `SettingsPageShell` ++the breadcrumb `<Link>`. No page uses `useParams`/`useNavigate`.++Reuse target: peel each page's config body (everything inside the+`!runtime.loaded` gate) into a reusable component; the page becomes+`SettingsPageShell + <XxxProviderConfig/>`; the wizard modal renders the same+component via a `backend`-switch dispatcher inside the existing Radix `Dialog`+(`ui/src/components/ui/dialog.tsx`, widen to `max-w-3xl`).++## Steps+1. **Extract provider config components** → `ui/src/components/settings/providers/`:+ - `ClaudeProviderConfig.tsx` (Claude page lines ~214–476: RuntimeCard + auth Card + BackendTestPanel + auth state/effects)+ - `CodexProviderConfig.tsx` (Codex page ~224–490; incl. surfaceBackendNotices)+ - `OpencodeProviderConfig.tsx` (OpenCode page ~509–1180: RuntimeCard w/ permission slot + provider catalog; keep retryTimer cleanup useEffect)+ - Move the loading gate INTO each config component.+ - `BackendProviderConfig.tsx` — thin `switch(backend)` dispatcher.+2. **Slim the 3 settings pages** to `SettingsPageShell` + `<XxxProviderConfig/>`. No behavior change on the settings route.+3. **AgentDetection.tsx** (wizard backend step) revamp:+ - Remove the **Default backend** selector (+ DEFAULT pill); also from the shared/settings surface (`agents.default_backend` UI). Confirm `default_backend` payload handling stays valid (Wizard.buildConfigPayload).+ - Keep **auto-detect** (`detectAll` on mount) + a Re-scan affordance.+ - **Missing backend → one-click Install** (existing `installAgent`).+ - **OpenCode → Set up Allow / permission** (existing `opencodeSetupPermission`).+ - **Two-row backend card**: top row = identity + (status + enable toggle) at the end; second row = action buttons.+ - Ready backend → **"Configure provider"** button opening `<Dialog>` with `<BackendProviderConfig backend={name}/>`; on close, re-run `detectAll()`.+ - Plain-language copy ("Set up your agent backends").+4. **PlatformSelection.tsx** (wizard platform step) revamp:+ - Two columns: left = **Avibe Workbench required/locked** card (mascot, REQUIRED, PWA "add to home screen" note, always-on); right = **optional** third-party IM logos (toggleable, no token entry) + single soft skip mention.+ - Remove inline token entry from the wizard; defer credential config to Settings → Platforms.+ - `WORKBENCH_PLATFORM_ID='avibe'` always enabled, not deselectable.+ - Plain-language heading.+5. **Wizard.tsx flow**: KEEP the per-platform IM credential steps+ (SlackConfig/DiscordConfig/…) as-is — they remain in the first-run flow for+ each selected chat platform (skippable via the wizard Skip button). The+ platform step is selection-only, but the wizard still walks each selected+ IM's credentials. ONLY the always-on workbench (avibe) is excluded from+ credential + channel step generation (it has no credentials). Do NOT+ remove/move the IM credential steps — that was an incorrect inference, not+ requested by the user.+6. **i18n**: add all new strings to `ui/src/i18n/en.json` + `zh.json` (1:1).+ Plain Chinese per user ("安装并配置 Agent 后端", "可跳过…在设置页继续配置", etc.).+7. **Verify**: `npm run build`; reviewer subagent; manual sanity; PR (non-draft) + Codex review watch.++## Decisions (from user)+- Workbench label = **"Avibe Workbench"** (consistent with PR #450).+- Skip-IM mention: once, gentle (subtitle), not emphasized.+- Default-backend selector: remove **everywhere** (setup + settings).+- Modal = 100% reuse of real provider page component; per-backend config+ components behind a dispatcher (Claude/Codex = auth form; OpenCode = provider+ catalog). No copy-paste.++## Notes / risks+- Built on top of PR #450 branch (avibe icon + `platform.avibe` i18n). Rebase+ onto master once #450 merges.+- OpenCode config owns a retry timer — keep its `useEffect` cleanup so the+ Dialog unmount clears it.+- `BackendTestPanel` type currently excludes `opencode` (uses OpencodeProviderTestPanel instead) — preserve.diff --git a/modules/im/avibe.py b/modules/im/avibe.pyindex 4f58e9243..febf59aed 100644--- a/modules/im/avibe.py+++ b/modules/im/avibe.py@@ -17,6 +17,7 @@ controller (see ``IMFactory.create_client``).from __future__ import annotations+import asyncioimport loggingimport uuidfrom dataclasses import dataclass@@ -67,6 +68,10 @@ class AvibeBot(BaseIMClient):super().__init__(config)self.formatter = AvibeFormatter()self._sse_publisher: Optional[SsePublisher] = None+ # Liveness primitives for the workbench-only run loop (see ``run``).+ # Created lazily inside ``run`` on the im-runtime thread's own loop.+ self._loop: Optional[asyncio.AbstractEventLoop] = None+ self._stop_event: Optional[asyncio.Event] = None# ------------------------------------------------------------------# SSE binding — used by ui_server in commit 08 to register a fan-out@@ -203,10 +208,60 @@ class AvibeBot(BaseIMClient):return Nonedef run(self) -> None:- logger.debug(- "AvibeBot.run: no event loop to start "- "(REST + SSE owned by vibe/ui_server.py)"- )+ """Run the workbench as the sole IM surface (workbench-only mode).++ Unlike the external adapters there is no socket/long-poll to drive:+ ui_server owns inbound REST + outbound SSE. But the controller ties+ service liveness to the IM-runtime thread — when ``im_client.run()``+ returns, ``_run_im_runtime`` stops the loop and the service exits.++ So we mirror the external adapters' contract: fire ``on_ready`` once+ (the workbench is "ready" the instant it starts — there is no remote+ handshake) so the controller starts poll-restore / update-checker /+ scheduled tasks, then BLOCK until :meth:`stop` is called. This is a+ no-op in the has-IM path: there the controller adds avibe to+ ``im_clients`` only as a delivery target and never invokes its+ ``run()`` (a real platform owns the runtime thread).+ """+ try:+ asyncio.run(self._run())+ except Exception: # noqa: BLE001+ logger.exception("AvibeBot run loop exited with error")++ async def _run(self) -> None:+ self._loop = asyncio.get_running_loop()+ self._stop_event = asyncio.Event()+ logger.info("Avibe workbench ready (in-process; REST + SSE owned by ui_server)")+ # ``on_ready`` is stored by ``BaseIMClient.register_callbacks`` as+ # ``self.on_ready_callback``. The controller wraps it with+ # ``_dispatch_to_controller_loop`` so awaiting it here (on the+ # im-runtime thread's loop) bridges onto the controller loop.+ on_ready = getattr(self, "on_ready_callback", None)+ if callable(on_ready):+ try:+ await on_ready()+ except Exception: # noqa: BLE001+ logger.exception("Avibe on_ready callback failed")+ # Block so the im-runtime thread does not return, keeping the+ # controller's ``run_forever`` alive until shutdown.+ await self._stop_event.wait()++ def stop(self) -> None:+ """Release the run loop so the im-runtime thread can exit.++ Called from the controller's (main-thread) ``cleanup_sync``; the+ stop event lives on the im-runtime thread's loop, so signal it+ thread-safely.+ """+ loop = self._loop+ event = self._stop_event+ if loop is None or event is None:+ return+ try:+ loop.call_soon_threadsafe(event.set)+ except RuntimeError:+ # Loop already closed/stopped — nothing left to release.+ pass# ------------------------------------------------------------------# Introspection — returns the locally-known identity for the singlediff --git a/modules/im/factory.py b/modules/im/factory.pyindex 522d53572..e65cf5412 100644--- a/modules/im/factory.py+++ b/modules/im/factory.py@@ -14,6 +14,16 @@ class IMFactory:@staticmethoddef create_client(config) -> BaseIMClient:clients = IMFactory.create_clients(config)+ # Workbench-only config (``platforms.enabled`` empty, or a legacy+ # ``["avibe"]``): ``create_clients`` skips the in-process workbench, so+ # the built map is empty. Return the in-process ``AvibeBot`` directly —+ # mirroring the controller's avibe fallback (``_init_modules``) — instead+ # of constructing ``MultiIMClient(clients={}, "avibe")``, which would+ # raise because the primary is absent from the empty map.+ if not clients:+ from modules.im.avibe import AvibeBot, AvibeConfig++ return AvibeBot(AvibeConfig())primary = getattr(getattr(config, "platforms", None), "primary", getattr(config, "platform", "slack"))if len(clients) == 1 and primary in clients:return clients[primary]@@ -32,11 +42,17 @@ class IMFactory:Raises:ValueError: If platform is not supported"""- from config.platform_registry import get_platform_descriptor+ from config.platform_registry import get_platform_descriptor, is_workbench_platformenabled_platforms = list(getattr(config, "enabled_platforms", lambda: [getattr(config, "platform", "slack")])())clients: dict[str, BaseIMClient] = {}for platform in enabled_platforms:+ # The in-process workbench (avibe) is never an IM transport: it has no+ # remote credentials and is wired separately by the controller. Skip it+ # here so an explicitly-enabled "avibe" can't crash create_client with+ # "Avibe configuration not found".+ if is_workbench_platform(platform):+ continuedescriptor = get_platform_descriptor(platform)logger.info("Creating %s client", platform)clients[platform] = descriptor.create_client(config)@@ -63,9 +79,14 @@ class IMFactory:Raises:ValueError: If configuration is invalid"""- from config.platform_registry import get_platform_descriptor+ from config.platform_registry import get_platform_descriptor, is_workbench_platformfor platform in getattr(config, "enabled_platforms", lambda: [getattr(config, "platform", "slack")])():+ # The in-process workbench (avibe) has no remote credentials to+ # validate and is wired separately by the controller — skip it,+ # mirroring create_clients.+ if is_workbench_platform(platform):+ continuedescriptor = get_platform_descriptor(platform)platform_config = descriptor.get_config(config)if platform_config is None:diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 2b45b83c9..39d12cf56 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -104,6 +104,37 @@ def test_save_config_merges_partial_payload(monkeypatch, tmp_path):assert updated.runtime.default_cwd == "/tmp/workdir"+def test_save_config_seeds_default_for_partial_payload_on_fresh_install(monkeypatch, tmp_path):+ """Regression: a fresh install (no config file yet) must accept the wizard's+ reused provider-config modal POSTing only ``{"agents": ...}``.++ Before the default-seed fix the partial payload went straight into+ ``V2Config.from_payload`` and raised (missing ``mode``/``runtime``), so the+ advertised first-run "Configure provider" flow failed until a config existed.+ """+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))++ import pytest++ with pytest.raises(FileNotFoundError):+ api.load_config() # precondition: truly fresh, no config file++ created = api.save_config(+ {"agents": {"claude": {"enabled": True, "cli_path": "claude", "default_model": "sonnet"}}}+ )++ # The partial save merges onto the workbench-only default and persists.+ assert created.mode == "self_host"+ assert created.agents.claude.enabled is True+ assert created.agents.claude.default_model == "sonnet"+ # Configuring a provider mid-wizard must not complete setup...+ assert created.setup_completed is False+ assert created.setup_state()["needs_setup"] is True+ # ...nor leave a phantom Slack transport: the seeded base is workbench-only.+ assert created.platforms.enabled == []+ assert created.platforms.primary == "avibe"++def test_save_config_defaults_show_duration_to_false_for_new_config(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex 37a76a987..1c71206c9 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -629,7 +629,10 @@ def test_task_update_requires_at_least_one_change(tmp_path: Path) -> None:parser = cli.build_parser()args = parser.parse_args(["task", "update", task.id])- with patch("vibe.cli._task_store", return_value=store):+ with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),+ patch("vibe.cli._task_store", return_value=store),+ ):result, payload = _capture_stderr_json(cli.cmd_task_update, args)assert result == 1@@ -651,7 +654,10 @@ def test_task_update_modifies_existing_task_without_changing_id(tmp_path: Path,["task", "update", task.id, "--name", "Morning summary", "--cron", "*/30 * * * *", "--message", "updated"])- with patch("vibe.cli._task_store", return_value=store):+ with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),+ patch("vibe.cli._task_store", return_value=store),+ ):result = cli.cmd_task_update(args)assert result == 0@@ -702,7 +708,10 @@ def test_task_update_replaces_post_to_with_deliver_key(tmp_path: Path, capsys) -parser = cli.build_parser()args = parser.parse_args(["task", "update", task.id, "--deliver-key", "slack::channel::C999"])- with patch("vibe.cli._task_store", return_value=store):+ with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),+ patch("vibe.cli._task_store", return_value=store),+ ):result = cli.cmd_task_update(args)assert result == 0@@ -937,6 +946,7 @@ def test_agent_run_create_session_uses_scope_anchor_for_channel_deliver_key(tmp_)with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli._agent_store", return_value=agent_store),patch("vibe.cli._task_request_store", return_value=request_store),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),@@ -1056,6 +1066,7 @@ def test_agent_run_rejects_post_to_thread_for_threadless_session_before_enqueue(args = _parse_agent_run(["--async", "--session-id", session_id, "--post-to", "thread", "--message", "hello"])with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli._agent_store", return_value=agent_store),patch("vibe.cli._task_request_store", return_value=request_store),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),@@ -1142,6 +1153,7 @@ def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_paargs = _parse_agent_run(["--async", "--session-id", session_id, "--message", "hello"])with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli._agent_store", return_value=agent_store),patch("vibe.cli._task_request_store", return_value=request_store),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),@@ -1445,6 +1457,7 @@ def test_reserve_definition_session_uses_canonicalized_scope_agent(tmp_path: Pat)with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),):@@ -1493,6 +1506,7 @@ def test_reserve_definition_session_rejects_unresolved_legacy_scope_backend(tmp_)with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),pytest.raises(cli.TaskCliError) as exc,diff --git a/tests/test_core_services_settings.py b/tests/test_core_services_settings.pyindex f8ce8aa3b..fc5cfc347 100644--- a/tests/test_core_services_settings.py+++ b/tests/test_core_services_settings.py@@ -29,7 +29,9 @@ def isolated_state(monkeypatch, tmp_path):def test_public_surface_is_stable():expected = {+ "default_config","load_config",+ "load_config_or_default","get_settings_store","reload_settings_store","reset_settings_store",@@ -44,6 +46,50 @@ def test_load_config_requires_file_by_default(isolated_state):settings_service.load_config()+def test_default_config_is_fresh_and_needs_setup():+ # The shared fresh-install factory must never look like a finished setup:+ # no credentials, ``setup_completed`` False, ``needs_setup`` True.+ config = settings_service.default_config()+ assert config.mode == "self_host"+ assert config.setup_completed is False+ assert config.configured_platforms() == []+ assert config.setup_state()["needs_setup"] is True+ # Workbench-only first-run state: no external IM enabled, primary anchored+ # to the workbench. Guards against the PlatformsConfig ["slack"] dataclass+ # default leaking in and persisting a phantom Slack transport on skip.+ assert config.platforms.enabled == []+ assert config.platforms.primary == "avibe"+++def test_load_config_or_default_returns_default_without_persisting(isolated_state, tmp_path):+ # The read-side default backs GET /api/config on a fresh install: the+ # setup wizard (and the reused provider-config modal that calls+ # getConfig()) must load before any config file exists — without a raise+ # and without turning the read into a write.+ target = tmp_path / "config.json"+ assert not target.exists()++ config = settings_service.load_config_or_default(target)++ assert config.setup_state()["needs_setup"] is True+ assert config.setup_completed is False+ assert not target.exists(), "reading a missing config must not create the file"+++def test_load_config_or_default_reads_disk_when_present(isolated_state, tmp_path):+ # Once a real config exists, the on-disk value wins (here: a completed+ # setup is reported as completed, never overwritten by the fresh default).+ target = tmp_path / "config.json"+ seeded = settings_service.default_config()+ seeded.setup_completed = True+ seeded.save(target)++ config = settings_service.load_config_or_default(target)++ assert config.setup_completed is True+ assert config.setup_state()["needs_setup"] is False++def test_load_config_seeds_default_when_factory_given(isolated_state, tmp_path):target = tmp_path / "config.json"diff --git a/tests/test_platform_registry.py b/tests/test_platform_registry.pyindex 6e4d7ad29..5af1c9f21 100644--- a/tests/test_platform_registry.py+++ b/tests/test_platform_registry.py@@ -3,9 +3,18 @@ from __future__ import annotationsfrom types import SimpleNamespaceimport config.platform_registry as platform_registry-from config.platform_registry import PlatformCapabilities, PlatformDescriptor, get_platform_descriptor-from config.v2_config import PlatformsConfig, V2Config+from config.platform_registry import (+ WORKBENCH_PLATFORM_ID,+ PlatformCapabilities,+ PlatformDescriptor,+ get_platform_descriptor,+ im_platform_ids,+ is_workbench_platform,+)+from config.v2_config import PlatformsConfig, SlackConfig, V2Config+from modules.im.avibe import AvibeBotfrom modules.im.factory import IMFactory+from modules.im.slack import SlackBotdef test_platform_catalog_exposes_capability_flags() -> None:@@ -77,3 +86,85 @@ def test_registry_addition_drives_platform_validation_and_readiness(monkeypatch)assert fake_config.configured_platforms() == ["mockchat"]assert "mockchat" in IMFactory.get_supported_platforms()+++def test_is_workbench_platform_identifies_avibe() -> None:+ assert WORKBENCH_PLATFORM_ID == "avibe"+ assert is_workbench_platform("avibe") is True+ assert is_workbench_platform("slack") is False+++def test_im_platform_ids_excludes_workbench() -> None:+ ids = im_platform_ids()++ assert "avibe" not in ids+ assert {"slack", "discord", "telegram", "lark", "wechat"} <= set(ids)+++def test_catalog_payload_exposes_kind_distinction() -> None:+ catalog = {item["id"]: item for item in platform_registry.platform_catalog_payload()}++ assert catalog["avibe"]["kind"] == "workbench"+ assert catalog["slack"]["kind"] == "im"+ assert catalog["discord"]["kind"] == "im"+++def _config_with_enabled(enabled: list[str]) -> SimpleNamespace:+ return SimpleNamespace(+ platform="slack",+ slack=SlackConfig(bot_token="xoxb-test"),+ enabled_platforms=lambda: list(enabled),+ )+++def test_create_clients_skips_workbench_when_only_avibe_enabled() -> None:+ # The controller wires the in-process workbench itself; the IM factory must+ # never try to build an "avibe" client (it has no AppCompatConfig and would+ # raise "Avibe configuration not found").+ clients = IMFactory.create_clients(_config_with_enabled(["avibe"]))++ assert clients == {}+ assert "avibe" not in clients+++def test_create_clients_builds_real_platforms_but_skips_workbench() -> None:+ clients = IMFactory.create_clients(_config_with_enabled(["slack", "avibe"]))++ assert list(clients.keys()) == ["slack"]+ assert isinstance(clients["slack"], SlackBot)+ assert not any(isinstance(client, AvibeBot) for client in clients.values())+++def test_create_client_returns_avibe_for_workbench_only_empty_enabled() -> None:+ # Workbench-only config: no external IM platform is enabled, so the built+ # client map is empty. ``create_client`` must return the in-process+ # ``AvibeBot`` (mirroring the controller's avibe fallback) rather than+ # constructing ``MultiIMClient({}, "avibe")``, which would raise because the+ # primary is absent from the empty map.+ config = _config_with_enabled([])+ config.platforms = SimpleNamespace(enabled=[], primary="avibe")++ client = IMFactory.create_client(config)++ assert isinstance(client, AvibeBot)+++def test_create_client_returns_avibe_for_legacy_avibe_only_enabled() -> None:+ # Older configs persisted the workbench-only state as ``["avibe"]`` instead+ # of an empty list. ``create_clients`` skips the workbench either way, so the+ # singular helper must still resolve to the in-process ``AvibeBot``.+ client = IMFactory.create_client(_config_with_enabled(["avibe"]))++ assert isinstance(client, AvibeBot)+++def test_create_client_returns_single_real_client_when_one_platform_enabled() -> None:+ # Sanity guard that the workbench-only short-circuit does not regress the+ # ordinary single-platform path: a lone enabled platform returns that+ # client directly (not wrapped in MultiIMClient).+ config = _config_with_enabled(["slack"])+ config.platforms = SimpleNamespace(enabled=["slack"], primary="slack")++ client = IMFactory.create_client(config)++ assert isinstance(client, SlackBot)diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex d0c609632..0ef1b3f8e 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -137,6 +137,29 @@ def test_harness_routes_page_filter_and_return_counts(monkeypatch, tmp_path):assert counts["runs"]["all"] == 4+def test_config_get_on_fresh_install_returns_default_needing_setup(monkeypatch, tmp_path):+ # Fresh install edge: no config file exists yet, but the setup wizard+ # (and the reused provider-config modal that calls getConfig()) must be+ # able to load. GET /api/config must serve an in-memory default with+ # needs_setup=True instead of propagating FileNotFoundError as a 500 —+ # and must not create the file (the read stays a read; save_config owns+ # the first write).+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ from config import paths++ assert not paths.get_config_path().exists()++ client = app.test_client()+ response = client.get("/api/config")++ assert response.status_code == 200+ data = response.get_json()+ assert data["mode"] == "self_host"+ assert data["setup_completed"] is False+ assert data["setup_state"]["needs_setup"] is True+ assert not paths.get_config_path().exists(), "GET must not persist a config file"++def test_run_maybe_async_offloads_sync_handlers_without_losing_context():import asyncioimport threadingdiff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.pyindex e92804932..560033257 100644--- a/tests/test_v2_compat_platforms.py+++ b/tests/test_v2_compat_platforms.py@@ -77,6 +77,32 @@ def test_to_app_config_preserves_telegram_config():assert compat.telegram.bot_token == "123456:test-token"+def test_to_app_config_workbench_only_yields_no_enabled_platforms() -> None:+ # A workbench-only V2Config (empty enabled, primary anchored to "avibe")+ # must surface an empty enabled list in the compat view too, so the IM+ # factory creates no clients and the controller wires the in-process Avibe+ # surface itself. Falling back to ``[self.platform]`` here would make the+ # factory try (and fail) to build an "avibe" client from a missing config.+ config = V2Config(+ mode="self_host",+ version="v2",+ platforms=PlatformsConfig(enabled=[], primary="slack"),+ slack=SlackConfig(),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ update=UpdateConfig(),+ )+ config.platforms.validate()+ config.platform = config.platforms.primary++ compat = to_app_config(config)++ assert compat.platform == "avibe"+ assert compat.platforms == {"enabled": [], "primary": "avibe"}+ assert compat.enabled_platforms() == []++def test_to_app_config_uses_shared_agent_defaults() -> None:config = V2Config(mode="self_host",diff --git a/tests/test_v2_config_platform_registry.py b/tests/test_v2_config_platform_registry.pyindex a2cbca50f..b2a9a203b 100644--- a/tests/test_v2_config_platform_registry.py+++ b/tests/test_v2_config_platform_registry.py@@ -37,6 +37,7 @@ def test_setup_state_counts_telegram_credentials() -> None:platform="telegram",platforms=PlatformsConfig(enabled=["telegram"], primary="telegram"),telegram=TelegramConfig(bot_token="123456:test-token"),+ setup_completed=True,)assert config.platform_has_credentials("telegram") is True@@ -61,6 +62,78 @@ def test_setup_state_only_counts_enabled_platforms() -> None:assert config.setup_state()["needs_setup"] is True+def test_setup_state_uses_setup_completed_flag() -> None:+ # ``needs_setup`` is gated solely on the explicit ``setup_completed`` flag,+ # independent of whether any platform credentials are configured. A+ # workbench-only install (no IM credentials) that finished the wizard is+ # therefore not bounced back to /setup.+ config = _base_config(setup_completed=True)++ assert config.configured_platforms() == []+ assert config.setup_state()["needs_setup"] is False+++def test_from_payload_migrates_legacy_setup_completed_true() -> None:+ # A payload that predates the flag (no ``setup_completed`` key) but has a+ # mode plus a credentialed enabled platform migrates to completed=True.+ payload = api.config_to_payload(+ _base_config(+ platform="telegram",+ platforms=PlatformsConfig(enabled=["telegram"], primary="telegram"),+ telegram=TelegramConfig(bot_token="123456:test-token"),+ ),+ include_secrets=True,+ )+ payload.pop("setup_completed", None)++ config = V2Config.from_payload(payload)++ assert config.setup_completed is True+ assert config.setup_state()["needs_setup"] is False+++def test_from_payload_migrates_legacy_setup_completed_false() -> None:+ # A legacy payload (no ``setup_completed`` key) whose only enabled platform+ # lacks credentials migrates to completed=False, so the wizard still runs.+ payload = api.config_to_payload(+ _base_config(+ platform="telegram",+ platforms=PlatformsConfig(enabled=["telegram"], primary="telegram"),+ telegram=TelegramConfig(bot_token=""),+ ),+ include_secrets=True,+ )+ payload.pop("setup_completed", None)++ config = V2Config.from_payload(payload)++ assert config.setup_completed is False+ assert config.setup_state()["needs_setup"] is True+++def test_validate_strips_workbench_and_retargets_primary() -> None:+ # A legacy/hand-edited config with avibe alongside a real IM (and avibe as+ # primary) must normalize: avibe is stripped from `enabled` and the primary+ # is retargeted to the real platform, so the IM factory/controller never see+ # a stranded 'avibe' primary (which would crash startup).+ platforms = PlatformsConfig(enabled=["avibe", "slack"], primary="avibe")+ platforms.validate()+ assert platforms.enabled == ["slack"]+ assert platforms.primary == "slack"++ # avibe trailing with a real primary: stripped, primary untouched.+ trailing = PlatformsConfig(enabled=["slack", "avibe"], primary="slack")+ trailing.validate()+ assert trailing.enabled == ["slack"]+ assert trailing.primary == "slack"++ # avibe-only enabled normalizes to workbench-only.+ workbench = PlatformsConfig(enabled=["avibe"], primary="avibe")+ workbench.validate()+ assert workbench.enabled == []+ assert workbench.primary == "avibe"++def test_config_payload_includes_platform_catalog_and_setup_state() -> None:config = _base_config(platforms=PlatformsConfig(enabled=["slack", "discord", "telegram", "lark", "wechat"], primary="slack"),@@ -69,6 +142,7 @@ def test_config_payload_includes_platform_catalog_and_setup_state() -> None:telegram=TelegramConfig(bot_token="123456:test-token"),lark=LarkConfig(app_id="app-id", app_secret="app-secret"),wechat=WeChatConfig(bot_token="wechat-token"),+ setup_completed=True,)payload = api.config_to_payload(config)@@ -91,6 +165,50 @@ def test_config_payload_includes_platform_catalog_and_setup_state() -> None:assert payload["ui"]["chat_message_font_size"] == 14+def test_platforms_validate_allows_empty_enabled_and_anchors_avibe() -> None:+ # Workbench-only install: the wizard saves no external IM platform. Empty+ # ``enabled`` must validate (no longer raise) and anchor ``primary`` to the+ # in-process Avibe surface without force-inserting a real IM into ``enabled``.+ platforms = PlatformsConfig(enabled=[], primary="slack")++ platforms.validate()++ assert platforms.primary == "avibe"+ assert platforms.enabled == []+++def test_platforms_validate_keeps_non_empty_enabled_unchanged() -> None:+ # Has-IM behavior is untouched: the primary is still force-inserted into a+ # non-empty enabled list at the front.+ platforms = PlatformsConfig(enabled=["discord"], primary="slack")++ platforms.validate()++ assert platforms.primary == "slack"+ assert platforms.enabled == ["slack", "discord"]+++def test_workbench_only_config_round_trips_with_avibe_primary() -> None:+ config = _base_config(+ platforms=PlatformsConfig(enabled=[], primary="slack"),+ setup_completed=True,+ )+ # ``save()`` validates before persisting; mirror that so the serialized+ # payload reflects what actually lands on disk for a workbench-only install.+ config.platforms.validate()+ config.platform = config.platforms.primary++ payload = api.config_to_payload(config, include_secrets=True)+ assert payload["platforms"] == {"enabled": [], "primary": "avibe"}++ restored = V2Config.from_payload(payload)++ assert restored.platforms.primary == "avibe"+ assert restored.platforms.enabled == []+ assert restored.platform == "avibe"+ assert restored.enabled_platforms() == []++def test_chat_message_font_size_is_clamped() -> None:payload = api.config_to_payload(_base_config())payload["ui"]["chat_message_font_size"] = 99diff --git a/tests/test_workbench_only_runtime.py b/tests/test_workbench_only_runtime.pynew file mode 100644index 000000000..014998d76--- /dev/null+++ b/tests/test_workbench_only_runtime.py@@ -0,0 +1,151 @@+"""Workbench-only runtime: zero external IM platforms.++A workbench-only install enables no Slack/Discord/Telegram/Lark/WeChat+platform. The Avibe Workbench (in-process Web UI) is the sole inbound surface.+These tests cover the two delicate seams that make that work end-to-end:++1. Controller ``_init_modules`` must register the in-process ``AvibeBot`` as the+ SOLE IM client, anchor the primary platform to "avibe", and wire a settings+ manager for it — without crashing on the empty enabled-platform set.+2. ``AvibeBot.run`` must fire ``on_ready`` exactly once (so the controller starts+ poll-restore / scheduled tasks / update checker) and then BLOCK so the+ IM-runtime thread does not return, keeping the controller's ``run_forever``+ alive until ``stop`` is called.++The has-IM path is exercised by the broader multi-platform suite; here we only+assert the workbench-only behavior that previously raised.+"""++from __future__ import annotations++import asyncio+import sys+import threading+import time+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config.v2_compat import to_app_config+from config.v2_config import V2Config+from core.controller import Controller+from modules.im.avibe import AvibeBot, AvibeConfig+from modules.im.base import MessageContext+++def _workbench_only_app_config():+ payload = {+ "platform": "slack",+ "platforms": {"enabled": [], "primary": "slack"},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "setup_completed": True,+ }+ return to_app_config(V2Config.from_payload(payload))+++def test_init_modules_registers_avibe_as_sole_client_for_workbench_only():+ app_config = _workbench_only_app_config()+ # The compat view of a workbench-only config exposes no enabled platforms.+ assert app_config.enabled_platforms() == []++ controller = Controller.__new__(Controller)+ controller.config = app_config+ controller.enabled_platforms = list(app_config.enabled_platforms())+ controller.primary_platform = getattr(getattr(app_config, "platforms", None), "primary", app_config.platform)++ controller._init_modules()++ assert list(controller.im_clients.keys()) == ["avibe"]+ assert isinstance(controller.im_client, AvibeBot)+ assert controller.primary_platform == "avibe"+ # The primary-anchored settings manager resolves (no KeyError on an empty+ # enabled-platform set) for both the no-context and avibe-context cases.+ assert controller.get_settings_manager_for_context(None).platform == "avibe"+ avibe_ctx = MessageContext(user_id="u", channel_id="c", platform="avibe")+ assert controller.get_settings_manager_for_context(avibe_ctx).platform == "avibe"+ # Agent routing has a route for the avibe primary.+ assert "avibe" in controller.agent_router.platform_routes+++def test_avibe_run_fires_on_ready_once_then_blocks_until_stop():+ # Stand-in for the controller event loop + its _dispatch_to_controller_loop+ # bridge, so we exercise the real cross-loop hand-off AvibeBot.run relies on.+ controller_loop = asyncio.new_event_loop()+ ready_calls: list[bool] = []++ def _start_loop() -> None:+ asyncio.set_event_loop(controller_loop)+ controller_loop.run_forever()++ loop_thread = threading.Thread(target=_start_loop, daemon=True)+ loop_thread.start()+ try:+ # Wait for the loop to actually be running before scheduling onto it.+ for _ in range(100):+ if controller_loop.is_running():+ break+ time.sleep(0.01)++ async def _on_ready() -> None:+ assert asyncio.get_running_loop() is controller_loop+ ready_calls.append(True)++ def _dispatch_to_controller_loop(callback):+ async def _wrapped(*args, **kwargs):+ try:+ current = asyncio.get_running_loop()+ except RuntimeError:+ current = None+ if current is controller_loop:+ return await callback(*args, **kwargs)+ future = asyncio.run_coroutine_threadsafe(callback(*args, **kwargs), controller_loop)+ return await asyncio.wrap_future(future)++ return _wrapped++ bot = AvibeBot(AvibeConfig())+ bot.register_callbacks(on_message=None, on_ready=_dispatch_to_controller_loop(_on_ready))++ returned: list[bool] = []++ def _run_im() -> None:+ bot.run()+ returned.append(True)++ im_thread = threading.Thread(target=_run_im, name="im-runtime", daemon=True)+ im_thread.start()++ # on_ready fires once and run() blocks (the thread stays alive).+ for _ in range(100):+ if ready_calls:+ break+ time.sleep(0.01)+ assert ready_calls == [True]+ time.sleep(0.05)+ assert im_thread.is_alive() is True+ assert returned == []++ # stop() (called from another thread, like cleanup_sync) releases run().+ bot.stop()+ im_thread.join(timeout=3)+ assert im_thread.is_alive() is False+ assert returned == [True]+ # on_ready did not fire a second time.+ assert ready_calls == [True]+ finally:+ controller_loop.call_soon_threadsafe(controller_loop.stop)+ loop_thread.join(timeout=3)+ controller_loop.close()+++def test_avibe_stop_is_safe_before_run():+ # cleanup_sync may call stop() even if run() never started (e.g. early+ # failure). It must not raise.+ bot = AvibeBot(AvibeConfig())+ bot.stop()diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsxindex 8e0573322..0c66892d3 100644--- a/ui/src/components/Wizard.tsx+++ b/ui/src/components/Wizard.tsx@@ -119,6 +119,10 @@ export const Wizard: React.FC = () => {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'diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsxindex 52da30e2a..820fe68fe 100644--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx@@ -1,200 +1,13 @@-import React, { useEffect, useMemo, useState } from 'react';+import React from 'react';import { Link } from 'react-router-dom';import { useTranslation } from 'react-i18next';-import {- AlertTriangle,- ArrowLeft,- CheckCircle2,- Info,- KeyRound,- Pencil,- RotateCcw,- Save,- Sparkles,- Trash2,-} from 'lucide-react';+import { ArrowLeft } 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 { SettingsPageShell } from './SettingsPageShell';-import { BackendOAuthPanel } from './BackendOAuthPanel';-import { BackendTestPanel } from './BackendTestPanel';-import { BackendRuntimeCard } from './shared/BackendRuntimeCard';-import { SegmentedRadio } from './shared/SegmentedRadio';-import { useBackendRuntime } from './shared/useBackendRuntime';-import { useOAuthFlowLock } from './shared/useOAuthFlowLock';-import { useApi } from '@/context/ApiContext';-import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';-import { useToast } from '@/context/ToastContext';--const BACKEND_ID = 'claude';-const DEFAULT_CLI = 'claude';+import { ClaudeProviderConfig } from './providers/ClaudeProviderConfig';export const SettingsClaudeProviderPage: React.FC = () => {const { t } = useTranslation();- const api = useApi();- 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 [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 [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 || '';- setAuthMode(initialMode);- setBaseUrl(initialBase);- setSavedAuthMode(initialMode);- 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 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 V2Config; leaves any OAuth tokens in- // ``~/.claude/credentials.json`` (or the OS keychain) alone. Lets- // the user clear a stale key without having to also re-do 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);- setBaseUrl(fresh.base_url || '');- setSavedBaseUrl(fresh.base_url || '');- setApiKey('');- setEditingKey(false);- showToast(t('settings.backends.claudeApiKeyRemoved'), 'success');- } catch (err: any) {- showToast(- t('settings.backends.claudeApiKeyRemoveFailed', { detail: err?.message || '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.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 || '';- setAuthMode(nextMode);- setBaseUrl(nextBase);- setSavedAuthMode(nextMode);- setSavedBaseUrl(nextBase);- setApiKey('');- setEditingKey(false);- // Claude restart is synthetic (one-shot CLI) so result.restart.ok- // is always true; treat any falsy state defensively just in case.- if (result.restart?.ok === false) {- showToast(result.restart.message || t('settings.backends.claudeSaveSuccess'), 'warning');- } else {- showToast(t('settings.backends.claudeSaveSuccess'), 'success');- }- } catch (err: any) {- showToast(err?.message || t('settings.backends.claudeSaveFailed'), 'error');- } finally {- setAuthSaving(false);- }- };return (<SettingsPageShell@@ -208,273 +21,7 @@ export const SettingsClaudeProviderPage: React.FC = () => {</Link>}>- {!runtime.loaded ? (- <div className="text-sm text-muted">{t('common.loading')}</div>- ) : (- <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"- runtime={runtime}- />-- {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.activeAuthApiKey')}- </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}- // ``has_oauth_credentials`` flips when ``~/.claude/credentials.json``- // carries a usable token bundle — that's a real signal we can- // trust on Linux/Docker. macOS keychain installs still report- // false, but a successful in-session login flips the panel's- // own state anyway.- signedIn={!!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 htmlFor="claude-api-key" className="text-xs font-medium uppercase text-muted">- {t('settings.backends.claudeApiKeyLabel')}- </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- tokens in ``~/.claude/credentials.json`` /- keychain 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 hover:bg-destructive/10 hover:text-destructive"- >- <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('settings.backends.claudeApiKeyPlaceholder') 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" />- <div className="flex flex-col gap-1">- <p className="text-[12px] font-medium text-gold">- {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 ||- 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>- )}+ <ClaudeProviderConfig /></SettingsPageShell>);};diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsxindex d6b90efaa..1a8a57a15 100644--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx@@ -1,210 +1,13 @@-import React, { useEffect, useMemo, useState } from 'react';+import React from 'react';import { Link } from 'react-router-dom';-import { ArrowLeft, Bot, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save, Trash2 } from 'lucide-react';+import { ArrowLeft } 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 { SettingsPageShell } from './SettingsPageShell';-import { BackendRuntimeCard } from './shared/BackendRuntimeCard';-import { SegmentedRadio } from './shared/SegmentedRadio';-import { surfaceBackendNotices } from './shared/surfaceBackendNotices';-import { useBackendRuntime } from './shared/useBackendRuntime';-import { useOAuthFlowLock } from './shared/useOAuthFlowLock';--const BACKEND_ID = 'codex';-const DEFAULT_CLI = 'codex';+import { CodexProviderConfig } from './providers/CodexProviderConfig';export const SettingsCodexProviderPage: React.FC = () => {const { t } = useTranslation();- const api = useApi();- 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: any) {- showToast(- t('settings.backends.codexApiKeyRemoveFailed', { detail: err?.message || '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: any) {- showToast(err?.message || t('settings.backends.codexSaveFailed'), 'error');- } finally {- setSaving(false);- }- };return (<SettingsPageShell@@ -218,277 +21,7 @@ export const SettingsCodexProviderPage: React.FC = () => {</Link>}>- {loading || !runtime.loaded ? (- <div className="text-sm text-muted">{t('common.loading')}</div>- ) : (- <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}- />-- <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">- {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">- {t('settings.backends.codexCredentialsStoreKeyringWarn', { store: state.credentials_store })}- </p>- )}- </div>-- {authMode === 'oauth' && (- <BackendOAuthPanel- backend="codex"- signedIn={!!state?.has_chatgpt_tokens}- 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 hover:bg-destructive/10 hover:text-destructive"- >- <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>- )}+ <CodexProviderConfig /></SettingsPageShell>);};diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsxindex 7d10ec7bf..9a661a241 100644--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx@@ -1,495 +1,13 @@-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import React from 'react';import { Link } from 'react-router-dom';import { useTranslation } from 'react-i18next';-import {- AlertCircle,- ArrowLeft,- Check,- ChevronDown,- ChevronUp,- Cpu,- Info,- KeyRound,- Pencil,- RefreshCw,- RotateCcw,- Save,- Search,- Server,- Settings,- Star,- Terminal,- Trash2,- X,-} from 'lucide-react';-import clsx from 'clsx';+import { ArrowLeft } 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 { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { SettingsPageShell } from './SettingsPageShell';-import { BackendOAuthPanel } from './BackendOAuthPanel';-import { OpencodeProviderTestPanel } from './OpencodeProviderTestPanel';-import { BackendRuntimeCard } from './shared/BackendRuntimeCard';-import { useBackendRuntime } from './shared/useBackendRuntime';-import { useApi } from '@/context/ApiContext';-import type { OpencodeProvider } from '@/context/ApiContext';-import { useToast } from '@/context/ToastContext';--type PermissionState = 'idle' | 'loading' | 'success' | 'error';-type FilterMode = 'all' | 'configured' | 'oauth' | 'local';--// Per-provider edit state — kept in a record so the page can render the-// grid statelessly and only allocate inputs for the expanded card.-type ProviderEditState = {- apiKey: string;- baseUrl: string;- saving: boolean;- removing: boolean;- error: string | null;- // Mirrors the Codex / Claude pattern: false = show ``api_key_masked``- // read-only with a Replace button; true = empty editable input ready- // for a fresh key. Toggled by the pencil button next to the masked- // preview. Reset to false on successful save / remove / reload.- editingKey: boolean;-};--const BACKEND_ID = 'opencode';-const DEFAULT_CLI = 'opencode';-// Server startup is asynchronous (OpenCode app spawn + port bind). Retry-// the introspection fan-out a handful of times before falling back to the-// "server not reachable" banner so the user can still configure values.-const SERVER_START_MAX_RETRIES = 5;-const SERVER_START_RETRY_DELAY_MS = 3000;--const FILTER_MODES: ReadonlyArray<FilterMode> = ['all', 'configured', 'oauth', 'local'];--const emptyEdit = (): ProviderEditState => ({- apiKey: '',- baseUrl: '',- saving: false,- removing: false,- error: null,- editingKey: false,-});--const providerMatchesFilter = (provider: OpencodeProvider, mode: FilterMode): boolean => {- switch (mode) {- case 'configured':- return provider.configured;- case 'oauth':- return provider.oauth_available;- case 'local':- return provider.local;- case 'all':- default:- return true;- }-};--const providerMatchesSearch = (provider: OpencodeProvider, q: string): boolean => {- if (!q) return true;- const needle = q.toLowerCase();- if (provider.id.toLowerCase().includes(needle)) return true;- if (provider.name.toLowerCase().includes(needle)) return true;- if (provider.description.toLowerCase().includes(needle)) return true;- return provider.models.some((m) => m.toLowerCase().includes(needle));-};+import { OpencodeProviderConfig } from './providers/OpencodeProviderConfig';export const SettingsOpencodeProviderPage: React.FC = () => {const { t } = useTranslation();- const api = useApi();- const { showToast } = useToast();-- // Runtime state — shared with Claude / Codex pages via the hook.- const runtime = useBackendRuntime({- backend: BACKEND_ID,- defaultCli: DEFAULT_CLI,- fallbackDefaultBackend: BACKEND_ID,- });- const [permissionState, setPermissionState] = useState<PermissionState>('idle');- const [permissionMessage, setPermissionMessage] = useState('');-- // Provider catalog state.- const [providers, setProviders] = useState<OpencodeProvider[] | null>(null);- const [defaultProvider, setDefaultProvider] = useState<string | null>(null);- const [providersLoading, setProvidersLoading] = useState(false);- const [providersError, setProvidersError] = useState<string | null>(null);- const [serverStartAttempts, setServerStartAttempts] = useState(0);- // ``true`` when opencode.json carries ``permission: "allow"`` — the- // Settings page suppresses the "Allow tool calls" affordance once- // this is the case (page feedback: a permanent "Setup permission"- // button is misleading once permission is already set).- const [permissionAllowed, setPermissionAllowed] = useState(false);-- // Toolbar state.- const [searchQuery, setSearchQuery] = useState('');- const [filterMode, setFilterMode] = useState<FilterMode>('all');-- // Inline-expansion state — only one card open at a time.- const [expandedId, setExpandedId] = useState<string | null>(null);- const [editByProvider, setEditByProvider] = useState<Record<string, ProviderEditState>>({});-- // Default-provider popover state.- const [defaultPopoverOpen, setDefaultPopoverOpen] = useState(false);- const [defaultSearchQuery, setDefaultSearchQuery] = useState('');- const [settingDefault, setSettingDefault] = useState(false);-- // Server-start retry timer cleanup.- const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- // useEffect closure captures the initial loadProviders; ref lets the- // retry timer call the latest implementation without re-arming on every- // state update.- const loadProvidersRef = useRef<(() => Promise<void>) | null>(null);-- const loadProviders = useCallback(async () => {- setProvidersLoading(true);- setProvidersError(null);- try {- const result = await api.getOpencodeProviders();- if (result.ok && result.providers) {- setProviders(result.providers);- setDefaultProvider(result.default_provider || null);- setPermissionAllowed(result.permission_allowed === true);- setServerStartAttempts(0);- setProvidersError(null);- } else {- setProviders((prev) => prev ?? []);- setProvidersError(result.message || t('settings.backends.opencodeProvidersError'));- }- } catch (e: any) {- setProviders((prev) => prev ?? []);- setProvidersError(e?.message || t('settings.backends.opencodeProvidersError'));- } finally {- setProvidersLoading(false);- }- }, [api, t]);-- useEffect(() => {- loadProvidersRef.current = loadProviders;- }, [loadProviders]);-- // Runtime initial-load + cli_path/detect/install/save/toggle live in- // ``useBackendRuntime``. This page-specific effect just drives the- // providers fan-out: load when the runtime is enabled, clear when- // it's not. Triggered whenever the optimistic enabled flag changes- // (matches the original "toggle then reload" UX exactly).- useEffect(() => {- if (!runtime.loaded) return;- // If the initial getConfig() failed, ``runtime.enabled`` is still- // the pre-load default rather than persisted state. Don't trigger- // provider fetches in that case — the toast in the runtime hook- // already informed the user; firing requests now would just emit- // misleading "server stopped" errors.- if (runtime.configError) return;- if (runtime.enabled) {- setServerStartAttempts(0);- void loadProviders();- } else {- setProviders(null);- setProvidersError(null);- }- return () => {- if (retryTimerRef.current) clearTimeout(retryTimerRef.current);- };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [runtime.enabled, runtime.loaded, runtime.configError]);-- // Auto-retry server-start failures — common when the user has just- // enabled the backend. After SERVER_START_MAX_RETRIES the user can hit- // Refresh manually; we stop the implicit retry to avoid background- // request loops.- useEffect(() => {- if (retryTimerRef.current) {- clearTimeout(retryTimerRef.current);- retryTimerRef.current = null;- }- if (!runtime.enabled) return;- if (!providersError) return;- if (providersLoading) return;- if (serverStartAttempts >= SERVER_START_MAX_RETRIES) return;- retryTimerRef.current = setTimeout(() => {- setServerStartAttempts((n) => n + 1);- void loadProvidersRef.current?.();- }, SERVER_START_RETRY_DELAY_MS);- return () => {- if (retryTimerRef.current) {- clearTimeout(retryTimerRef.current);- retryTimerRef.current = null;- }- };- }, [runtime.enabled, providersError, providersLoading, serverStartAttempts]);-- const setupPermission = async () => {- setPermissionState('loading');- setPermissionMessage('');- try {- const result = await api.opencodeSetupPermission();- setPermissionState(result.ok ? 'success' : 'error');- setPermissionMessage(result.message);- showToast(result.message, result.ok ? 'success' : 'error');- if (result.ok) {- // Flip locally so the affordance vanishes immediately rather- // than waiting for the next provider refresh tick — the next- // ``loadProviders`` will recompute the value from disk anyway.- setPermissionAllowed(true);- }- } catch (e: any) {- setPermissionState('error');- const msg = e?.message || String(e);- setPermissionMessage(msg);- showToast(msg, 'error');- }- };-- // ``onSaveRuntime`` and ``toggleEnabled`` are owned by- // ``useBackendRuntime``; the providers reload/clear side-effect- // that used to live inside the page's toggle handler is now driven- // by the ``useEffect([runtime.enabled, runtime.loaded])`` above.-- // ---- Expansion / per-provider editing ------ const openProvider = (provider: OpencodeProvider) => {- setExpandedId(provider.id);- setEditByProvider((prev) => {- if (prev[provider.id]) return prev;- // Pre-populate baseUrl from the persisted opencode.json override so- // the input round-trips: open card → see existing value → edit →- // save. Leaving it blank on every open would let a re-save wipe the- // value because the form is the only baseURL signal we forward.- const seeded = emptyEdit();- if (provider.base_url) {- seeded.baseUrl = provider.base_url;- }- return { ...prev, [provider.id]: seeded };- });- };-- const closeProvider = () => {- // Wipe the in-memory plaintext key/base-url for the closing card so- // collapsing acts as a panic-revert: defense-in-depth in case the- // user typed a key but did not save it.- if (expandedId) {- setEditByProvider((prev) => {- if (!prev[expandedId]) return prev;- return { ...prev, [expandedId]: emptyEdit() };- });- }- setExpandedId(null);- };-- const onToggleProvider = (provider: OpencodeProvider) => {- if (expandedId === provider.id) {- closeProvider();- } else {- openProvider(provider);- }- };-- const updateEdit = (providerId: string, patch: Partial<ProviderEditState>) => {- setEditByProvider((prev) => ({- ...prev,- [providerId]: { ...(prev[providerId] || emptyEdit()), ...patch },- }));- };-- 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();- 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');- await loadProviders();- } catch (e: any) {- updateEdit(provider.id, {- saving: false,- error: e?.message || (t('settings.backends.opencodeProviderSaveFailed') as string),- });- }- };-- const onRemoveProviderAuth = async (provider: OpencodeProvider) => {- // Confirm copy matches what's actually about to be removed.- const confirmKey =- provider.active_auth_type === 'oauth'- ? 'settings.backends.opencodeProviderRemoveOauthConfirm'- : 'settings.backends.opencodeProviderRemoveConfirm';- const confirmed = window.confirm(- t(confirmKey, { name: provider.name }) as string,- );- if (!confirmed) return;- updateEdit(provider.id, { removing: true, error: null });- try {- const result = await api.deleteOpencodeProviderAuth(provider.id);- if (!result.ok) {- updateEdit(provider.id, {- removing: false,- error: result.message || (t('settings.backends.opencodeProviderRemoveFailed') as string),- });- return;- }- updateEdit(provider.id, { removing: false, error: null });- showToast(t('settings.backends.opencodeProviderRemoved'), 'success');- await loadProviders();- } catch (e: any) {- updateEdit(provider.id, {- removing: false,- error: e?.message || (t('settings.backends.opencodeProviderRemoveFailed') as string),- });- }- };-- // ---- Default-provider selection ------ const pickDefaultProvider = async (provider: OpencodeProvider) => {- if (!provider.configured) {- // Surfacing "set the key first" is more discoverable than silently- // ignoring the click — expand the card and let the user fill it in.- setDefaultPopoverOpen(false);- setDefaultSearchQuery('');- openProvider(provider);- showToast(- t('settings.backends.opencodeDefaultNeedsKey', { name: provider.name }),- 'warning'- );- return;- }- if (provider.id === defaultProvider) {- setDefaultPopoverOpen(false);- setDefaultSearchQuery('');- return;- }- setSettingDefault(true);- try {- const result = await api.setOpencodeDefaultProvider(provider.id);- if (!result.ok) {- showToast(- result.message || (t('settings.backends.opencodeDefaultSaveFailed') as string),- 'error'- );- return;- }- setDefaultProvider(result.default_provider || provider.id);- showToast(t('settings.backends.opencodeDefaultSaved', { name: provider.name }), 'success');- setDefaultPopoverOpen(false);- setDefaultSearchQuery('');- } catch (e: any) {- showToast(e?.message || (t('settings.backends.opencodeDefaultSaveFailed') as string), 'error');- } finally {- setSettingDefault(false);- }- };-- // ---- Derived collections ------ const visibleProviders = useMemo(() => {- if (!providers) return [];- return providers.filter(- (p) => providerMatchesFilter(p, filterMode) && providerMatchesSearch(p, searchQuery)- );- }, [providers, filterMode, searchQuery]);-- const popoverProviders = useMemo(() => {- if (!providers) return [];- return providers.filter((p) => providerMatchesSearch(p, defaultSearchQuery));- }, [providers, defaultSearchQuery]);-- const configuredCount = providers?.filter((p) => p.configured).length || 0;- const totalCount = providers?.length || 0;- const defaultProviderObj = useMemo(- () => providers?.find((p) => p.id === defaultProvider) || null,- [providers, defaultProvider]- );-- const filterLabel = (mode: FilterMode) => {- switch (mode) {- case 'all':- return t('settings.backends.opencodeFilterAll');- case 'configured':- return t('settings.backends.opencodeFilterConfigured');- case 'oauth':- return t('settings.backends.opencodeFilterOauth');- case 'local':- return t('settings.backends.opencodeFilterLocal');- }- };-- // ---- Status badge selection ----- //- // The order here matches the plan doc: configured wins, then OAuth- // availability, then local, finally "not set" for unconfigured cloud- // providers. Multi-flag providers therefore surface the most useful- // signal first.- const renderProviderBadge = (provider: OpencodeProvider) => {- if (provider.configured) {- // Show *which* auth source is live so the user can distinguish- // OAuth-signed-in from API-key-saved without expanding the card.- // Dual-mode providers (openai supports both) carry only one entry- // in auth.json at a time, so this matches what OpenCode uses.- const activeLabel =- provider.active_auth_type === 'oauth'- ? t('settings.backends.opencodeBadgeConfiguredOauth')- : provider.active_auth_type === 'api'- ? t('settings.backends.opencodeBadgeConfiguredApiKey')- : t('settings.backends.opencodeBadgeConfigured');- return (- <Badge variant="success" className="gap-1">- <Check className="size-3" />- {activeLabel}- </Badge>- );- }- if (provider.oauth_available) {- return (- <Badge variant="info">{t('settings.backends.opencodeBadgeOauth')}</Badge>- );- }- if (provider.local) {- return (- <Badge variant="secondary">{t('settings.backends.opencodeBadgeLocal')}</Badge>- );- }- return <Badge variant="outline">{t('settings.backends.opencodeBadgeUnset')}</Badge>;- };-- // ---- Render ----return (<SettingsPageShell@@ -503,682 +21,7 @@ export const SettingsOpencodeProviderPage: React.FC = () => {</Link>}>- {!runtime.loaded ? (- <div className="text-sm text-muted">{t('common.loading')}</div>- ) : (- <div className="flex flex-col gap-4">- <BackendRuntimeCard- backend={BACKEND_ID}- label="OpenCode"- description={t('settings.backends.opencodeDescription')}- Icon={Terminal}- iconTileClassName="bg-violet-soft"- iconClassName="text-violet"- runtime={runtime}- extraSlot={- // ``permission: "allow"`` setup is OpenCode-specific: without- // it the daemon prompts on every tool call and Vibe Remote- // can't reply. Hidden once opencode.json carries the value.- runtime.cliStatus === 'ok' && !permissionAllowed ? (- <div className="rounded-lg border border-gold/30 bg-gold/10 px-3 py-2.5">- <p className="mb-2 text-[12px] text-gold">- {t('agentDetection.permissionHintStrong')}- </p>- <div className="flex flex-wrap items-center gap-3">- <Button- variant="brand-gold"- size="xs"- onClick={() => void setupPermission()}- disabled={permissionState === 'loading'}- >- {permissionState === 'loading' ? (- <RefreshCw className="size-3.5 animate-spin" />- ) : (- <Settings className="size-3.5" />- )}- {t('agentDetection.setupPermission')}- </Button>- {permissionState === 'success' && (- <span className="text-[12px] text-mint">{permissionMessage}</span>- )}- {permissionState === 'error' && (- <span className="text-[12px] text-destructive">{permissionMessage}</span>- )}- </div>- </div>- ) : null- }- />-- {/* Card 2 — provider catalog. */}- <Card>- <CardContent className="flex flex-col gap-5 p-6">- <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">- <div className="flex items-center gap-3">- <div className="flex size-11 shrink-0 items-center justify-center rounded-[10px] bg-cyan-soft">- <Server size={22} className="text-cyan" />- </div>- <div className="flex flex-col gap-0.5">- <div className="flex flex-wrap items-center gap-2">- <span className="text-[15px] font-semibold text-foreground">- {t('settings.backends.opencodeProvidersTitle')}- </span>- {runtime.enabled && providers && (- <Badge variant={providersError ? 'warning' : 'success'}>- {providersError- ? t('settings.backends.opencodeServerStopped')- : t('settings.backends.opencodeServerRunning')}- </Badge>- )}- {!runtime.enabled && (- <Badge variant="secondary">- {t('settings.backends.opencodeBackendDisabled')}- </Badge>- )}- {runtime.enabled && providers && providers.length > 0 && (- <Badge variant="outline">- {t('settings.backends.opencodeProvidersCount', {- configured: configuredCount,- total: totalCount,- })}- </Badge>- )}- </div>- <span className="text-[12px] text-muted">- {t('settings.backends.opencodeProvidersSubtitle')}- </span>- </div>- </div>- <div className="flex items-center gap-2">- <Button- type="button"- variant="secondary"- size="sm"- onClick={() => {- setServerStartAttempts(0);- void loadProviders();- }}- disabled={!runtime.enabled || providersLoading}- >- <RefreshCw- className={clsx('size-3.5', providersLoading && 'animate-spin')}- />- {t('settings.backends.opencodeRefresh')}- </Button>- </div>- </div>-- {!runtime.enabled && (- <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-2.5 text-[12px] text-muted">- {t('settings.backends.opencodeDisabledBanner')}- </div>- )}-- {runtime.enabled && (- <>- {/* Toolbar — search + filter chips + default-provider pill. */}- <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">- <div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-center">- <div className="relative w-full sm:max-w-xs">- <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted" />- <Input- type="text"- placeholder={t('settings.backends.opencodeSearchPlaceholder') as string}- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- className="h-9 pl-8 text-[12px]"- autoComplete="off"- spellCheck={false}- />- </div>- <div className="flex flex-wrap items-center gap-1.5">- {FILTER_MODES.map((mode) => {- const active = filterMode === mode;- return (- <button- key={mode}- type="button"- onClick={() => setFilterMode(mode)}- className={clsx(- 'rounded-full border px-3 py-1 text-[11px] font-semibold transition-colors',- active- ? 'border-mint/40 bg-mint-soft text-mint'- : 'border-border bg-surface text-muted hover:text-foreground'- )}- >- {filterLabel(mode)}- </button>- );- })}- </div>- </div>-- {/* Default-provider pill. */}- <Popover- open={defaultPopoverOpen}- onOpenChange={(open) => {- setDefaultPopoverOpen(open);- if (!open) setDefaultSearchQuery('');- }}- >- <PopoverTrigger asChild>- <Button- type="button"- variant="outline"- size="sm"- disabled={!providers || providers.length === 0}- className="justify-between gap-2 text-[12px]"- >- <Star className="size-3.5 text-mint" />- <span className="text-muted">- {t('settings.backends.opencodeDefaultLabel')}:- </span>- <span className="font-mono text-[12px] text-foreground">- {defaultProviderObj- ? defaultProviderObj.name- : defaultProvider- ? defaultProvider- : t('settings.backends.opencodeDefaultUnset')}- </span>- <ChevronDown className="size-3.5 text-muted" />- </Button>- </PopoverTrigger>- <PopoverContent align="end" className="w-80 p-0">- <div className="flex flex-col gap-2 p-3">- <Label className="text-xs font-medium uppercase text-muted">- {t('settings.backends.opencodeDefaultPopoverTitle')}- </Label>- <div className="relative">- <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted" />- <Input- type="text"- placeholder={- t('settings.backends.opencodeSearchPlaceholder') as string- }- value={defaultSearchQuery}- onChange={(e) => setDefaultSearchQuery(e.target.value)}- className="h-8 pl-8 text-[12px]"- autoComplete="off"- spellCheck={false}- />- </div>- </div>- <div className="max-h-72 overflow-y-auto border-t border-border">- {popoverProviders.length === 0 ? (- <div className="px-3 py-2 text-[12px] text-muted">- {t('settings.backends.opencodeDefaultPopoverEmpty')}- </div>- ) : (- <ul className="flex flex-col">- {popoverProviders.map((provider) => {- const isCurrent = provider.id === defaultProvider;- return (- <li key={provider.id}>- <button- type="button"- onClick={() => void pickDefaultProvider(provider)}- disabled={settingDefault}- className={clsx(- 'flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-[12px] transition-colors',- 'hover:bg-surface-2',- isCurrent && 'bg-mint-soft/40'- )}- >- <span className="flex flex-col gap-0.5">- <span className="font-medium text-foreground">- {provider.name}- </span>- <span className="font-mono text-[11px] text-muted">- {provider.id}- </span>- </span>- <span className="flex items-center gap-2">- {provider.configured ? (- <Badge variant="success" className="gap-1">- <Check className="size-3" />- {t('settings.backends.opencodeBadgeConfigured')}- </Badge>- ) : provider.oauth_available ? (- <Badge variant="info">- {t('settings.backends.opencodeBadgeOauth')}- </Badge>- ) : provider.local ? (- <Badge variant="secondary">- {t('settings.backends.opencodeBadgeLocal')}- </Badge>- ) : (- <Badge variant="outline">- {t('settings.backends.opencodeBadgeUnset')}- </Badge>- )}- {isCurrent && <Check className="size-3.5 text-mint" />}- </span>- </button>- </li>- );- })}- </ul>- )}- </div>- </PopoverContent>- </Popover>- </div>-- {/* Server-starting / error banner. */}- {providersError && (- <div className="flex items-start gap-2 rounded-lg border border-gold/30 bg-gold/[0.08] px-3 py-2.5">- <AlertCircle className="mt-0.5 size-3.5 shrink-0 text-gold" />- <div className="flex flex-1 flex-col gap-1">- <p className="text-[12px] font-medium text-gold">- {serverStartAttempts < SERVER_START_MAX_RETRIES- ? t('settings.backends.opencodeServerStarting')- : t('settings.backends.opencodeServerUnreachable')}- </p>- <p className="text-[12px] leading-relaxed text-muted">{providersError}</p>- </div>- {serverStartAttempts < SERVER_START_MAX_RETRIES && (- <span className="shrink-0 text-[11px] text-muted">- {t('settings.backends.opencodeServerRetryCount', {- attempt: serverStartAttempts + 1,- max: SERVER_START_MAX_RETRIES,- })}- </span>- )}- </div>- )}-- {/* Initial loading skeleton. */}- {providersLoading && !providers && (- <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-6 text-center text-[12px] text-muted">- <RefreshCw className="mx-auto mb-2 size-4 animate-spin text-cyan" />- {t('settings.backends.opencodeProvidersLoading')}- </div>- )}-- {/* Empty state — server reports no providers at all. */}- {!providersLoading && providers && providers.length === 0 && !providersError && (- <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-6 text-center text-[12px] text-muted">- {t('settings.backends.opencodeProvidersEmpty')}- </div>- )}-- {/* Empty state — search/filter excluded everything. */}- {!providersLoading &&- providers &&- providers.length > 0 &&- visibleProviders.length === 0 && (- <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-6 text-center text-[12px] text-muted">- {t('settings.backends.opencodeProvidersFilterEmpty')}- </div>- )}-- {/* Grid. */}- {visibleProviders.length > 0 && (- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">- {visibleProviders.map((provider) => {- const expanded = expandedId === provider.id;- const edit = editByProvider[provider.id] || emptyEdit();- const isDefault = defaultProvider === provider.id;- return (- <div- key={provider.id}- className={clsx(- 'flex flex-col rounded-lg border bg-surface transition-colors',- expanded ? 'border-mint/40 shadow-[0_0_24px_-12px_rgba(91,255,160,0.6)]' : 'border-border hover:border-border-strong',- expanded && 'md:col-span-2'- )}- >- <button- type="button"- onClick={() => onToggleProvider(provider)}- className="flex w-full items-start justify-between gap-3 px-4 py-3 text-left"- >- <div className="flex flex-1 flex-col gap-1">- <div className="flex flex-wrap items-center gap-2">- <span className="text-[13px] font-semibold text-foreground">- {provider.name}- </span>- {renderProviderBadge(provider)}- {isDefault && (- <Badge variant="warning" className="gap-1">- <Star className="size-3" />- {t('settings.backends.opencodeDefaultBadge')}- </Badge>- )}- </div>- <span className="font-mono text-[11px] text-muted">- {provider.id} ·{' '}- {t('settings.backends.opencodeProviderModelsCount', {- count: provider.models.length,- })}- </span>- {provider.description && (- <span className="text-[12px] leading-relaxed text-muted">- {provider.description}- </span>- )}- </div>- {expanded ? (- <ChevronUp className="mt-0.5 size-4 shrink-0 text-muted" />- ) : (- <ChevronDown className="mt-0.5 size-4 shrink-0 text-muted" />- )}- </button>-- {expanded && (- <div className="flex flex-col gap-4 border-t border-border bg-background px-4 py-4">- <div className="flex flex-wrap items-center gap-2">- <Button- type="button"- variant="secondary"- size="xs"- onClick={closeProvider}- >- <X className="size-3.5" />- {t('settings.backends.opencodeProviderCollapse')}- </Button>- {provider.configured && (- <Button- type="button"- variant="outline"- size="xs"- onClick={() => void onRemoveProviderAuth(provider)}- disabled={edit.removing || edit.saving}- className="text-destructive"- >- {edit.removing ? (- <RefreshCw className="size-3.5 animate-spin" />- ) : (- <Trash2 className="size-3.5" />- )}- {/* Label reflects what's actually- about to be removed (OpenCode's- auth.json carries exactly one- entry per provider at a time —- ``api`` or ``oauth`` — so the- single DELETE drops whichever- is set; we just need to be- honest in the label). */}- {provider.active_auth_type === 'oauth'- ? t('settings.backends.opencodeProviderRemoveOauth')- : t('settings.backends.opencodeProviderRemove')}- </Button>- )}- {!provider.configured && !isDefault && provider.local && (- <span className="text-[11px] text-muted">- {t('settings.backends.opencodeProviderLocalHint')}- </span>- )}- </div>-- <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={provider.configured}- title={t('settings.backends.opencodeProviderOauthPanelTitle', {- name: provider.name,- })}- subtitle={t('settings.backends.opencodeProviderOauthPanelSubtitle')}- hideRemove- onSuccess={() => {- // 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>- {provider.configured && 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={- provider.configured- ? (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">- {provider.configured- ? t('settings.backends.opencodeProviderApiKeyStored')- : t('settings.backends.opencodeProviderApiKeyMissing')}- </p>- {provider.configured && edit.editingKey && (- <button- type="button"- className="text-[11px] text-muted underline-offset-2 transition hover:text-foreground hover:underline"- 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">- {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>- );- })()}-- {/* Per-provider connectivity probe.- Gated on ``configured`` because- testing an unconfigured provider- always fails with- ``invalid_credentials`` — adds- noise without signal. Each card- owns its own panel so users can- debug providers independently. */}- {provider.configured && (- <OpencodeProviderTestPanel- providerId={provider.id}- providerName={provider.name}- models={provider.models}- defaultModel={provider.default_model}- />- )}- </div>-- <div className="flex flex-col gap-2">- <Label className="text-[11px] font-medium uppercase text-muted">- {t('settings.backends.opencodeProviderModels')}- </Label>- <div className="max-h-56 overflow-y-auto rounded-md border border-border bg-surface px-3 py-2">- {provider.models.length === 0 ? (- <p className="text-[12px] text-muted">- {t('settings.backends.opencodeProviderModelsEmpty')}- </p>- ) : (- <ul className="flex flex-col gap-1">- {provider.models.map((model) => (- <li- key={model}- className="flex items-center gap-2 font-mono text-[12px] text-foreground"- >- <Cpu className="size-3 text-muted" />- <span className="truncate">{model}</span>- {provider.default_model === model && (- <Badge variant="success" className="ml-auto">- {t(- 'settings.backends.opencodeProviderDefaultModel'- )}- </Badge>- )}- </li>- ))}- </ul>- )}- </div>- </div>- </div>- </div>- )}- </div>- );- })}- </div>- )}-- <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.opencodeProvidersInfo')}- </p>- </div>- </>- )}- </CardContent>- </Card>- </div>- )}+ <OpencodeProviderConfig /></SettingsPageShell>);};diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsxindex aeb4fd7c4..aee4c9cc4 100644--- a/ui/src/components/settings/SettingsPlatformsPage.tsx+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx@@ -6,7 +6,14 @@ import { Check, ChevronUp, Loader2, Pencil, RefreshCw, RotateCw } from 'lucide-rimport { useApi } from '@/context/ApiContext';import { useStatus } from '@/context/StatusContext';import { useToast } from '@/context/ToastContext';-import { getEnabledPlatforms, getPlatformCatalog, getPrimaryPlatform, platformHasCredentials } from '@/lib/platforms';+import {+ WORKBENCH_PLATFORM_ID,+ getEnabledPlatforms,+ getImPlatforms,+ getPlatformCatalog,+ getPrimaryPlatform,+ platformHasCredentials,+} from '@/lib/platforms';import { PlatformIcon } from '@/components/visual';import { SlackConfig } from '@/components/steps/SlackConfig';import { DiscordConfig } from '@/components/steps/DiscordConfig';@@ -44,6 +51,13 @@ export const SettingsPlatformsPage: React.FC = () => {}, [api]);const platformCatalog = useMemo(() => (config ? getPlatformCatalog(config) : []), [config]);+ // The in-process workbench is always-on and cannot be toggled as an IM+ // transport, so it is excluded from the enable grid (mirroring the wizard).+ // The full catalog is kept for descriptor/title lookups elsewhere.+ const togglablePlatforms = useMemo(+ () => (config ? getImPlatforms(config) : []),+ [config]+ );const enabledPlatforms = useMemo(() => (config ? getEnabledPlatforms(config) : []), [config]);const primary = useMemo(() => (config ? getPrimaryPlatform(config) : ''), [config]);@@ -89,9 +103,11 @@ export const SettingsPlatformsPage: React.FC = () => {const toggleDraftPlatform = (id: string) => {setDraftEnabled((prev) => {if (prev.includes(id)) {+ // Allow clearing the last platform: an empty set is the supported+ // workbench-only state (Apply anchors primary to "avibe").const next = prev.filter((p) => p !== id);if (next.length && draftPrimary === id) setDraftPrimary(next[0]);- return next.length ? next : prev;+ return next;}const next = [...prev, id];if (!prev.length) setDraftPrimary(id);@@ -100,8 +116,15 @@ export const SettingsPlatformsPage: React.FC = () => {};const applyEnabled = async () => {- if (!draftEnabled.length) return;- const resolvedPrimary = draftEnabled.includes(draftPrimary) ? draftPrimary : draftEnabled[0];+ // An empty external-platform set is the supported workbench-only state:+ // the in-process Avibe Workbench is the sole inbound surface, so anchor+ // ``primary`` to "avibe" (mirroring the wizard/backend/controller, which+ // all anchor the primary to the workbench when no IM platform is enabled).+ // For a non-empty set, keep the user's primary if it survived the edit,+ // otherwise fall back to the first remaining platform.+ const resolvedPrimary = draftEnabled.length+ ? (draftEnabled.includes(draftPrimary) ? draftPrimary : draftEnabled[0])+ : WORKBENCH_PLATFORM_ID;const nextData = {...config,platform: resolvedPrimary,@@ -195,7 +218,7 @@ export const SettingsPlatformsPage: React.FC = () => {<p className="text-[12px] leading-relaxed text-muted">{t('platform.subtitle')}</p><div className="grid grid-cols-2 gap-2.5 md:grid-cols-3 lg:grid-cols-5">- {platformCatalog.map((platform) => {+ {togglablePlatforms.map((platform) => {const id = platform.id;const active = draftEnabled.includes(id);const tile = PLATFORM_TILE_STYLES[id] || { bg: 'bg-foreground/[0.04]', border: 'border-foreground/[0.10]' };@@ -248,7 +271,7 @@ export const SettingsPlatformsPage: React.FC = () => {variant="brand"size="xs"onClick={() => void applyEnabled()}- disabled={!draftEnabled.length || savingEnabled}+ disabled={savingEnabled}>{savingEnabled ? <RefreshCw size={12} className="animate-spin" /> : <Check size={12} />}{t('platform.apply')}diff --git a/ui/src/components/settings/providers/BackendProviderConfig.tsx b/ui/src/components/settings/providers/BackendProviderConfig.tsxnew file mode 100644index 000000000..87c8e34b3--- /dev/null+++ b/ui/src/components/settings/providers/BackendProviderConfig.tsx@@ -0,0 +1,31 @@+import type { BackendId } from '../shared/useBackendRuntime';+import { ClaudeProviderConfig } from './ClaudeProviderConfig';+import { CodexProviderConfig } from './CodexProviderConfig';+import { OpencodeProviderConfig } from './OpencodeProviderConfig';++/**+ * Dispatches to the backend-specific config body. The same component+ * tree is rendered by the settings route (wrapped in ``SettingsPageShell``)+ * and the setup wizard modal, so neither callsite copies the per-backend+ * logic.+ */+export function BackendProviderConfig({+ backend,+ hideEnableToggle,+ deferRestart,+}: {+ backend: BackendId;+ hideEnableToggle?: boolean;+ deferRestart?: boolean;+}) {+ switch (backend) {+ case 'claude':+ return <ClaudeProviderConfig hideEnableToggle={hideEnableToggle} deferRestart={deferRestart} />;+ case 'codex':+ return <CodexProviderConfig hideEnableToggle={hideEnableToggle} deferRestart={deferRestart} />;+ case 'opencode':+ return <OpencodeProviderConfig hideEnableToggle={hideEnableToggle} deferRestart={deferRestart} />;+ default:+ return null;+ }+}diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsxnew file mode 100644index 000000000..0971c7527--- /dev/null+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx@@ -0,0 +1,470 @@+import React, { useEffect, useMemo, useState } from '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 { SegmentedRadio } from '../shared/SegmentedRadio';+import { useBackendRuntime } from '../shared/useBackendRuntime';+import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';+import { useApi } from '@/context/ApiContext';+import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++const BACKEND_ID = 'claude';+const DEFAULT_CLI = 'claude';++export const ClaudeProviderConfig: React.FC<{+ hideEnableToggle?: boolean;+ deferRestart?: boolean;+}> = ({ hideEnableToggle, deferRestart } = {}) => {+ const { t } = useTranslation();+ const api = useApi();+ 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,+ deferRestart,+ });++ // 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 [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 [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 || '';+ setAuthMode(initialMode);+ setBaseUrl(initialBase);+ setSavedAuthMode(initialMode);+ 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 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 V2Config; leaves any OAuth tokens in+ // ``~/.claude/credentials.json`` (or the OS keychain) alone. Lets+ // the user clear a stale key without having to also re-do 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);+ setBaseUrl(fresh.base_url || '');+ setSavedBaseUrl(fresh.base_url || '');+ setApiKey('');+ setEditingKey(false);+ showToast(t('settings.backends.claudeApiKeyRemoved'), 'success');+ } catch (err: any) {+ showToast(+ t('settings.backends.claudeApiKeyRemoveFailed', { detail: err?.message || '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.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 || '';+ setAuthMode(nextMode);+ setBaseUrl(nextBase);+ setSavedAuthMode(nextMode);+ setSavedBaseUrl(nextBase);+ setApiKey('');+ setEditingKey(false);+ // Claude restart is synthetic (one-shot CLI) so result.restart.ok+ // is always true; treat any falsy state defensively just in case.+ if (result.restart?.ok === false) {+ showToast(result.restart.message || t('settings.backends.claudeSaveSuccess'), 'warning');+ } else {+ showToast(t('settings.backends.claudeSaveSuccess'), 'success');+ }+ } catch (err: any) {+ showToast(err?.message || 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"+ runtime={runtime}+ hideEnableToggle={hideEnableToggle}+ />++ {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.activeAuthApiKey')}+ </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}+ // ``has_oauth_credentials`` flips when ``~/.claude/credentials.json``+ // carries a usable token bundle — that's a real signal we can+ // trust on Linux/Docker. macOS keychain installs still report+ // false, but a successful in-session login flips the panel's+ // own state anyway.+ signedIn={!!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 htmlFor="claude-api-key" className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.claudeApiKeyLabel')}+ </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+ tokens in ``~/.claude/credentials.json`` /+ keychain 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 hover:bg-destructive/10 hover:text-destructive"+ >+ <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('settings.backends.claudeApiKeyPlaceholder') 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" />+ <div className="flex flex-col gap-1">+ <p className="text-[12px] font-medium text-gold">+ {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 ||+ 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>+ );+};diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsxnew file mode 100644index 000000000..3b07b3504--- /dev/null+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx@@ -0,0 +1,485 @@+import React, { useEffect, useMemo, useState } from 'react';+import { Bot, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save, Trash2 } 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 { SegmentedRadio } from '../shared/SegmentedRadio';+import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';+import { useBackendRuntime } from '../shared/useBackendRuntime';+import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';++const BACKEND_ID = 'codex';+const DEFAULT_CLI = 'codex';++export const CodexProviderConfig: React.FC<{+ hideEnableToggle?: boolean;+ deferRestart?: boolean;+}> = ({ hideEnableToggle, deferRestart } = {}) => {+ const { t } = useTranslation();+ const api = useApi();+ 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,+ deferRestart,+ });++ 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: any) {+ showToast(+ t('settings.backends.codexApiKeyRemoveFailed', { detail: err?.message || '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: any) {+ showToast(err?.message || 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}+ />++ <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">+ {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">+ {t('settings.backends.codexCredentialsStoreKeyringWarn', { store: state.credentials_store })}+ </p>+ )}+ </div>++ {authMode === 'oauth' && (+ <BackendOAuthPanel+ backend="codex"+ signedIn={!!state?.has_chatgpt_tokens}+ 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 hover:bg-destructive/10 hover:text-destructive"+ >+ <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>+ );+};diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsxnew file mode 100644index 000000000..c9e7d0b21--- /dev/null+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx@@ -0,0 +1,1174 @@+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ AlertCircle,+ Check,+ ChevronDown,+ ChevronUp,+ Cpu,+ Info,+ KeyRound,+ Pencil,+ RefreshCw,+ RotateCcw,+ Save,+ Search,+ Server,+ Settings,+ Star,+ Terminal,+ Trash2,+ X,+} from 'lucide-react';+import clsx from 'clsx';++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 { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';+import { BackendOAuthPanel } from '../BackendOAuthPanel';+import { OpencodeProviderTestPanel } from '../OpencodeProviderTestPanel';+import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';+import { useBackendRuntime } from '../shared/useBackendRuntime';+import { useApi } from '@/context/ApiContext';+import type { OpencodeProvider } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++type PermissionState = 'idle' | 'loading' | 'success' | 'error';+type FilterMode = 'all' | 'configured' | 'oauth' | 'local';++// Per-provider edit state — kept in a record so the page can render the+// grid statelessly and only allocate inputs for the expanded card.+type ProviderEditState = {+ apiKey: string;+ baseUrl: string;+ saving: boolean;+ removing: boolean;+ error: string | null;+ // Mirrors the Codex / Claude pattern: false = show ``api_key_masked``+ // read-only with a Replace button; true = empty editable input ready+ // for a fresh key. Toggled by the pencil button next to the masked+ // preview. Reset to false on successful save / remove / reload.+ editingKey: boolean;+};++const BACKEND_ID = 'opencode';+const DEFAULT_CLI = 'opencode';+// Server startup is asynchronous (OpenCode app spawn + port bind). Retry+// the introspection fan-out a handful of times before falling back to the+// "server not reachable" banner so the user can still configure values.+const SERVER_START_MAX_RETRIES = 5;+const SERVER_START_RETRY_DELAY_MS = 3000;++const FILTER_MODES: ReadonlyArray<FilterMode> = ['all', 'configured', 'oauth', 'local'];++const emptyEdit = (): ProviderEditState => ({+ apiKey: '',+ baseUrl: '',+ saving: false,+ removing: false,+ error: null,+ editingKey: false,+});++const providerMatchesFilter = (provider: OpencodeProvider, mode: FilterMode): boolean => {+ switch (mode) {+ case 'configured':+ return provider.configured;+ case 'oauth':+ return provider.oauth_available;+ case 'local':+ return provider.local;+ case 'all':+ default:+ return true;+ }+};++const providerMatchesSearch = (provider: OpencodeProvider, q: string): boolean => {+ if (!q) return true;+ const needle = q.toLowerCase();+ if (provider.id.toLowerCase().includes(needle)) return true;+ if (provider.name.toLowerCase().includes(needle)) return true;+ if (provider.description.toLowerCase().includes(needle)) return true;+ return provider.models.some((m) => m.toLowerCase().includes(needle));+};++export const OpencodeProviderConfig: React.FC<{+ hideEnableToggle?: boolean;+ deferRestart?: boolean;+}> = ({ hideEnableToggle, deferRestart } = {}) => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();++ // Runtime state — shared with Claude / Codex pages via the hook.+ const runtime = useBackendRuntime({+ backend: BACKEND_ID,+ defaultCli: DEFAULT_CLI,+ fallbackDefaultBackend: BACKEND_ID,+ deferRestart,+ });+ const [permissionState, setPermissionState] = useState<PermissionState>('idle');+ const [permissionMessage, setPermissionMessage] = useState('');++ // Provider catalog state.+ const [providers, setProviders] = useState<OpencodeProvider[] | null>(null);+ const [defaultProvider, setDefaultProvider] = useState<string | null>(null);+ const [providersLoading, setProvidersLoading] = useState(false);+ const [providersError, setProvidersError] = useState<string | null>(null);+ const [serverStartAttempts, setServerStartAttempts] = useState(0);+ // ``true`` when opencode.json carries ``permission: "allow"`` — the+ // Settings page suppresses the "Allow tool calls" affordance once+ // this is the case (page feedback: a permanent "Setup permission"+ // button is misleading once permission is already set).+ const [permissionAllowed, setPermissionAllowed] = useState(false);++ // Toolbar state.+ const [searchQuery, setSearchQuery] = useState('');+ const [filterMode, setFilterMode] = useState<FilterMode>('all');++ // Inline-expansion state — only one card open at a time.+ const [expandedId, setExpandedId] = useState<string | null>(null);+ const [editByProvider, setEditByProvider] = useState<Record<string, ProviderEditState>>({});++ // Default-provider popover state.+ const [defaultPopoverOpen, setDefaultPopoverOpen] = useState(false);+ const [defaultSearchQuery, setDefaultSearchQuery] = useState('');+ const [settingDefault, setSettingDefault] = useState(false);++ // Server-start retry timer cleanup.+ const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // useEffect closure captures the initial loadProviders; ref lets the+ // retry timer call the latest implementation without re-arming on every+ // state update.+ const loadProvidersRef = useRef<(() => Promise<void>) | null>(null);++ const loadProviders = useCallback(async () => {+ setProvidersLoading(true);+ setProvidersError(null);+ try {+ const result = await api.getOpencodeProviders();+ if (result.ok && result.providers) {+ setProviders(result.providers);+ setDefaultProvider(result.default_provider || null);+ setPermissionAllowed(result.permission_allowed === true);+ setServerStartAttempts(0);+ setProvidersError(null);+ } else {+ setProviders((prev) => prev ?? []);+ setProvidersError(result.message || t('settings.backends.opencodeProvidersError'));+ }+ } catch (e: any) {+ setProviders((prev) => prev ?? []);+ setProvidersError(e?.message || t('settings.backends.opencodeProvidersError'));+ } finally {+ setProvidersLoading(false);+ }+ }, [api, t]);++ useEffect(() => {+ loadProvidersRef.current = loadProviders;+ }, [loadProviders]);++ // Runtime initial-load + cli_path/detect/install/save/toggle live in+ // ``useBackendRuntime``. This page-specific effect just drives the+ // providers fan-out: load when the runtime is enabled, clear when+ // it's not. Triggered whenever the optimistic enabled flag changes+ // (matches the original "toggle then reload" UX exactly).+ useEffect(() => {+ if (!runtime.loaded) return;+ // If the initial getConfig() failed, ``runtime.enabled`` is still+ // the pre-load default rather than persisted state. Don't trigger+ // provider fetches in that case — the toast in the runtime hook+ // already informed the user; firing requests now would just emit+ // misleading "server stopped" errors.+ if (runtime.configError) return;+ if (runtime.enabled) {+ setServerStartAttempts(0);+ void loadProviders();+ } else {+ setProviders(null);+ setProvidersError(null);+ }+ return () => {+ if (retryTimerRef.current) clearTimeout(retryTimerRef.current);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [runtime.enabled, runtime.loaded, runtime.configError]);++ // Auto-retry server-start failures — common when the user has just+ // enabled the backend. After SERVER_START_MAX_RETRIES the user can hit+ // Refresh manually; we stop the implicit retry to avoid background+ // request loops.+ useEffect(() => {+ if (retryTimerRef.current) {+ clearTimeout(retryTimerRef.current);+ retryTimerRef.current = null;+ }+ if (!runtime.enabled) return;+ if (!providersError) return;+ if (providersLoading) return;+ if (serverStartAttempts >= SERVER_START_MAX_RETRIES) return;+ retryTimerRef.current = setTimeout(() => {+ setServerStartAttempts((n) => n + 1);+ void loadProvidersRef.current?.();+ }, SERVER_START_RETRY_DELAY_MS);+ return () => {+ if (retryTimerRef.current) {+ clearTimeout(retryTimerRef.current);+ retryTimerRef.current = null;+ }+ };+ }, [runtime.enabled, providersError, providersLoading, serverStartAttempts]);++ const setupPermission = async () => {+ setPermissionState('loading');+ setPermissionMessage('');+ try {+ const result = await api.opencodeSetupPermission();+ setPermissionState(result.ok ? 'success' : 'error');+ setPermissionMessage(result.message);+ showToast(result.message, result.ok ? 'success' : 'error');+ if (result.ok) {+ // Flip locally so the affordance vanishes immediately rather+ // than waiting for the next provider refresh tick — the next+ // ``loadProviders`` will recompute the value from disk anyway.+ setPermissionAllowed(true);+ }+ } catch (e: any) {+ setPermissionState('error');+ const msg = e?.message || String(e);+ setPermissionMessage(msg);+ showToast(msg, 'error');+ }+ };++ // ``onSaveRuntime`` and ``toggleEnabled`` are owned by+ // ``useBackendRuntime``; the providers reload/clear side-effect+ // that used to live inside the page's toggle handler is now driven+ // by the ``useEffect([runtime.enabled, runtime.loaded])`` above.++ // ---- Expansion / per-provider editing ----++ const openProvider = (provider: OpencodeProvider) => {+ setExpandedId(provider.id);+ setEditByProvider((prev) => {+ if (prev[provider.id]) return prev;+ // Pre-populate baseUrl from the persisted opencode.json override so+ // the input round-trips: open card → see existing value → edit →+ // save. Leaving it blank on every open would let a re-save wipe the+ // value because the form is the only baseURL signal we forward.+ const seeded = emptyEdit();+ if (provider.base_url) {+ seeded.baseUrl = provider.base_url;+ }+ return { ...prev, [provider.id]: seeded };+ });+ };++ const closeProvider = () => {+ // Wipe the in-memory plaintext key/base-url for the closing card so+ // collapsing acts as a panic-revert: defense-in-depth in case the+ // user typed a key but did not save it.+ if (expandedId) {+ setEditByProvider((prev) => {+ if (!prev[expandedId]) return prev;+ return { ...prev, [expandedId]: emptyEdit() };+ });+ }+ setExpandedId(null);+ };++ const onToggleProvider = (provider: OpencodeProvider) => {+ if (expandedId === provider.id) {+ closeProvider();+ } else {+ openProvider(provider);+ }+ };++ const updateEdit = (providerId: string, patch: Partial<ProviderEditState>) => {+ setEditByProvider((prev) => ({+ ...prev,+ [providerId]: { ...(prev[providerId] || emptyEdit()), ...patch },+ }));+ };++ 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();+ 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');+ await loadProviders();+ } catch (e: any) {+ updateEdit(provider.id, {+ saving: false,+ error: e?.message || (t('settings.backends.opencodeProviderSaveFailed') as string),+ });+ }+ };++ const onRemoveProviderAuth = async (provider: OpencodeProvider) => {+ // Confirm copy matches what's actually about to be removed.+ const confirmKey =+ provider.active_auth_type === 'oauth'+ ? 'settings.backends.opencodeProviderRemoveOauthConfirm'+ : 'settings.backends.opencodeProviderRemoveConfirm';+ const confirmed = window.confirm(+ t(confirmKey, { name: provider.name }) as string,+ );+ if (!confirmed) return;+ updateEdit(provider.id, { removing: true, error: null });+ try {+ const result = await api.deleteOpencodeProviderAuth(provider.id);+ if (!result.ok) {+ updateEdit(provider.id, {+ removing: false,+ error: result.message || (t('settings.backends.opencodeProviderRemoveFailed') as string),+ });+ return;+ }+ updateEdit(provider.id, { removing: false, error: null });+ showToast(t('settings.backends.opencodeProviderRemoved'), 'success');+ await loadProviders();+ } catch (e: any) {+ updateEdit(provider.id, {+ removing: false,+ error: e?.message || (t('settings.backends.opencodeProviderRemoveFailed') as string),+ });+ }+ };++ // ---- Default-provider selection ----++ const pickDefaultProvider = async (provider: OpencodeProvider) => {+ if (!provider.configured) {+ // Surfacing "set the key first" is more discoverable than silently+ // ignoring the click — expand the card and let the user fill it in.+ setDefaultPopoverOpen(false);+ setDefaultSearchQuery('');+ openProvider(provider);+ showToast(+ t('settings.backends.opencodeDefaultNeedsKey', { name: provider.name }),+ 'warning'+ );+ return;+ }+ if (provider.id === defaultProvider) {+ setDefaultPopoverOpen(false);+ setDefaultSearchQuery('');+ return;+ }+ setSettingDefault(true);+ try {+ const result = await api.setOpencodeDefaultProvider(provider.id);+ if (!result.ok) {+ showToast(+ result.message || (t('settings.backends.opencodeDefaultSaveFailed') as string),+ 'error'+ );+ return;+ }+ setDefaultProvider(result.default_provider || provider.id);+ showToast(t('settings.backends.opencodeDefaultSaved', { name: provider.name }), 'success');+ setDefaultPopoverOpen(false);+ setDefaultSearchQuery('');+ } catch (e: any) {+ showToast(e?.message || (t('settings.backends.opencodeDefaultSaveFailed') as string), 'error');+ } finally {+ setSettingDefault(false);+ }+ };++ // ---- Derived collections ----++ const visibleProviders = useMemo(() => {+ if (!providers) return [];+ return providers.filter(+ (p) => providerMatchesFilter(p, filterMode) && providerMatchesSearch(p, searchQuery)+ );+ }, [providers, filterMode, searchQuery]);++ const popoverProviders = useMemo(() => {+ if (!providers) return [];+ return providers.filter((p) => providerMatchesSearch(p, defaultSearchQuery));+ }, [providers, defaultSearchQuery]);++ const configuredCount = providers?.filter((p) => p.configured).length || 0;+ const totalCount = providers?.length || 0;+ const defaultProviderObj = useMemo(+ () => providers?.find((p) => p.id === defaultProvider) || null,+ [providers, defaultProvider]+ );++ const filterLabel = (mode: FilterMode) => {+ switch (mode) {+ case 'all':+ return t('settings.backends.opencodeFilterAll');+ case 'configured':+ return t('settings.backends.opencodeFilterConfigured');+ case 'oauth':+ return t('settings.backends.opencodeFilterOauth');+ case 'local':+ return t('settings.backends.opencodeFilterLocal');+ }+ };++ // ---- Status badge selection ----+ //+ // The order here matches the plan doc: configured wins, then OAuth+ // availability, then local, finally "not set" for unconfigured cloud+ // providers. Multi-flag providers therefore surface the most useful+ // signal first.+ const renderProviderBadge = (provider: OpencodeProvider) => {+ if (provider.configured) {+ // Show *which* auth source is live so the user can distinguish+ // OAuth-signed-in from API-key-saved without expanding the card.+ // Dual-mode providers (openai supports both) carry only one entry+ // in auth.json at a time, so this matches what OpenCode uses.+ const activeLabel =+ provider.active_auth_type === 'oauth'+ ? t('settings.backends.opencodeBadgeConfiguredOauth')+ : provider.active_auth_type === 'api'+ ? t('settings.backends.opencodeBadgeConfiguredApiKey')+ : t('settings.backends.opencodeBadgeConfigured');+ return (+ <Badge variant="success" className="gap-1">+ <Check className="size-3" />+ {activeLabel}+ </Badge>+ );+ }+ if (provider.oauth_available) {+ return (+ <Badge variant="info">{t('settings.backends.opencodeBadgeOauth')}</Badge>+ );+ }+ if (provider.local) {+ return (+ <Badge variant="secondary">{t('settings.backends.opencodeBadgeLocal')}</Badge>+ );+ }+ return <Badge variant="outline">{t('settings.backends.opencodeBadgeUnset')}</Badge>;+ };++ // ---- Render ----++ 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="OpenCode"+ description={t('settings.backends.opencodeDescription')}+ Icon={Terminal}+ iconTileClassName="bg-violet-soft"+ iconClassName="text-violet"+ runtime={runtime}+ hideEnableToggle={hideEnableToggle}+ extraSlot={+ // ``permission: "allow"`` setup is OpenCode-specific: without+ // it the daemon prompts on every tool call and Vibe Remote+ // can't reply. Hidden once opencode.json carries the value.+ runtime.cliStatus === 'ok' && !permissionAllowed ? (+ <div className="rounded-lg border border-gold/30 bg-gold/10 px-3 py-2.5">+ <p className="mb-2 text-[12px] text-gold">+ {t('agentDetection.permissionHintStrong')}+ </p>+ <div className="flex flex-wrap items-center gap-3">+ <Button+ variant="brand-gold"+ size="xs"+ onClick={() => void setupPermission()}+ disabled={permissionState === 'loading'}+ >+ {permissionState === 'loading' ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Settings className="size-3.5" />+ )}+ {t('agentDetection.setupPermission')}+ </Button>+ {permissionState === 'success' && (+ <span className="text-[12px] text-mint">{permissionMessage}</span>+ )}+ {permissionState === 'error' && (+ <span className="text-[12px] text-destructive">{permissionMessage}</span>+ )}+ </div>+ </div>+ ) : null+ }+ />++ {/* Card 2 — provider catalog. */}+ <Card>+ <CardContent className="flex flex-col gap-5 p-6">+ <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">+ <div className="flex items-center gap-3">+ <div className="flex size-11 shrink-0 items-center justify-center rounded-[10px] bg-cyan-soft">+ <Server size={22} className="text-cyan" />+ </div>+ <div className="flex flex-col gap-0.5">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[15px] font-semibold text-foreground">+ {t('settings.backends.opencodeProvidersTitle')}+ </span>+ {runtime.enabled && providers && (+ <Badge variant={providersError ? 'warning' : 'success'}>+ {providersError+ ? t('settings.backends.opencodeServerStopped')+ : t('settings.backends.opencodeServerRunning')}+ </Badge>+ )}+ {!runtime.enabled && (+ <Badge variant="secondary">+ {t('settings.backends.opencodeBackendDisabled')}+ </Badge>+ )}+ {runtime.enabled && providers && providers.length > 0 && (+ <Badge variant="outline">+ {t('settings.backends.opencodeProvidersCount', {+ configured: configuredCount,+ total: totalCount,+ })}+ </Badge>+ )}+ </div>+ <span className="text-[12px] text-muted">+ {t('settings.backends.opencodeProvidersSubtitle')}+ </span>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => {+ setServerStartAttempts(0);+ void loadProviders();+ }}+ disabled={!runtime.enabled || providersLoading}+ >+ <RefreshCw+ className={clsx('size-3.5', providersLoading && 'animate-spin')}+ />+ {t('settings.backends.opencodeRefresh')}+ </Button>+ </div>+ </div>++ {!runtime.enabled && (+ <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-2.5 text-[12px] text-muted">+ {t('settings.backends.opencodeDisabledBanner')}+ </div>+ )}++ {runtime.enabled && (+ <>+ {/* Toolbar — search + filter chips + default-provider pill. */}+ <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">+ <div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-center">+ <div className="relative w-full sm:max-w-xs">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted" />+ <Input+ type="text"+ placeholder={t('settings.backends.opencodeSearchPlaceholder') as string}+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="h-9 pl-8 text-[12px]"+ autoComplete="off"+ spellCheck={false}+ />+ </div>+ <div className="flex flex-wrap items-center gap-1.5">+ {FILTER_MODES.map((mode) => {+ const active = filterMode === mode;+ return (+ <button+ key={mode}+ type="button"+ onClick={() => setFilterMode(mode)}+ className={clsx(+ 'rounded-full border px-3 py-1 text-[11px] font-semibold transition-colors',+ active+ ? 'border-mint/40 bg-mint-soft text-mint'+ : 'border-border bg-surface text-muted hover:text-foreground'+ )}+ >+ {filterLabel(mode)}+ </button>+ );+ })}+ </div>+ </div>++ {/* Default-provider pill. */}+ <Popover+ open={defaultPopoverOpen}+ onOpenChange={(open) => {+ setDefaultPopoverOpen(open);+ if (!open) setDefaultSearchQuery('');+ }}+ >+ <PopoverTrigger asChild>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={!providers || providers.length === 0}+ className="justify-between gap-2 text-[12px]"+ >+ <Star className="size-3.5 text-mint" />+ <span className="text-muted">+ {t('settings.backends.opencodeDefaultLabel')}:+ </span>+ <span className="font-mono text-[12px] text-foreground">+ {defaultProviderObj+ ? defaultProviderObj.name+ : defaultProvider+ ? defaultProvider+ : t('settings.backends.opencodeDefaultUnset')}+ </span>+ <ChevronDown className="size-3.5 text-muted" />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-80 p-0">+ <div className="flex flex-col gap-2 p-3">+ <Label className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.opencodeDefaultPopoverTitle')}+ </Label>+ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted" />+ <Input+ type="text"+ placeholder={+ t('settings.backends.opencodeSearchPlaceholder') as string+ }+ value={defaultSearchQuery}+ onChange={(e) => setDefaultSearchQuery(e.target.value)}+ className="h-8 pl-8 text-[12px]"+ autoComplete="off"+ spellCheck={false}+ />+ </div>+ </div>+ <div className="max-h-72 overflow-y-auto border-t border-border">+ {popoverProviders.length === 0 ? (+ <div className="px-3 py-2 text-[12px] text-muted">+ {t('settings.backends.opencodeDefaultPopoverEmpty')}+ </div>+ ) : (+ <ul className="flex flex-col">+ {popoverProviders.map((provider) => {+ const isCurrent = provider.id === defaultProvider;+ return (+ <li key={provider.id}>+ <button+ type="button"+ onClick={() => void pickDefaultProvider(provider)}+ disabled={settingDefault}+ className={clsx(+ 'flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-[12px] transition-colors',+ 'hover:bg-surface-2',+ isCurrent && 'bg-mint-soft/40'+ )}+ >+ <span className="flex flex-col gap-0.5">+ <span className="font-medium text-foreground">+ {provider.name}+ </span>+ <span className="font-mono text-[11px] text-muted">+ {provider.id}+ </span>+ </span>+ <span className="flex items-center gap-2">+ {provider.configured ? (+ <Badge variant="success" className="gap-1">+ <Check className="size-3" />+ {t('settings.backends.opencodeBadgeConfigured')}+ </Badge>+ ) : provider.oauth_available ? (+ <Badge variant="info">+ {t('settings.backends.opencodeBadgeOauth')}+ </Badge>+ ) : provider.local ? (+ <Badge variant="secondary">+ {t('settings.backends.opencodeBadgeLocal')}+ </Badge>+ ) : (+ <Badge variant="outline">+ {t('settings.backends.opencodeBadgeUnset')}+ </Badge>+ )}+ {isCurrent && <Check className="size-3.5 text-mint" />}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </PopoverContent>+ </Popover>+ </div>++ {/* Server-starting / error banner. */}+ {providersError && (+ <div className="flex items-start gap-2 rounded-lg border border-gold/30 bg-gold/[0.08] px-3 py-2.5">+ <AlertCircle className="mt-0.5 size-3.5 shrink-0 text-gold" />+ <div className="flex flex-1 flex-col gap-1">+ <p className="text-[12px] font-medium text-gold">+ {serverStartAttempts < SERVER_START_MAX_RETRIES+ ? t('settings.backends.opencodeServerStarting')+ : t('settings.backends.opencodeServerUnreachable')}+ </p>+ <p className="text-[12px] leading-relaxed text-muted">{providersError}</p>+ </div>+ {serverStartAttempts < SERVER_START_MAX_RETRIES && (+ <span className="shrink-0 text-[11px] text-muted">+ {t('settings.backends.opencodeServerRetryCount', {+ attempt: serverStartAttempts + 1,+ max: SERVER_START_MAX_RETRIES,+ })}+ </span>+ )}+ </div>+ )}++ {/* Initial loading skeleton. */}+ {providersLoading && !providers && (+ <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-6 text-center text-[12px] text-muted">+ <RefreshCw className="mx-auto mb-2 size-4 animate-spin text-cyan" />+ {t('settings.backends.opencodeProvidersLoading')}+ </div>+ )}++ {/* Empty state — server reports no providers at all. */}+ {!providersLoading && providers && providers.length === 0 && !providersError && (+ <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-6 text-center text-[12px] text-muted">+ {t('settings.backends.opencodeProvidersEmpty')}+ </div>+ )}++ {/* Empty state — search/filter excluded everything. */}+ {!providersLoading &&+ providers &&+ providers.length > 0 &&+ visibleProviders.length === 0 && (+ <div className="rounded-lg border border-border bg-surface-2/60 px-3 py-6 text-center text-[12px] text-muted">+ {t('settings.backends.opencodeProvidersFilterEmpty')}+ </div>+ )}++ {/* Grid. */}+ {visibleProviders.length > 0 && (+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">+ {visibleProviders.map((provider) => {+ const expanded = expandedId === provider.id;+ const edit = editByProvider[provider.id] || emptyEdit();+ const isDefault = defaultProvider === provider.id;+ return (+ <div+ key={provider.id}+ className={clsx(+ 'flex flex-col rounded-lg border bg-surface transition-colors',+ expanded ? 'border-mint/40 shadow-[0_0_24px_-12px_rgba(91,255,160,0.6)]' : 'border-border hover:border-border-strong',+ expanded && 'md:col-span-2'+ )}+ >+ <button+ type="button"+ onClick={() => onToggleProvider(provider)}+ className="flex w-full items-start justify-between gap-3 px-4 py-3 text-left"+ >+ <div className="flex flex-1 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[13px] font-semibold text-foreground">+ {provider.name}+ </span>+ {renderProviderBadge(provider)}+ {isDefault && (+ <Badge variant="warning" className="gap-1">+ <Star className="size-3" />+ {t('settings.backends.opencodeDefaultBadge')}+ </Badge>+ )}+ </div>+ <span className="font-mono text-[11px] text-muted">+ {provider.id} ·{' '}+ {t('settings.backends.opencodeProviderModelsCount', {+ count: provider.models.length,+ })}+ </span>+ {provider.description && (+ <span className="text-[12px] leading-relaxed text-muted">+ {provider.description}+ </span>+ )}+ </div>+ {expanded ? (+ <ChevronUp className="mt-0.5 size-4 shrink-0 text-muted" />+ ) : (+ <ChevronDown className="mt-0.5 size-4 shrink-0 text-muted" />+ )}+ </button>++ {expanded && (+ <div className="flex flex-col gap-4 border-t border-border bg-background px-4 py-4">+ <div className="flex flex-wrap items-center gap-2">+ <Button+ type="button"+ variant="secondary"+ size="xs"+ onClick={closeProvider}+ >+ <X className="size-3.5" />+ {t('settings.backends.opencodeProviderCollapse')}+ </Button>+ {provider.configured && (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => void onRemoveProviderAuth(provider)}+ disabled={edit.removing || edit.saving}+ className="text-destructive"+ >+ {edit.removing ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Trash2 className="size-3.5" />+ )}+ {/* Label reflects what's actually+ about to be removed (OpenCode's+ auth.json carries exactly one+ entry per provider at a time —+ ``api`` or ``oauth`` — so the+ single DELETE drops whichever+ is set; we just need to be+ honest in the label). */}+ {provider.active_auth_type === 'oauth'+ ? t('settings.backends.opencodeProviderRemoveOauth')+ : t('settings.backends.opencodeProviderRemove')}+ </Button>+ )}+ {!provider.configured && !isDefault && provider.local && (+ <span className="text-[11px] text-muted">+ {t('settings.backends.opencodeProviderLocalHint')}+ </span>+ )}+ </div>++ <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={provider.configured}+ title={t('settings.backends.opencodeProviderOauthPanelTitle', {+ name: provider.name,+ })}+ subtitle={t('settings.backends.opencodeProviderOauthPanelSubtitle')}+ hideRemove+ onSuccess={() => {+ // 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>+ {provider.configured && 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={+ provider.configured+ ? (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">+ {provider.configured+ ? t('settings.backends.opencodeProviderApiKeyStored')+ : t('settings.backends.opencodeProviderApiKeyMissing')}+ </p>+ {provider.configured && edit.editingKey && (+ <button+ type="button"+ className="text-[11px] text-muted underline-offset-2 transition hover:text-foreground hover:underline"+ 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">+ {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>+ );+ })()}++ {/* Per-provider connectivity probe.+ Gated on ``configured`` because+ testing an unconfigured provider+ always fails with+ ``invalid_credentials`` — adds+ noise without signal. Each card+ owns its own panel so users can+ debug providers independently. */}+ {provider.configured && (+ <OpencodeProviderTestPanel+ providerId={provider.id}+ providerName={provider.name}+ models={provider.models}+ defaultModel={provider.default_model}+ />+ )}+ </div>++ <div className="flex flex-col gap-2">+ <Label className="text-[11px] font-medium uppercase text-muted">+ {t('settings.backends.opencodeProviderModels')}+ </Label>+ <div className="max-h-56 overflow-y-auto rounded-md border border-border bg-surface px-3 py-2">+ {provider.models.length === 0 ? (+ <p className="text-[12px] text-muted">+ {t('settings.backends.opencodeProviderModelsEmpty')}+ </p>+ ) : (+ <ul className="flex flex-col gap-1">+ {provider.models.map((model) => (+ <li+ key={model}+ className="flex items-center gap-2 font-mono text-[12px] text-foreground"+ >+ <Cpu className="size-3 text-muted" />+ <span className="truncate">{model}</span>+ {provider.default_model === model && (+ <Badge variant="success" className="ml-auto">+ {t(+ 'settings.backends.opencodeProviderDefaultModel'+ )}+ </Badge>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}++ <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.opencodeProvidersInfo')}+ </p>+ </div>+ </>+ )}+ </CardContent>+ </Card>+ </div>+ );+};diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsxindex e7dffe562..3bb1c15a1 100644--- a/ui/src/components/settings/shared/BackendRuntimeCard.tsx+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx@@ -45,6 +45,15 @@ export interface BackendRuntimeCardProps {* Claude / Codex don't supply one.*/extraSlot?: React.ReactNode;+ /**+ * Hide the enable ``ToggleSwitch`` in the header. Used by the setup+ * wizard, where each backend card already owns a separate enable+ * toggle (local wizard state) and the embedded provider config must+ * not render a second, immediately-persisting control that diverges+ * from it. Defaults to ``false`` so the settings route keeps the+ * toggle exactly as before.+ */+ hideEnableToggle?: boolean;}/**@@ -69,6 +78,7 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({iconClassName,runtime,extraSlot,+ hideEnableToggle,}) => {const { t } = useTranslation();const inputId = `${backend}-cli-path`;@@ -98,7 +108,9 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({cliStatus={runtime.cliStatus}onChanged={runtime.handleLifecycleChanged}/>- <ToggleSwitch enabled={runtime.enabled} onClick={runtime.toggleEnabled} />+ {!hideEnableToggle && (+ <ToggleSwitch enabled={runtime.enabled} onClick={runtime.toggleEnabled} />+ )}</div></div>diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.tsindex c691bb63a..b07eafe4a 100644--- a/ui/src/components/settings/shared/useBackendRuntime.ts+++ b/ui/src/components/settings/shared/useBackendRuntime.ts@@ -25,6 +25,16 @@ export interface UseBackendRuntimeOptions {* backend`` so toggling enabled-state never wipes the global default.*/fallbackDefaultBackend?: BackendId;+ /**+ * Skip the controller restart in ``onSaveRuntime`` and treat the save as+ * successful once the config write lands. Used by the setup wizard, where+ * the controller is not necessarily running yet — there, attempting a+ * restart and treating "not acknowledged" as a failure would surface a+ * spurious failed/dirty save even though the cli_path write succeeded. The+ * settings route leaves this unset so saving a CLI path still restarts the+ * backend exactly as before.+ */+ deferRestart?: boolean;}export interface BackendRuntimeState {@@ -80,6 +90,7 @@ export function useBackendRuntime({backend,defaultCli,fallbackDefaultBackend = 'opencode',+ deferRestart = false,}: UseBackendRuntimeOptions): BackendRuntimeState {const api = useApi();const { showToast } = useToast();@@ -193,9 +204,16 @@ export function useBackendRuntime({config?.agents?.default_backend ||fallbackDefaultBackend;await api.saveConfig({ agents: { ...nextAgents, default_backend: defaultBackend } });- const restart = await api.restartBackend(backend);- if (!restart?.ok) {- throw new Error(restart?.message || t('common.saveFailed'));+ // In the wizard the controller may not be running yet, so a restart+ // would (correctly) go un-acknowledged. Treat the config write as the+ // success boundary there and skip the restart — the controller picks up+ // the new cli_path when it next starts. The settings route keeps the+ // restart so an edit to a live backend takes effect immediately.+ if (!deferRestart) {+ const restart = await api.restartBackend(backend);+ if (!restart?.ok) {+ throw new Error(restart?.message || t('common.saveFailed'));+ }}setSavedCliPath(cliPath);showToast(t('common.saved'), 'success');@@ -204,7 +222,7 @@ export function useBackendRuntime({} finally {setSavingRuntime(false);}- }, [api, backend, cliPath, defaultCli, enabled, fallbackDefaultBackend, showToast, t]);+ }, [api, backend, cliPath, defaultCli, deferRestart, enabled, fallbackDefaultBackend, showToast, t]);const toggleEnabled = useCallback(() => {const next = !enabled;diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex 8d362c211..6da49744b 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState } from 'react';+import React, { useEffect, useRef, useState } from 'react';import {ArrowLeft,ArrowRight,@@ -7,8 +7,8 @@ import {Download,ExternalLink,RefreshCw,- Search,Settings,+ Sliders,} from 'lucide-react';import { Link } from 'react-router-dom';import { useTranslation } from 'react-i18next';@@ -17,9 +17,12 @@ import { useApi } from '../../context/ApiContext';import { BackendIcon, EyebrowBadge, WizardCard } from '../visual';import type { BackendId } from '../visual';import { BackendLifecycleChip } from '../settings/BackendLifecycleChip';-import { CompactField, CompactSelect, ToggleSwitch } from '../settings/SettingsPrimitives';+import { ToggleSwitch } from '../settings/SettingsPrimitives';+import { BackendProviderConfig } from '../settings/providers/BackendProviderConfig';+import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';import { Button } from '../ui/button';-import { AGENT_BACKENDS, DEFAULT_AGENT_STATE, DEFAULT_BACKEND_ID, getBackendUiMeta } from '@/lib/agentBackends';+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';+import { DEFAULT_AGENT_STATE, DEFAULT_BACKEND_ID, getBackendUiMeta } from '@/lib/agentBackends';interface AgentDetectionProps {data: any;@@ -39,6 +42,11 @@ type PermissionState = 'idle' | 'loading' | 'success' | 'error';const DEFAULT_AGENTS = DEFAULT_AGENT_STATE as Record<string, AgentState>;+// Backends with a dedicated provider config body (rendered in the wizard+// modal / the settings route). Mirrors ``BackendProviderConfig``'s switch —+// anything outside this set has no provider UI to configure.+const PROVIDER_BACKENDS: ReadonlySet<string> = new Set(['claude', 'codex', 'opencode']);+const normalizeAgents = (source: any): Record<string, AgentState> => {const raw = source?.agents || {};return Object.fromEntries(@@ -57,13 +65,17 @@ const normalizeAgents = (source: any): Record<string, AgentState> => {};// Mirrors design.pen JHgjz (Backends wizard step) and qVHh4 (Settings → Backends).-// 920-wide WizardCard, mint eyebrow, compact backend cards with header (icon, label,-// status pill, switch) and body (CLI path + detect, optional permission/install row).+// Each backend renders as a two-row card: a header row (icon, label, one-line+// 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 }) => {const { t } = useTranslation();const api = useApi();- const [checking, setChecking] = useState(false);- const [defaultBackend, setDefaultBackend] = useState<string>(+ // Persisted routing default. The selector UI was removed, but the value is+ // still threaded through ``handlePrimaryAction``'s payload so toggling+ // backends never wipes the saved ``agents.default_backend``.+ const [defaultBackend] = useState<string>(data.default_backend || data.agents?.default_backend || DEFAULT_BACKEND_ID);const [agents, setAgents] = useState<Record<string, AgentState>>(normalizeAgents(data));@@ -74,6 +86,12 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onRecord<string, { ok: boolean; message: string; output?: string | null }>>({});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);+ // True while a provider-modal close is reloading config into ``agents``; the+ // promise lets handlePrimaryAction wait for and fold in that reload.+ const [syncing, setSyncing] = useState(false);+ const syncRef = useRef<Promise<Record<string, AgentState> | null> | null>(null);const isMissing = (agent: AgentState) => agent.status === 'missing';const isAnyInstalling = Object.values(installingAgents).some(Boolean);@@ -84,26 +102,64 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on}, []);const detect = async (name: string, binary?: string) => {- setChecking(true);- try {- const result = await api.detectCli(binary || name);- setAgents((prev) => ({- ...prev,- [name]: {- ...prev[name],- cli_path: result.path || prev[name].cli_path,- status: result.found ? 'ok' : 'missing',- },- }));- } finally {- setChecking(false);- }+ const result = await api.detectCli(binary || name);+ setAgents((prev) => ({+ ...prev,+ [name]: {+ ...prev[name],+ cli_path: result.path || prev[name].cli_path,+ status: result.found ? 'ok' : 'missing',+ },+ }));};const detectAll = async () => {await Promise.all(Object.entries(agents).map(([name, agent]) => detect(name, agent.cli_path)));};+ // Re-read persisted config after the provider modal closes so runtime edits+ // made inside it (enabled / cli_path via useBackendRuntime) flow back into the+ // wizard's local ``agents`` state — otherwise handlePrimaryAction would save a+ // stale snapshot and clobber them. Then re-detect to refresh the status pill.+ const syncBackendFromConfig = async (name: string): Promise<Record<string, AgentState> | null> => {+ setSyncing(true);+ let cliPath = agents[name]?.cli_path;+ let synced: Record<string, AgentState> | null = null;+ try {+ const config = await api.getConfig();+ const saved = config?.agents?.[name];+ if (saved) {+ if (typeof saved.cli_path === 'string' && saved.cli_path) {+ cliPath = saved.cli_path;+ }+ // Spread the full persisted backend so provider-level fields the modal+ // may have changed (e.g. opencode default_provider / default_model) are+ // refreshed too — not just enabled / cli_path.+ const merged: AgentState = {+ ...agents[name],+ ...saved,+ cli_path: cliPath || agents[name].cli_path,+ };+ // ``enabled`` is owned by the live card toggle, never this async sync's+ // snapshot: closing the provider modal kicks off this sync, but the user+ // may flip the toggle before it resolves. Apply the *live* enable state+ // at both consumers — ``prev`` here, and the live ``agents`` in+ // handlePrimaryAction — so a just-flipped toggle is never reverted.+ synced = { [name]: merged };+ setAgents((prev) => ({+ ...prev,+ [name]: { ...prev[name], ...merged, enabled: prev[name].enabled },+ }));+ }+ await detect(name, cliPath);+ } catch {+ // Best-effort: fall back to whatever we already have.+ } finally {+ setSyncing(false);+ }+ return synced;+ };+const toggle = (name: string, enabled: boolean) => {setAgents((prev) => ({...prev,@@ -168,7 +224,39 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst canContinue = Object.values(agents).some((agent) => agent.enabled);const handlePrimaryAction = async () => {- const nextData = { agents, default_backend: defaultBackend };+ // Wait for an in-flight provider-modal sync and fold its result into the+ // snapshot we save, so a quick close-then-continue can't persist a stale+ // ``agents`` object that reverts edits made inside the modal.+ let mergedAgents = agents;+ if (syncRef.current) {+ try {+ const synced = await syncRef.current;+ if (synced) {+ // Fold provider edits from the modal into the saved snapshot, but keep+ // ``enabled`` from the live ``agents`` state — a toggle flipped after+ // the sync started must win over the sync's stale snapshot.+ mergedAgents = { ...agents };+ for (const [backendName, syncedAgent] of Object.entries(synced)) {+ mergedAgents[backendName] = {+ ...syncedAgent,+ enabled: agents[backendName]?.enabled ?? syncedAgent.enabled,+ };+ }+ }+ } catch {+ // ignore — fall back to the current snapshot+ }+ syncRef.current = null;+ }+ // Don't persist a default backend the user just disabled — fall back to an+ // enabled one so default-routed sessions don't target a disabled backend.+ const enabledNames = Object.entries(mergedAgents)+ .filter(([, agent]) => agent.enabled)+ .map(([backendName]) => backendName);+ const effectiveDefault = enabledNames.includes(defaultBackend)+ ? defaultBackend+ : (enabledNames[0] ?? defaultBackend);+ const nextData = { agents: mergedAgents, default_backend: effectiveDefault };if (isPage && onSave) {await onSave(nextData);return;@@ -181,195 +269,206 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on// Page mode keeps the existing settings shell — render the inner content onlyconst Inner = (<>- <div className="flex flex-col gap-3 rounded-xl border border-border bg-background px-4 py-3 md:flex-row md:items-end md:justify-between">- <label className="min-w-0 flex-1">+ <div className="flex flex-col gap-3 rounded-xl border border-border bg-background px-4 py-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="min-w-0"><span className="text-[11px] font-semibold uppercase tracking-[0.12em] text-muted">- {t('agentDetection.defaultBackend')}+ {t('agentDetection.backendsLabel')}</span>- <CompactSelect- value={defaultBackend}- onChange={(e) => setDefaultBackend(e.target.value)}- className="mt-1 w-full md:max-w-[260px]"- >- {AGENT_BACKENDS.map((backend) => (- <option key={backend.id} value={backend.id}>- {backend.label}- {backend.id === DEFAULT_BACKEND_ID ? ` ${t('agentDetection.recommended')}` : ''}- </option>- ))}- </CompactSelect>- </label>- <Button- type="button"- variant="secondary"- size="sm"- onClick={detectAll}- >- <Search className="size-3.5" /> {t('common.detectAll')}+ <p className="mt-0.5 text-[12px] leading-snug text-muted">{t('agentDetection.detectedHelper')}</p>+ </div>+ <Button type="button" variant="secondary" size="sm" onClick={detectAll} className="shrink-0">+ <RefreshCw className="size-3.5" /> {t('agentDetection.rescan')}</Button></div><div className="flex flex-col gap-3">{Object.entries(agents).map(([name, agent]) => {const meta = getBackendUiMeta(name);+ const ready = agent.status === 'ok';+ const description = t(`settings.backends.${name}Description`, { defaultValue: '' });+ // Supported backends can open the provider config regardless of+ // detection status — the modal's runtime card lets the user point at a+ // custom CLI path when auto-detection missed an installed binary.+ const canConfigure = PROVIDER_BACKENDS.has(name);return (<divkey={name}- className="overflow-hidden rounded-xl border border-border bg-background transition-colors hover:border-border-strong"+ className="flex flex-col gap-3.5 rounded-xl border border-border bg-background px-5 py-4 transition-colors hover:border-border-strong">- <div className="flex items-center justify-between gap-3 border-b border-border px-5 py-3.5">- <div className="flex min-w-0 items-center gap-3">- <div className="flex size-9 items-center justify-center rounded-lg border border-border bg-surface-2">- <BackendIcon backend={name as BackendId} size={18} />+ {/* Top row — identity + status + enable switch. */}+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="flex size-9 shrink-0 items-center justify-center rounded-lg border border-border bg-surface-2">+ <BackendIcon backend={name as BackendId} size={18} variant="glyph" />+ </div>+ <div className="min-w-0">+ <h3 className="text-[13px] font-semibold text-foreground">{meta.label}</h3>+ {description && (+ <p className="mt-0.5 truncate text-[11px] leading-snug text-muted">{description}</p>+ )}+ </div></div>- <div className="min-w-0">- <h3 className="text-[13px] font-semibold text-foreground">{meta.label}</h3>- <div className="mt-0.5 text-[11px] text-muted">{t('agentDetection.cliPath')}</div>+ <div className="flex shrink-0 items-center gap-3">+ <BackendLifecycleChip+ name={name}+ enabled={agent.enabled}+ cliStatus={agent.status || 'unknown'}+ onChanged={async (info) => {+ // After a successful (re)install the chip hands back the+ // path the installer landed at — adopt it before+ // detecting, otherwise a stale ``agent.cli_path`` from+ // this render keeps the row in a false ``missing`` state.+ const installedPath = info?.installedPath || null;+ if (installedPath) {+ setAgents((prev) => ({+ ...prev,+ [name]: { ...prev[name], cli_path: installedPath },+ }));+ }+ await detect(name, installedPath || agent.cli_path);+ }}+ />+ <ToggleSwitch enabled={agent.enabled} onClick={() => toggle(name, !agent.enabled)} /></div></div>- <div className="flex items-center gap-3">- <BackendLifecycleChip- name={name}- enabled={agent.enabled}- cliStatus={agent.status || 'unknown'}- onChanged={async (info) => {- // After a successful (re)install the chip hands back the- // path the installer landed at — adopt it before- // detecting, otherwise a stale ``agent.cli_path`` from- // this render keeps the row in a false ``missing`` state.- const installedPath = info?.installedPath || null;- if (installedPath) {- setAgents((prev) => ({- ...prev,- [name]: { ...prev[name], cli_path: installedPath },- }));- }- await detect(name, installedPath || agent.cli_path);- }}- />- <ToggleSwitch- enabled={agent.enabled}- onClick={() => toggle(name, !agent.enabled)}- />- </div>- </div>- <div className="space-y-3 px-5 py-3.5">- <div className="flex gap-2">- <CompactField- type="text"- value={agent.cli_path}- onChange={(e) =>- setAgents((prev) => ({- ...prev,- [name]: { ...prev[name], cli_path: e.target.value },- }))- }- placeholder={t('agentDetection.cliPathPlaceholder', { name })}- className="flex-1 font-mono"- />- <Button- type="button"- variant="secondary"- size="sm"- onClick={() => detect(name, agent.cli_path)}- disabled={checking}- >- {checking ? <RefreshCw className="size-3.5 animate-spin" /> : <Search className="size-3.5" />}- {t('common.detect')}- </Button>- </div>+ {/* Action row — configure / set up Allow / install. */}+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-3">+ {canConfigure &&+ (isPage ? (+ meta.settingsRoute && (+ <Button asChild variant="secondary" size="sm">+ <Link to={meta.settingsRoute}>+ <Sliders className="size-3.5" />+ {t('agentDetection.configureProvider')}+ <ExternalLink className="size-3.5" />+ </Link>+ </Button>+ )+ ) : (+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => setProviderModal(name)}+ >+ <Sliders className="size-3.5" />+ {t('agentDetection.configureProvider')}+ </Button>+ ))}- {isMissing(agent) && (- <div className="space-y-2 rounded-lg border border-cyan/30 bg-cyan/[0.06] px-3 py-2.5">- <p className="text-[11px] text-cyan">{t('agentDetection.installHint')}</p>- <div className="flex flex-wrap items-center gap-3">- <Button- variant="brand-cyan"- size="xs"- onClick={() => installAgent(name)}- disabled={isAnyInstalling}- >- {installingAgents[name] ? (- <RefreshCw className="size-3.5 animate-spin" />- ) : (- <Download className="size-3.5" />- )}- {installingAgents[name] ? t('agentDetection.installing') : t('agentDetection.installAgent')}- </Button>- {installResults[name]?.message && (- <span- className={clsx(- 'text-[11px]',- installResults[name].ok ? 'text-mint' : 'text-danger'- )}+ {name === 'opencode' && ready && (+ <>+ <Button+ type="button"+ variant="brand-gold"+ size="sm"+ onClick={setupPermission}+ disabled={permissionState === 'loading'}>- {installResults[name].message}- </span>- )}- </div>- {installResults[name]?.output && (- <div>- <button- onClick={() => toggleOutput(name)}- className="inline-flex items-center gap-1 text-[11px] text-cyan transition hover:text-cyan/80"+ {permissionState === 'loading' ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Settings className="size-3.5" />+ )}+ {t('agentDetection.setupPermission')}+ </Button>+ {permissionState === 'success' && (+ <span className="text-[11px] text-mint">{permissionMessage}</span>+ )}+ {permissionState === 'error' && (+ <span className="text-[11px] text-danger">{permissionMessage}</span>+ )}+ </>+ )}++ {isMissing(agent) && (+ <>+ <Button+ type="button"+ variant="brand-cyan"+ size="sm"+ onClick={() => installAgent(name)}+ disabled={isAnyInstalling}>- {expandedOutputs[name] ? <ChevronUp size={12} /> : <ChevronDown size={12} />}- {t('agentDetection.showOutput')}- </button>- {expandedOutputs[name] && (- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-background px-3 py-2 font-mono text-[11px] text-muted">- {installResults[name].output}- </pre>+ {installingAgents[name] ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Download className="size-3.5" />+ )}+ {installingAgents[name]+ ? t('agentDetection.installing')+ : t('agentDetection.installAgentNamed', { name: meta.label })}+ </Button>+ {installResults[name]?.message && (+ <span+ className={clsx('text-[11px]', installResults[name].ok ? 'text-mint' : 'text-danger')}+ >+ {installResults[name].message}+ </span>)}- </div>+ </>)}</div>- )}-- {name === 'opencode' && agent.status === 'ok' && (- <div className="rounded-lg border border-gold/30 bg-gold/10 px-3 py-2.5">- <p className="mb-2 text-[11px] text-gold">{t('agentDetection.permissionHint')}</p>- <div className="flex flex-wrap items-center gap-3">- <Button- variant="brand-gold"- size="xs"- onClick={setupPermission}- disabled={permissionState === 'loading'}++ {isMissing(agent) && installResults[name]?.output && (+ <div>+ <button+ onClick={() => toggleOutput(name)}+ className="inline-flex items-center gap-1 text-[11px] text-cyan transition hover:text-cyan/80">- {permissionState === 'loading' ? (- <RefreshCw className="size-3.5 animate-spin" />- ) : (- <Settings className="size-3.5" />- )}- {t('agentDetection.setupPermission')}- </Button>- {permissionState === 'success' && (- <span className="text-[11px] text-mint">{permissionMessage}</span>- )}- {permissionState === 'error' && (- <span className="text-[11px] text-danger">{permissionMessage}</span>+ {expandedOutputs[name] ? <ChevronUp size={12} /> : <ChevronDown size={12} />}+ {t('agentDetection.showOutput')}+ </button>+ {expandedOutputs[name] && (+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-background px-3 py-2 font-mono text-[11px] text-muted">+ {installResults[name].output}+ </pre>)}</div>- </div>- )}-- {isPage && meta.settingsRoute && (- <div className="flex justify-end">- <Button asChild variant="ghost" size="sm">- <Link to={meta.settingsRoute}>- <Settings className="size-3.5" />- {t('settings.backends.openProviderPage')}- <ExternalLink className="size-3.5" />- </Link>- </Button>- </div>- )}- </div>+ )}+ </div></div>);})}</div>++ {/* 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. Keep the promise so Continue can await it.+ if (name) syncRef.current = syncBackendFromConfig(name);+ }+ }}+ >+ <DialogContent className="max-w-3xl">+ <DialogHeader>+ <DialogTitle>+ {providerModal+ ? t('agentDetection.configureProviderTitle', { name: getBackendUiMeta(providerModal).label })+ : ''}+ </DialogTitle>+ </DialogHeader>+ {providerModal && (+ // ``deferRestart``: the wizard runs before/while the controller+ // is started, so the embedded runtime Save persists the cli_path+ // without attempting a (would-be-unacknowledged) restart that+ // otherwise reads as a failed/dirty save.+ <BackendProviderConfig backend={providerModal as RuntimeBackendId} hideEnableToggle deferRestart />+ )}+ </DialogContent>+ </Dialog>+ )}</>);@@ -378,7 +477,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on<div className="flex flex-col gap-4">{Inner}<div className="flex justify-end">- <Button variant="brand" size="default" onClick={() => void handlePrimaryAction()} disabled={!canContinue}>+ <Button variant="brand" size="default" onClick={() => void handlePrimaryAction()} disabled={!canContinue || syncing}>{t('common.save')}</Button></div>@@ -428,7 +527,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onvariant="brand"size="default"onClick={() => void handlePrimaryAction()}- disabled={!canContinue}+ disabled={!canContinue || syncing}>{t('common.continue')}<ArrowRight size={14} strokeWidth={2.25} />diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsxindex 6b68addf7..43daf0168 100644--- a/ui/src/components/steps/PlatformSelection.tsx+++ b/ui/src/components/steps/PlatformSelection.tsx@@ -1,10 +1,16 @@import React, { useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';-import { ArrowLeft, ArrowRight, Check, ExternalLink, Info, Loader2, Plus } from 'lucide-react';+import { ArrowLeft, ArrowRight, Check, CircleCheckBig, ExternalLink, Loader2, Lock, Plus, Smartphone } from 'lucide-react';import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';-import { getEnabledPlatforms, getPlatformCatalog, getPrimaryPlatform } from '../../lib/platforms';+import {+ getEnabledPlatforms,+ getImPlatforms,+ getPlatformCatalog,+ getPrimaryPlatform,+ WORKBENCH_PLATFORM_ID,+} from '../../lib/platforms';import { EyebrowBadge, PlatformIcon, WizardCard } from '../visual';import { Button } from '../ui/button';import { Input } from '../ui/input';@@ -63,6 +69,10 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNeconst { t } = useTranslation();const api = useApi();const { showToast } = useToast();+ // The Avibe Workbench card is purely presentational — it is not part of the+ // selectable IM set. ``selected`` / ``platforms.enabled`` tracks only the+ // optional third-party chat platforms (and may be empty for a workbench-only+ // setup).const initialPlatforms = useMemo(() => getEnabledPlatforms(data), [data]);const platformCatalog = useMemo(() => getPlatformCatalog(data), [data]);const [selected, setSelected] = useState<string[]>(initialPlatforms);@@ -82,11 +92,8 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNesetSelected((current) => {if (current.includes(platform)) {const next = current.filter((item) => item !== platform);- if (!next.length) {- return current;- }if (primary === platform) {- setPrimary(next[0]);+ setPrimary(next[0] ?? '');}return next;}@@ -111,8 +118,10 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe};const handleContinue = async () => {- const normalized = selected.length ? selected : [platformCatalog[0]?.id || 'slack'];- const resolvedPrimary = normalized.includes(primary) ? primary : normalized[0];+ // Workbench-only setups are valid, so allow an empty IM selection — do not+ // force a fallback platform into the enabled set.+ const normalized = selected;+ const resolvedPrimary = normalized.includes(primary) ? primary : (normalized[0] ?? '');const nextData = {...credentialDraft,discord_client_id: credentialDraft.discord?.client_id || '',@@ -480,8 +489,11 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe);}- // Wizard mode — design.pen jXiOv: WizardCard 840 wide with tile grid + tip.- // Primary platform is implicit: first selected, then locked to that order.+ // Wizard mode — design.pen jXiOv: WizardCard with a required always-on Avibe+ // Workbench card on the left and an optional grid of third-party chat+ // platforms on the right. Primary platform is implicit: first selected, then+ // locked to that order.+ const chatPlatforms = getImPlatforms(data);return (<div className="flex w-full justify-center"><WizardCard className="gap-8">@@ -493,53 +505,82 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe<p className="max-w-[680px] text-[15px] leading-[1.5] text-muted">{t('platform.subtitle')}</p></div>- <div className="grid w-full grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-5">- {platformCatalog.map((platform) => {- const option = platform.id;- const active = selected.includes(option);- const tileTint = PLATFORM_TILE_STYLES[option] || {- bg: 'bg-foreground/[0.04]',- border: 'border-foreground/[0.10]',- };- return (- <button- type="button"- key={option}- onClick={() => togglePlatform(option)}- className={clsx(- 'flex flex-col items-center gap-2.5 rounded-xl px-4 py-5 transition-colors',- active- ? 'border-2 border-mint bg-mint/[0.16]'- : 'border border-foreground/[0.08] bg-background hover:border-foreground/[0.16] hover:bg-foreground/[0.02]'- )}- >- <span- className={clsx(- 'inline-flex size-11 items-center justify-center rounded-[10px] border',- tileTint.bg,- tileTint.border- )}- >- <PlatformIcon platform={option} size={22} />- </span>- <span- className={clsx(- 'text-[13px] leading-tight transition-colors',- active ? 'font-bold text-foreground' : 'font-medium text-muted'- )}- >- {t(platform.title_key || `platform.${option}.title`)}- </span>- </button>- );- })}- </div>+ <div className="flex flex-col items-stretch gap-5 lg:flex-row">+ {/* Required always-on workbench — not toggleable. */}+ <div className="flex w-full flex-col gap-3.5 rounded-xl border-2 border-mint bg-mint/[0.08] p-5 lg:w-[340px]">+ <div className="flex items-center justify-between">+ <span className="inline-flex size-[52px] items-center justify-center rounded-xl border border-mint/40 bg-mint/10">+ <PlatformIcon platform={WORKBENCH_PLATFORM_ID} size={28} />+ </span>+ <span className="inline-flex items-center gap-1 rounded-full bg-mint px-2.5 py-1 text-[10px] font-bold text-primary-foreground">+ <Lock className="size-3" />+ {t('platform.workbenchRequired')}+ </span>+ </div>+ <div className="flex flex-col gap-1.5">+ <h3 className="text-[17px] font-bold text-foreground">{t('platform.avibe.title')}</h3>+ <p className="text-[13px] leading-[1.5] text-muted">{t('platform.workbenchDesc')}</p>+ </div>+ <div className="flex items-center gap-2 rounded-lg border border-cyan/30 bg-cyan/[0.08] px-3 py-2.5">+ <Smartphone className="size-4 shrink-0 text-cyan" />+ <span className="text-[12px] leading-[1.4] text-foreground">{t('platform.workbenchPwa')}</span>+ </div>+ <div className="mt-auto flex items-center gap-2">+ <CircleCheckBig className="size-4 shrink-0 text-mint" />+ <span className="text-[12px] font-semibold text-mint">{t('platform.workbenchAlwaysOn')}</span>+ </div>+ </div>- <div className="flex items-center gap-2 rounded-lg border border-foreground/[0.08] bg-foreground/[0.04] px-4 py-2.5">- <Info className="size-3.5 shrink-0 text-cyan" />- <span className="text-[12px] leading-[1.45] text-muted">- {t('platform.selectedSummary', { count: selected.length })}- </span>+ {/* Optional third-party chat platforms. */}+ <div className="flex flex-1 flex-col gap-3">+ <div className="flex items-center justify-between">+ <h3 className="text-[14px] font-semibold text-foreground">{t('platform.chatPlatformsTitle')}</h3>+ <span className="rounded-full border border-border px-2.5 py-0.5 text-[10px] text-muted">+ {t('platform.optionalLabel')}+ </span>+ </div>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">+ {chatPlatforms.map((platform) => {+ const option = platform.id;+ const active = selected.includes(option);+ const tileTint = PLATFORM_TILE_STYLES[option] || {+ bg: 'bg-foreground/[0.04]',+ border: 'border-foreground/[0.10]',+ };+ return (+ <button+ type="button"+ key={option}+ onClick={() => togglePlatform(option)}+ className={clsx(+ 'flex flex-col items-center gap-2.5 rounded-xl px-4 py-5 transition-colors',+ active+ ? 'border-2 border-mint bg-mint/[0.16]'+ : 'border border-foreground/[0.08] bg-background hover:border-foreground/[0.16] hover:bg-foreground/[0.02]'+ )}+ >+ <span+ className={clsx(+ 'inline-flex size-11 items-center justify-center rounded-[10px] border',+ tileTint.bg,+ tileTint.border+ )}+ >+ <PlatformIcon platform={option} size={22} />+ </span>+ <span+ className={clsx(+ 'text-[13px] leading-tight transition-colors',+ active ? 'font-bold text-foreground' : 'font-medium text-muted'+ )}+ >+ {t(platform.title_key || `platform.${option}.title`)}+ </span>+ </button>+ );+ })}+ </div>+ </div></div><div className="flex items-center justify-between border-t border-border pt-4">@@ -558,7 +599,6 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNevariant="brand"size="default"onClick={() => void handleContinue()}- disabled={!selected.length}>{t('common.continue')}<ArrowRight size={14} strokeWidth={2.25} />diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsxindex bd53d681c..3400ad120 100644--- a/ui/src/components/steps/Summary.tsx+++ b/ui/src/components/steps/Summary.tsx@@ -123,6 +123,18 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {await control('start');+ // ``enabledPlatforms`` only ever lists real IM platforms — the always-on+ // workbench is stripped by PlatformsConfig.validate() before any config+ // reaches the UI. An empty list is therefore a workbench-only setup.+ if (enabledPlatforms.length === 0) {+ // Workbench-only setup — there is no external bot to bind, so finish+ // instead of falling through to a bogus bind-code flow.+ setSaving(false);+ setTimeout(() => {+ navigate('/');+ }, 1000);+ return;+ }if (enabledPlatforms.every((platform) => platform === 'wechat')) {setSaving(false);showToast(t('wechat.setupComplete'));@@ -490,6 +502,12 @@ const buildConfigPayload = (data: any) => {ack_mode: data.ack_mode,show_duration: data.show_duration ?? false,language: data.language,+ // Finishing the wizard is the explicit signal that setup is complete. Set+ // here (Summary's own payload, the one saved on Finish) rather than in+ // Wizard.tsx's intermediate-step payload so the flag is only persisted once+ // the user actually reaches and completes the final step (including the+ // Skip → Summary → Finish path).+ setup_completed: true,};};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 06d9d84aa..fe5f8adbe 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -663,8 +663,14 @@},"platform": {"eyebrow": "03 — Platforms",- "title": "Choose a Platform",- "subtitle": "Select one or more chat platforms to connect.",+ "title": "Where you'll talk to your agent",+ "subtitle": "Your Avibe Workbench is always on — a built-in web app you can even add to your phone's home screen. Connect chat platforms like Slack or Telegram too, or skip and set them up later.",+ "workbenchRequired": "REQUIRED",+ "workbenchDesc": "Your built-in web chat for talking to agents — always on, nothing to set up.",+ "workbenchPwa": "Add to your phone's home screen — use it like a native app.",+ "workbenchAlwaysOn": "Always enabled",+ "chatPlatformsTitle": "Chat platforms",+ "optionalLabel": "OPTIONAL","primary": "Primary","primaryTitle": "Primary Platform","primaryDesc": "Used for compatibility ordering and default UI focus.",@@ -978,8 +984,14 @@},"agentDetection": {"eyebrow": "Backends",- "title": "Agent Configuration",- "subtitle": "Detect local CLI paths and choose enabled backends.",+ "title": "Set up your agent backends",+ "subtitle": "We scan this machine for installed agents. Turn on the ones you have, and install anything that's missing.",+ "backendsLabel": "Agent backends",+ "detectedHelper": "Detected automatically on this machine — enable what you have, install anything missing.",+ "rescan": "Re-scan",+ "configureProvider": "Configure provider",+ "configureProviderTitle": "Configure {{name}}",+ "installAgentNamed": "Install {{name}}","defaultBackend": "Default Backend","cliPath": "CLI Path","cliPathPlaceholder": "Path to {{name}} CLI...",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 70ec065e7..73f0e39f6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -663,8 +663,14 @@},"platform": {"eyebrow": "03 — 平台",- "title": "选择平台",- "subtitle": "选择一个或多个要连接的聊天平台。",+ "title": "你在哪里和 Agent 聊天",+ "subtitle": "Avibe Workbench 一直开着,是内置的网页应用,还能添加到手机主屏。也可以顺便接上 Slack、Telegram 这类聊天平台,或者先跳过,以后再设置。",+ "workbenchRequired": "必备",+ "workbenchDesc": "内置的网页聊天,用来和 Agent 对话,一直开着,不用配置。",+ "workbenchPwa": "添加到手机主屏,像原生 App 一样用。",+ "workbenchAlwaysOn": "始终开启",+ "chatPlatformsTitle": "聊天平台",+ "optionalLabel": "可选","primary": "主平台","primaryTitle": "主平台","primaryDesc": "仅用于兼容排序和默认界面展示焦点。",@@ -978,8 +984,14 @@},"agentDetection": {"eyebrow": "后端",- "title": "Agent 配置",- "subtitle": "检测本地 CLI 路径并选择启用的后端",+ "title": "安装并配置 Agent 后端",+ "subtitle": "我们会自动扫描这台电脑上装好的 Agent。把你有的打开,缺的直接装上。",+ "backendsLabel": "Agent 后端",+ "detectedHelper": "已自动扫描这台电脑——有的就打开,缺的就装上。",+ "rescan": "重新扫描",+ "configureProvider": "配置模型供应商",+ "configureProviderTitle": "配置 {{name}}",+ "installAgentNamed": "安装 {{name}}","defaultBackend": "默认后端","cliPath": "CLI 路径","cliPathPlaceholder": "{{name}} CLI 路径...",diff --git a/ui/src/lib/platforms.ts b/ui/src/lib/platforms.tsindex d7ea3aad9..022f69f75 100644--- a/ui/src/lib/platforms.ts+++ b/ui/src/lib/platforms.ts@@ -25,6 +25,10 @@ export type PlatformDescriptor = {description_key?: string;credential_fields?: string[];capabilities?: PlatformCapabilities;+ // Structural distinction mirrored from the backend registry: real IM+ // transports are 'im', the always-on in-process workbench is 'workbench'.+ // Optional so older payloads (pre-kind) still type-check.+ kind?: 'im' | 'workbench';};// The local Vibe Remote web workbench, surfaced as a peer platform so it shares@@ -147,12 +151,21 @@ export const getPlatformCatalog = (data: any): PlatformDescriptor[] => {export const getPlatformIds = (data: any): PlatformName[] => getPlatformCatalog(data).map((platform) => platform.id);+// Catalog entries that are real IM transports (excludes the in-process Avibe+// Workbench). The single place IM-list surfaces (wizard / settings) filter the+// workbench out of the selectable platform set — use the structural ``kind``+// when present, falling back to the id-check for older payloads without it.+export const getImPlatforms = (data: any): PlatformDescriptor[] =>+ getPlatformCatalog(data).filter((p) => (p.kind ? p.kind !== 'workbench' : !isWorkbenchPlatform(p.id)));+export const getEnabledPlatforms = (data: any): PlatformName[] => {const catalogIds = new Set(getPlatformIds(data));const enabled = data?.platforms?.enabled;- if (Array.isArray(enabled) && enabled.length > 0) {+ if (Array.isArray(enabled)) {const filtered = enabled.filter((platform: string): platform is PlatformName => catalogIds.has(platform));- if (filtered.length > 0) return filtered;+ // Honor an explicitly empty list (workbench-only). A non-empty list that+ // filters to nothing is malformed → fall through to the legacy fallback.+ if (filtered.length > 0 || enabled.length === 0) return filtered;}const legacy = data?.platform;if (catalogIds.has(legacy)) {@@ -167,6 +180,11 @@ export const getPrimaryPlatform = (data: any): PlatformName => {if (enabled.includes(primary)) {return primary as PlatformName;}+ // Workbench-only saves primary="avibe" with enabled=[], so a saved primary+ // that is a known catalog id stays authoritative even when not in `enabled`.+ if (primary && getPlatformIds(data).includes(primary)) {+ return primary as PlatformName;+ }return enabled[0] || getPlatformCatalog(data)[0]?.id || 'slack';};diff --git a/vibe/api.py b/vibe/api.pyindex 272a1cb95..143e2847f 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -613,7 +613,27 @@ def save_config(payload: dict) -> V2Config:base_config = load_config()base_payload = config_to_payload(base_config, include_secrets=True)except FileNotFoundError:- base_payload = {}+ # Fresh install: no config file yet. Seed the same workbench-only+ # default the read side (GET /api/config) serves, so a partial+ # first-run save — e.g. the wizard's reused provider-config modal+ # POSTing just ``{"agents": ...}`` — merges onto a valid base+ # instead of feeding a partial payload straight into+ # ``V2Config.from_payload`` (which requires ``mode``/``runtime`` and+ # would raise). ``base_config`` stays ``None`` so the Discord-scope+ # preservation below (which keys off a real prior config) is skipped.+ from core.services.settings import default_config++ base_payload = config_to_payload(default_config(), include_secrets=True)+ # Don't let the seed's workbench-only ``platforms`` shadow+ # from_payload's legacy ``platform`` -> ``platforms`` migration: when+ # the request is a legacy single-platform update (``platform`` set,+ # ``platforms`` absent), drop the seed's platform fields so the+ # request's own platform still derives ``platforms.enabled``. The+ # wizard always sends ``platforms`` and is unaffected; a bare partial+ # save (neither key) keeps the workbench-only seed.+ if "platform" in payload and "platforms" not in payload:+ base_payload.pop("platforms", None)+ base_payload.pop("platform", None)merged_payload = _deep_merge_dicts(base_payload, payload) if base_payload else payloadmerged_payload = _merge_legacy_discord_guild_scope_fields(merged_payload, payload, base_config)@@ -709,6 +729,7 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic"include_user_info": config.include_user_info,"reply_enhancements": config.reply_enhancements,"show_pages_prompt": config.show_pages_prompt,+ "setup_completed": config.setup_completed,}return payloaddiff --git a/vibe/cli.py b/vibe/cli.pyindex 3706a3157..37bcc5de2 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -26,15 +26,7 @@ from tzlocal import get_localzone_namefrom sqlalchemy import selectfrom config import SettingsStore, paths-from config.v2_config import (- AgentsConfig,- ClaudeConfig,- CodexConfig,- OpenCodeConfig,- RuntimeConfig,- SlackConfig,- V2Config,-)+from config.v2_config import V2Configfrom core.scheduled_tasks import (ScheduledTaskStore,TaskExecutionStore,@@ -682,18 +674,12 @@ def _open_browser(url: str) -> bool:def _default_config():- return V2Config(- mode="self_host",- version="v2",- slack=SlackConfig(bot_token="", app_token=""),- runtime=RuntimeConfig(default_cwd=str(Path.home() / "work")),- agents=AgentsConfig(- default_backend="opencode",- opencode=OpenCodeConfig(enabled=True, cli_path="opencode"),- claude=ClaudeConfig(enabled=True, cli_path="claude"),- codex=CodexConfig(enabled=False, cli_path="codex"),- ),- )+ # Single source of truth lives in ``core.services.settings`` so the CLI's+ # seed-on-first-run default and the UI's read-side default (GET /api/config+ # on a fresh install) can never drift apart.+ from core.services import settings as settings_service++ return settings_service.default_config()def _ensure_config():diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 11142f72c..23ce3420e 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1600,8 +1600,15 @@ def doctor_get():@app.route("/api/config", methods=["GET"])def config_get():from vibe import api+ from core.services import settings as settings_service- config = api.load_config()+ # On a truly fresh install no config file exists yet, but the setup+ # wizard (and the provider-config modal it reuses, which calls+ # ``getConfig()``) must still load. Serve an in-memory default whose+ # ``setup_state.needs_setup`` is True so the wizard shows and a fresh+ # default is never mistaken for a completed setup. The write side+ # (``save_config``) already creates the file on the first real save.+ config = settings_service.load_config_or_default()return jsonify(api.config_to_payload(config))