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): wire Settings → Backends OAuth UI to web flow
cyhb4e9f837c7fc
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsxnew file mode 100644index 000000000..cadad6833--- /dev/null+++ b/ui/src/components/settings/BackendOAuthPanel.tsx@@ -0,0 +1,390 @@+import React, { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { AlertTriangle, CheckCircle2, Copy, ExternalLink, LogIn, X } from 'lucide-react';+import clsx from 'clsx';++import { Button } from '../ui/button';+import { Input } from '../ui/input';+import { Label } from '../ui/label';+import { useApi } from '@/context/ApiContext';+import type { OAuthWebState } from '@/context/ApiContext';+import { useToast } from '@/context/ToastContext';++type Backend = 'claude' | 'codex';++type LocalState = 'idle' | OAuthWebState;++const POLL_INTERVAL_MS = 2000;+// Stop polling 16 minutes in (matches AgentAuthService.setup_timeout_seconds+// which gives the user 15 minutes to complete login). Anything still+// polling past that has been abandoned and just burns the UI server's+// background OAuth loop.+const POLL_DEADLINE_MS = 16 * 60 * 1000;++export type BackendOAuthPanelProps = {+ backend: Backend;+ /** When ``true`` the user is already signed in (read from the backend's+ * ``get*Auth`` endpoint). We still render a "re-authenticate" button so+ * rotating credentials without dropping to a terminal stays one click. */+ signedIn: boolean;+ /** Heading text shown on the panel (e.g. "Claude account login"). */+ title: string;+ /** Short paragraph under the heading describing what login does. */+ subtitle: string;+ /** Optional callback fired once after the flow lands on ``state === "success"``.+ * The parent typically re-reads ``getClaudeAuth`` / ``getCodexAuth`` here so+ * the on-screen "signed in" indicators move. */+ onSuccess?: () => void;+};++/**+ * Drives the Settings → Backends OAuth flow that mirrors the IM ``/setup``+ * command. Calls the four web endpoints added in PR #282 R5:+ *+ * - POST /backend/<backend>/auth/oauth/start+ * - GET /backend/<backend>/auth/oauth/status/<flow_id>+ * - POST /backend/<backend>/auth/oauth/submit-code (Claude only)+ * - POST /backend/<backend>/auth/oauth/cancel+ *+ * Claude returns a manual auth URL + asks for a callback code; Codex+ * returns a device URL + device code and self-completes when the user+ * finishes auth on OpenAI's side. The state machine + polling are shared.+ */+export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({+ backend,+ signedIn,+ title,+ subtitle,+ onSuccess,+}) => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();++ const [state, setState] = useState<LocalState>('idle');+ const [flowId, setFlowId] = useState<string | null>(null);+ const [url, setUrl] = useState<string | null>(null);+ const [deviceCode, setDeviceCode] = useState<string | null>(null);+ const [code, setCode] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const [starting, setStarting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const pollTimer = useRef<number | null>(null);+ const pollDeadlineRef = useRef<number | null>(null);+ const onSuccessRef = useRef(onSuccess);+ onSuccessRef.current = onSuccess;++ const stopPolling = () => {+ if (pollTimer.current !== null) {+ window.clearTimeout(pollTimer.current);+ pollTimer.current = null;+ }+ pollDeadlineRef.current = null;+ };++ const resetToIdle = () => {+ stopPolling();+ setState('idle');+ setFlowId(null);+ setUrl(null);+ setDeviceCode(null);+ setCode('');+ setError(null);+ };++ // Poll the status endpoint until the flow lands on a terminal state.+ // The server holds the flow alive across requests on its own event loop,+ // so dropping the timer on success/failure is safe — we'll never miss a+ // transition by stopping early.+ useEffect(() => {+ return () => stopPolling();+ }, []);++ const scheduleNextPoll = (currentFlowId: string) => {+ if (pollDeadlineRef.current !== null && Date.now() > pollDeadlineRef.current) {+ setError(t('settings.backends.oauthPollTimedOut') as string);+ setState('failed');+ stopPolling();+ return;+ }+ pollTimer.current = window.setTimeout(() => {+ void pollOnce(currentFlowId);+ }, POLL_INTERVAL_MS);+ };++ const pollOnce = async (currentFlowId: string) => {+ try {+ const data = await api.getOAuthWebStatus(backend, currentFlowId);+ if (!data.ok) {+ setError(data.error || 'flow_not_found');+ setState('failed');+ stopPolling();+ return;+ }+ if (data.url) setUrl(data.url);+ if (data.device_code) setDeviceCode(data.device_code);+ if (data.state) setState(data.state);+ if (data.state === 'success') {+ stopPolling();+ showToast(t('settings.backends.oauthSuccess'), 'success');+ onSuccessRef.current?.();+ return;+ }+ if (data.state === 'failed' || data.state === 'cancelled') {+ setError(data.error || (data.state === 'cancelled' ? 'cancelled' : 'unknown_failure'));+ stopPolling();+ return;+ }+ scheduleNextPoll(currentFlowId);+ } catch (err: any) {+ setError(err?.message || 'poll_failed');+ setState('failed');+ stopPolling();+ }+ };++ const startFlow = async () => {+ setStarting(true);+ setError(null);+ setCode('');+ try {+ const result = await api.startOAuthWeb(backend, true);+ if (!result.ok || !result.flow_id) {+ setError(result.error || result.detail || 'start_failed');+ setState('failed');+ return;+ }+ setFlowId(result.flow_id);+ setUrl(result.url || null);+ setDeviceCode(result.device_code || null);+ setState(result.state || 'starting');+ pollDeadlineRef.current = Date.now() + POLL_DEADLINE_MS;+ scheduleNextPoll(result.flow_id);+ } catch (err: any) {+ setError(err?.message || 'start_failed');+ setState('failed');+ } finally {+ setStarting(false);+ }+ };++ const cancelFlow = async () => {+ if (!flowId) {+ resetToIdle();+ return;+ }+ stopPolling();+ try {+ await api.cancelOAuthWeb(backend, flowId);+ } catch (err) {+ // Swallow — even if the cancel rountrip failed, the UI should still+ // return to the idle state so the user can retry without a stuck+ // panel. The server-side flow times out on its own at 900s.+ }+ resetToIdle();+ };++ const submitCallback = async () => {+ if (!flowId) return;+ const trimmed = code.trim();+ if (!trimmed) return;+ setSubmitting(true);+ setError(null);+ try {+ const result = await api.submitOAuthWebCode(backend, flowId, trimmed);+ if (!result.ok) {+ setError(result.error || result.detail || 'submit_failed');+ return;+ }+ // Server transitioned the flow to "verifying"; reflect that locally+ // so the UI hides the code input immediately rather than waiting for+ // the next poll tick.+ setState('verifying');+ } catch (err: any) {+ setError(err?.message || 'submit_failed');+ } finally {+ setSubmitting(false);+ }+ };++ const copyUrl = async () => {+ if (!url) return;+ try {+ await navigator.clipboard.writeText(url);+ showToast(t('settings.backends.oauthUrlCopied'), 'success');+ } catch {+ showToast(t('common.copyFailed'), 'error');+ }+ };++ const copyDeviceCode = async () => {+ if (!deviceCode) return;+ try {+ await navigator.clipboard.writeText(deviceCode);+ showToast(t('settings.backends.oauthDeviceCodeCopied'), 'success');+ } catch {+ showToast(t('common.copyFailed'), 'error');+ }+ };++ const isActive = state !== 'idle' && state !== 'success' && state !== 'failed' && state !== 'cancelled';+ const showStartButton = state === 'idle' || state === 'success' || state === 'failed' || state === 'cancelled';+ const claudeAwaitingCode = backend === 'claude' && state === 'awaiting_code';+ const codexShowDevice = backend === 'codex' && state === 'awaiting_code' && url && deviceCode;++ const startLabel = signedIn+ ? t('settings.backends.oauthReauthenticate')+ : t(`settings.backends.${backend === 'claude' ? 'claudeSignInButton' : 'codexSignInButton'}`);++ return (+ <div className="flex flex-col gap-4 rounded-lg border border-border bg-surface-2/60 p-4">+ <div className="flex flex-col gap-1">+ <p className="text-[13px] font-semibold text-foreground">{title}</p>+ <p className="text-[12px] leading-relaxed text-muted">{subtitle}</p>+ </div>++ {signedIn && state === 'idle' && (+ <div className="flex items-start gap-2 rounded-md border border-mint/30 bg-mint-soft/40 px-3 py-2">+ <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-mint" />+ <p className="text-[12px] text-mint">+ {t(`settings.backends.${backend === 'claude' ? 'claudeOauthSignedIn' : 'codexOauthSignedIn'}`)}+ </p>+ </div>+ )}++ {state === 'success' && (+ <div className="flex items-start gap-2 rounded-md border border-mint/30 bg-mint-soft/40 px-3 py-2">+ <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-mint" />+ <p className="text-[12px] text-mint">{t('settings.backends.oauthSuccess')}</p>+ </div>+ )}++ {error && (+ <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/[0.08] px-3 py-2">+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0 text-destructive" />+ <p className="text-[12px] leading-relaxed text-destructive">+ {t('settings.backends.oauthFailed', { detail: error })}+ </p>+ </div>+ )}++ {state === 'starting' && (+ <p className="text-[12px] text-muted">{t('settings.backends.oauthStarting')}</p>+ )}++ {state === 'verifying' && (+ <p className="text-[12px] text-muted">{t('settings.backends.oauthVerifying')}</p>+ )}++ {url && (state === 'awaiting_code' || state === 'starting' || state === 'verifying') && (+ <div className="flex flex-col gap-2 rounded-md border border-border bg-background px-3 py-2.5">+ <Label className="text-[11px] font-medium uppercase tracking-wide text-muted">+ {t('settings.backends.oauthAuthUrlLabel')}+ </Label>+ <div className="flex flex-wrap items-center gap-2">+ <a+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ className={clsx(+ 'inline-flex max-w-full items-center gap-1.5 break-all rounded-md',+ 'bg-cyan-soft/40 px-2 py-1 font-mono text-[12px] text-cyan',+ 'transition-colors hover:bg-cyan-soft hover:text-cyan',+ )}+ >+ <ExternalLink className="size-3 shrink-0" />+ <span className="break-all">{url}</span>+ </a>+ <Button type="button" variant="secondary" size="xs" onClick={() => void copyUrl()}>+ <Copy className="size-3" />+ {t('common.copy')}+ </Button>+ </div>+ </div>+ )}++ {codexShowDevice && (+ <div className="flex flex-col gap-2 rounded-md border border-border bg-background px-3 py-2.5">+ <Label className="text-[11px] font-medium uppercase tracking-wide text-muted">+ {t('settings.backends.codexDeviceCodeLabel')}+ </Label>+ <div className="flex flex-wrap items-center gap-2">+ <code className="rounded-md bg-cyan-soft/40 px-2.5 py-1 font-mono text-[14px] font-semibold tracking-[0.18em] text-cyan">+ {deviceCode}+ </code>+ <Button type="button" variant="secondary" size="xs" onClick={() => void copyDeviceCode()}>+ <Copy className="size-3" />+ {t('common.copy')}+ </Button>+ </div>+ <p className="text-[12px] leading-relaxed text-muted">+ {t('settings.backends.codexDeviceInstructions')}+ </p>+ </div>+ )}++ {claudeAwaitingCode && (+ <div className="flex flex-col gap-2">+ <Label htmlFor={`oauth-code-${backend}`} className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.claudeCallbackCodeLabel')}+ </Label>+ <div className="flex gap-2">+ <Input+ id={`oauth-code-${backend}`}+ type="text"+ autoComplete="off"+ spellCheck={false}+ placeholder={t('settings.backends.claudeCallbackCodePlaceholder') as string}+ value={code}+ onChange={(e) => setCode(e.target.value)}+ className="font-mono"+ disabled={submitting}+ />+ <Button+ type="button"+ variant="brand"+ size="sm"+ onClick={() => void submitCallback()}+ disabled={submitting || !code.trim()}+ >+ {submitting ? t('common.submitting') : t('common.submit')}+ </Button>+ </div>+ <p className="text-[12px] leading-relaxed text-muted">+ {t('settings.backends.claudeCallbackCodeHint')}+ </p>+ </div>+ )}++ <div className="flex items-center justify-between gap-2">+ {showStartButton ? (+ <Button+ type="button"+ variant="brand"+ size="default"+ onClick={() => void startFlow()}+ disabled={starting}+ >+ <LogIn className="size-3.5" />+ {starting ? t('common.loading') : startLabel}+ </Button>+ ) : (+ <span className="text-[12px] text-muted">+ {t('settings.backends.oauthInProgress')}+ </span>+ )}+ {isActive && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => void cancelFlow()}+ >+ <X className="size-3.5" />+ {t('common.cancel')}+ </Button>+ )}+ </div>+ </div>+ );+};diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsxindex 069d75c2f..a38fcd676 100644--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx@@ -4,7 +4,6 @@ import { useTranslation } from 'react-i18next';import {AlertTriangle,ArrowLeft,- CheckCircle2,ChevronDown,ChevronUp,Download,@@ -24,6 +23,7 @@ import { Input } from '../ui/input';import { Label } from '../ui/label';import { SettingsPageShell } from './SettingsPageShell';import { BackendLifecycleChip } from './BackendLifecycleChip';+import { BackendOAuthPanel } from './BackendOAuthPanel';import { ToggleSwitch } from './SettingsPrimitives';import { useApi } from '@/context/ApiContext';import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';@@ -225,12 +225,17 @@ export const SettingsClaudeProviderPage: React.FC = () => {const onSaveAuth = async () => {setAuthSaving(true);try {- const payload = {+ // Omit base_url when in OAuth mode so toggling auth_mode does not+ // clear a relay URL the user configured in api_key mode — the+ // backend treats "absent" as "preserve stored value".+ const payload: Record<string, unknown> = {auth_mode: authMode,api_key: authMode === 'api_key' ? (apiKey || undefined) : null,- base_url: baseUrl.trim() || null,};- const result = await api.saveClaudeAuth(payload);+ if (authMode === 'api_key') {+ payload.base_url = baseUrl.trim() || null;+ }+ const result = await api.saveClaudeAuth(payload as any);if (result.ok === false) {showToast(result.message || t('settings.backends.claudeSaveFailed'), 'error');return;@@ -444,71 +449,88 @@ export const SettingsClaudeProviderPage: React.FC = () => {</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>+ <BackendOAuthPanel+ backend={BACKEND_ID}+ // Claude OAuth credentials live in the keychain on Mac,+ // ``~/.claude/credentials.json`` elsewhere — we don't probe+ // either here. The panel always offers a Sign-in button;+ // a successful in-session login flips the label to+ // "Re-authenticate" via its own state.+ signedIn={false}+ title={t('settings.backends.claudeOauthPanelTitle')}+ subtitle={t('settings.backends.claudeOauthPanelSubtitle')}+ onSuccess={() => {+ // Re-fetch the auth state so the "Signed in" pill and+ // any masked-key indicators reflect the fresh login+ // immediately rather than waiting for a page reload.+ void api+ .getClaudeAuth()+ .then((data) => {+ setAuthState(data);+ setAuthMode(data.auth_mode);+ setBaseUrl(data.base_url || '');+ })+ .catch(() => {+ // Already toasted upstream; leave UI on previous state.+ });+ }}+ />)}{authMode === 'api_key' && (- <div className="flex flex-col gap-2">- <Label htmlFor="claude-api-key" className="text-xs font-medium uppercase text-muted">- {t('settings.backends.claudeApiKeyLabel')}- </Label>- <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 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>- <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>+ <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 inheriteddiff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsxindex 2650604e1..a5a3ccb8c 100644--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx@@ -11,6 +11,7 @@ import { Label } from '../ui/label';import { useApi } from '@/context/ApiContext';import type { CodexAuthMode, CodexAuthState } from '@/context/ApiContext';import { useToast } from '@/context/ToastContext';+import { BackendOAuthPanel } from './BackendOAuthPanel';import { SettingsPageShell } from './SettingsPageShell';// Mirrors the segmented-radio pattern in shared/RoutingConfigPanel.tsx so@@ -104,15 +105,21 @@ export const SettingsCodexProviderPage: React.FC = () => {const onSave = async () => {setSaving(true);try {- const payload = {+ // In OAuth mode base_url does not apply, so omit it entirely — the+ // backend's three-state payload semantics preserve whatever is+ // already stored. This keeps a relay URL the user had configured in+ // api_key mode intact when they toggle to OAuth and back.+ const payload: Record<string, unknown> = {auth_mode: authMode,// Send a fresh key only when the user typed one; an empty string// lets the server reuse the stored key (useful when the user is// just updating the base URL).api_key: authMode === 'api_key' ? (apiKey || undefined) : null,- base_url: baseUrl.trim() || null,};- const result = await api.saveCodexAuth(payload);+ if (authMode === 'api_key') {+ payload.base_url = baseUrl.trim() || null;+ }+ const result = await api.saveCodexAuth(payload as any);if (result.ok === false) {// The server returns ok:false for validation/persist failures// (e.g. missing api_key when auth_mode is "api_key") with HTTP 200,@@ -171,11 +178,6 @@ export const SettingsCodexProviderPage: React.FC = () => {? t('settings.backends.codexAuthModeApiKeyHint'): t('settings.backends.codexAuthModeOauthHint')}</p>- {authMode === 'oauth' && state?.has_chatgpt_tokens && (- <p className="text-[12px] text-mint">- {t('settings.backends.codexHasChatgptTokens')}- </p>- )}{state?.auth_mode_uncertain && (// Codex stores credentials in the OS keychain by default// (``cli_auth_credentials_store=auto``). When there's no@@ -197,56 +199,82 @@ export const SettingsCodexProviderPage: React.FC = () => {)}</div>+ {authMode === 'oauth' && (+ <BackendOAuthPanel+ backend="codex"+ signedIn={!!state?.has_chatgpt_tokens}+ title={t('settings.backends.codexOauthPanelTitle')}+ subtitle={t('settings.backends.codexOauthPanelSubtitle')}+ onSuccess={() => {+ // Re-read Codex auth state so the "ChatGPT tokens detected"+ // line and any keychain hints catch up with the freshly+ // minted credential without a manual page reload.+ void api+ .getCodexAuth()+ .then((data) => {+ setState(data);+ setAuthMode(data.auth_mode);+ setBaseUrl(data.base_url || '');+ })+ .catch(() => {+ /* ApiContext already toasted; leave existing state. */+ });+ }}+ />+ )}+{authMode === 'api_key' && (- <div className="flex flex-col gap-2">- <Label htmlFor="codex-api-key" className="text-xs font-medium uppercase text-muted">- {t('settings.backends.codexApiKeyLabel')}- </Label>- <div className="relative">- <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />- <Input- id="codex-api-key"- type="password"- autoComplete="off"- spellCheck={false}- placeholder={t('settings.backends.codexApiKeyPlaceholder') as string}- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- className="pl-9 font-mono"- />+ <>+ <div className="flex flex-col gap-2">+ <Label htmlFor="codex-api-key" className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.codexApiKeyLabel')}+ </Label>+ <div className="relative">+ <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />+ <Input+ id="codex-api-key"+ type="password"+ autoComplete="off"+ spellCheck={false}+ placeholder={t('settings.backends.codexApiKeyPlaceholder') as string}+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ className="pl-9 font-mono"+ />+ </div>+ <p className="text-[12px] text-muted">{apiKeyStatus}</p></div>- <p className="text-[12px] text-muted">{apiKeyStatus}</p>- </div>- )}- <div className="flex flex-col gap-2">- <Label htmlFor="codex-base-url" className="text-xs font-medium uppercase text-muted">- {t('settings.backends.codexBaseUrlLabel')}- </Label>- <div className="flex gap-2">- <Input- id="codex-base-url"- type="url"- autoComplete="off"- spellCheck={false}- placeholder={t('settings.backends.codexBaseUrlPlaceholder') as string}- value={baseUrl}- onChange={(e) => setBaseUrl(e.target.value)}- className="font-mono"- />- <Button- type="button"- variant="secondary"- size="sm"- onClick={() => setBaseUrl('')}- disabled={!baseUrl}- >- <RotateCcw className="size-3.5" />- {t('settings.backends.codexBaseUrlReset')}- </Button>- </div>- <p className="text-[12px] text-muted">{t('settings.backends.codexBaseUrlHint')}</p>- </div>+ <div className="flex flex-col gap-2">+ <Label htmlFor="codex-base-url" className="text-xs font-medium uppercase text-muted">+ {t('settings.backends.codexBaseUrlLabel')}+ </Label>+ <div className="flex gap-2">+ <Input+ id="codex-base-url"+ type="url"+ autoComplete="off"+ spellCheck={false}+ placeholder={t('settings.backends.codexBaseUrlPlaceholder') as string}+ value={baseUrl}+ onChange={(e) => setBaseUrl(e.target.value)}+ className="font-mono"+ />+ <Button+ type="button"+ variant="secondary"+ size="sm"+ onClick={() => setBaseUrl('')}+ disabled={!baseUrl}+ >+ <RotateCcw className="size-3.5" />+ {t('settings.backends.codexBaseUrlReset')}+ </Button>+ </div>+ <p className="text-[12px] text-muted">{t('settings.backends.codexBaseUrlHint')}</p>+ </div>+ </>+ )}<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" />diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 088546028..06ede5d49 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -25,6 +25,14 @@ export type ApiContextType = {saveCodexAuth: (payload: CodexAuthPayload) => Promise<CodexAuthSaveResult>;getClaudeAuth: () => Promise<ClaudeAuthState>;saveClaudeAuth: (payload: ClaudeAuthPayload) => Promise<ClaudeAuthSaveResult>;+ startOAuthWeb: (backend: 'claude' | 'codex', forceReset?: boolean) => Promise<OAuthWebStartResult>;+ getOAuthWebStatus: (backend: 'claude' | 'codex', flowId: string) => Promise<OAuthWebStatus>;+ submitOAuthWebCode: (+ backend: 'claude' | 'codex',+ flowId: string,+ code: string,+ ) => Promise<OAuthWebMutationResult>;+ cancelOAuthWeb: (backend: 'claude' | 'codex', flowId: string) => Promise<OAuthWebMutationResult>;getOpencodeProviders: () => Promise<OpencodeProviderListResult>;setOpencodeProviderAuth: (providerId: string,@@ -205,6 +213,43 @@ export type ClaudeAuthSaveResult = ClaudeAuthState & {// + ``/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 OAuthWebState =+ | 'starting'+ | 'awaiting_code'+ | 'verifying'+ | 'success'+ | 'failed'+ | 'cancelled';++export type OAuthWebStartResult = {+ ok: boolean;+ flow_id?: string;+ backend?: 'claude' | 'codex';+ state?: OAuthWebState;+ url?: string | null;+ device_code?: string | null;+ awaiting_code?: boolean;+ error?: string;+ detail?: string;+};++export type OAuthWebStatus = {+ ok: boolean;+ flow_id?: string;+ backend?: 'claude' | 'codex';+ state?: OAuthWebState;+ url?: string | null;+ device_code?: string | null;+ awaiting_code?: boolean;+ error?: string | null;+};++export type OAuthWebMutationResult = {+ ok: boolean;+ error?: string;+ detail?: string;+};+export type OpencodeProvider = {id: string;name: string;@@ -328,6 +373,23 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrensaveCodexAuth: (payload) => postJson('/backend/codex/auth', payload),getClaudeAuth: () => getJson('/backend/claude/auth'),saveClaudeAuth: (payload) => postJson('/backend/claude/auth', payload),+ startOAuthWeb: (backend, forceReset = true) =>+ postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/start`, {+ force_reset: forceReset,+ }),+ getOAuthWebStatus: (backend, flowId) =>+ getJson(+ `/backend/${encodeURIComponent(backend)}/auth/oauth/status/${encodeURIComponent(flowId)}`,+ ),+ submitOAuthWebCode: (backend, flowId, code) =>+ postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/submit-code`, {+ flow_id: flowId,+ code,+ }),+ cancelOAuthWeb: (backend, flowId) =>+ postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/cancel`, {+ flow_id: flowId,+ }),getOpencodeProviders: () => getJson('/backend/opencode/providers'),setOpencodeProviderAuth: (providerId, apiKey, baseUrl) =>// Forward ``base_url`` only when the caller passed somethingdiff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 8e540e8f0..bdec7fd3a 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -41,6 +41,8 @@"viewLogs": "View logs","saveAndRestart": "Save & Restart","close": "Close",+ "submit": "Submit",+ "submitting": "Submitting…","copyFailed": "Copy failed, please copy it manually","themeSystem": "System theme","themeLight": "Light theme",@@ -109,7 +111,7 @@"codexBackToBackends": "Back to backends","codexAuthModeLabel": "Authentication mode","codexAuthModeOauth": "Sign in with ChatGPT",- "codexAuthModeOauthHint": "Run `codex login` in a terminal to complete the OAuth flow. Vibe Remote stops managing the API key while this is selected.",+ "codexAuthModeOauthHint": "Use a ChatGPT account to authorize Codex. Vibe Remote stops managing the API key while this is selected.","codexAuthModeApiKey": "OpenAI API key","codexAuthModeApiKeyHint": "Codex will call the OpenAI-compatible endpoint with the key below. Switch to ChatGPT login if you prefer not to manage a key.","codexApiKeyLabel": "API key",@@ -120,7 +122,13 @@"codexBaseUrlPlaceholder": "https://api.openai.com/v1","codexBaseUrlHint": "Leave empty to use OpenAI's default endpoint. Compatible relays (e.g. Azure OpenAI, OpenRouter) accept their own URL here.","codexBaseUrlReset": "Reset to default",- "codexHasChatgptTokens": "Codex has cached ChatGPT credentials from a previous `codex login`.",+ "codexHasChatgptTokens": "Codex has cached ChatGPT credentials from a previous sign-in.",+ "codexOauthSignedIn": "Codex is signed in via ChatGPT.",+ "codexOauthPanelTitle": "Sign in with your ChatGPT account",+ "codexOauthPanelSubtitle": "Open the device URL below, enter the code, and finish login in your browser. Codex will detect completion automatically.",+ "codexSignInButton": "Sign in with ChatGPT",+ "codexDeviceCodeLabel": "Device code",+ "codexDeviceInstructions": "Open the URL above, paste the device code, and complete sign-in in your browser. This page updates automatically when Codex receives the callback.","codexCredentialsStoreKeyringWarn": "Codex is currently set to store credentials in the OS keychain ({{store}}). Saving here will switch it to file storage so Vibe Remote can manage the API key directly.","codexAuthModeUncertain": "Codex is set to store credentials in the OS keychain ({{store}}), so the current auth state cannot be read here. Choose a mode below and save — Vibe Remote will switch Codex to file storage so future reads stay accurate.","codexInfoHint": "Saving here writes `~/.codex/auth.json` and `~/.codex/config.toml`, then restarts the persistent app-server so the next request uses the new settings.",@@ -130,11 +138,16 @@"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.",+ "claudeAuthModeOauthHint": "Use your Anthropic account to authorize Claude Code. Vibe Remote stops managing the API key while this is selected.","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.",+ "claudeOauthSignedIn": "Claude is signed in.",+ "claudeOauthPanelTitle": "Sign in with your Anthropic account",+ "claudeOauthPanelSubtitle": "Open the authorization URL below, approve access, then paste the callback code Anthropic shows you.",+ "claudeSignInButton": "Sign in with Claude",+ "claudeCallbackCodeLabel": "Authorization code",+ "claudeCallbackCodePlaceholder": "code#state",+ "claudeCallbackCodeHint": "Anthropic shows a value like `abc123#xyz`. Paste it here exactly — Vibe Remote forwards it to Claude Code.","claudeApiKeyLabel": "API key","claudeApiKeyPlaceholder": "sk-ant-...","claudeApiKeyConfigured": "A key of length {{length}} is currently stored.",@@ -150,6 +163,16 @@"claudeSaving": "Saving…","claudeSaveSuccess": "Claude auth saved","claudeSaveFailed": "Could not save Claude auth",+ "oauthAuthUrlLabel": "Authorization URL",+ "oauthInProgress": "Login in progress…",+ "oauthStarting": "Starting OAuth flow…",+ "oauthVerifying": "Verifying credentials…",+ "oauthSuccess": "Signed in successfully.",+ "oauthFailed": "OAuth flow failed: {{detail}}",+ "oauthPollTimedOut": "Login did not complete within the allowed time. Please retry.",+ "oauthUrlCopied": "URL copied to clipboard.",+ "oauthDeviceCodeCopied": "Device code copied to clipboard.",+ "oauthReauthenticate": "Re-authenticate","opencodeProvidersTitle": "Providers","opencodeProvidersSubtitle": "Lazy-loaded from the OpenCode server · auth handled via API key or `opencode auth login`","opencodeProvidersCount": "{{configured}}/{{total}} configured",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e4d0c7568..a73a7ac3d 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -41,6 +41,8 @@"viewLogs": "查看日志","saveAndRestart": "保存并重启","close": "关闭",+ "submit": "提交",+ "submitting": "提交中…","copyFailed": "复制失败,请手动复制","themeSystem": "跟随系统主题","themeLight": "浅色主题",@@ -109,7 +111,7 @@"codexBackToBackends": "返回后端列表","codexAuthModeLabel": "认证方式","codexAuthModeOauth": "使用 ChatGPT 登录",- "codexAuthModeOauthHint": "请在终端执行 `codex login` 完成 OAuth 流程。选中此项后,Vibe Remote 不再管理 API Key。",+ "codexAuthModeOauthHint": "使用 ChatGPT 账号授权 Codex。选中此项后,Vibe Remote 不再管理 API Key。","codexAuthModeApiKey": "OpenAI API Key","codexAuthModeApiKeyHint": "Codex 会用下方的 Key 调用 OpenAI 兼容接口。如果不希望托管 Key,可切回 ChatGPT 登录。","codexApiKeyLabel": "API Key",@@ -120,7 +122,13 @@"codexBaseUrlPlaceholder": "https://api.openai.com/v1","codexBaseUrlHint": "留空则使用 OpenAI 默认接口。兼容网关(如 Azure OpenAI、OpenRouter)可填入各自的 URL。","codexBaseUrlReset": "重置为默认",- "codexHasChatgptTokens": "检测到上一次 `codex login` 缓存的 ChatGPT 凭据。",+ "codexHasChatgptTokens": "检测到上一次登录缓存的 ChatGPT 凭据。",+ "codexOauthSignedIn": "Codex 已通过 ChatGPT 登录。",+ "codexOauthPanelTitle": "使用 ChatGPT 账号登录",+ "codexOauthPanelSubtitle": "在下方打开设备授权链接、输入设备码,并在浏览器里完成登录。Codex 会自动检测完成状态。",+ "codexSignInButton": "使用 ChatGPT 登录",+ "codexDeviceCodeLabel": "设备码",+ "codexDeviceInstructions": "打开上面的链接、粘贴设备码,然后在浏览器里完成登录。Codex 收到回调后此页会自动刷新。","codexCredentialsStoreKeyringWarn": "Codex 当前设置为把凭据存储在系统钥匙串中({{store}})。保存后将切换为文件存储,Vibe Remote 才能直接读写 API key。","codexAuthModeUncertain": "Codex 当前设置为把凭据存储在系统钥匙串中({{store}}),此处读不到登录状态。请在下方选择一种模式并保存——Vibe Remote 会将 Codex 切换为文件存储,后续读取就能保持准确。","codexInfoHint": "保存会写入 `~/.codex/auth.json` 与 `~/.codex/config.toml`,并重启常驻 app-server 以加载新配置。",@@ -130,11 +138,16 @@"codexSaveFailed": "保存 Codex 认证失败","claudeAuthModeLabel": "认证方式","claudeAuthModeOauth": "Claude 账号登录",- "claudeAuthModeOauthHint": "在终端运行 `claude login` 完成 Anthropic 账号登录。Vibe Remote 会自动复用这些令牌,并停止管理 API Key。",+ "claudeAuthModeOauthHint": "使用 Anthropic 账号授权 Claude Code。选中此项后,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。",+ "claudeOauthSignedIn": "Claude 已登录。",+ "claudeOauthPanelTitle": "使用 Anthropic 账号登录",+ "claudeOauthPanelSubtitle": "打开下方授权链接、批准访问,然后粘贴 Anthropic 返回给你的回调码。",+ "claudeSignInButton": "使用 Claude 登录",+ "claudeCallbackCodeLabel": "授权码",+ "claudeCallbackCodePlaceholder": "code#state",+ "claudeCallbackCodeHint": "Anthropic 会展示类似 `abc123#xyz` 的值,请原样粘贴到这里。Vibe Remote 会把它转交给 Claude Code 完成登录。","claudeApiKeyLabel": "API Key","claudeApiKeyPlaceholder": "sk-ant-...","claudeApiKeyConfigured": "当前已保存一份长度为 {{length}} 的 Key。",@@ -150,6 +163,16 @@"claudeSaving": "保存中…","claudeSaveSuccess": "Claude 认证已保存","claudeSaveFailed": "保存 Claude 认证失败",+ "oauthAuthUrlLabel": "授权链接",+ "oauthInProgress": "登录进行中…",+ "oauthStarting": "正在启动 OAuth 流程…",+ "oauthVerifying": "正在验证凭据…",+ "oauthSuccess": "登录成功。",+ "oauthFailed": "OAuth 失败:{{detail}}",+ "oauthPollTimedOut": "登录在允许时间内未完成,请重试。",+ "oauthUrlCopied": "链接已复制到剪贴板。",+ "oauthDeviceCodeCopied": "设备码已复制到剪贴板。",+ "oauthReauthenticate": "重新登录","opencodeProvidersTitle": "服务商","opencodeProvidersSubtitle": "从 OpenCode Server 实时拉取 · 通过 API Key 或 `opencode auth login` 完成授权","opencodeProvidersCount": "已配置 {{configured}}/{{total}}",diff --git a/vibe/api.py b/vibe/api.pyindex 2fad7570b..3348fb7eb 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2313,12 +2313,19 @@ def save_codex_auth(payload: dict) -> dict: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):+ # Three-state ``base_url`` payload (matches the OpenCode provider save+ # handler and the new web Settings → OAuth flow): omitting the key+ # means "leave the stored value alone" so toggling auth_mode does not+ # accidentally clear a relay URL the user had set up in api_key mode.+ base_url_present = "base_url" in payload+ raw_base_url = payload.get("base_url") if base_url_present else None+ if base_url_present and 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+ base_url_change: Optional[str] = None+ if base_url_present:+ base_url_change = raw_base_url.strip() if isinstance(raw_base_url, str) else None+ if base_url_change == "":+ base_url_change = Noneif auth_mode == "api_key" and not api_key:# Allow callers to PATCH base_url alone by reusing the stored key.@@ -2346,10 +2353,23 @@ def save_codex_auth(payload: dict) -> dict:if not api_key:return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}+ # Resolve the effective base_url: explicit payload wins, otherwise+ # preserve whatever V2Config currently has.+ if base_url_present:+ effective_base_url = base_url_change+ else:+ with CONFIG_LOCK:+ try:+ existing_cfg = load_config()+ stored_codex = getattr(getattr(existing_cfg, "agents", None), "codex", None)+ effective_base_url = getattr(stored_codex, "base_url", None) or None+ except Exception:+ effective_base_url = None+from vibe.codex_config import apply_codex_authtry:- apply_codex_auth(auth_mode=auth_mode, api_key=api_key, base_url=base_url)+ apply_codex_auth(auth_mode=auth_mode, api_key=api_key, base_url=effective_base_url)except ValueError as exc:return {"ok": False, "message": str(exc)}except OSError as exc:@@ -2363,7 +2383,7 @@ def save_codex_auth(payload: dict) -> dict:config = V2Config()config.agents.codex.auth_mode = auth_modeconfig.agents.codex.api_key = api_key if auth_mode == "api_key" else None- config.agents.codex.base_url = base_url+ config.agents.codex.base_url = effective_base_urlconfig.save()restart_result = restart_backend("codex")@@ -2467,12 +2487,17 @@ def save_claude_auth(payload: dict) -> dict: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):+ # Three-state ``base_url`` payload semantics (matches Codex/OpenCode):+ # absent key → keep stored value; null/blank → clear; non-blank → set.+ base_url_present = "base_url" in payload+ raw_base_url = payload.get("base_url") if base_url_present else None+ if base_url_present and 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+ base_url_change: Optional[str] = None+ if base_url_present:+ base_url_change = raw_base_url.strip() if isinstance(raw_base_url, str) else None+ if base_url_change == "":+ base_url_change = Noneif auth_mode == "api_key" and not api_key:# Reuse stored key for base-URL-only updates. Unlike Codex we@@ -2504,7 +2529,9 @@ def save_claude_auth(payload: dict) -> dict:config = V2Config()config.agents.claude.auth_mode = auth_modeconfig.agents.claude.api_key = api_key if auth_mode == "api_key" else None- config.agents.claude.base_url = base_url+ if base_url_present:+ config.agents.claude.base_url = base_url_change+ # else: keep whatever is already stored (omitted payload key).config.save()# Claude is one-shot per request — no daemon to restart. Return a