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
refactor(ui): extract shared backend settings components, add Codex Runtime card
cyhbf143dd9db67
diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsxindex db5392607..1b6333041 100644--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx@@ -5,20 +5,14 @@ import {AlertTriangle,ArrowLeft,CheckCircle2,- ChevronDown,- ChevronUp,- Download,Info,KeyRound,Pencil,- RefreshCw,RotateCcw,Save,- Search,Sparkles,Trash2,} from 'lucide-react';-import clsx from 'clsx';import { Badge } from '../ui/badge';import { Button } from '../ui/button';@@ -26,84 +20,30 @@ 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 { BackendOAuthPanel } from './BackendOAuthPanel';import { BackendTestPanel } from './BackendTestPanel';-import { ToggleSwitch } from './SettingsPrimitives';+import { BackendRuntimeCard } from './shared/BackendRuntimeCard';+import { SegmentedRadio } from './shared/SegmentedRadio';+import { useBackendRuntime } from './shared/useBackendRuntime';+import { useOAuthFlowLock } from './shared/useOAuthFlowLock';import { useApi } from '@/context/ApiContext';import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';-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;- disabled?: boolean;-}> = ({ value, onChange, options, ariaLabel, disabled }) => (- <div- role="radiogroup"- aria-label={ariaLabel}- aria-disabled={disabled || undefined}- className={clsx(- 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',- disabled && 'opacity-60',- )}- >- {options.map((opt) => {- const active = value === opt.id;- return (- <button- key={opt.id}- type="button"- role="radio"- aria-checked={active}- disabled={disabled}- 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',- disabled && 'cursor-not-allowed',- )}- >- {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);+ // Runtime state — CLI detection + lifecycle. Shared with Codex /+ // OpenCode pages via the ``useBackendRuntime`` hook.+ const runtime = useBackendRuntime({+ backend: BACKEND_ID,+ defaultCli: DEFAULT_CLI,+ });// Auth state — OAuth vs API-key.const [authState, setAuthState] = useState<ClaudeAuthState | null>(null);@@ -123,53 +63,17 @@ export const SettingsClaudeProviderPage: React.FC = () => {const [savedAuthMode, setSavedAuthMode] = useState<ClaudeAuthMode>('oauth');const [savedBaseUrl, setSavedBaseUrl] = useState('');// Freeze the auth-mode segmented radio while the OAuth panel is mid-- // handshake. Same iOS Safari issue as the Codex page: a Copy tap- // can bounce the radio and tear down the in-flight login. The- // ``disabled`` HTML attribute alone isn't enough — the user has- // reproduced the flip with the radio rendered disabled, so we- // also guard at the setter (the radio click cannot win even if- // iOS smuggles the event through whatever quirky path).- const [oauthFlowActive, setOauthFlowActive] = useState(false);- const oauthFlowActiveRef = React.useRef(oauthFlowActive);- oauthFlowActiveRef.current = oauthFlowActive;- const guardedSetAuthMode = React.useCallback(- (next: ClaudeAuthMode) => {- if (oauthFlowActiveRef.current) {- // eslint-disable-next-line no-console- console.warn(- '[claude-auth-mode] rejected change to %s while OAuth flow active',- next,- );- showToast(t('settings.backends.oauthFlowLockedToast'), 'warning');- return;- }- setAuthMode(next);- },- [showToast, t],- );+ // handshake. Shared with Codex / OpenCode via ``useOAuthFlowLock``.+ const { oauthFlowActive, setOauthFlowActive, guardedSetAuthMode } =+ useOAuthFlowLock<ClaudeAuthMode>({+ setAuthMode,+ warnTag: 'claude-auth-mode',+ });useEffect(() => {+ // Runtime config (enabled + cli_path + initial detect) is owned by+ // ``useBackendRuntime``. This effect only loads auth state.let cancelled = false;-- // 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) => {@@ -201,71 +105,8 @@ export const SettingsClaudeProviderPage: React.FC = () => {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(() =>[@@ -358,8 +199,6 @@ export const SettingsClaudeProviderPage: React.FC = () => {}};- const runtimeDirty = cliPath !== savedCliPath;-return (<SettingsPageShellactiveTab="backends"@@ -372,159 +211,19 @@ export const SettingsClaudeProviderPage: React.FC = () => {</Link>}>- {!loaded ? (+ {!runtime.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>+ <BackendRuntimeCard+ backend={BACKEND_ID}+ label="Claude Code"+ description={t('settings.backends.claudeDescription')}+ Icon={Sparkles}+ iconTileClassName="bg-cyan-soft"+ iconClassName="text-cyan"+ runtime={runtime}+ />{authLoading ? (<div className="text-sm text-muted">{t('common.loading')}</div>diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsxindex ec73ac4a2..672574502 100644--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx@@ -1,8 +1,7 @@import React, { useEffect, useMemo, useState } from 'react';import { Link } from 'react-router-dom';-import { ArrowLeft, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save, Trash2 } from 'lucide-react';+import { ArrowLeft, Bot, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save, Trash2 } from 'lucide-react';import { useTranslation } from 'react-i18next';-import clsx from 'clsx';import { Badge } from '../ui/badge';import { Button } from '../ui/button';@@ -10,60 +9,33 @@ import { Card, CardContent } from '../ui/card';import { Input } from '../ui/input';import { Label } from '../ui/label';import { useApi } from '@/context/ApiContext';-import type { BackendNotice, CodexAuthMode, CodexAuthState } from '@/context/ApiContext';+import type { CodexAuthMode, CodexAuthState } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';import { BackendOAuthPanel } from './BackendOAuthPanel';import { BackendTestPanel } from './BackendTestPanel';import { SettingsPageShell } from './SettingsPageShell';+import { BackendRuntimeCard } from './shared/BackendRuntimeCard';+import { SegmentedRadio } from './shared/SegmentedRadio';+import { surfaceBackendNotices } from './shared/surfaceBackendNotices';+import { useBackendRuntime } from './shared/useBackendRuntime';+import { useOAuthFlowLock } from './shared/useOAuthFlowLock';-// Mirrors the segmented-radio pattern in shared/RoutingConfigPanel.tsx so-// Codex's auth-mode toggle reads like the rest of the Settings surface.-const SegmentedRadio: React.FC<{- value: CodexAuthMode;- onChange: (next: CodexAuthMode) => void;- options: ReadonlyArray<{ id: CodexAuthMode; label: string }>;- ariaLabel: string;- disabled?: boolean;-}> = ({ value, onChange, options, ariaLabel, disabled }) => (- <div- role="radiogroup"- aria-label={ariaLabel}- aria-disabled={disabled || undefined}- className={clsx(- 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',- disabled && 'opacity-60',- )}- >- {options.map((opt) => {- const active = value === opt.id;- return (- <button- key={opt.id}- type="button"- role="radio"- aria-checked={active}- disabled={disabled}- 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',- disabled && 'cursor-not-allowed',- )}- >- {opt.label}- </button>- );- })}- </div>-);+const BACKEND_ID = 'codex';+const DEFAULT_CLI = 'codex';export const SettingsCodexProviderPage: React.FC = () => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();+ // Runtime state — shared across all backend pages via the hook. Adds+ // the Runtime card affordances (lifecycle chip / toggle / CLI path+ // detect / install) that #282 omitted from the Codex page.+ const runtime = useBackendRuntime({+ backend: BACKEND_ID,+ defaultCli: DEFAULT_CLI,+ });+const [state, setState] = useState<CodexAuthState | null>(null);const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);@@ -82,40 +54,13 @@ export const SettingsCodexProviderPage: React.FC = () => {// button that never has a no-op state is noisy and confusing.const [savedAuthMode, setSavedAuthMode] = useState<CodexAuthMode>('oauth');const [savedBaseUrl, setSavedBaseUrl] = useState('');- // When the OAuth panel is mid-flow (device code visible, polling),- // freeze the auth-mode segmented radio. Without this lock, an- // accidental tap (iOS Safari emits one after the "Copy" tap in- // testing) tears down the in-progress login.- const [oauthFlowActive, setOauthFlowActive] = useState(false);- // We need to read the latest value of ``oauthFlowActive`` from- // inside the guarded setter without rebuilding the setter on every- // render — a ref keeps it stable for callbacks. The button's- // ``disabled`` attribute alone is NOT enough on iOS Safari: the- // user has reproduced the tab flipping while the radio is rendered- // disabled. We do not know the exact event path that smuggles the- // click through (URL-bar collapse reflow, fastclick coordinate- // drift, synthetic gesture), so the only bulletproof defense is- // rejecting the state mutation at its source.- const oauthFlowActiveRef = React.useRef(oauthFlowActive);- oauthFlowActiveRef.current = oauthFlowActive;- const guardedSetAuthMode = React.useCallback(- (next: CodexAuthMode) => {- if (oauthFlowActiveRef.current) {- // Visible warning in devtools so any future regression is- // attributable. The toast is for users who happen to be- // staring at the screen when this rejects.- // eslint-disable-next-line no-console- console.warn(- '[codex-auth-mode] rejected change to %s while OAuth flow active',- next,- );- showToast(t('settings.backends.oauthFlowLockedToast'), 'warning');- return;- }- setAuthMode(next);- },- [showToast, t],- );+ // Freeze the auth-mode segmented radio while the OAuth panel is mid-+ // handshake. Shared with Claude / OpenCode via ``useOAuthFlowLock``.+ const { oauthFlowActive, setOauthFlowActive, guardedSetAuthMode } =+ useOAuthFlowLock<CodexAuthMode>({+ setAuthMode,+ warnTag: 'codex-auth-mode',+ });useEffect(() => {let cancelled = false;@@ -171,33 +116,6 @@ export const SettingsCodexProviderPage: React.FC = () => {? t('settings.backends.codexApiKeyConfigured', { length: state.api_key_length }): t('settings.backends.codexApiKeyMissing');- // Surface non-fatal config-rewrite warnings from the server as warning- // toasts. Today the only emitter is ``cleared_custom_relay_pointer``- // (an OAuth switch where the user's ``model_provider`` pointed at a- // custom relay whose ``base_url`` won't accept OAuth tokens — we- // cleared the pointer so Codex falls back to OpenAI's default- // endpoint). Without this banner the user sees a green "saved" toast- // and then a 401 on their next message.- const surfaceNotices = (notices: BackendNotice[] | undefined) => {- if (!notices || notices.length === 0) return;- for (const notice of notices) {- if (notice.code === 'cleared_custom_relay_pointer') {- showToast(- t('settings.backends.codexNoticeClearedRelayPointer', {- provider: notice.provider_id || 'custom',- url: notice.base_url || '',- }),- 'warning',- );- } else {- showToast(- t('settings.backends.codexNoticeGeneric', { code: notice.code }),- 'warning',- );- }- }- };-const onRemoveApiKey = async () => {// Drop just the API key (V2Config + auth.json's OPENAI_API_KEY),// leave OAuth tokens intact. Codex's CLI prefers the API key when@@ -226,7 +144,7 @@ export const SettingsCodexProviderPage: React.FC = () => {setApiKey('');setEditingKey(false);showToast(t('settings.backends.codexApiKeyRemoved'), 'success');- surfaceNotices(result.notices);+ surfaceBackendNotices(result.notices, showToast, t);} catch (err: any) {showToast(t('settings.backends.codexApiKeyRemoveFailed', { detail: err?.message || 'unknown' }),@@ -280,7 +198,7 @@ export const SettingsCodexProviderPage: React.FC = () => {} else {showToast(t('settings.backends.codexSaveSuccess'), 'success');}- surfaceNotices(result.notices);+ surfaceBackendNotices(result.notices, showToast, t);} catch (err: any) {showToast(err?.message || t('settings.backends.codexSaveFailed'), 'error');} finally {@@ -300,15 +218,26 @@ export const SettingsCodexProviderPage: React.FC = () => {</Link>}>- {loading ? (+ {loading || !runtime.loaded ? (<div className="text-sm text-muted">{t('common.loading')}</div>) : (- <Card>- <CardContent className="flex flex-col gap-5 p-6">- <div className="flex flex-col gap-2">- <div className="flex items-center justify-between gap-3">- <Label className="text-xs font-medium uppercase text-muted">- {t('settings.backends.codexAuthModeLabel')}+ <div className="flex flex-col gap-4">+ <BackendRuntimeCard+ backend={BACKEND_ID}+ label="Codex"+ description={t('settings.backends.codexDescription')}+ Icon={Bot}+ iconTileClassName="bg-gold"+ iconClassName="text-gold-foreground"+ runtime={runtime}+ />++ <Card>+ <CardContent className="flex flex-col gap-5 p-6">+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-3">+ <Label className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.codexAuthModeLabel')}</Label>{state?.active_auth_mode && state.active_auth_mode !== 'none' && (<Badge@@ -556,9 +485,7 @@ export const SettingsCodexProviderPage: React.FC = () => {})()}</CardContent></Card>- )}- {!loading && (- <div className="mt-4">+<BackendTestPanel backend="codex" /></div>)}diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsxindex c5e84604d..3145db157 100644--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx@@ -8,7 +8,6 @@ import {ChevronDown,ChevronUp,Cpu,- Download,Info,KeyRound,Pencil,@@ -32,15 +31,14 @@ 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 { BackendOAuthPanel } from './BackendOAuthPanel';import { OpencodeProviderTestPanel } from './OpencodeProviderTestPanel';-import { ToggleSwitch } from './SettingsPrimitives';+import { BackendRuntimeCard } from './shared/BackendRuntimeCard';+import { useBackendRuntime } from './shared/useBackendRuntime';import { useApi } from '@/context/ApiContext';import type { OpencodeProvider } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';-type CliStatus = 'unknown' | 'ok' | 'missing';type PermissionState = 'idle' | 'loading' | 'success' | 'error';type FilterMode = 'all' | 'configured' | 'oauth' | 'local';@@ -106,23 +104,14 @@ export const SettingsOpencodeProviderPage: React.FC = () => {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);+ // Runtime state — shared with Claude / Codex pages via the hook.+ const runtime = useBackendRuntime({+ backend: BACKEND_ID,+ defaultCli: DEFAULT_CLI,+ fallbackDefaultBackend: BACKEND_ID,+ });const [permissionState, setPermissionState] = useState<PermissionState>('idle');const [permissionMessage, setPermissionMessage] = useState('');- const [savingRuntime, setSavingRuntime] = useState(false);// Provider catalog state.const [providers, setProviders] = useState<OpencodeProvider[] | null>(null);@@ -156,24 +145,6 @@ export const SettingsOpencodeProviderPage: React.FC = () => {// 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);@@ -201,33 +172,25 @@ export const SettingsOpencodeProviderPage: React.FC = () => {loadProvidersRef.current = loadProviders;}, [loadProviders]);+ // Runtime initial-load + cli_path/detect/install/save/toggle live in+ // ``useBackendRuntime``. This page-specific effect just drives the+ // providers fan-out: load when the runtime is enabled, clear when+ // it's not. Triggered whenever the optimistic enabled flag changes+ // (matches the original "toggle then reload" UX exactly).useEffect(() => {- 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);- });+ if (!runtime.loaded) return;+ if (runtime.enabled) {+ setServerStartAttempts(0);+ void loadProviders();+ } else {+ setProviders(null);+ setProvidersError(null);+ }return () => {- cancelled = true;if (retryTimerRef.current) clearTimeout(retryTimerRef.current);};// eslint-disable-next-line react-hooks/exhaustive-deps- }, [api]);+ }, [runtime.enabled, runtime.loaded]);// Auto-retry server-start failures — common when the user has just// enabled the backend. After SERVER_START_MAX_RETRIES the user can hit@@ -238,7 +201,7 @@ export const SettingsOpencodeProviderPage: React.FC = () => {clearTimeout(retryTimerRef.current);retryTimerRef.current = null;}- if (!enabled) return;+ if (!runtime.enabled) return;if (!providersError) return;if (providersLoading) return;if (serverStartAttempts >= SERVER_START_MAX_RETRIES) return;@@ -252,30 +215,7 @@ export const SettingsOpencodeProviderPage: React.FC = () => {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);- }- };+ }, [runtime.enabled, providersError, providersLoading, serverStartAttempts]);const setupPermission = async () => {setPermissionState('loading');@@ -299,61 +239,10 @@ export const SettingsOpencodeProviderPage: React.FC = () => {}};- 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);- }- })();- };+ // ``onSaveRuntime`` and ``toggleEnabled`` are owned by+ // ``useBackendRuntime``; the providers reload/clear side-effect+ // that used to live inside the page's toggle handler is now driven+ // by the ``useEffect([runtime.enabled, runtime.loaded])`` above.// ---- Expansion / per-provider editing ----@@ -543,8 +432,6 @@ export const SettingsOpencodeProviderPage: React.FC = () => {[providers, defaultProvider]);- const runtimeDirty = cliPath !== savedCliPath;-const filterLabel = (mode: FilterMode) => {switch (mode) {case 'all':@@ -610,124 +497,27 @@ export const SettingsOpencodeProviderPage: React.FC = () => {</Link>}>- {!loaded ? (+ {!runtime.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>- )}-- {/* Hide the Allow affordance once opencode.json carries- ``permission: "allow"``. Until then show the strong- copy that explains why the agent will stall without- this setting. */}- {cliStatus === 'ok' && !permissionAllowed && (+ <BackendRuntimeCard+ backend={BACKEND_ID}+ label="OpenCode"+ description={t('settings.backends.opencodeDescription')}+ Icon={Terminal}+ iconTileClassName="bg-violet-soft"+ iconClassName="text-violet"+ runtime={runtime}+ extraSlot={+ // ``permission: "allow"`` setup is OpenCode-specific: without+ // it the daemon prompts on every tool call and Vibe Remote+ // can't reply. Hidden once opencode.json carries the value.+ runtime.cliStatus === 'ok' && !permissionAllowed ? (<div className="rounded-lg border border-gold/30 bg-gold/10 px-3 py-2.5">- <p className="mb-2 text-[12px] text-gold">{t('agentDetection.permissionHintStrong')}</p>+ <p className="mb-2 text-[12px] text-gold">+ {t('agentDetection.permissionHintStrong')}+ </p><div className="flex flex-wrap items-center gap-3"><Buttonvariant="brand-gold"@@ -750,23 +540,9 @@ export const SettingsOpencodeProviderPage: React.FC = () => {)}</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>+ ) : null+ }+ />{/* Card 2 — provider catalog. */}<Card>@@ -781,19 +557,19 @@ export const SettingsOpencodeProviderPage: React.FC = () => {<span className="text-[15px] font-semibold text-foreground">{t('settings.backends.opencodeProvidersTitle')}</span>- {enabled && providers && (+ {runtime.enabled && providers && (<Badge variant={providersError ? 'warning' : 'success'}>{providersError? t('settings.backends.opencodeServerStopped'): t('settings.backends.opencodeServerRunning')}</Badge>)}- {!enabled && (+ {!runtime.enabled && (<Badge variant="secondary">{t('settings.backends.opencodeBackendDisabled')}</Badge>)}- {enabled && providers && providers.length > 0 && (+ {runtime.enabled && providers && providers.length > 0 && (<Badge variant="outline">{t('settings.backends.opencodeProvidersCount', {configured: configuredCount,@@ -816,7 +592,7 @@ export const SettingsOpencodeProviderPage: React.FC = () => {setServerStartAttempts(0);void loadProviders();}}- disabled={!enabled || providersLoading}+ disabled={!runtime.enabled || providersLoading}><RefreshCwclassName={clsx('size-3.5', providersLoading && 'animate-spin')}@@ -826,13 +602,13 @@ export const SettingsOpencodeProviderPage: React.FC = () => {</div></div>- {!enabled && (+ {!runtime.enabled && (<div className="rounded-lg border border-border bg-surface-2/60 px-3 py-2.5 text-[12px] text-muted">{t('settings.backends.opencodeDisabledBanner')}</div>)}- {enabled && (+ {runtime.enabled && (<>{/* Toolbar — search + filter chips + default-provider pill. */}<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsxnew file mode 100644index 000000000..e7dffe562--- /dev/null+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx@@ -0,0 +1,210 @@+import React from 'react';+import { useTranslation } from 'react-i18next';+import {+ ChevronDown,+ ChevronUp,+ Download,+ RefreshCw,+ Save,+ Search,+} from 'lucide-react';+import type { LucideIcon } 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 { BackendLifecycleChip } from '../BackendLifecycleChip';+import { ToggleSwitch } from '../SettingsPrimitives';+import type { BackendRuntimeState, BackendId } from './useBackendRuntime';++export interface BackendRuntimeCardProps {+ /** Backend id used by ``BackendLifecycleChip`` + ``installAgent``. */+ backend: BackendId;+ /** Display name shown in the card header (e.g. "Claude Code"). */+ label: string;+ /** Short description sentence under the name. */+ description: string;+ /** Lucide icon component used in the header tile. */+ Icon: LucideIcon;+ /**+ * Tailwind class string for the icon tile background, e.g.+ * ``"bg-cyan-soft"`` (Claude) / ``"bg-gold"`` (Codex) /+ * ``"bg-violet-soft"`` (OpenCode). Keeps brand colour consistent+ * with the icon-only chip used elsewhere in the design.+ */+ iconTileClassName: string;+ /** Tailwind class for the icon glyph colour, e.g. ``"text-cyan"``. */+ iconClassName: string;+ /** Runtime state object from ``useBackendRuntime``. */+ runtime: BackendRuntimeState;+ /**+ * Optional extra row rendered between the install-hint and the Save+ * button. OpenCode uses this for the ``permission: allow`` affordance;+ * Claude / Codex don't supply one.+ */+ extraSlot?: React.ReactNode;+}++/**+ * Settings → Backends Runtime card. Identical visual layout across+ * Claude / Codex / OpenCode pages — previously copy-pasted; lifted+ * here once it became clear new backends inherit the affordances for+ * free instead of needing a third clone (the omission of this card+ * from the Codex page in #282 was the trigger).+ *+ * The component owns no state — pages pass a ``BackendRuntimeState``+ * from ``useBackendRuntime`` and the chip's ``onChanged`` callback is+ * already wired by the hook. The Runtime card stays purely visual so+ * pages remain free to compose it alongside any auth / providers /+ * test panels below.+ */+export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({+ backend,+ label,+ description,+ Icon,+ iconTileClassName,+ iconClassName,+ runtime,+ extraSlot,+}) => {+ const { t } = useTranslation();+ const inputId = `${backend}-cli-path`;++ return (+ <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={clsx(+ 'flex size-11 shrink-0 items-center justify-center rounded-[10px]',+ iconTileClassName,+ )}+ >+ <Icon size={22} className={iconClassName} />+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-[15px] font-semibold text-foreground">{label}</span>+ <span className="text-[12px] text-muted">{description}</span>+ </div>+ </div>+ <div className="flex items-center gap-3">+ <BackendLifecycleChip+ name={backend}+ enabled={runtime.enabled}+ cliStatus={runtime.cliStatus}+ onChanged={runtime.handleLifecycleChanged}+ />+ <ToggleSwitch enabled={runtime.enabled} onClick={runtime.toggleEnabled} />+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <Label htmlFor={inputId} className="text-xs font-medium uppercase text-muted">+ {t('agentDetection.cliPath')}+ </Label>+ <div className="flex gap-2">+ <Input+ id={inputId}+ type="text"+ autoComplete="off"+ spellCheck={false}+ placeholder={t('agentDetection.cliPathPlaceholder', { name: backend }) as string}+ value={runtime.cliPath}+ onChange={(e) => runtime.setCliPath(e.target.value)}+ className="font-mono"+ />+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => void runtime.detect(runtime.cliPath)}+ disabled={runtime.detecting}+ >+ {runtime.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>++ {runtime.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 runtime.install()}+ disabled={runtime.installing}+ >+ {runtime.installing ? (+ <RefreshCw className="size-3.5 animate-spin" />+ ) : (+ <Download className="size-3.5" />+ )}+ {runtime.installing+ ? t('agentDetection.installing')+ : t('agentDetection.installAgent')}+ </Button>+ {runtime.installResult?.message && (+ <span+ className={clsx(+ 'text-[12px]',+ runtime.installResult.ok ? 'text-mint' : 'text-destructive',+ )}+ >+ {runtime.installResult.message}+ </span>+ )}+ </div>+ {runtime.installResult?.output && (+ <div>+ <button+ type="button"+ onClick={() => runtime.setInstallOutputOpen((v) => !v)}+ className="inline-flex items-center gap-1 text-[11px] text-cyan transition hover:text-cyan/80"+ >+ {runtime.installOutputOpen ? (+ <ChevronUp size={12} />+ ) : (+ <ChevronDown size={12} />+ )}+ {t('agentDetection.showOutput')}+ </button>+ {runtime.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">+ {runtime.installResult.output}+ </pre>+ )}+ </div>+ )}+ </div>+ )}++ {extraSlot}++ {runtime.runtimeDirty && (+ <div className="flex justify-end">+ <Button+ variant="brand"+ size="default"+ onClick={() => void runtime.onSaveRuntime()}+ disabled={runtime.savingRuntime}+ >+ <Save className="size-3.5" />+ {runtime.savingRuntime ? t('common.saving') : t('common.save')}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>+ );+};diff --git a/ui/src/components/settings/shared/SegmentedRadio.tsx b/ui/src/components/settings/shared/SegmentedRadio.tsxnew file mode 100644index 000000000..07f371293--- /dev/null+++ b/ui/src/components/settings/shared/SegmentedRadio.tsx@@ -0,0 +1,73 @@+import clsx from 'clsx';++/**+ * Generic segmented-radio control used by the Settings → Backends auth-mode+ * tabs (Claude / Codex / OpenCode) and elsewhere. Previously cloned inline in+ * every page that needed it; lifted here once a third caller appeared.+ *+ * Visual contract mirrors ``shared/RoutingConfigPanel.tsx``:+ * - The whole row is one `role="radiogroup"` with the active option styled+ * mint-on-mint-soft and inactive options muted.+ * - When ``disabled`` is true, the row dims and individual buttons reject+ * clicks. Callers that need a stronger lock (e.g. defending against an iOS+ * Safari quirk where ``disabled`` buttons still register a tap) should+ * ALSO guard the state mutation site itself — see ``useOAuthFlowLock``.+ *+ * The generic ``T`` is a string-literal union of the radio's possible+ * values, so ``onChange`` is typed strictly to the option ids.+ */+export type SegmentedRadioOption<T extends string> = {+ id: T;+ label: string;+};++export interface SegmentedRadioProps<T extends string> {+ value: T;+ onChange: (next: T) => void;+ options: ReadonlyArray<SegmentedRadioOption<T>>;+ ariaLabel: string;+ disabled?: boolean;+}++export function SegmentedRadio<T extends string>({+ value,+ onChange,+ options,+ ariaLabel,+ disabled,+}: SegmentedRadioProps<T>) {+ return (+ <div+ role="radiogroup"+ aria-label={ariaLabel}+ aria-disabled={disabled || undefined}+ className={clsx(+ 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',+ disabled && 'opacity-60',+ )}+ >+ {options.map((opt) => {+ const active = value === opt.id;+ return (+ <button+ key={opt.id}+ type="button"+ role="radio"+ aria-checked={active}+ disabled={disabled}+ 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',+ disabled && 'cursor-not-allowed',+ )}+ >+ {opt.label}+ </button>+ );+ })}+ </div>+ );+}diff --git a/ui/src/components/settings/shared/surfaceBackendNotices.ts b/ui/src/components/settings/shared/surfaceBackendNotices.tsnew file mode 100644index 000000000..02a580046--- /dev/null+++ b/ui/src/components/settings/shared/surfaceBackendNotices.ts@@ -0,0 +1,43 @@+import type { TFunction } from 'i18next';++import type { BackendNotice } from '@/context/ApiContext';++export type ShowToast = (+ message: string,+ type?: 'success' | 'error' | 'warning',+) => void;++/**+ * Surface server-side ``notices`` (from a save / remove response) as+ * warning toasts. Today the only code-driven notice is+ * ``cleared_custom_relay_pointer`` (Codex relay-URL cleanup when+ * switching to OAuth), but the helper is shaped to accept arbitrary+ * future codes — unknown codes fall through to a generic+ * ``codexNoticeGeneric``-style toast so the user at least sees that+ * the server reported a notable side-effect.+ *+ * Previously each provider page duplicated this switch inline.+ */+export function surfaceBackendNotices(+ notices: BackendNotice[] | undefined,+ showToast: ShowToast,+ t: TFunction,+): void {+ if (!notices || notices.length === 0) return;+ for (const notice of notices) {+ if (notice.code === 'cleared_custom_relay_pointer') {+ showToast(+ t('settings.backends.codexNoticeClearedRelayPointer', {+ provider: notice.provider_id || 'custom',+ url: notice.base_url || '',+ }),+ 'warning',+ );+ continue;+ }+ showToast(+ t('settings.backends.codexNoticeGeneric', { code: notice.code }),+ 'warning',+ );+ }+}diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.tsnew file mode 100644index 000000000..4da8af32a--- /dev/null+++ b/ui/src/components/settings/shared/useBackendRuntime.ts@@ -0,0 +1,245 @@+import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useApi } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++export type CliStatus = 'unknown' | 'ok' | 'missing';++export type BackendId = 'claude' | 'codex' | 'opencode';++export interface InstallResult {+ ok: boolean;+ message: string;+ output?: string | null;+}++export interface UseBackendRuntimeOptions {+ /** Backend identifier used in V2Config keys and install_agent dispatch. */+ backend: BackendId;+ /** Fallback CLI binary name when V2Config carries no override. */+ defaultCli: string;+ /**+ * Default backend used by the routing layer when the user has not picked+ * one explicitly. The Save path persists this into ``agents.default_+ * backend`` so toggling enabled-state never wipes the global default.+ */+ fallbackDefaultBackend?: BackendId;+}++export interface BackendRuntimeState {+ /** Initial V2Config + first detect() call have finished. */+ loaded: boolean;+ enabled: boolean;+ cliPath: string;+ cliStatus: CliStatus;+ detecting: boolean;+ installing: boolean;+ installResult: InstallResult | null;+ installOutputOpen: boolean;+ savingRuntime: boolean;+ /** True once the user has typed a path different from the saved one. */+ runtimeDirty: boolean;++ setCliPath: (next: string) => void;+ setInstallOutputOpen: (open: boolean | ((prev: boolean) => boolean)) => void;+ /** Runs ``detectCli`` and updates ``cliPath`` + ``cliStatus``. */+ detect: (binary?: string) => Promise<void>;+ /** Calls ``installAgent`` then re-runs detect with the resolved path. */+ install: () => Promise<void>;+ /** Persists ``enabled`` + ``cliPath`` into V2Config. */+ onSaveRuntime: () => Promise<void>;+ /** Optimistically flip ``enabled`` + persist; rolls back on save failure. */+ toggleEnabled: () => void;+ /**+ * Pass to ``BackendLifecycleChip.onChanged``. Updates ``cliPath`` when+ * the chip reports a fresh install path and re-runs detect.+ */+ handleLifecycleChanged: (info: { installedPath?: string | null } | undefined | null) => Promise<void>;+}++/**+ * Encapsulates the runtime (CLI lifecycle) state shared by every+ * Settings → Backends provider page. Previously each page (Claude /+ * OpenCode / Codex) duplicated ~120 lines of state declarations + the+ * same detect / install / save / toggle handlers; differences were the+ * backend id and the fallback CLI name. Pulling it into a hook means+ * the next backend gets the same lifecycle for free, and any bug fix+ * lands once.+ */+export function useBackendRuntime({+ backend,+ defaultCli,+ fallbackDefaultBackend = 'opencode',+}: UseBackendRuntimeOptions): BackendRuntimeState {+ const api = useApi();+ const { showToast } = useToast();+ const { t } = useTranslation();++ const [loaded, setLoaded] = useState(false);+ const [enabled, setEnabled] = useState(true);+ const [cliPath, setCliPath] = useState(defaultCli);+ const [savedCliPath, setSavedCliPath] = useState(defaultCli);+ const [cliStatus, setCliStatus] = useState<CliStatus>('unknown');+ const [detecting, setDetecting] = useState(false);+ const [installing, setInstalling] = useState(false);+ const [installResult, setInstallResult] = useState<InstallResult | null>(null);+ const [installOutputOpen, setInstallOutputOpen] = useState(false);+ const [savingRuntime, setSavingRuntime] = useState(false);++ const detect = useCallback(+ async (binary?: string) => {+ setDetecting(true);+ try {+ const result = await api.detectCli(binary || cliPath || defaultCli);+ const nextPath = result.path || cliPath || defaultCli;+ setCliPath(nextPath);+ setCliStatus(result.found ? 'ok' : 'missing');+ } catch (e: any) {+ setCliStatus('missing');+ showToast(e?.message || t('common.saveFailed'), 'error');+ } finally {+ setDetecting(false);+ }+ },+ [api, cliPath, defaultCli, showToast, t],+ );++ // Initial load: read V2Config for ``enabled`` + ``cli_path`` and then+ // probe the CLI. Independent of any auth-state fetch the page also+ // performs — that's owned by the page, not the runtime hook.+ useEffect(() => {+ let cancelled = false;+ api+ .getConfig()+ .then((config) => {+ if (cancelled) return;+ const agent = config?.agents?.[backend];+ const initialEnabled = typeof agent?.enabled === 'boolean' ? agent.enabled : true;+ const initialPath = agent?.cli_path || defaultCli;+ setEnabled(initialEnabled);+ setCliPath(initialPath);+ setSavedCliPath(initialPath);+ setLoaded(true);+ void detect(initialPath);+ })+ .catch(() => {+ if (!cancelled) setLoaded(true);+ });+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [api, backend, defaultCli]);++ const install = useCallback(async () => {+ setInstalling(true);+ setInstallResult(null);+ setInstallOutputOpen(false);+ try {+ const result = await api.installAgent(backend);+ 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);+ }+ }, [api, backend, cliPath, detect, showToast, t]);++ const onSaveRuntime = useCallback(async () => {+ setSavingRuntime(true);+ try {+ const config = await api.getConfig();+ const nextAgents = {+ ...(config?.agents || {}),+ [backend]: {+ ...(config?.agents?.[backend] || {}),+ enabled,+ cli_path: cliPath || defaultCli,+ },+ };+ const defaultBackend =+ config?.default_backend ||+ config?.agents?.default_backend ||+ fallbackDefaultBackend;+ 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);+ }+ }, [api, backend, cliPath, defaultCli, enabled, fallbackDefaultBackend, showToast, t]);++ const toggleEnabled = useCallback(() => {+ const next = !enabled;+ setEnabled(next);+ // Persist immediately so the routing layer picks up the flip+ // without forcing the user to also click Save (the Save button+ // is reserved for cli_path edits). Roll back on failure.+ void (async () => {+ try {+ const config = await api.getConfig();+ const nextAgents = {+ ...(config?.agents || {}),+ [backend]: {+ ...(config?.agents?.[backend] || {}),+ enabled: next,+ },+ };+ const defaultBackend =+ config?.default_backend ||+ config?.agents?.default_backend ||+ fallbackDefaultBackend;+ await api.saveConfig({+ agents: { ...nextAgents, default_backend: defaultBackend },+ });+ } catch (e: any) {+ showToast(e?.message || t('common.saveFailed'), 'error');+ setEnabled(!next);+ }+ })();+ }, [api, backend, enabled, fallbackDefaultBackend, showToast, t]);++ const handleLifecycleChanged = useCallback(+ async (info: { installedPath?: string | null } | undefined | null) => {+ const installedPath = info?.installedPath || null;+ if (installedPath) setCliPath(installedPath);+ await detect(installedPath || cliPath);+ },+ [cliPath, detect],+ );++ const runtimeDirty = cliPath !== savedCliPath;++ return {+ loaded,+ enabled,+ cliPath,+ cliStatus,+ detecting,+ installing,+ installResult,+ installOutputOpen,+ savingRuntime,+ runtimeDirty,+ setCliPath,+ setInstallOutputOpen,+ detect,+ install,+ onSaveRuntime,+ toggleEnabled,+ handleLifecycleChanged,+ };+}diff --git a/ui/src/components/settings/shared/useOAuthFlowLock.ts b/ui/src/components/settings/shared/useOAuthFlowLock.tsnew file mode 100644index 000000000..7f25ecda5--- /dev/null+++ b/ui/src/components/settings/shared/useOAuthFlowLock.ts@@ -0,0 +1,77 @@+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useToast } from '@/context/ToastContext';++export interface UseOAuthFlowLockOptions<TMode extends string> {+ /** The real auth-mode setter that the page owns. */+ setAuthMode: (next: TMode) => void;+ /**+ * Tag used in the ``console.warn`` when a guarded write is rejected.+ * Pick something page-specific (e.g. ``claude-auth-mode``) so+ * future regressions are attributable in DevTools.+ */+ warnTag: string;+}++export interface OAuthFlowLock<TMode extends string> {+ oauthFlowActive: boolean;+ setOauthFlowActive: (active: boolean) => void;+ /**+ * Drop-in replacement for the page's ``setAuthMode``. When an OAuth+ * flow is mid-handshake, calls become no-ops with a console.warn ++ * warning toast — so an iOS Safari quirk that smuggles a click past+ * a ``disabled`` button can't tear down the in-progress login.+ */+ guardedSetAuthMode: (next: TMode) => void;+}++/**+ * Guard the auth-mode switcher while a backend OAuth flow is in flight.+ *+ * Background: on iOS Safari, tapping the device-code "Copy" button on the+ * Codex / Claude OAuth panel was flipping the surrounding segmented radio+ * from OAuth to API Key, tearing down the login. The eventual root-cause+ * fix lives in ApiContext memoization (so the page's mount-time+ * ``useEffect([api])`` no longer re-fires on toast renders), but as belt-+ * and-suspenders we ALSO refuse the state mutation while a flow is mid-+ * handshake. The ``disabled`` HTML attribute is not enough on its own —+ * the user has reproduced the flip with the radio rendered disabled.+ *+ * Pages call this once and pass ``guardedSetAuthMode`` to the+ * ``SegmentedRadio`` and ``setOauthFlowActive`` to the+ * ``BackendOAuthPanel.onActiveChange`` prop.+ */+export function useOAuthFlowLock<TMode extends string>({+ setAuthMode,+ warnTag,+}: UseOAuthFlowLockOptions<TMode>): OAuthFlowLock<TMode> {+ const { showToast } = useToast();+ const { t } = useTranslation();++ const [oauthFlowActive, setOauthFlowActive] = useState(false);+ // Ref so the guard always sees the latest value without rebuilding the+ // callback (and therefore the SegmentedRadio's ``onChange`` reference)+ // on every render.+ const oauthFlowActiveRef = useRef(oauthFlowActive);+ oauthFlowActiveRef.current = oauthFlowActive;++ const guardedSetAuthMode = useCallback(+ (next: TMode) => {+ if (oauthFlowActiveRef.current) {+ // eslint-disable-next-line no-console+ console.warn(+ '[%s] rejected change to %s while OAuth flow active',+ warnTag,+ next,+ );+ showToast(t('settings.backends.oauthFlowLockedToast'), 'warning');+ return;+ }+ setAuthMode(next);+ },+ [setAuthMode, showToast, t, warnTag],+ );++ return { oauthFlowActive, setOauthFlowActive, guardedSetAuthMode };+}