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(backends): provider config UI + auth for Claude and OpenCode (Phases B+C)
cyh66fd0f24a0b8
diff --git a/AGENTS.md b/AGENTS.mdindex 219407cbb..4551b5083 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -101,6 +101,14 @@ Rules:- after running the script, verify the service is healthy before handing back to the user- prefer Docker regression over local `vibe` whenever validating cross-platform behavior, setup wizard behavior, or user-facing IM flows+Worktree gotcha — `_tmp/three-regression/vibe/` is per-worktree:++- the regression container bind-mounts `${PWD}/_tmp/three-regression/vibe` to `/data/vibe_remote`, so the volume points at whichever worktree ran the script most recently+- running `./scripts/run_three_regression.sh` from a different worktree silently swaps the bound volume — the new container sees a fresh/empty state, losing pairing (`remote_access` config), agent CLI binaries, sessions, etc.+- symptom: `test-app.avibe.bot` (or any paired `vibe_cloud` URL) returns Cloudflare **1033** because cloudflared never starts inside the new container — no `tunnel_token` in `config.json`+- before switching worktrees for regression, either sync the state directory (`cp -a` from old to new worktree's `_tmp/three-regression/`) or copy at minimum the `remote_access` block in `config/config.json`, then `docker exec ... vibe remote start` to re-spawn cloudflared+- the simplest discipline: always run regression from the same worktree until the user explicitly says to move+## 4. Configuration and Routing ModelPersistent configuration is centered on `config/v2_config.py` and the Web UI.diff --git a/docs/plans/backend-provider-config.md b/docs/plans/backend-provider-config.mdindex f90c45fd5..ef223dea8 100644--- a/docs/plans/backend-provider-config.md+++ b/docs/plans/backend-provider-config.md@@ -75,7 +75,8 @@ flagging with the user before committing to bundling.- **Claude** — one-shot CLI per request. API-key mode is realized byinjecting `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL` env vars at- invocation time (the SDK already honors these).+ invocation time (the SDK already honors these). **No restart needed**:+ the next user message picks up new V2Config values automatically.- **Codex** — persistent `codex app-server` per cwd. API-key mode isrealized by writing `~/.codex/config.toml`; the daemon picks upchanges via `restart_backend('codex')` (PR #282 wires this).@@ -84,6 +85,138 @@ flagging with the user before committing to bundling.plus `set_api_key_auth(provider_id, key)` HTTP call; the server ishot-reloaded via the existing `_install_opencode_api_key()` flow.+### Audit status (resolved 2026-05-12, post-codex landing)++| Layer | Claude | Codex | OpenCode |+| --- | --- | --- | --- |+| V2Config schema | ✅ done | ✅ done | ✅ done (`default_provider`) |+| On-disk writer / state reader | ❌ none yet | ✅ `vibe/codex_config.py` | ✅ existing `vibe/opencode_config.py` + `OpenCodeServer.set_api_key_auth` |+| HTTP API in `vibe/api.py` | ❌ missing | ✅ `get_codex_auth/save_codex_auth` | ❌ missing |+| Route in `vibe/ui_server.py` | ❌ missing | ✅ `/backend/codex/auth` GET+POST | ❌ missing |+| Env / process glue | ✅ `session_handler.py:570` injects V2Config-driven `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL` before `ClaudeSDKClient` | ✅ `restart_backend('codex')` | ✅ existing OpenCode server hot-reload |+| Settings page UI | ❌ stub only (CLI detect) | ✅ `SettingsCodexProviderPage.tsx` | ❌ stub only (CLI detect + permissions) |+| ApiContext methods | ❌ missing | ✅ `getCodexAuth/saveCodexAuth` | ❌ missing |+| i18n keys | partial (`settings.backends.claudeTitle/Subtitle/Description`) | ✅ full Codex set | partial (`settings.backends.opencodeTitle/Subtitle/Description`) |++The remaining work is therefore **Claude end-to-end (E + B)** and+**OpenCode end-to-end (E + D)** — plus the Phase F i18n strings. Phases+A (scaffolding) and Codex are complete from the prior commits on this+branch.++### Product UX considerations++Treat the three pages as **edit-only surfaces** the user reaches when+they want to *change* an existing setup. First-run still uses the+`AgentDetection` wizard. Each page must work for three user journeys:++**J1 · First-time inspection** — user signed in via `claude login`+yesterday, opens the page today. Expected: page renders quickly, shows+"OAuth signed in" without prompting for anything, exposes the API-key+fallback panel collapsed by default so it doesn't shout.++**J2 · Switch to API gateway / proxy** — user wants to point Claude at+their corporate Anthropic gateway, or Codex at Azure OpenAI, or+OpenCode at openrouter. Expected: toggle auth_mode → paste key → set+Base URL → Save. The page must clearly say "the next message goes+through this gateway" so the user trusts the change took effect (no+silent fallback to the old endpoint).++**J3 · Rotate a leaked key** — user got a security alert; needs to+paste a fresh key and confirm the old one is gone everywhere. Expected:+saving a non-empty key overwrites the stored one *and* the+masked-length display updates immediately (e.g. "key configured ·+sk-...64 chars"). Saving an empty key while in api_key mode must NOT+silently revert — it must either keep the existing key (with a clear+hint that we did) or reject the form.++**Trust & safety details (apply to all three pages):**++- API key input is `type="password"`; never log or render plaintext.+- The page never *preloads* the stored key into the input. Empty input+ = "keep whatever is stored"; a non-empty value = "replace it". A+ status line ("Configured · 48 chars" / "Not configured") tells the+ user which state they are in.+- **No copy button on the key field.** A copy button on a password+ input invites users to leave the plaintext in their clipboard; we+ don't ship that affordance for credentials. (The Codex page already+ follows this rule.)+- Base URL is plain text; we do show a Reset button that clears it back+ to the SDK / Codex / OpenCode default.+- Inputs disabled while a save is in flight; toast surfaces both+ success and "saved but restart failed" partial states.++**Cross-page consistency** — the three pages reuse the same building+blocks: `SettingsPageShell` (breadcrumb + title + subtitle),+`BackendLifecycleChip` in the header right cluster, `SegmentedRadio`+for binary auth-mode choices (cloned from `RoutingConfigPanel`), and+the same Input / Label / Button primitives from+`ui/src/components/ui/*`. No bespoke styled buttons or pills.++### OpenCode page — detailed UX++**Header / toolbar layout** (matches `design.pen` frame `x53H1P`):++- Header left (`ocHeadL`): violet code icon + title "OpenCode" + status+ chip (Running / Stopped) + count chip (`14 providers` from+ introspection) + subtitle "Lazy-loaded from CLI · auth handled via+ API key or `opencode auth login`".+- Header right (`ocHeadR`): Refresh-providers button (re-runs the+ introspection fan-out) + Backend-enabled toggle.+- Toolbar row (`ocToolbar`): full-text search across provider id ++ name + model ids, filter chips (`All · Configured · OAuth available ·+ Local`), and a **Default-provider** pill on the right showing the+ current pick with a chevron-down (clicks → popover with the same+ provider list).++**Provider grid** — fully dynamic, sourced from `GET /backend/opencode/providers`.+Cards render a uniform shape:++- Top row: provider name + per-card status badge+ (`Configured` mint / `OAuth available` info / `Local` secondary /+ `Not set` outline-muted) + a chevron / disclosure affordance.+- Middle: `<id> · N models · <one-line description>` in monospace muted+ text (read from the provider's catalog entry).+- Footer: contextual call-to-action for unconfigured cloud providers+ ("Set API key") or local providers ("Start <provider> + load a+ model").++Cards are clickable; clicking expands one card inline (single+expansion at a time, like the design's `ocAnthropicExp` example):++- Expanded header repeats the badge + adds three actions: **Test**+ (punted to Phase D), **Remove key** (DELETE auth, with confirm), and+ **Collapse**.+- Expanded body has two columns:+ - Left: auth mode segmented control (when both OAuth and API key+ are supported) + API Key input (password + Configured/length+ line) + Base URL input + Reset.+ - Right: searchable models list (read from the provider catalog) —+ read-only for v1 (whitelist editing is out of scope).++**Default-provider selector** — only **configured** providers are+selectable. Picking a non-configured provider must first prompt the+user to set its key (auto-expand that card). Saved via+`POST /backend/opencode/default-provider`. The pill updates+immediately on success; the change is also reflected in+`V2Config.agents.opencode.default_provider` so it persists across+restarts and shows up in the lifecycle chip's "default" label.++**Empty / error states:**++- Backend disabled → grid is hidden, replaced by a banner "Enable+ OpenCode in the header to manage providers". The auth-mode toggle is+ the only interactive control.+- Backend enabled but server not running → grid renders with a thin+ "Server starting…" banner; introspection retries every 3s up to 5+ attempts. After that, fall back to a stub catalog from+ `~/.config/opencode/opencode.json` plus a "Server not reachable —+ showing stored configuration" warning so the user can still edit.+- Introspection succeeded but `providers` is empty → render a single+ "OpenCode returned no providers; run `opencode auth list` from a+ terminal to diagnose" panel.+- Per-provider 4xx/5xx on save → keep the expanded panel open, show+ the error inline, do not collapse.+### V2Config schema (Python)```pythondiff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 55e29cb27..de821c369 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -805,6 +805,72 @@ class OpenCodeServerManager:error_text = await resp.text()raise RuntimeError(f"Failed to set OpenCode auth: {resp.status} {error_text}")+ async def remove_provider_auth(self, provider_id: str) -> None:+ """Drop a provider's stored credentials via OpenCode's auth endpoint.++ Used by the Settings UI's "Remove key" action. OpenCode treats 404+ as already-removed, which we silently accept so the UI can issue+ DELETE optimistically without first checking presence.+ """++ await self.ensure_running()++ async with self._request_scope():+ session = await self._get_http_session()+ async with session.delete(+ f"{self.base_url}/auth/{provider_id}",+ ) as resp:+ if resp.status in (200, 204, 404):+ return+ error_text = await resp.text()+ raise RuntimeError(+ f"Failed to remove OpenCode auth for {provider_id}: {resp.status} {error_text}"+ )++ async def get_providers(self) -> Dict[str, Any]:+ """Fetch the full provider catalog from the running OpenCode server.++ Returns the raw shape OpenCode reports: ``{all: {...}, default:+ {...}, connected: [...]}``. Callers (``vibe.api.get_opencode_providers``)+ merge this with the auth-method map from ``get_provider_auth`` to+ produce the per-card ``configured`` / ``oauth_available`` /+ ``local`` flags surfaced in the Settings UI.+ """++ await self.ensure_running()++ async with self._request_scope():+ session = await self._get_http_session()+ try:+ async with session.get(f"{self.base_url}/provider") as resp:+ if resp.status == 200:+ return await resp.json()+ return {}+ except Exception as e:+ logger.warning(f"Failed to get OpenCode providers: {e}")+ return {}++ async def get_provider_auth(self) -> Dict[str, Any]:+ """Fetch the per-provider auth-method index from OpenCode.++ Shape is ``{providerId: [{type, label?, ...}, ...]}`` — providers+ that support OAuth surface a ``{"type": "oauth", ...}`` entry,+ local providers (Ollama / LM Studio) report an empty list.+ """++ await self.ensure_running()++ async with self._request_scope():+ session = await self._get_http_session()+ try:+ async with session.get(f"{self.base_url}/provider/auth") as resp:+ if resp.status == 200:+ return await resp.json()+ return {}+ except Exception as e:+ logger.warning(f"Failed to get OpenCode provider/auth: {e}")+ return {}+def _load_opencode_user_config(self) -> Optional[Dict[str, Any]]:"""Load and cache opencode.json config file.diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 3cac75ba9..2b9af30e5 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -6,7 +6,9 @@ import { ChannelList } from './components/steps/ChannelList';import { UserList } from './components/steps/UserList';import { SettingsDiagnosticsPage } from './components/settings/SettingsDiagnosticsPage';import { SettingsBackendsPage } from './components/settings/SettingsBackendsPage';+import { SettingsClaudeProviderPage } from './components/settings/SettingsClaudeProviderPage';import { SettingsCodexProviderPage } from './components/settings/SettingsCodexProviderPage';+import { SettingsOpencodeProviderPage } from './components/settings/SettingsOpencodeProviderPage';import { SettingsLogsPage } from './components/settings/SettingsLogsPage';import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPage';@@ -78,6 +80,8 @@ function AppRoutes() {<Route path="/settings/service" element={<SettingsServicePage />} /><Route path="/settings/platforms" element={<SettingsPlatformsPage />} /><Route path="/settings/backends" element={<SettingsBackendsPage />} />+ <Route path="/settings/backends/opencode" element={<SettingsOpencodeProviderPage />} />+ <Route path="/settings/backends/claude" element={<SettingsClaudeProviderPage />} /><Route path="/settings/backends/codex" element={<SettingsCodexProviderPage />} /><Route path="/settings/messaging" element={<SettingsMessagingPage />} /><Route path="/settings/diagnostics" element={<SettingsDiagnosticsPage />} />diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsxindex e43d422bc..2fb72ad1d 100644--- a/ui/src/components/settings/BackendLifecycleChip.tsx+++ b/ui/src/components/settings/BackendLifecycleChip.tsx@@ -67,10 +67,10 @@ const deriveVisual = (// that window the local detection is the fresher signal — trust it and// do not flip the chip to error just because the saved config is stale.if (cliStatus !== 'ok' && runtime && runtime.installed === false) return 'error';- // A daemon-backed backend whose process was killed externally must surface- // as error so the popover offers Restart — a stopped daemon outranks both- // "update available" and "ready".- if (runtime?.supports_restart && runtime.process_status === 'stopped') return 'error';+ // ``opencode serve`` and ``codex app-server`` are lazy-spawn daemons: they+ // stay stopped until a session needs them, so ``process_status === 'stopped'``+ // is the normal idle state, not an error. Restart still works on demand+ // from the popover.if (runtime?.has_update) return 'update';if (cliStatus === 'ok') return 'ready';return 'loading';diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsxindex 20fa076ca..774394a28 100644--- a/ui/src/components/settings/SettingsBackendsPage.tsx+++ b/ui/src/components/settings/SettingsBackendsPage.tsx@@ -1,25 +1,201 @@import React, { useEffect, useState } from 'react';+import { Link } from 'react-router-dom';import { useTranslation } from 'react-i18next';+import { Bot, ChevronRight, Settings2, Sparkles, Terminal } from 'lucide-react';+import clsx from 'clsx';-import { AgentDetection } from '@/components/steps/AgentDetection';+import { Button } from '../ui/button';+import { Badge } from '../ui/badge';+import { CompactSelect, ToggleSwitch } from './SettingsPrimitives';+import { BackendLifecycleChip } from './BackendLifecycleChip';+import { SettingsPageShell } from './SettingsPageShell';import { useApi } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';-import { SettingsPageShell } from './SettingsPageShell';++// Mirrors design.pen qVHh4 (VR/CM/Backends): top bar with default-backend+// picker, then three horizontal cards (OpenCode/Claude/Codex). Each card+// surfaces icon + name/description + status chip + enable toggle + a+// "Configure" link that drills into the level-2 provider page. CLI path,+// detect, install, and permission profile live on the provider page now —+// keep the level-1 page about routing decisions, not setup mechanics.++type CliStatus = 'unknown' | 'ok' | 'missing';++type AgentState = {+ enabled: boolean;+ cli_path: string;+ status: CliStatus;+};++type BackendMeta = {+ id: string;+ label: string;+ Icon: React.ComponentType<{ size?: number; className?: string }>;+ // Tile background ($--violet-soft / $--cyan-soft / $--gold) and inner icon color.+ // Codex matches design.pen's solid gold tile so the brand pop survives in light mode.+ tileCls: string;+ iconCls: string;+ routeKey?: 'opencode' | 'claude' | 'codex';+};++const BACKENDS: BackendMeta[] = [+ {+ id: 'opencode',+ label: 'OpenCode',+ Icon: Terminal,+ tileCls: 'bg-violet-soft',+ iconCls: 'text-violet',+ routeKey: 'opencode',+ },+ {+ id: 'claude',+ label: 'Claude Code',+ Icon: Sparkles,+ tileCls: 'bg-cyan-soft',+ iconCls: 'text-cyan',+ routeKey: 'claude',+ },+ {+ id: 'codex',+ label: 'Codex',+ Icon: Bot,+ tileCls: 'bg-gold',+ iconCls: 'text-gold-foreground',+ routeKey: 'codex',+ },+];++const DEFAULT_AGENTS: Record<string, AgentState> = {+ opencode: { enabled: true, cli_path: 'opencode', status: 'unknown' },+ claude: { enabled: true, cli_path: 'claude', status: 'unknown' },+ codex: { enabled: false, cli_path: 'codex', status: 'unknown' },+};++const normalizeAgents = (source: any): Record<string, AgentState> => {+ const raw = source?.agents || {};+ return Object.fromEntries(+ Object.entries(DEFAULT_AGENTS).map(([name, fallback]) => {+ const next = raw?.[name] || {};+ return [+ name,+ {+ enabled: typeof next.enabled === 'boolean' ? next.enabled : fallback.enabled,+ cli_path: next.cli_path || fallback.cli_path,+ status: (next.status as CliStatus) || fallback.status,+ },+ ];+ })+ );+};export const SettingsBackendsPage: React.FC = () => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();- const [config, setConfig] = useState<any>(null);++ const [loaded, setLoaded] = useState(false);+ const [agents, setAgents] = useState<Record<string, AgentState>>(DEFAULT_AGENTS);+ const [defaultBackend, setDefaultBackend] = useState<string>('opencode');useEffect(() => {- api.getConfig().then(setConfig).catch(() => {});+ let cancelled = false;+ api+ .getConfig()+ .then((config) => {+ if (cancelled) return;+ setAgents(normalizeAgents(config));+ setDefaultBackend(+ config?.default_backend || config?.agents?.default_backend || 'opencode'+ );+ setLoaded(true);+ })+ .catch(() => {+ if (!cancelled) setLoaded(true);+ });+ return () => {+ cancelled = true;+ };}, [api]);- const handleSave = async (nextData: { agents: any; default_backend: string }) => {- await api.saveConfig({ agents: { ...nextData.agents, default_backend: nextData.default_backend } });- setConfig((prev: any) => ({ ...(prev || {}), agents: { ...nextData.agents, default_backend: nextData.default_backend } }));- showToast(t('common.saved'), 'success');+ // Detect each CLI on mount so the status pill reflects reality without+ // making the user click Detect manually. Runs after the first config load.+ useEffect(() => {+ if (!loaded) return;+ let cancelled = false;+ (async () => {+ const results = await Promise.all(+ Object.entries(agents).map(async ([name, agent]) => {+ try {+ const result = await api.detectCli(agent.cli_path || name);+ return [name, result] as const;+ } catch {+ return [name, null] as const;+ }+ })+ );+ if (cancelled) return;+ setAgents((prev) => {+ const next = { ...prev };+ for (const [name, result] of results) {+ if (!result) continue;+ next[name] = {+ ...next[name],+ cli_path: result.path || next[name].cli_path,+ status: result.found ? 'ok' : 'missing',+ };+ }+ return next;+ });+ })();+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [loaded]);++ const persist = async (nextAgents: Record<string, AgentState>, nextDefault: string) => {+ try {+ await api.saveConfig({+ agents: { ...nextAgents, default_backend: nextDefault },+ });+ showToast(t('common.saved'), 'success');+ } catch (e: any) {+ showToast(e?.message || t('common.saveFailed'), 'error');+ }+ };++ const handleToggle = async (name: string, enabled: boolean) => {+ const nextAgents = { ...agents, [name]: { ...agents[name], enabled } };+ setAgents(nextAgents);+ await persist(nextAgents, defaultBackend);+ };++ const handleDefaultChange = async (next: string) => {+ setDefaultBackend(next);+ // If the chosen default is disabled, flip it on so the routing target is+ // actually reachable — saves the user an extra round trip to enable it.+ let nextAgents = agents;+ if (!agents[next]?.enabled) {+ nextAgents = { ...agents, [next]: { ...agents[next], enabled: true } };+ setAgents(nextAgents);+ }+ await persist(nextAgents, next);+ };++ const refreshDetectionFor = async (name: string, cli_path: string) => {+ try {+ const result = await api.detectCli(cli_path || name);+ setAgents((prev) => ({+ ...prev,+ [name]: {+ ...prev[name],+ cli_path: result.path || prev[name].cli_path,+ status: result.found ? 'ok' : 'missing',+ },+ }));+ } catch {+ // ignore — chip falls back to muted "loading" pill+ }};return (@@ -28,10 +204,109 @@ export const SettingsBackendsPage: React.FC = () => {title={t('settings.backendsTitle')}subtitle={t('settings.backendsSubtitle')}>- {config ? (- <AgentDetection data={config} onNext={() => {}} isPage onSave={handleSave} />- ) : (+ {!loaded ? (<div className="text-sm text-muted">{t('common.loading')}</div>+ ) : (+ <div className="flex flex-col gap-3.5">+ <div className="flex flex-col gap-3 rounded-xl border border-border bg-background px-5 py-4 md:flex-row md:items-center md:justify-between">+ <div className="flex flex-col gap-1">+ <span className="text-[14px] font-semibold text-foreground">+ {t('settings.backends.routingTitle')}+ </span>+ <span className="max-w-[520px] text-[12px] leading-snug text-muted">+ {t('settings.backends.routingHint')}+ </span>+ </div>+ <label className="flex items-center gap-2 self-start md:self-auto">+ <span className="text-[11px] font-medium text-muted">+ {t('settings.backends.defaultLabel')}+ </span>+ <CompactSelect+ value={defaultBackend}+ onChange={(e) => void handleDefaultChange(e.target.value)}+ className="min-w-[180px]"+ aria-label={t('settings.backends.defaultLabel') as string}+ >+ {BACKENDS.map((b) => (+ <option key={b.id} value={b.id}>+ {b.label}+ </option>+ ))}+ </CompactSelect>+ </label>+ </div>++ {BACKENDS.map((meta) => {+ const agent = agents[meta.id];+ const Icon = meta.Icon;+ const isDefault = defaultBackend === meta.id;+ const route = meta.routeKey ? `/settings/backends/${meta.routeKey}` : null;++ return (+ <div+ key={meta.id}+ className="flex flex-col gap-4 rounded-xl border border-border bg-background px-5 py-4 transition-colors hover:border-border-strong md:flex-row md:items-center"+ >+ <div className="flex min-w-0 flex-1 items-center gap-4">+ <div+ className={clsx(+ 'flex size-11 shrink-0 items-center justify-center rounded-[10px]',+ meta.tileCls+ )}+ >+ <Icon size={22} className={meta.iconCls} />+ </div>+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[15px] font-semibold text-foreground">+ {meta.label}+ </span>+ {isDefault && (+ <Badge variant="success" className="font-mono uppercase tracking-[0.08em]">+ {t('settings.backends.defaultBadge')}+ </Badge>+ )}+ </div>+ <p className="text-[12px] leading-snug text-muted">+ {t(`settings.backends.${meta.id}Description`)}+ </p>+ </div>+ </div>++ <div className="flex flex-wrap items-center gap-3 md:shrink-0 md:justify-end">+ <BackendLifecycleChip+ name={meta.id}+ enabled={agent.enabled}+ cliStatus={agent.status}+ onChanged={async (info) => {+ const installedPath = info?.installedPath || null;+ if (installedPath) {+ setAgents((prev) => ({+ ...prev,+ [meta.id]: { ...prev[meta.id], cli_path: installedPath },+ }));+ }+ await refreshDetectionFor(meta.id, installedPath || agent.cli_path);+ }}+ />+ <ToggleSwitch+ enabled={agent.enabled}+ onClick={() => void handleToggle(meta.id, !agent.enabled)}+ />+ {route && (+ <Button asChild variant="secondary" size="xs">+ <Link to={route} aria-label={t('settings.backends.configure', { name: meta.label }) as string}>+ <Settings2 className="size-3.5" />+ {t('settings.backends.configure')}+ <ChevronRight className="size-3.5" />+ </Link>+ </Button>+ )}+ </div>+ </div>+ );+ })}+ </div>)}</SettingsPageShell>);diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsxnew file mode 100644index 000000000..069d75c2f--- /dev/null+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx@@ -0,0 +1,554 @@+import React, { useEffect, useMemo, useState } from 'react';+import { Link } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import {+ AlertTriangle,+ ArrowLeft,+ CheckCircle2,+ ChevronDown,+ ChevronUp,+ Download,+ Info,+ KeyRound,+ RefreshCw,+ RotateCcw,+ Save,+ Search,+ Sparkles,+} from 'lucide-react';+import clsx from 'clsx';++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 { BackendLifecycleChip } from './BackendLifecycleChip';+import { ToggleSwitch } from './SettingsPrimitives';+import { useApi } from '@/context/ApiContext';+import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++type CliStatus = 'unknown' | 'ok' | 'missing';++const BACKEND_ID = 'claude';+const DEFAULT_CLI = 'claude';++// Mirrors the segmented-radio pattern from RoutingConfigPanel / Codex page.+// Kept inline rather than promoted to ui/* until a third caller appears —+// see plan doc "Cross-page consistency": SegmentedRadio is cloned for now,+// promote on Phase D consolidation.+const SegmentedRadio: React.FC<{+ value: ClaudeAuthMode;+ onChange: (next: ClaudeAuthMode) => void;+ options: ReadonlyArray<{ id: ClaudeAuthMode; label: string }>;+ ariaLabel: string;+}> = ({ value, onChange, options, ariaLabel }) => (+ <div+ role="radiogroup"+ aria-label={ariaLabel}+ className="flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5"+ >+ {options.map((opt) => {+ const active = value === opt.id;+ return (+ <button+ key={opt.id}+ type="button"+ role="radio"+ aria-checked={active}+ onClick={() => onChange(opt.id)}+ className={clsx(+ 'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',+ active+ ? 'border border-mint/30 bg-mint-soft font-bold text-mint'+ : 'font-medium text-muted hover:text-foreground'+ )}+ >+ {opt.label}+ </button>+ );+ })}+ </div>+);++export const SettingsClaudeProviderPage: React.FC = () => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();++ // Runtime state — CLI detection + lifecycle.+ const [loaded, setLoaded] = useState(false);+ const [enabled, setEnabled] = useState(true);+ const [cliPath, setCliPath] = useState(DEFAULT_CLI);+ const [savedCliPath, setSavedCliPath] = useState(DEFAULT_CLI);+ const [cliStatus, setCliStatus] = useState<CliStatus>('unknown');+ const [detecting, setDetecting] = useState(false);+ const [installing, setInstalling] = useState(false);+ const [installResult, setInstallResult] = useState<{+ ok: boolean;+ message: string;+ output?: string | null;+ } | null>(null);+ const [installOutputOpen, setInstallOutputOpen] = useState(false);+ const [savingRuntime, setSavingRuntime] = useState(false);++ // Auth state — OAuth vs API-key.+ const [authState, setAuthState] = useState<ClaudeAuthState | null>(null);+ const [authLoading, setAuthLoading] = useState(true);+ const [authSaving, setAuthSaving] = useState(false);+ const [authMode, setAuthMode] = useState<ClaudeAuthMode>('oauth');+ const [apiKey, setApiKey] = useState('');+ const [baseUrl, setBaseUrl] = useState('');++ useEffect(() => {+ let cancelled = false;++ // Load runtime config (enabled + cli_path) and kick off CLI detect.+ api+ .getConfig()+ .then((config) => {+ if (cancelled) return;+ const agent = config?.agents?.[BACKEND_ID];+ const initialEnabled = typeof agent?.enabled === 'boolean' ? agent.enabled : true;+ const initialPath = agent?.cli_path || DEFAULT_CLI;+ setEnabled(initialEnabled);+ setCliPath(initialPath);+ setSavedCliPath(initialPath);+ setLoaded(true);+ void detect(initialPath);+ })+ .catch(() => {+ if (!cancelled) setLoaded(true);+ });++ // Load auth state in parallel — independent of CLI detection.+ api+ .getClaudeAuth()+ .then((data) => {+ if (cancelled) return;+ setAuthState(data);+ setAuthMode(data.auth_mode);+ setBaseUrl(data.base_url || '');+ // Never preload api_key; only its length is returned. Empty input+ // means "keep whatever is stored" on save.+ setApiKey('');+ })+ .catch(() => {+ // ApiContext already toasted; leave the page on its defaults.+ })+ .finally(() => {+ if (!cancelled) setAuthLoading(false);+ });++ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [api]);++ const detect = async (binary?: string) => {+ setDetecting(true);+ try {+ const result = await api.detectCli(binary || cliPath || DEFAULT_CLI);+ const nextPath = result.path || cliPath || DEFAULT_CLI;+ setCliPath(nextPath);+ setCliStatus(result.found ? 'ok' : 'missing');+ } catch (e: any) {+ setCliStatus('missing');+ showToast(e?.message || t('common.saveFailed'), 'error');+ } finally {+ setDetecting(false);+ }+ };++ const install = async () => {+ setInstalling(true);+ setInstallResult(null);+ setInstallOutputOpen(false);+ try {+ const result = await api.installAgent(BACKEND_ID);+ const installedPath = typeof result.path === 'string' && result.path ? result.path : null;+ setInstallResult({ ok: result.ok, message: result.message, output: result.output });+ if (result.ok) {+ if (installedPath) setCliPath(installedPath);+ await detect(installedPath || cliPath);+ showToast(result.message || t('agentDetection.installAgent'), 'success');+ } else {+ showToast(result.message || t('common.saveFailed'), 'error');+ }+ } catch (e: any) {+ setInstallResult({ ok: false, message: String(e), output: null });+ showToast(e?.message || String(e), 'error');+ } finally {+ setInstalling(false);+ }+ };++ const onSaveRuntime = async () => {+ setSavingRuntime(true);+ try {+ const config = await api.getConfig();+ const nextAgents = {+ ...(config?.agents || {}),+ [BACKEND_ID]: {+ ...(config?.agents?.[BACKEND_ID] || {}),+ enabled,+ cli_path: cliPath || DEFAULT_CLI,+ },+ };+ const defaultBackend =+ config?.default_backend || config?.agents?.default_backend || 'opencode';+ await api.saveConfig({ agents: { ...nextAgents, default_backend: defaultBackend } });+ setSavedCliPath(cliPath);+ showToast(t('common.saved'), 'success');+ } catch (e: any) {+ showToast(e?.message || t('common.saveFailed'), 'error');+ } finally {+ setSavingRuntime(false);+ }+ };++ 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 onSaveAuth = async () => {+ setAuthSaving(true);+ try {+ const payload = {+ auth_mode: authMode,+ api_key: authMode === 'api_key' ? (apiKey || undefined) : null,+ base_url: baseUrl.trim() || null,+ };+ const result = await api.saveClaudeAuth(payload);+ if (result.ok === false) {+ showToast(result.message || t('settings.backends.claudeSaveFailed'), 'error');+ return;+ }+ setAuthState(result);+ setAuthMode(result.auth_mode);+ setBaseUrl(result.base_url || '');+ setApiKey('');+ // 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);+ }+ };++ const runtimeDirty = cliPath !== savedCliPath;++ return (+ <SettingsPageShell+ activeTab="backends"+ title={t('settings.backends.claudeTitle')}+ subtitle={t('settings.backends.claudeSubtitle')}+ breadcrumb={+ <Link to="/settings/backends" className="inline-flex items-center gap-1.5 hover:text-foreground">+ <ArrowLeft className="size-3" />+ {t('settings.backends.codexBackToBackends')}+ </Link>+ }+ >+ {!loaded ? (+ <div className="text-sm text-muted">{t('common.loading')}</div>+ ) : (+ <div className="flex flex-col gap-4">+ <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">+ <Sparkles size={22} className="text-cyan" />+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-[15px] font-semibold text-foreground">Claude Code</span>+ <span className="text-[12px] text-muted">+ {t('settings.backends.claudeDescription')}+ </span>+ </div>+ </div>+ <div className="flex items-center gap-3">+ <BackendLifecycleChip+ name={BACKEND_ID}+ enabled={enabled}+ cliStatus={cliStatus}+ onChanged={async (info) => {+ const installedPath = info?.installedPath || null;+ if (installedPath) setCliPath(installedPath);+ await detect(installedPath || cliPath);+ }}+ />+ <ToggleSwitch+ enabled={enabled}+ onClick={() => {+ const next = !enabled;+ setEnabled(next);+ void (async () => {+ try {+ const config = await api.getConfig();+ const nextAgents = {+ ...(config?.agents || {}),+ [BACKEND_ID]: {+ ...(config?.agents?.[BACKEND_ID] || {}),+ enabled: next,+ },+ };+ const defaultBackend =+ config?.default_backend ||+ config?.agents?.default_backend ||+ 'opencode';+ await api.saveConfig({+ agents: { ...nextAgents, default_backend: defaultBackend },+ });+ } catch (e: any) {+ showToast(e?.message || t('common.saveFailed'), 'error');+ setEnabled(!next);+ }+ })();+ }}+ />+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <Label htmlFor="claude-cli-path" className="text-xs font-medium uppercase text-muted">+ {t('agentDetection.cliPath')}+ </Label>+ <div className="flex gap-2">+ <Input+ id="claude-cli-path"+ type="text"+ autoComplete="off"+ spellCheck={false}+ placeholder={t('agentDetection.cliPathPlaceholder', { name: BACKEND_ID }) as string}+ value={cliPath}+ onChange={(e) => setCliPath(e.target.value)}+ className="font-mono"+ />+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => void detect(cliPath)}+ disabled={detecting}+ >+ {detecting ? <RefreshCw className="size-3.5 animate-spin" /> : <Search className="size-3.5" />}+ {t('common.detect')}+ </Button>+ </div>+ <p className="text-[12px] text-muted">{t('settings.backends.cliPathHint')}</p>+ </div>++ {cliStatus === 'missing' && (+ <div className="space-y-2 rounded-lg border border-cyan/30 bg-cyan/[0.06] px-3 py-2.5">+ <p className="text-[12px] text-cyan">{t('agentDetection.installHint')}</p>+ <div className="flex flex-wrap items-center gap-3">+ <Button+ variant="brand-cyan"+ size="xs"+ onClick={() => void install()}+ disabled={installing}+ >+ {installing ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Download className="size-3.5" />+ )}+ {installing ? t('agentDetection.installing') : t('agentDetection.installAgent')}+ </Button>+ {installResult?.message && (+ <span+ className={clsx(+ 'text-[12px]',+ installResult.ok ? 'text-mint' : 'text-destructive'+ )}+ >+ {installResult.message}+ </span>+ )}+ </div>+ {installResult?.output && (+ <div>+ <button+ type="button"+ onClick={() => setInstallOutputOpen((v) => !v)}+ className="inline-flex items-center gap-1 text-[11px] text-cyan transition hover:text-cyan/80"+ >+ {installOutputOpen ? <ChevronUp size={12} /> : <ChevronDown size={12} />}+ {t('agentDetection.showOutput')}+ </button>+ {installOutputOpen && (+ <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">+ {installResult.output}+ </pre>+ )}+ </div>+ )}+ </div>+ )}++ {runtimeDirty && (+ <div className="flex justify-end">+ <Button+ variant="brand"+ size="default"+ onClick={() => void onSaveRuntime()}+ disabled={savingRuntime}+ >+ <Save className="size-3.5" />+ {savingRuntime ? t('common.saving') : t('common.save')}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>++ {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">+ <Label className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.claudeAuthModeLabel')}+ </Label>+ <SegmentedRadio+ value={authMode}+ onChange={setAuthMode}+ options={modeOptions}+ ariaLabel={t('settings.backends.claudeAuthModeLabel') as string}+ />+ <p className="text-[12px] leading-relaxed text-muted">+ {authMode === 'api_key'+ ? t('settings.backends.claudeAuthModeApiKeyHint')+ : t('settings.backends.claudeAuthModeOauthHint')}+ </p>+ </div>++ {authMode === 'oauth' && (+ <div className="flex items-start gap-2 rounded-lg border border-mint/30 bg-mint-soft/40 px-3 py-2.5">+ <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-mint" />+ <div className="flex flex-col gap-1">+ <p className="text-[12px] font-medium text-mint">+ {t('settings.backends.claudeOauthSignedIn')}+ </p>+ <p className="text-[12px] leading-relaxed text-muted">+ {t('settings.backends.claudeOauthHint')}+ </p>+ </div>+ </div>+ )}++ {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>+ <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}+ />+ </div>+ <p className="text-[12px] text-muted">{apiKeyStatus}</p>+ </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>++ {authState?.settings_conflict && (+ // Claude Code applies its own ``env`` block on top of inherited+ // env, so a hand-edited ``settings.json`` will override the+ // V2Config-injected key at launch. Warn loudly — silently+ // letting a saved key be ignored is the worst outcome.+ <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>+ )}++ <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>++ <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>+ )}+ </div>+ )}+ </SettingsPageShell>+ );+};diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsxnew file mode 100644index 000000000..398ce4c07--- /dev/null+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx@@ -0,0 +1,1228 @@+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Link } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import {+ AlertCircle,+ ArrowLeft,+ Check,+ ChevronDown,+ ChevronUp,+ Cpu,+ Download,+ Info,+ KeyRound,+ 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 { SettingsPageShell } from './SettingsPageShell';+import { BackendLifecycleChip } from './BackendLifecycleChip';+import { ToggleSwitch } from './SettingsPrimitives';+import { useApi } from '@/context/ApiContext';+import type { OpencodeProvider } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++type CliStatus = 'unknown' | 'ok' | 'missing';+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;+};++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,+});++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 SettingsOpencodeProviderPage: React.FC = () => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();++ // Runtime state (mirrors Claude / Codex page conventions).+ const [loaded, setLoaded] = useState(false);+ const [enabled, setEnabled] = useState(true);+ const [cliPath, setCliPath] = useState(DEFAULT_CLI);+ const [savedCliPath, setSavedCliPath] = useState(DEFAULT_CLI);+ const [cliStatus, setCliStatus] = useState<CliStatus>('unknown');+ const [detecting, setDetecting] = useState(false);+ const [installing, setInstalling] = useState(false);+ const [installResult, setInstallResult] = useState<{+ ok: boolean;+ message: string;+ output?: string | null;+ } | null>(null);+ const [installOutputOpen, setInstallOutputOpen] = useState(false);+ const [permissionState, setPermissionState] = useState<PermissionState>('idle');+ const [permissionMessage, setPermissionMessage] = useState('');+ const [savingRuntime, setSavingRuntime] = useState(false);++ // 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);++ // 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 detect = useCallback(+ async (binary?: string) => {+ setDetecting(true);+ try {+ const result = await api.detectCli(binary || cliPath || DEFAULT_CLI);+ const nextPath = result.path || cliPath || DEFAULT_CLI;+ setCliPath(nextPath);+ setCliStatus(result.found ? 'ok' : 'missing');+ } catch (e: any) {+ setCliStatus('missing');+ showToast(e?.message || t('common.saveFailed'), 'error');+ } finally {+ setDetecting(false);+ }+ },+ [api, cliPath, showToast, t]+ );++ 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);+ 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]);++ useEffect(() => {+ let cancelled = false;+ api+ .getConfig()+ .then((config) => {+ if (cancelled) return;+ const agent = config?.agents?.[BACKEND_ID];+ const initialEnabled = typeof agent?.enabled === 'boolean' ? agent.enabled : true;+ const initialPath = agent?.cli_path || DEFAULT_CLI;+ setEnabled(initialEnabled);+ setCliPath(initialPath);+ setSavedCliPath(initialPath);+ setLoaded(true);+ void detect(initialPath);+ if (initialEnabled) {+ void loadProviders();+ }+ })+ .catch(() => {+ if (!cancelled) setLoaded(true);+ });+ return () => {+ cancelled = true;+ if (retryTimerRef.current) clearTimeout(retryTimerRef.current);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [api]);++ // 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 (!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;+ }+ };+ }, [enabled, providersError, providersLoading, serverStartAttempts]);++ const install = async () => {+ setInstalling(true);+ setInstallResult(null);+ setInstallOutputOpen(false);+ try {+ const result = await api.installAgent(BACKEND_ID);+ const installedPath = typeof result.path === 'string' && result.path ? result.path : null;+ setInstallResult({ ok: result.ok, message: result.message, output: result.output });+ if (result.ok) {+ if (installedPath) setCliPath(installedPath);+ await detect(installedPath || cliPath);+ showToast(result.message || t('agentDetection.installAgent'), 'success');+ } else {+ showToast(result.message || t('common.saveFailed'), 'error');+ }+ } catch (e: any) {+ setInstallResult({ ok: false, message: String(e), output: null });+ showToast(e?.message || String(e), 'error');+ } finally {+ setInstalling(false);+ }+ };++ 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');+ } catch (e: any) {+ setPermissionState('error');+ const msg = e?.message || String(e);+ setPermissionMessage(msg);+ showToast(msg, 'error');+ }+ };++ const onSaveRuntime = async () => {+ setSavingRuntime(true);+ try {+ const config = await api.getConfig();+ const nextAgents = {+ ...(config?.agents || {}),+ [BACKEND_ID]: {+ ...(config?.agents?.[BACKEND_ID] || {}),+ enabled,+ cli_path: cliPath || DEFAULT_CLI,+ },+ };+ const defaultBackend =+ config?.default_backend || config?.agents?.default_backend || BACKEND_ID;+ await api.saveConfig({ agents: { ...nextAgents, default_backend: defaultBackend } });+ setSavedCliPath(cliPath);+ showToast(t('common.saved'), 'success');+ } catch (e: any) {+ showToast(e?.message || t('common.saveFailed'), 'error');+ } finally {+ setSavingRuntime(false);+ }+ };++ const toggleEnabled = () => {+ const next = !enabled;+ setEnabled(next);+ void (async () => {+ try {+ const config = await api.getConfig();+ const nextAgents = {+ ...(config?.agents || {}),+ [BACKEND_ID]: {+ ...(config?.agents?.[BACKEND_ID] || {}),+ enabled: next,+ },+ };+ const defaultBackend =+ config?.default_backend || config?.agents?.default_backend || BACKEND_ID;+ await api.saveConfig({+ agents: { ...nextAgents, default_backend: defaultBackend },+ });+ if (next) {+ setServerStartAttempts(0);+ void loadProviders();+ } else {+ setProviders(null);+ setProvidersError(null);+ }+ } catch (e: any) {+ showToast(e?.message || t('common.saveFailed'), 'error');+ setEnabled(!next);+ }+ })();+ };++ // ---- Expansion / per-provider editing ----++ const openProvider = (provider: OpencodeProvider) => {+ setExpandedId(provider.id);+ setEditByProvider((prev) => {+ if (prev[provider.id]) return prev;+ return { ...prev, [provider.id]: emptyEdit() };+ });+ };++ 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();+ if (!key) {+ updateEdit(provider.id, {+ error: t('settings.backends.opencodeProviderApiKeyRequired') as string,+ });+ return;+ }+ updateEdit(provider.id, { saving: true, error: null });+ try {+ const result = await api.setOpencodeProviderAuth(provider.id, key);+ if (!result.ok) {+ updateEdit(provider.id, {+ saving: false,+ error: result.message || (t('settings.backends.opencodeProviderSaveFailed') as string),+ });+ return;+ }+ updateEdit(provider.id, { saving: false, apiKey: '', 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) => {+ const confirmed = window.confirm(+ t('settings.backends.opencodeProviderRemoveConfirm', { 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 runtimeDirty = cliPath !== savedCliPath;++ 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) {+ return (+ <Badge variant="success" className="gap-1">+ <Check className="size-3" />+ {t('settings.backends.opencodeBadgeConfigured')}+ </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+ activeTab="backends"+ title={t('settings.backends.opencodeTitle')}+ subtitle={t('settings.backends.opencodeSubtitle')}+ breadcrumb={+ <Link to="/settings/backends" className="inline-flex items-center gap-1.5 hover:text-foreground">+ <ArrowLeft className="size-3" />+ {t('settings.backends.codexBackToBackends')}+ </Link>+ }+ >+ {!loaded ? (+ <div className="text-sm text-muted">{t('common.loading')}</div>+ ) : (+ <div className="flex flex-col gap-4">+ {/* Card 1 — runtime / lifecycle. Mirrors Claude page shape. */}+ <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-violet-soft">+ <Terminal size={22} className="text-violet" />+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-[15px] font-semibold text-foreground">OpenCode</span>+ <span className="text-[12px] text-muted">+ {t('settings.backends.opencodeDescription')}+ </span>+ </div>+ </div>+ <div className="flex items-center gap-3">+ <BackendLifecycleChip+ name={BACKEND_ID}+ enabled={enabled}+ cliStatus={cliStatus}+ onChanged={async (info) => {+ const installedPath = info?.installedPath || null;+ if (installedPath) setCliPath(installedPath);+ await detect(installedPath || cliPath);+ }}+ />+ <ToggleSwitch enabled={enabled} onClick={toggleEnabled} />+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <Label htmlFor="opencode-cli-path" className="text-xs font-medium uppercase text-muted">+ {t('agentDetection.cliPath')}+ </Label>+ <div className="flex gap-2">+ <Input+ id="opencode-cli-path"+ type="text"+ autoComplete="off"+ spellCheck={false}+ placeholder={t('agentDetection.cliPathPlaceholder', { name: BACKEND_ID }) as string}+ value={cliPath}+ onChange={(e) => setCliPath(e.target.value)}+ className="font-mono"+ />+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => void detect(cliPath)}+ disabled={detecting}+ >+ {detecting ? <RefreshCw className="size-3.5 animate-spin" /> : <Search className="size-3.5" />}+ {t('common.detect')}+ </Button>+ </div>+ <p className="text-[12px] text-muted">{t('settings.backends.cliPathHint')}</p>+ </div>++ {cliStatus === 'missing' && (+ <div className="space-y-2 rounded-lg border border-cyan/30 bg-cyan/[0.06] px-3 py-2.5">+ <p className="text-[12px] text-cyan">{t('agentDetection.installHint')}</p>+ <div className="flex flex-wrap items-center gap-3">+ <Button+ variant="brand-cyan"+ size="xs"+ onClick={() => void install()}+ disabled={installing}+ >+ {installing ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Download className="size-3.5" />+ )}+ {installing ? t('agentDetection.installing') : t('agentDetection.installAgent')}+ </Button>+ {installResult?.message && (+ <span+ className={clsx(+ 'text-[12px]',+ installResult.ok ? 'text-mint' : 'text-destructive'+ )}+ >+ {installResult.message}+ </span>+ )}+ </div>+ {installResult?.output && (+ <div>+ <button+ type="button"+ onClick={() => setInstallOutputOpen((v) => !v)}+ className="inline-flex items-center gap-1 text-[11px] text-cyan transition hover:text-cyan/80"+ >+ {installOutputOpen ? <ChevronUp size={12} /> : <ChevronDown size={12} />}+ {t('agentDetection.showOutput')}+ </button>+ {installOutputOpen && (+ <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">+ {installResult.output}+ </pre>+ )}+ </div>+ )}+ </div>+ )}++ {cliStatus === 'ok' && (+ <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.permissionHint')}</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>+ )}++ {runtimeDirty && (+ <div className="flex justify-end">+ <Button+ variant="brand"+ size="default"+ onClick={() => void onSaveRuntime()}+ disabled={savingRuntime}+ >+ <Save className="size-3.5" />+ {savingRuntime ? t('common.saving') : t('common.save')}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>++ {/* 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>+ {enabled && providers && (+ <Badge variant={providersError ? 'warning' : 'success'}>+ {providersError+ ? t('settings.backends.opencodeServerStopped')+ : t('settings.backends.opencodeServerRunning')}+ </Badge>+ )}+ {!enabled && (+ <Badge variant="secondary">+ {t('settings.backends.opencodeBackendDisabled')}+ </Badge>+ )}+ {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={!enabled || providersLoading}+ >+ <RefreshCw+ className={clsx('size-3.5', providersLoading && 'animate-spin')}+ />+ {t('settings.backends.opencodeRefresh')}+ </Button>+ </div>+ </div>++ {!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>+ )}++ {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" />+ )}+ {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 && (+ <div className="rounded-md border border-cyan/30 bg-cyan/[0.06] px-3 py-2">+ <p className="text-[11px] font-medium text-cyan">+ {t('settings.backends.opencodeProviderOauthAvailable')}+ </p>+ <p className="text-[11px] leading-relaxed text-muted">+ {t('settings.backends.opencodeProviderOauthHint', {+ id: provider.id,+ })}+ </p>+ </div>+ )}++ <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>+ <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}+ />+ </div>+ <p className="text-[11px] text-muted">+ {provider.configured+ ? t('settings.backends.opencodeProviderApiKeyStored')+ : t('settings.backends.opencodeProviderApiKeyMissing')}+ </p>+ </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>+ )}++ <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>+ </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>+ )}+ </SettingsPageShell>+ );+};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex d875e3bd9..6b2e2fe91 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -23,6 +23,12 @@ export type ApiContextType = {restartBackend: (name: string) => Promise<BackendRestartResult>;getCodexAuth: () => Promise<CodexAuthState>;saveCodexAuth: (payload: CodexAuthPayload) => Promise<CodexAuthSaveResult>;+ getClaudeAuth: () => Promise<ClaudeAuthState>;+ saveClaudeAuth: (payload: ClaudeAuthPayload) => Promise<ClaudeAuthSaveResult>;+ getOpencodeProviders: () => Promise<OpencodeProviderListResult>;+ setOpencodeProviderAuth: (providerId: string, apiKey: string) => Promise<OpencodeMutationResult>;+ deleteOpencodeProviderAuth: (providerId: string) => Promise<OpencodeMutationResult>;+ setOpencodeDefaultProvider: (providerId: string) => Promise<OpencodeMutationResult>;slackAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;slackChannels: (botToken: string, browseAll?: boolean) => Promise<any>;slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;@@ -150,6 +156,69 @@ export type CodexAuthSaveResult = CodexAuthState & {restart?: BackendRestartResult;};+export type ClaudeAuthMode = 'oauth' | 'api_key';++// Claude's auth surface differs structurally from Codex: V2Config is the+// sole writer (no disk-side ``apply_claude_auth``) and the CLI inherits+// env vars per request rather than via a persistent daemon. We still+// inspect ``~/.claude/settings.json`` so the UI can warn when a+// hand-edited ``env`` block would override the V2Config-injected key at+// launch (Claude Code layers settings.json env on top of inherited env).+export type ClaudeAuthState = {+ ok: boolean;+ auth_mode: ClaudeAuthMode;+ has_api_key: boolean;+ api_key_length: number;+ base_url: string | null;+ settings_path: string | null;+ settings_exists: boolean;+ settings_env_has_key: boolean;+ settings_env_key_length: number;+ settings_env_key_var: 'ANTHROPIC_API_KEY' | 'ANTHROPIC_AUTH_TOKEN' | null;+ settings_env_base_url: string | null;+ settings_conflict: boolean;+ message?: string;+};++export type ClaudeAuthPayload = {+ auth_mode: ClaudeAuthMode;+ api_key?: string | null;+ base_url?: string | null;+};++export type ClaudeAuthSaveResult = ClaudeAuthState & {+ restart?: BackendRestartResult;+};++// One entry in the OpenCode provider grid. The full catalog is built+// dynamically on the server by merging ``/provider`` + ``/provider/auth``+// + ``/config/providers`` — there is **no** hard-coded list in the UI.+// ``local`` is inferred from the absence of network auth methods (Ollama,+// LM Studio); the page renders its own "Local" badge for those rows.+export type OpencodeProvider = {+ id: string;+ name: string;+ description: string;+ configured: boolean;+ oauth_available: boolean;+ local: boolean;+ models: string[];+ default_model: string | null;+};++export type OpencodeProviderListResult = {+ ok: boolean;+ message?: string;+ providers?: OpencodeProvider[];+ default_provider?: string;+};++export type OpencodeMutationResult = {+ ok: boolean;+ message?: string;+ default_provider?: string;+};+const ApiContext = createContext<ApiContextType | undefined>(undefined);export const useApi = () => {@@ -210,6 +279,19 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenreturn res.json();};+ // DELETE wrapper that routes 4xx/5xx through ``handleApiError`` so the+ // global toast and console-error surface stay consistent with+ // ``getJson``/``postJson``. Legacy callers (removeUser, deleteBindCode)+ // still call ``apiFetch().then(r => r.json())`` directly — that's a+ // separate cleanup; new endpoints should use this helper.+ const deleteJson = async (path: string) => {+ const res = await apiFetch(path, { method: 'DELETE' });+ if (!res.ok) {+ await handleApiError(res, path);+ }+ return res.json();+ };+const value: ApiContextType = {getConfig: () => getJson('/config'),getPlatformCatalog: () => getJson('/platforms'),@@ -230,6 +312,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenrestartBackend: (name) => postJson(`/backend/${encodeURIComponent(name)}/restart`, {}),getCodexAuth: () => getJson('/backend/codex/auth'),saveCodexAuth: (payload) => postJson('/backend/codex/auth', payload),+ getClaudeAuth: () => getJson('/backend/claude/auth'),+ saveClaudeAuth: (payload) => postJson('/backend/claude/auth', payload),+ getOpencodeProviders: () => getJson('/backend/opencode/providers'),+ setOpencodeProviderAuth: (providerId, apiKey) =>+ postJson(`/backend/opencode/provider/${encodeURIComponent(providerId)}/auth`, { api_key: apiKey }),+ deleteOpencodeProviderAuth: (providerId) =>+ deleteJson(`/backend/opencode/provider/${encodeURIComponent(providerId)}/auth`),+ setOpencodeDefaultProvider: (providerId) =>+ postJson('/backend/opencode/default-provider', { provider_id: providerId }),slackAuthTest: (botToken, proxyUrl) => postJson('/slack/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),slackChannels: (botToken, browseAll) => postJson('/slack/channels', { bot_token: botToken, browse_all: browseAll || false }),slackManifest: () => getJson('/slack/manifest'),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex e252133eb..66c3fa081 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -88,6 +88,19 @@"backendsTitle": "Backends","backendsSubtitle": "Manage agent backends, default routing, and local CLI availability.","backends": {+ "routingTitle": "Default routing",+ "routingHint": "Pick the backend that powers new conversations by default. Per-group overrides are configured on the Groups page.",+ "defaultLabel": "Default",+ "defaultBadge": "Default",+ "configure": "Configure",+ "cliPathHint": "Vibe Remote runs this command for every request. Use an absolute path if the binary is not on $PATH.",+ "opencodeTitle": "OpenCode provider",+ "opencodeSubtitle": "Detect or install the OpenCode CLI and apply the permission profile that lets it skip approval prompts.",+ "opencodeDescription": "Multi-provider open agent · CLI binary detection + permission profile",+ "claudeTitle": "Claude Code provider",+ "claudeSubtitle": "Detect or install the Claude Code CLI. Sign in or supply an API key from the CLI itself.",+ "claudeDescription": "Anthropic agent · sign in with Claude or supply an API key",+ "codexDescription": "OpenAI agent · ChatGPT login or OPENAI_API_KEY","openProviderPage": "Configure provider","providerOauth": "OAuth (default)","providerApiKey": "API key",@@ -113,7 +126,86 @@"codexSave": "Save and restart Codex","codexSaving": "Saving…","codexSaveSuccess": "Codex auth saved",- "codexSaveFailed": "Could not save Codex auth"+ "codexSaveFailed": "Could not save Codex auth",+ "claudeAuthModeLabel": "Authentication mode",+ "claudeAuthModeOauth": "Sign in with Claude",+ "claudeAuthModeOauthHint": "Run `claude login` in a terminal to sign in with your Anthropic account. Vibe Remote will inherit those tokens automatically and stop managing the API key.",+ "claudeAuthModeApiKey": "Anthropic API key",+ "claudeAuthModeApiKeyHint": "Vibe Remote injects this key into Claude Code via `ANTHROPIC_API_KEY` at launch. Switch to Claude sign-in if you prefer not to manage a key here.",+ "claudeOauthSignedIn": "Using Claude account sign-in",+ "claudeOauthHint": "Claude Code reads its OAuth tokens directly from its own keychain. No API key is needed unless you want to override that route.",+ "claudeApiKeyLabel": "API key",+ "claudeApiKeyPlaceholder": "sk-ant-...",+ "claudeApiKeyConfigured": "A key of length {{length}} is currently stored.",+ "claudeApiKeyMissing": "No API key stored yet.",+ "claudeBaseUrlLabel": "Base URL (optional)",+ "claudeBaseUrlPlaceholder": "https://api.anthropic.com",+ "claudeBaseUrlHint": "Leave empty to use Anthropic's default endpoint. Compatible relays (e.g. Bedrock proxies, AWS endpoints) accept their own URL here.",+ "claudeBaseUrlReset": "Reset to default",+ "claudeSettingsConflictTitle": "Claude settings.json overrides this key",+ "claudeSettingsConflictBody": "Claude Code layers `env` blocks from {{path}} on top of inherited environment variables. The `{{var}}` value in that file will win at launch unless you remove or update it.",+ "claudeInfoHint": "Saving here writes the key into Vibe Remote's V2 config so Claude Code receives it as `ANTHROPIC_API_KEY` (or `ANTHROPIC_AUTH_TOKEN`) on the next request. Claude restarts per request, so no daemon restart is needed.",+ "claudeSave": "Save Claude auth",+ "claudeSaving": "Saving…",+ "claudeSaveSuccess": "Claude auth saved",+ "claudeSaveFailed": "Could not save Claude auth",+ "opencodeProvidersTitle": "Providers",+ "opencodeProvidersSubtitle": "Lazy-loaded from the OpenCode server · auth handled via API key or `opencode auth login`",+ "opencodeProvidersCount": "{{configured}}/{{total}} configured",+ "opencodeServerRunning": "Server reachable",+ "opencodeServerStopped": "Server unavailable",+ "opencodeServerStarting": "Server starting…",+ "opencodeServerUnreachable": "Server not reachable",+ "opencodeServerRetryCount": "Retry {{attempt}}/{{max}}",+ "opencodeBackendDisabled": "Backend disabled",+ "opencodeDisabledBanner": "Enable OpenCode in the header to manage providers. The auth-mode toggle is the only interactive control while the backend is off.",+ "opencodeRefresh": "Refresh",+ "opencodeSearchPlaceholder": "Search providers, models, IDs…",+ "opencodeFilterAll": "All",+ "opencodeFilterConfigured": "Configured",+ "opencodeFilterOauth": "OAuth available",+ "opencodeFilterLocal": "Local",+ "opencodeBadgeConfigured": "Configured",+ "opencodeBadgeOauth": "OAuth available",+ "opencodeBadgeLocal": "Local",+ "opencodeBadgeUnset": "Not set",+ "opencodeDefaultBadge": "Default",+ "opencodeDefaultLabel": "Default provider",+ "opencodeDefaultUnset": "Unset",+ "opencodeDefaultPopoverTitle": "Pick the default provider",+ "opencodeDefaultPopoverEmpty": "No providers match that search.",+ "opencodeDefaultNeedsKey": "{{name}} has no API key yet — set one to make it the default.",+ "opencodeDefaultSaved": "{{name}} is now the default provider.",+ "opencodeDefaultSaveFailed": "Could not change the default provider.",+ "opencodeProvidersLoading": "Loading providers from OpenCode…",+ "opencodeProvidersEmpty": "OpenCode returned no providers. Run `opencode auth list` from a terminal to diagnose.",+ "opencodeProvidersFilterEmpty": "No providers match the current search or filter.",+ "opencodeProvidersError": "Could not load the OpenCode provider catalog.",+ "opencodeProvidersInfo": "Provider data is fetched live from the OpenCode server. Saving an API key writes to `~/.local/share/opencode/auth.json` via the server's `/auth` endpoint.",+ "opencodeProviderModelsCount": "{{count}} models",+ "opencodeProviderModelsEmpty": "No models reported by this provider.",+ "opencodeProviderModels": "Models",+ "opencodeProviderDefaultModel": "Default",+ "opencodeProviderApiKey": "API key",+ "opencodeProviderApiKeyPlaceholder": "Paste the provider's API key",+ "opencodeProviderApiKeyPlaceholderStored": "Enter a new key to replace the stored one",+ "opencodeProviderApiKeyStored": "A key is currently stored on disk.",+ "opencodeProviderApiKeyMissing": "No API key stored for this provider yet.",+ "opencodeProviderApiKeyRequired": "Enter the provider's API key before saving.",+ "opencodeProviderBaseUrl": "Base URL (optional)",+ "opencodeProviderBaseUrlPlaceholder": "https://provider.example.com/v1",+ "opencodeProviderBaseUrlHint": "Provider-level overrides go in `~/.config/opencode/opencode.json`. Leave empty to use the provider's default.",+ "opencodeProviderOauthAvailable": "OAuth login available",+ "opencodeProviderOauthHint": "You can also run `opencode auth login {{id}}` in a terminal to authenticate without storing a key here.",+ "opencodeProviderLocalHint": "Local providers do not need credentials — start the runtime and load a model.",+ "opencodeProviderSave": "Save key",+ "opencodeProviderSaved": "Provider credentials saved.",+ "opencodeProviderSaveFailed": "Could not save provider credentials.",+ "opencodeProviderRemove": "Remove key",+ "opencodeProviderRemoveConfirm": "Remove the saved key for {{name}}?",+ "opencodeProviderRemoved": "Provider credentials removed.",+ "opencodeProviderRemoveFailed": "Could not remove provider credentials.",+ "opencodeProviderCollapse": "Collapse"},"messagingTitle": "Messaging","messagingSubtitle": "Tune global reply behavior, acknowledgements, and message visibility defaults.",@@ -553,13 +645,13 @@"statusReady": "Ready","statusUpdating": "Updating","statusDisabled": "Disabled",- "statusError": "Not running",+ "statusError": "Not installed","statusUpdateAvailable": "Update available","currentVersion": "Current version","latestVersion": "Latest version","readyHint": "Running the latest release.","updateHint": "Update available: {{from}} → {{to}}",- "errorHint": "{{name}} is not running. Try restarting or reinstalling.",+ "errorHint": "{{name}} CLI is not installed. Install it from this card to enable the backend.","disabledHint": "Toggle this backend on in the card header to activate.","upgrading": "Upgrading…","upgradeNow": "Upgrade",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1f344cb65..0b6aeb2cb 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -88,6 +88,19 @@"backendsTitle": "后端","backendsSubtitle": "管理 agent 后端、默认路由和本地 CLI 可用性。","backends": {+ "routingTitle": "默认路由",+ "routingHint": "选择默认承载新会话的后端。每个群组的覆盖项在「群组」页配置。",+ "defaultLabel": "默认",+ "defaultBadge": "默认",+ "configure": "配置",+ "cliPathHint": "Vibe Remote 会用该命令执行每次请求。如果二进制不在 $PATH 中,请填写绝对路径。",+ "opencodeTitle": "OpenCode Provider",+ "opencodeSubtitle": "检测或安装 OpenCode CLI,并应用允许跳过审批的权限配置。",+ "opencodeDescription": "多 Provider 开放 Agent · CLI 检测 + 权限配置",+ "claudeTitle": "Claude Code Provider",+ "claudeSubtitle": "检测或安装 Claude Code CLI。登录与 API Key 请直接通过 CLI 完成。",+ "claudeDescription": "Anthropic Agent · 通过 Claude 登录或填入 API Key",+ "codexDescription": "OpenAI Agent · 通过 ChatGPT 登录或 OPENAI_API_KEY","openProviderPage": "配置 Provider","providerOauth": "OAuth(默认)","providerApiKey": "API Key",@@ -113,7 +126,86 @@"codexSave": "保存并重启 Codex","codexSaving": "保存中…","codexSaveSuccess": "Codex 认证已保存",- "codexSaveFailed": "保存 Codex 认证失败"+ "codexSaveFailed": "保存 Codex 认证失败",+ "claudeAuthModeLabel": "认证方式",+ "claudeAuthModeOauth": "Claude 账号登录",+ "claudeAuthModeOauthHint": "在终端运行 `claude login` 完成 Anthropic 账号登录。Vibe Remote 会自动复用这些令牌,并停止管理 API Key。",+ "claudeAuthModeApiKey": "Anthropic API Key",+ "claudeAuthModeApiKeyHint": "Vibe Remote 会在每次启动 Claude Code 时通过 `ANTHROPIC_API_KEY` 注入下方的 Key。若不想在此处管理 Key,可切换到 Claude 账号登录。",+ "claudeOauthSignedIn": "使用 Claude 账号登录",+ "claudeOauthHint": "Claude Code 会从自带的钥匙串里读取 OAuth 令牌。除非你想覆盖这条链路,否则无需再单独提供 API Key。",+ "claudeApiKeyLabel": "API Key",+ "claudeApiKeyPlaceholder": "sk-ant-...",+ "claudeApiKeyConfigured": "当前已保存一份长度为 {{length}} 的 Key。",+ "claudeApiKeyMissing": "尚未保存 API Key。",+ "claudeBaseUrlLabel": "Base URL(可选)",+ "claudeBaseUrlPlaceholder": "https://api.anthropic.com",+ "claudeBaseUrlHint": "留空则使用 Anthropic 默认地址;兼容中转(如 Bedrock 代理、AWS Endpoint)可在此填写自定义地址。",+ "claudeBaseUrlReset": "恢复默认",+ "claudeSettingsConflictTitle": "Claude settings.json 中的 env 会覆盖此处保存的 Key",+ "claudeSettingsConflictBody": "Claude Code 启动时会把 {{path}} 中的 `env` 块叠加到继承到的环境变量之上,文件内 `{{var}}` 的值会优先生效,除非你删除或更新它。",+ "claudeInfoHint": "保存后会写入 Vibe Remote 的 V2 配置,下次请求时通过 `ANTHROPIC_API_KEY`(或 `ANTHROPIC_AUTH_TOKEN`)传给 Claude Code。Claude 每次请求独立启动,无需重启常驻进程。",+ "claudeSave": "保存 Claude 认证",+ "claudeSaving": "保存中…",+ "claudeSaveSuccess": "Claude 认证已保存",+ "claudeSaveFailed": "保存 Claude 认证失败",+ "opencodeProvidersTitle": "服务商",+ "opencodeProvidersSubtitle": "从 OpenCode Server 实时拉取 · 通过 API Key 或 `opencode auth login` 完成授权",+ "opencodeProvidersCount": "已配置 {{configured}}/{{total}}",+ "opencodeServerRunning": "服务器可用",+ "opencodeServerStopped": "服务器不可用",+ "opencodeServerStarting": "服务器启动中…",+ "opencodeServerUnreachable": "无法连接到 OpenCode 服务器",+ "opencodeServerRetryCount": "第 {{attempt}}/{{max}} 次重试",+ "opencodeBackendDisabled": "后端已禁用",+ "opencodeDisabledBanner": "请在卡片顶部启用 OpenCode 后再管理服务商。后端关闭时只有认证模式开关可操作。",+ "opencodeRefresh": "刷新",+ "opencodeSearchPlaceholder": "搜索服务商、模型或 ID…",+ "opencodeFilterAll": "全部",+ "opencodeFilterConfigured": "已配置",+ "opencodeFilterOauth": "支持 OAuth",+ "opencodeFilterLocal": "本地",+ "opencodeBadgeConfigured": "已配置",+ "opencodeBadgeOauth": "支持 OAuth",+ "opencodeBadgeLocal": "本地",+ "opencodeBadgeUnset": "未配置",+ "opencodeDefaultBadge": "默认",+ "opencodeDefaultLabel": "默认服务商",+ "opencodeDefaultUnset": "未设置",+ "opencodeDefaultPopoverTitle": "选择默认服务商",+ "opencodeDefaultPopoverEmpty": "没有匹配的服务商。",+ "opencodeDefaultNeedsKey": "{{name}} 还没有 API Key,请先设置后再设为默认。",+ "opencodeDefaultSaved": "已将 {{name}} 设为默认服务商。",+ "opencodeDefaultSaveFailed": "切换默认服务商失败。",+ "opencodeProvidersLoading": "正在从 OpenCode 加载服务商…",+ "opencodeProvidersEmpty": "OpenCode 未返回任何服务商,建议在终端执行 `opencode auth list` 检查。",+ "opencodeProvidersFilterEmpty": "没有符合当前搜索或筛选的服务商。",+ "opencodeProvidersError": "无法读取 OpenCode 服务商列表。",+ "opencodeProvidersInfo": "服务商数据从 OpenCode 服务器实时拉取。保存 API Key 会通过 Server 的 `/auth` 接口写入 `~/.local/share/opencode/auth.json`。",+ "opencodeProviderModelsCount": "{{count}} 个模型",+ "opencodeProviderModelsEmpty": "该服务商未上报模型。",+ "opencodeProviderModels": "模型列表",+ "opencodeProviderDefaultModel": "默认",+ "opencodeProviderApiKey": "API Key",+ "opencodeProviderApiKeyPlaceholder": "粘贴服务商的 API Key",+ "opencodeProviderApiKeyPlaceholderStored": "输入新 Key 以替换已保存的内容",+ "opencodeProviderApiKeyStored": "已在磁盘上保存了一份 Key。",+ "opencodeProviderApiKeyMissing": "尚未保存该服务商的 API Key。",+ "opencodeProviderApiKeyRequired": "请先填写 API Key 再保存。",+ "opencodeProviderBaseUrl": "Base URL(可选)",+ "opencodeProviderBaseUrlPlaceholder": "https://provider.example.com/v1",+ "opencodeProviderBaseUrlHint": "服务商级别的覆盖配置位于 `~/.config/opencode/opencode.json`。留空则使用默认地址。",+ "opencodeProviderOauthAvailable": "支持 OAuth 登录",+ "opencodeProviderOauthHint": "也可以在终端执行 `opencode auth login {{id}}`,无需在此保存 API Key。",+ "opencodeProviderLocalHint": "本地服务商不需要凭据,启动运行时并加载模型即可。",+ "opencodeProviderSave": "保存 Key",+ "opencodeProviderSaved": "服务商凭据已保存。",+ "opencodeProviderSaveFailed": "保存服务商凭据失败。",+ "opencodeProviderRemove": "移除 Key",+ "opencodeProviderRemoveConfirm": "确定要删除 {{name}} 的已保存 Key 吗?",+ "opencodeProviderRemoved": "服务商凭据已删除。",+ "opencodeProviderRemoveFailed": "移除服务商凭据失败。",+ "opencodeProviderCollapse": "收起"},"messagingTitle": "消息","messagingSubtitle": "统一配置全局回复行为、ACK 策略以及消息显示默认值。",@@ -553,13 +645,13 @@"statusReady": "就绪","statusUpdating": "升级中","statusDisabled": "已停用",- "statusError": "未运行",+ "statusError": "未安装","statusUpdateAvailable": "可升级","currentVersion": "当前版本","latestVersion": "最新版本","readyHint": "当前已是最新版本。","updateHint": "可升级:{{from}} → {{to}}",- "errorHint": "{{name}} 当前未运行,可尝试重启或重新安装。",+ "errorHint": "{{name}} CLI 未安装,请在卡片上点击安装以启用该后端。","disabledHint": "请在卡片顶部开关中启用该后端。","upgrading": "正在升级…","upgradeNow": "立即升级",diff --git a/vibe/api.py b/vibe/api.pyindex 9deed5f2e..2b9b95cf4 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2204,6 +2204,405 @@ def save_codex_auth(payload: dict) -> dict:return state+def get_claude_auth() -> dict:+ """Return the user-facing Claude auth state for the Settings UI.++ Claude differs from Codex in two structural ways:++ 1. We never write to ``~/.claude/settings.json``. V2Config is the sole+ writer; the Claude CLI subprocess inherits ``ANTHROPIC_*`` vars+ from the env we set in ``session_handler.py`` at launch time.+ 2. OAuth tokens minted by ``claude login`` live in the OS keychain,+ which we cannot portably inspect. The "OAuth signed in" signal is+ therefore inferred from "no API key is configured" — the UI shows+ a hint pointing users at ``claude login`` if they need to switch.++ We still inspect ``settings.json`` because the user (or their tooling)+ may have put ``ANTHROPIC_AUTH_TOKEN`` / ``ANTHROPIC_BASE_URL`` there.+ When that happens *and* V2Config also has a key, settings.json wins+ at launch (Claude Code applies its ``env`` block on top of inherited+ env). The UI surfaces a warning so users aren't confused by stale+ keys silently overriding what they just saved.+ """+ from vibe.claude_config import read_claude_auth_state++ disk_state = read_claude_auth_state()+ try:+ config = load_config()+ cfg = getattr(getattr(config, "agents", None), "claude", None)+ configured_mode = getattr(cfg, "auth_mode", None)+ configured_key = getattr(cfg, "api_key", None) or ""+ configured_base = getattr(cfg, "base_url", None) or ""+ except Exception:+ configured_mode = None+ configured_key = ""+ configured_base = ""++ configured_key = configured_key.strip() if isinstance(configured_key, str) else ""+ configured_base = configured_base.strip() if isinstance(configured_base, str) else ""++ has_api_key = bool(configured_key)+ if configured_mode in _VALID_AUTH_MODES:+ auth_mode = configured_mode+ else:+ auth_mode = "api_key" if has_api_key else "oauth"++ # When settings.json also defines a key, the live CLI uses that one+ # rather than the V2Config-injected one. Flag the conflict so the+ # UI can warn the user before they assume their newly-saved key is+ # in effect.+ settings_conflict = bool(disk_state.get("settings_env_has_key")) and has_api_key++ return {+ "ok": True,+ "auth_mode": auth_mode,+ "has_api_key": has_api_key,+ "api_key_length": len(configured_key),+ "base_url": configured_base or None,+ "settings_path": disk_state.get("settings_path"),+ "settings_exists": bool(disk_state.get("settings_exists")),+ "settings_env_has_key": bool(disk_state.get("settings_env_has_key")),+ "settings_env_key_length": int(disk_state.get("settings_env_key_length") or 0),+ "settings_env_key_var": disk_state.get("settings_env_key_var"),+ "settings_env_base_url": disk_state.get("settings_env_base_url"),+ "settings_conflict": settings_conflict,+ }+++def save_claude_auth(payload: dict) -> dict:+ """Persist Claude auth into V2Config.++ No disk writes — V2Config is the source of truth and+ ``session_handler.py`` injects the resulting env vars at each+ one-shot CLI launch. Claude is a per-request subprocess so there is+ no daemon to restart; the *next* user message picks up the change.++ Empty ``api_key`` while in ``api_key`` mode is treated as "keep the+ stored key" — same UX promise as Codex — so callers can PATCH the+ base URL without re-typing the secret. An empty key with no stored+ fallback is rejected.+ """+ if not isinstance(payload, dict):+ return {"ok": False, "message": "Payload must be an object"}++ auth_mode = payload.get("auth_mode")+ if auth_mode not in _VALID_AUTH_MODES:+ return {"ok": False, "message": f"auth_mode must be one of {sorted(_VALID_AUTH_MODES)}"}++ raw_api_key = payload.get("api_key")+ if raw_api_key is not None and not isinstance(raw_api_key, str):+ return {"ok": False, "message": "api_key must be a string"}+ api_key = raw_api_key.strip() if isinstance(raw_api_key, str) else None++ raw_base_url = payload.get("base_url")+ if raw_base_url is not None and not isinstance(raw_base_url, str):+ return {"ok": False, "message": "base_url must be a string"}+ base_url = raw_base_url.strip() if isinstance(raw_base_url, str) else None+ if base_url == "":+ base_url = None++ if auth_mode == "api_key" and not api_key:+ # Reuse stored key for base-URL-only updates. Unlike Codex we+ # have no live-disk fallback (V2Config is sole writer), so we+ # only consult ``settings.json`` for legacy installs where the+ # user pre-configured the relay there and never re-typed the+ # secret into the Settings UI.+ with CONFIG_LOCK:+ try:+ existing = load_config()+ stored = getattr(getattr(existing, "agents", None), "claude", None)+ api_key = getattr(stored, "api_key", None) or None+ except Exception:+ api_key = None+ if not api_key:+ try:+ from vibe.claude_config import read_claude_api_key_from_settings++ api_key = read_claude_api_key_from_settings()+ except Exception:+ api_key = None+ if not api_key:+ return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}++ with CONFIG_LOCK:+ try:+ config = load_config()+ except FileNotFoundError:+ config = V2Config()+ config.agents.claude.auth_mode = auth_mode+ config.agents.claude.api_key = api_key if auth_mode == "api_key" else None+ config.agents.claude.base_url = base_url+ config.save()++ # Claude is one-shot per request — no daemon to restart. Return a+ # synthetic restart result so the UI handles the same response shape+ # as Codex / OpenCode and the toast wording can stay consistent.+ state = get_claude_auth()+ state["restart"] = {+ "ok": True,+ "message": "Claude relaunches per request; the next message uses the new auth.",+ }+ return state+++# ---------------------------------------------------------------------------+# OpenCode provider configuration+# ---------------------------------------------------------------------------+#+# The OpenCode page in Settings → Backends is fully dynamic: we never ship+# a hard-coded provider list. Instead we fan out to the running OpenCode+# server (``GET /provider`` for the catalog, ``GET /provider/auth`` for+# the auth-method index, ``GET /config/providers`` for model lists) and+# merge the responses into a per-card view with ``configured`` /+# ``oauth_available`` / ``local`` flags.+#+# Writes go through OpenCode's own ``PUT /auth/<id>`` /+# ``DELETE /auth/<id>`` endpoints (already wrapped by+# ``OpenCodeServer.set_api_key_auth`` / ``remove_provider_auth``); we+# also persist ``default_provider`` into ``V2Config`` so the chip and+# routing layers stay in sync across restarts.+++async def _opencode_get_server():+ """Spin up a transient OpenCodeServerManager instance for HTTP calls.++ Mirrors the pattern used by ``opencode_options_async``: pull the+ OpenCode config from V2Config, request a manager instance, ensure+ the daemon is reachable, and let the caller drive its HTTP methods.+ Returns ``None`` if OpenCode is disabled — callers translate that+ into a UI-friendly error.+ """+ from config.v2_compat import to_app_config+ from modules.agents.opencode import OpenCodeServerManager++ config = to_app_config(V2Config.load())+ if not config.opencode:+ return None+ opencode_config = config.opencode+ server = await OpenCodeServerManager.get_instance(+ binary=opencode_config.binary,+ port=opencode_config.port,+ request_timeout_seconds=opencode_config.request_timeout_seconds,+ )+ await server.ensure_running()+ return server+++def _is_local_provider(provider_id: str, auth_methods: list) -> bool:+ """Heuristic: a provider is "local" if it has no network auth methods.++ OpenCode reports Ollama / LM Studio with an empty auth-method list+ (no API key, no OAuth — they listen on localhost). The Settings UI+ surfaces these with a dedicated "Local" badge so users understand+ why there is no key field to fill in.+ """+ if not auth_methods:+ return True+ if isinstance(provider_id, str) and provider_id.lower() in {"ollama", "lmstudio", "lm-studio"}:+ return True+ return False+++async def _get_opencode_providers_async() -> dict:+ """Build the merged provider catalog reported to the Settings UI."""+ server = await _opencode_get_server()+ if server is None:+ return {"ok": False, "message": "OpenCode is disabled in V2Config"}++ request_loop = asyncio.get_running_loop()+ try:+ providers_raw, auth_raw, config_raw = await asyncio.gather(+ server.get_providers(),+ server.get_provider_auth(),+ server.get_available_models(os.path.expanduser("~")),+ return_exceptions=False,+ )+ finally:+ await server.close_http_session(loop=request_loop)++ # OpenCode 0.5+: ``/provider`` returns ``{all: {...}, default: {...},+ # connected: [...]}``. Older builds returned just ``{providers: [...]}``;+ # accept both shapes so an upgrade-in-place doesn't break the UI.+ all_providers: dict = {}+ if isinstance(providers_raw, dict):+ if isinstance(providers_raw.get("all"), dict):+ all_providers = providers_raw["all"]+ elif isinstance(providers_raw.get("providers"), list):+ # legacy shape — coerce list of dicts into id-keyed map+ for entry in providers_raw["providers"]:+ pid = entry.get("id") if isinstance(entry, dict) else None+ if pid:+ all_providers[pid] = entry++ connected = providers_raw.get("connected") if isinstance(providers_raw, dict) else None+ connected_set = {pid for pid in connected if isinstance(pid, str)} if isinstance(connected, list) else set()++ model_index: dict = {}+ if isinstance(config_raw, dict):+ for entry in config_raw.get("providers", []) or []:+ pid = entry.get("id") if isinstance(entry, dict) else None+ if pid:+ model_index[pid] = entry++ auth_index = auth_raw if isinstance(auth_raw, dict) else {}++ # Resolve the user-configured default provider (V2Config wins because+ # the chip / lifecycle layer reads it from there; OpenCode's own+ # ``default`` block is a runtime hint we fall back to only when+ # V2Config has the schema default).+ default_provider = "anthropic"+ try:+ config = load_config()+ cfg = getattr(getattr(config, "agents", None), "opencode", None)+ configured_default = getattr(cfg, "default_provider", None)+ if isinstance(configured_default, str) and configured_default.strip():+ default_provider = configured_default.strip()+ except Exception:+ pass++ out_providers = []+ for pid, entry in all_providers.items():+ if not isinstance(entry, dict):+ continue+ auth_methods = auth_index.get(pid)+ auth_methods_list = auth_methods if isinstance(auth_methods, list) else []+ oauth_available = any(+ isinstance(method, dict) and method.get("type") == "oauth"+ for method in auth_methods_list+ )+ local = _is_local_provider(pid, auth_methods_list)+ configured = pid in connected_set+ models_for_provider = model_index.get(pid, {})+ provider_models = models_for_provider.get("models")+ if isinstance(provider_models, dict):+ model_ids = sorted(provider_models.keys())+ elif isinstance(provider_models, list):+ model_ids = [m.get("id") for m in provider_models if isinstance(m, dict) and m.get("id")]+ else:+ model_ids = []+ default_model = None+ defaults_block = config_raw.get("default") if isinstance(config_raw, dict) else None+ if isinstance(defaults_block, dict):+ raw_default = defaults_block.get(pid)+ if isinstance(raw_default, str):+ default_model = raw_default++ out_providers.append(+ {+ "id": pid,+ "name": entry.get("name") or pid,+ "description": entry.get("description") or "",+ "configured": configured,+ "oauth_available": oauth_available,+ "local": local,+ "models": model_ids,+ "default_model": default_model,+ }+ )++ out_providers.sort(key=lambda p: (not p["configured"], p["local"], p["id"]))++ return {+ "ok": True,+ "providers": out_providers,+ "default_provider": default_provider,+ }+++def get_opencode_providers() -> dict:+ """Sync wrapper for the OpenCode provider catalog."""+ try:+ return asyncio.run(_get_opencode_providers_async())+ except Exception as exc:+ logger.warning("OpenCode providers fetch failed: %s", exc, exc_info=True)+ return {"ok": False, "message": str(exc)}+++async def _save_opencode_provider_auth_async(provider_id: str, api_key: str) -> dict:+ server = await _opencode_get_server()+ if server is None:+ return {"ok": False, "message": "OpenCode is disabled in V2Config"}+ request_loop = asyncio.get_running_loop()+ try:+ await server.set_api_key_auth(provider_id, api_key)+ finally:+ await server.close_http_session(loop=request_loop)+ # Also clean the legacy ``opencode.json`` provider block so the UI+ # source of truth (OpenCode's own auth store) wins on next launch.+ try:+ from vibe.opencode_config import remove_opencode_provider_api_key++ await asyncio.to_thread(remove_opencode_provider_api_key, provider_id, logger_instance=logger)+ except Exception as exc:+ logger.debug("Legacy opencode.json cleanup skipped for %s: %s", provider_id, exc)+ return {"ok": True}+++def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:+ """Persist a single OpenCode provider's API key via the live daemon."""+ if not isinstance(provider_id, str) or not provider_id.strip():+ return {"ok": False, "message": "provider_id is required"}+ if not isinstance(payload, dict):+ return {"ok": False, "message": "Payload must be an object"}+ raw_key = payload.get("api_key")+ if not isinstance(raw_key, str) or not raw_key.strip():+ return {"ok": False, "message": "api_key is required"}+ api_key = raw_key.strip()+ try:+ return asyncio.run(_save_opencode_provider_auth_async(provider_id.strip(), api_key))+ except Exception as exc:+ logger.warning("OpenCode set-auth failed for %s: %s", provider_id, exc, exc_info=True)+ return {"ok": False, "message": str(exc)}+++async def _delete_opencode_provider_auth_async(provider_id: str) -> dict:+ server = await _opencode_get_server()+ if server is None:+ return {"ok": False, "message": "OpenCode is disabled in V2Config"}+ request_loop = asyncio.get_running_loop()+ try:+ await server.remove_provider_auth(provider_id)+ finally:+ await server.close_http_session(loop=request_loop)+ return {"ok": True}+++def delete_opencode_provider_auth(provider_id: str) -> dict:+ """Drop a single provider's stored credentials."""+ if not isinstance(provider_id, str) or not provider_id.strip():+ return {"ok": False, "message": "provider_id is required"}+ try:+ return asyncio.run(_delete_opencode_provider_auth_async(provider_id.strip()))+ except Exception as exc:+ logger.warning("OpenCode delete-auth failed for %s: %s", provider_id, exc, exc_info=True)+ return {"ok": False, "message": str(exc)}+++def set_opencode_default_provider(payload: dict) -> dict:+ """Persist ``V2Config.agents.opencode.default_provider``.++ No daemon contact required — OpenCode itself accepts a per-request+ ``provider`` field on messages, so the "default" is purely our+ routing concern. Storing it in V2Config keeps the chip and the+ routing layer in sync across restarts.+ """+ if not isinstance(payload, dict):+ return {"ok": False, "message": "Payload must be an object"}+ raw = payload.get("provider_id")+ if not isinstance(raw, str) or not raw.strip():+ return {"ok": False, "message": "provider_id is required"}+ provider_id = raw.strip()++ with CONFIG_LOCK:+ try:+ config = load_config()+ except FileNotFoundError:+ config = V2Config()+ config.agents.opencode.default_provider = provider_id+ config.save()+ return {"ok": True, "default_provider": provider_id}++def codex_models() -> dict:"""Best-effort merged list of Codex model options.diff --git a/vibe/claude_config.py b/vibe/claude_config.pynew file mode 100644index 000000000..2ccab7045--- /dev/null+++ b/vibe/claude_config.py@@ -0,0 +1,147 @@+"""Helpers for inspecting Claude Code's on-disk configuration.++Unlike Codex, Claude Code's API-key auth is realized purely via environment+variables — the Anthropic SDK honors ``ANTHROPIC_API_KEY`` (or+``ANTHROPIC_AUTH_TOKEN`` for relay setups) and ``ANTHROPIC_BASE_URL`` at+invocation time. ``core/handlers/session_handler.py`` already injects these+from ``V2Config.agents.claude`` before each one-shot CLI launch.++That means V2Config is our sole *writer*; we do **not** mutate+``~/.claude/settings.json``. But the Claude CLI itself reads that file at+launch and applies its ``env`` block on top of the inherited env — so a+hand-edited ``env.ANTHROPIC_AUTH_TOKEN`` there will override whatever we+just injected. The Settings UI needs to surface that conflict instead of+silently letting the user save a value that won't take effect.++This module is therefore read-only:++- ``read_claude_settings_env(...)`` returns whichever ``ANTHROPIC_*`` keys+ are present in ``~/.claude/settings.json`` so the UI can warn the user.+- ``read_claude_auth_state(...)`` rolls that up into the user-visible+ shape consumed by ``vibe.api.get_claude_auth``.++OAuth tokens minted by ``claude login`` live in the macOS keychain (or+the OS-specific equivalent), not on disk. We have no portable way to+inspect them, so the OAuth-signed-in signal is purely an inference from+"no API key is configured" plus "the CLI is reachable".+"""++from __future__ import annotations++import json+import logging+import os+from pathlib import Path+from typing import Any, Dict, Optional++logger = logging.getLogger(__name__)++# Keys we recognise inside ``~/.claude/settings.json``'s ``env`` block.+# ``ANTHROPIC_API_KEY`` is the SDK's documented variable; relay setups+# (e.g. Cloudflare-fronted gateways like ai-relay) prefer+# ``ANTHROPIC_AUTH_TOKEN``. We surface both so a hand-edited config+# doesn't silently invalidate the Settings UI.+RELEVANT_ENV_KEYS = (+ "ANTHROPIC_API_KEY",+ "ANTHROPIC_AUTH_TOKEN",+ "ANTHROPIC_BASE_URL",+)+++def get_claude_home(home: Path | None = None) -> Path:+ """Resolve the directory Claude Code reads ``settings.json`` from.++ Claude Code respects ``CLAUDE_CONFIG_DIR`` first (newer builds),+ falling back to ``~/.claude``. We mirror that precedence so the+ Settings UI reports on whichever directory the live CLI actually+ consults.+ """+ if home is not None:+ return home / ".claude"+ env_home = os.environ.get("CLAUDE_CONFIG_DIR")+ if env_home:+ return Path(env_home).expanduser()+ return Path.home() / ".claude"+++def get_claude_settings_path(home: Path | None = None) -> Path:+ """Return the absolute path to ``~/.claude/settings.json``."""+ return get_claude_home(home) / "settings.json"+++def _load_settings(path: Path) -> Dict[str, Any]:+ if not path.exists():+ return {}+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ if isinstance(data, dict):+ return data+ except Exception as exc:+ logger.warning("Claude settings.json parse failed (%s)", exc)+ return {}+++def read_claude_settings_env(home: Path | None = None) -> Dict[str, str]:+ """Extract Anthropic-relevant env vars from ``~/.claude/settings.json``.++ Returns the mapping verbatim (no length truncation, no masking) so+ callers can compute presence + length. The caller is responsible for+ redacting before forwarding to the UI.+ """+ settings = _load_settings(get_claude_settings_path(home))+ env_block = settings.get("env")+ if not isinstance(env_block, dict):+ return {}+ out: Dict[str, str] = {}+ for key in RELEVANT_ENV_KEYS:+ raw = env_block.get(key)+ if isinstance(raw, str) and raw.strip():+ out[key] = raw.strip()+ return out+++def read_claude_auth_state(home: Path | None = None) -> Dict[str, Any]:+ """Return the user-visible Claude auth state for the Settings UI.++ Reports on ``~/.claude/settings.json`` only — V2Config is layered on+ top by ``vibe.api.get_claude_auth``. Secrets never leave the server;+ we surface key length + a "settings.json conflict" flag.++ ``settings_env_has_key`` is true when settings.json carries either+ ``ANTHROPIC_API_KEY`` or ``ANTHROPIC_AUTH_TOKEN``. When this is true+ *and* V2Config also has a key, the Settings UI must warn that+ settings.json wins at launch (Claude Code applies its env block on+ top of whatever we inject). ``settings_path`` is forwarded so the+ warning can name the file the user needs to edit.+ """+ env_block = read_claude_settings_env(home)+ settings_path = get_claude_settings_path(home)++ settings_key = env_block.get("ANTHROPIC_API_KEY") or env_block.get(+ "ANTHROPIC_AUTH_TOKEN"+ )+ settings_base = env_block.get("ANTHROPIC_BASE_URL")+ return {+ "settings_path": str(settings_path),+ "settings_exists": settings_path.exists(),+ "settings_env_has_key": bool(settings_key),+ "settings_env_key_length": len(settings_key) if settings_key else 0,+ "settings_env_key_var": (+ "ANTHROPIC_API_KEY"+ if "ANTHROPIC_API_KEY" in env_block+ else ("ANTHROPIC_AUTH_TOKEN" if "ANTHROPIC_AUTH_TOKEN" in env_block else None)+ ),+ "settings_env_base_url": settings_base,+ }+++def read_claude_api_key_from_settings(home: Path | None = None) -> Optional[str]:+ """Return whichever Anthropic key ``settings.json`` has, if any.++ Used as a fallback when the UI sends a base-URL-only update: V2Config+ may be stale (older installs lacked ``api_key``), but the CLI still+ picks up whatever is in ``settings.json``. Prefer that over silently+ blanking the live key.+ """+ env_block = read_claude_settings_env(home)+ return env_block.get("ANTHROPIC_API_KEY") or env_block.get("ANTHROPIC_AUTH_TOKEN")diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 8d9515a93..188e61c94 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1593,6 +1593,75 @@ def backend_codex_auth_post():return jsonify(api.save_codex_auth(payload))[email protected]("/backend/claude/auth", methods=["GET"])+def backend_claude_auth_get():+ """Read the user-facing Claude auth state (masked secrets)."""+ from vibe import api++ return jsonify(api.get_claude_auth())++[email protected]("/backend/claude/auth", methods=["POST"])+def backend_claude_auth_post():+ """Persist Claude auth into V2Config.++ Body: ``{auth_mode: 'oauth'|'api_key', api_key?: string, base_url?: string}``.+ Claude relaunches per request, so no daemon restart is necessary —+ the next user message picks up the new env injection automatically.+ """+ from vibe import api++ payload = request.json or {}+ return jsonify(api.save_claude_auth(payload))++[email protected]("/backend/opencode/providers", methods=["GET"])+def backend_opencode_providers():+ """Return the merged OpenCode provider catalog for the Settings UI.++ Fans out to the live OpenCode daemon's ``/provider``, ``/provider/auth``,+ and ``/config/providers`` endpoints and merges them into a list of+ ``{id, name, configured, oauth_available, local, models, default_model}``.+ """+ from vibe import api++ return jsonify(api.get_opencode_providers())++[email protected]("/backend/opencode/provider/<provider_id>/auth", methods=["POST"])+def backend_opencode_provider_auth_post(provider_id: str):+ """Persist an API key for a single OpenCode provider.++ Body: ``{api_key: string}``. The key is forwarded to OpenCode via+ its ``PUT /auth/<id>`` endpoint.+ """+ from vibe import api++ payload = request.json or {}+ return jsonify(api.save_opencode_provider_auth(provider_id, payload))++[email protected]("/backend/opencode/provider/<provider_id>/auth", methods=["DELETE"])+def backend_opencode_provider_auth_delete(provider_id: str):+ """Drop the stored API key for a single OpenCode provider."""+ from vibe import api++ return jsonify(api.delete_opencode_provider_auth(provider_id))++[email protected]("/backend/opencode/default-provider", methods=["POST"])+def backend_opencode_default_provider():+ """Persist the user's default OpenCode provider into V2Config.++ Body: ``{provider_id: string}``. No daemon contact — the default+ is consulted at session-routing time, not by OpenCode itself.+ """+ from vibe import api++ payload = request.json or {}+ return jsonify(api.set_opencode_default_provider(payload))++@app.route("/browse", methods=["POST"])def browse_directory():"""List sub-directories of a given path for the directory picker UI."""