Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
/**
* ComputerUseSection — Settings →「电脑使用 / Computer Use」面板。
* ---------------------------------------------------------------------------
* 电脑使用类能力的统一入口。当前承载「浏览器自动化」(cindy_browser MCP):
* - 启用开关 (复用 builtin plugin 系统, id='browser', 项目级 .claude/settings.json)
* - 本机浏览器探测状态 (maker.browser.status — 只探测不启动)
* - 未探测到时引导去 Chrome 官方下载页
* 以及「直接操作电脑」能力 (cindy_computer MCP, machine-wide opt-in).
*
* 数据流:
* - mount → 并行拉 plugins.getState('browser', workingDir) (取 browser 开关态)
* + browser.status()。注意 browser 是 HOSTED_ELSEWHERE, 不在 plugins.list()
* 里, 必须按 id 直接读单个状态, 否则 find() 永远 undefined。
* - 各项配置独立加载;慢请求只影响对应控件,不阻塞整页。
* 浏览器开关读写完全复用 builtin plugin IPC, 不新造持久化通道。
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import {
Check,
ChevronDown,
Globe,
MonitorCog,
Download,
LogIn,
ExternalLink,
RefreshCw,
Smartphone,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import accessibilityPermissionIcon from '@/assets/system-settings/accessibility-icon.png';
import screenRecordingPermissionIcon from '@/assets/system-settings/screen-recording-icon.png';
import { toast } from '@/lib/toast';
import { Switch } from '@/components/ui/switch';
import { Spinner } from '@/components/ui/spinner';
import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { createLogger } from '@/lib/logger';
import { extractIpcError } from '@/utils/ipcError';
import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';
import { pluginMarketErrorKey } from '@/features/plugin/lib/pluginMarketErrorKey';
import { BrowserBackendSubsection } from './BrowserBackendSubsection';
import { useAutomationSettingsRead } from './useAutomationSettingsRead';
import { ComputerPermissionRow } from './ComputerPermissionRow';
import { BrowserRealProfileSubsection } from './BrowserRealProfileSubsection';
import {
RECOMMENDED_PAGE_CONTROL_PLUGIN_ID,
REAL_PROFILE_READ_DENIED,
type BrowserBackendHealth,
} from '../../../shared/browserBackend';
import { ghostInstallApprovalToken } from '../../../shared/ghost';
import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
import {
browserOpenForLoginErrorCode,
browserOpenForLoginToastKey,
} from './browserOpenForLoginError';
import {
androidDeviceLabel,
androidStatusFallback,
describeAndroidDeviceStatus,
getAndroidConnectionGuideKind,
} from './androidStatusPresentation';
import {
getComputerPermissionSwitchChecked,
isComputerPermissionPreflightInconclusive,
isComputerPermissionReady,
shouldStartComputerPermissionGuide,
} from './computerPermissionFlow';
import {
confirmEnableRealProfile,
guideFullDiskAccessAfterReadDenied,
} from './realProfilePermissionGuide';
const log = createLogger('ComputerUseSection');
const CHROME_DOWNLOAD_URL = 'https://www.google.com/chrome/';
const CUA_GITHUB_URL = 'https://github.com/trycua/cua';
const ANDROID_PLUGIN_ID = 'android';
const BROWSER_PLUGIN_ID = 'browser';
const COMPUTER_PLUGIN_ID = 'computer';
const COMPUTER_PERMISSION_POLL_INTERVAL_MS = 1_500;
const COMPUTER_PERMISSION_POLL_TIMEOUT_MS = 300_000;
const MAC_ACCESSIBILITY_SETTINGS_URL =
'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility';
const MAC_SCREEN_RECORDING_SETTINGS_URL =
'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture';
const ACTION_BUTTON_CLASS = cn(
'flex items-center gap-1.5 shrink-0 h-7 px-3 rounded-full',
'bg-[var(--settings-input-bg)] text-[var(--settings-section-title)]',
'text-12 font-medium hover:bg-[var(--surface-chip)] transition-colors',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
'disabled:opacity-50 disabled:pointer-events-none',
);
const ANDROID_AUTO_DEVICE_VALUE = '__auto__';
function browserBackendHealthFallback(
active: 'external' | 'rsb-webview' | 'user-browser',
): BrowserBackendHealth {
return {
active,
status: 'error',
canRecover: active === 'rsb-webview',
reason: 'status-failed',
};
}
function androidSourceLabelKey(source: AndroidAdbPathSource | null | undefined): string {
switch (source) {
case 'custom':
return 'settings.computerUse.android.adb.source.custom';
case 'env':
return 'settings.computerUse.android.adb.source.env';
case 'prepared':
return 'settings.computerUse.android.adb.source.prepared';
case 'bundled':
return 'settings.computerUse.android.adb.source.bundled';
case 'sdk':
return 'settings.computerUse.android.adb.source.sdk';
case 'path':
return 'settings.computerUse.android.adb.source.path';
default:
return 'settings.computerUse.android.adb.source.auto';
}
}
function isComputerAccessibilityPermissionReady(status: ComputerDriverStatus | null): boolean {
return status?.permissionState?.accessibility === 'granted';
}
function isComputerScreenRecordingPermissionReady(status: ComputerDriverStatus | null): boolean {
const permissionState = status?.permissionState;
// capturable 是 daemon 的 ScreenCaptureKit 实测,优先于 TCC 数据库记录(screenRecording):
// driver 更新后的 stale grant 表现为「记录 granted / 实测 missing」,必须按未授权展示,
// 让用户从徽章进系统设置重新授权;只有实测缺席(旧版 driver)才回退信记录。
if (permissionState?.screenRecordingCapturable === 'granted') return true;
if (permissionState?.screenRecordingCapturable === 'missing') return false;
return permissionState?.screenRecording === 'granted';
}
function getComputerPermissionLogSummary(status: ComputerDriverStatus | null) {
const permissionState = status?.permissionState;
return {
installed: status?.installed,
daemonRunning: status?.daemonRunning,
permissionStatus: permissionState?.status,
accessibility: permissionState?.accessibility,
screenRecording: permissionState?.screenRecording,
screenRecordingCapturable: permissionState?.screenRecordingCapturable,
source: permissionState?.source,
reason: permissionState?.reason,
};
}
interface ComputerUseSectionProps {
/** Active session working dir — the project whose .claude/settings.json the
* browser enable toggle reads/writes. */
workingDir?: string;
}
function ConfigurationReadStatus({
label,
status,
retry,
}: {
label: string;
status: 'loading' | 'retrying' | 'error' | 'ready';
retry: () => void;
}) {
const { t } = useTranslation();
if (status === 'ready') return null;
return (
<div
role="status"
aria-label={label}
className="flex flex-wrap items-center gap-2 border-t border-[var(--settings-theme-card-border)] px-4 py-3 text-12 text-[var(--settings-section-desc)]"
>
{status !== 'error' ? <Spinner size={12} /> : null}
<span>{t(`settings.computerUse.configurationRead.${status}`, { section: label })}</span>
{status === 'error' ? (
<Button variant="secondary" size="sm" onClick={retry}>
{t('settings.computerUse.configurationRead.retry')}
</Button>
) : null}
</div>
);
}
export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const { t, i18n } = useTranslation();
const browserRead = useAutomationSettingsRead(
'browser enable state',
useCallback(
async () =>
(await window.electronAPI.maker.plugins.getState(BROWSER_PLUGIN_ID, workingDir))
.effectiveEnabled,
[workingDir],
),
);
const { value: browserEnabled, setValue: setBrowserEnabled } = browserRead;
const [androidEnabled, setAndroidEnabled] = useState<boolean | null>(null);
const computerRead = useAutomationSettingsRead(
'computer enable state',
useCallback(
async () =>
(await window.electronAPI.maker.plugins.getState(COMPUTER_PLUGIN_ID)).effectiveEnabled,
[],
),
);
const { value: computerEnabled, setValue: setComputerEnabled } = computerRead;
const availabilityRead = useAutomationSettingsRead(
'browser detection',
useCallback(() => window.electronAPI.maker.browser.status(), []),
);
const availability = availabilityRead.value;
const [androidStatus, setAndroidStatus] = useState<AndroidStatusSummary | null>(null);
const [androidConfig, setAndroidConfig] = useState<AndroidAutomationConfigState | null>(null);
const [androidAdbPathDraft, setAndroidAdbPathDraft] = useState('');
const [androidAdbPathEdited, setAndroidAdbPathEdited] = useState(false);
const [computerStatus, setComputerStatus] = useState<ComputerDriverStatus | null>(null);
// Update results remain visible, including failures and cached check times.
const [driverUpdate, setDriverUpdate] = useState<ComputerDriverUpdateCheck | null>(null);
const [driverCheckPending, setDriverCheckPending] = useState(false);
const [driverCheckFailed, setDriverCheckFailed] = useState(false);
const [driverUpdatePending, setDriverUpdatePending] = useState(false);
// main 侧采样广播的下载进度;null = 未开始/已结束(显示通用「更新中…」)。
const [driverUpdateProgress, setDriverUpdateProgress] =
useState<ComputerDriverUpdateProgress | null>(null);
const [togglePending, setTogglePending] = useState(false);
const [androidTogglePending, setAndroidTogglePending] = useState(false);
const [androidStatusPending, setAndroidStatusPending] = useState(false);
const [androidDevicePending, setAndroidDevicePending] = useState(false);
const [androidAdbPathPending, setAndroidAdbPathPending] = useState(false);
const [androidPreparePending, setAndroidPreparePending] = useState(false);
const [computerTogglePending, setComputerTogglePending] = useState(false);
const [computerInstallPending, setComputerInstallPending] = useState(false);
const [computerPermissionPending, setComputerPermissionPending] = useState(false);
const [computerPermissionRecheckPending, setComputerPermissionRecheckPending] = useState(false);
const [computerDetailsOpen, setComputerDetailsOpen] = useState(false);
const computerUseSectionMountedRef = useRef(true);
const computerTogglePendingRef = useRef(false);
const computerPermissionPendingRef = useRef(false);
const computerPermissionPollTimerRef = useRef<number | null>(null);
// Native grant remains cancellable while the user is moving between Settings panes.
const computerPermissionGrantInProgressRef = useRef(false);
const computerEnableIntentRef = useRef(false);
// 授权流程代际号:引导弹窗「取消」时 +1。grant/preflight 的 await 期间用户可能
// 已取消,continuation 必须校验代际,否则被取消的流程仍会打开系统设置抢焦点。
const computerPermissionFlowSeqRef = useRef(0);
const computerPermissionCompletionInFlightRef = useRef(false);
const resetComputerPermissionFlow = useCallback(() => {
computerPermissionGrantInProgressRef.current = false;
}, []);
const cancelNativeComputerPermissionGrant = useCallback(() => {
void window.electronAPI.maker.computer.cancelPermissionGrant().catch((err) => {
log.debug('computer.cancelPermissionGrant failed (ignored)', err);
});
}, []);
useEffect(() => {
computerPermissionPendingRef.current = computerPermissionPending;
}, [computerPermissionPending]);
// Leaving Settings / Plugin detail invalidates the whole enable attempt,
// including install and fresh-preflight awaits before the guide is visible.
useEffect(() => {
computerUseSectionMountedRef.current = true;
return () => {
computerUseSectionMountedRef.current = false;
computerPermissionFlowSeqRef.current += 1;
computerEnableIntentRef.current = false;
computerPermissionCompletionInFlightRef.current = false;
const hadActivePermissionFlow =
computerTogglePendingRef.current ||
computerPermissionPendingRef.current ||
computerPermissionGrantInProgressRef.current;
resetComputerPermissionFlow();
if (hadActivePermissionFlow) {
cancelNativeComputerPermissionGrant();
}
computerTogglePendingRef.current = false;
};
}, [cancelNativeComputerPermissionGrant, resetComputerPermissionFlow]);
// 引导弹窗的取消:终止当前的一次性授权请求。
const handleCancelPermissionGuide = useCallback(() => {
computerPermissionFlowSeqRef.current += 1;
setComputerPermissionPending(false);
computerEnableIntentRef.current = false;
computerPermissionCompletionInFlightRef.current = false;
resetComputerPermissionFlow();
// 收割 main 侧在途的 grant 子进程:取消必须让原生授权流程真正停下,
// 而不是只藏起引导弹窗(否则 15s 复用窗口内下次点击还会接上旧流程)。
cancelNativeComputerPermissionGrant();
}, [cancelNativeComputerPermissionGrant, resetComputerPermissionFlow]);
const openComputerPermissionSettings = useCallback(
async (url: string, reason: string): Promise<boolean> => {
log.debug('opening computer permission settings', { reason, url });
const result = await window.electronAPI.openExternal(url);
if (!result.success) {
toast.error(t('settings.computerUse.directControl.toast.openPermissionSettingsFailed'));
return false;
}
return true;
},
[t],
);
// Native macOS onboarding observes the System Settings checkbox in main.
// Feed those changes back into this panel so the two permission steps can
// advance without asking the user to press Recheck.
useEffect(() => {
return window.electronAPI.maker.computer.onPermissionGuideStatusChanged((status) => {
setComputerStatus(status);
if (!computerPermissionPendingRef.current) return;
if (!status.installed || !isComputerPermissionReady(status)) {
return;
}
if (computerPermissionCompletionInFlightRef.current) return;
computerPermissionCompletionInFlightRef.current = true;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
cancelNativeComputerPermissionGrant();
if (computerEnableIntentRef.current || computerEnabled) {
void window.electronAPI.maker.plugins
.setEnabled(COMPUTER_PLUGIN_ID, true)
.then((result) => {
setComputerEnabled(true);
if (result.codexMcpRefreshed === false) {
toast.warning(t('settings.computerUse.codexRefreshDeferred'));
return;
}
toast.success(t('settings.computerUse.directControl.toast.enabled'));
})
.catch((err) => {
log.warn('plugins.setEnabled(computer) after native guide failed', err);
toast.error(t('settings.computerUse.directControl.toast.toggleFailed'));
})
.finally(() => {
computerPermissionCompletionInFlightRef.current = false;
});
} else {
computerPermissionCompletionInFlightRef.current = false;
}
});
}, [
cancelNativeComputerPermissionGrant,
computerEnabled,
resetComputerPermissionFlow,
setComputerEnabled,
t,
]);
const refreshComputerPermissionStatus = useCallback(
async (
reason: string,
options?: { fresh?: boolean; bypassCache?: boolean; passiveOnly?: boolean },
) => {
// fresh:重启 daemon 后现场实测 —— 「辅助功能被撤销」只有重启 daemon 才读得到。
// 仅在 driver 替换或已进入授权流程后使用;页面进入/Recheck 走 passiveOnly,
// 开启开关会重新验证可变的 macOS TCC 状态,不能消费可能已过期的页面快照。
const status = await window.electronAPI.maker.computer.status({
forcePermissionProbe: true,
...(options?.fresh ? { freshPermissionProbe: true } : {}),
...(options?.bypassCache ? { bypassPermissionProbeCache: true } : {}),
...(options?.passiveOnly ? { passivePermissionProbeOnly: true } : {}),
});
log.debug('computer permission status refreshed', {
flowReason: reason,
fresh: options?.fresh === true,
bypassCache: options?.bypassCache === true,
passiveOnly: options?.passiveOnly === true,
...getComputerPermissionLogSummary(status),
});
setComputerStatus(status);
return status;
},
[],
);
const requestComputerPermissionGrant = useCallback(
async (reason: string, openedPaneUrl?: string) => {
computerPermissionGrantInProgressRef.current = true;
log.debug('computer permission grant requested', { reason });
try {
const result = await window.electronAPI.maker.computer.grantPermissions({
// The native coach presents the drag/enable steps beside System Settings.
// Permission status itself advances only after explicit user actions.
showGuide: window.electronAPI.platform === 'darwin',
...(openedPaneUrl ? { openedPaneUrl } : {}),
});
log.debug('computer permission grant result', {
flowReason: reason,
ok: result.ok,
...getComputerPermissionLogSummary(result.status),
});
setComputerStatus(result.status);
return result.status;
} finally {
computerPermissionGrantInProgressRef.current = false;
}
},
[],
);
// 独立引导浮窗里的关闭按钮由 main 广播回来。
useEffect(() => {
return window.electronAPI.maker.computer.onPermissionGuideCancelled(
handleCancelPermissionGuide,
);
}, [handleCancelPermissionGuide]);
// 更新检查每次打开面板只跑一次;status 对象在 install/授权流程里会反复刷新,
// 用 ref 防止重复触发网络请求。
const driverUpdateCheckedRef = useRef(false);
const backendRead = useAutomationSettingsRead(
'browser backend configuration',
useCallback(async () => {
const state = await window.electronAPI.browserBackend?.getState?.();
// Only a genuinely absent older bridge uses the compatibility default.
// A failed read stays unknown, rather than inventing an active backend.
return {
active: state?.active ?? 'external',
useRealProfile: state?.useRealProfile === true,
};
}, []),
);
const { value: backendConfig, setValue: setBackendConfig } = backendRead;
const browserBackendKind = backendConfig?.active ?? null;
const setBrowserBackendKind = useCallback(
(active: 'external' | 'rsb-webview' | 'user-browser' | null) => {
setBackendConfig((current) => (current && active ? { ...current, active } : current));
},
[setBackendConfig],
);
const [browserBackendPending, setBrowserBackendPending] = useState(false);
const [browserBackendRecovering, setBrowserBackendRecovering] = useState(false);
const [browserBackendHealth, setBrowserBackendHealth] = useState<BrowserBackendHealth | null>(
null,
);
const useRealProfile = backendConfig?.useRealProfile ?? false;
const setUseRealProfile = useCallback(
(enabled: boolean) => {
setBackendConfig((current) => (current ? { ...current, useRealProfile: enabled } : current));
},
[setBackendConfig],
);
const navigate = useNavigate();
const userBrowserPlugin =
// Only the root instance can provide My browser (an organization copy with the same id cannot),
// so that is the one the setup steps install, enable and open.
useInstalledGhosts().find(
(ghost) => ghost.manifest.id === RECOMMENDED_PAGE_CONTROL_PLUGIN_ID && ghost.namespace == null,
) ?? null;
const [userBrowserSetupBusy, setUserBrowserSetupBusy] = useState(false);
// Health can include an automatic embedded-browser recovery and therefore
// take several seconds. Track the latest health owner so a late initial
// probe cannot overwrite a newer user-initiated switch or recovery result.
const browserBackendHealthSeqRef = useRef(0);
const browserBackendKindRef = useRef(browserBackendKind);
browserBackendKindRef.current = browserBackendKind;
const refreshUserBrowserHealth = useCallback(async () => {
const seq = browserBackendHealthSeqRef.current;
const next = await window.electronAPI.browserBackend?.getHealth?.().catch(() => null);
// A switch, recovery or newer read may have landed meanwhile (one read can take seconds);
// a late "My browser" answer must not replace the sidebar browser's state.
if (seq !== browserBackendHealthSeqRef.current || browserBackendKindRef.current !== 'user-browser') return;
if (next?.active === 'user-browser') {
browserBackendHealthSeqRef.current += 1;
setBrowserBackendHealth(next);
}
}, []);
// Step 1 happens right here: install the plugin from the market (Main still shows its usual
// permission confirmation) or turn it on, then re-check so the guidance moves on to step 2.
// Step 2, an installed version too old to connect, and anything unexpected open the plugin's own
// page, which has the update button and the extension install entry.
const handleSetUpUserBrowser = useCallback(async () => {
const openPluginPage = () =>
navigate(
userBrowserPlugin
? `/plugins?ghost=${encodeURIComponent(installedGhostStoragePart(userBrowserPlugin))}`
: '/plugins',
);
if (browserBackendHealth?.reason === 'extension-disconnected') {
// Open the store page in the user's own browser; the page polls and turns connected once the
// extension is added. Without a Chromium browser, the plugin page explains the other routes.
setUserBrowserSetupBusy(true);
const opened = await window.electronAPI.browserBackend
.openExtensionStore?.()
.catch(() => null);
setUserBrowserSetupBusy(false);
if (opened?.ok) toast.success(t('settings.computerUse.browserBackend.userBrowserSetup.storeOpened'));
else openPluginPage();
return;
}
if (browserBackendHealth?.reason !== 'plugin-missing' || userBrowserPlugin?.enabled) {
openPluginPage();
return;
}
setUserBrowserSetupBusy(true);
try {
if (userBrowserPlugin) {
await window.electronAPI.ghosts.setEnabled(
installedGhostStoragePart(userBrowserPlugin),
true,
ghostInstallApprovalToken(userBrowserPlugin.approval),
);
} else {
// Market ids are opaque; the plugin is found by the ghost id it installs as.
const item = (await window.electronAPI.pluginMarket.snapshot()).items.find(
(entry) => entry.ghostId === RECOMMENDED_PAGE_CONTROL_PLUGIN_ID,
);
const detail = item ? await window.electronAPI.pluginMarket.detail(item.pluginId) : null;
if (detail?.installState !== 'not-installed') {
openPluginPage();
return;
}
const result = await window.electronAPI.pluginMarket.install(detail.pluginId, {
expectedReleaseId: detail.releaseId,
expectedManifest: detail.manifest,
allowSourceReplacement: false,
});
toast.success(t('settings.ghosts.toast.installed', { name: result.ghost.manifest.name }));
}
await refreshUserBrowserHealth();
} catch (error) {
const code = extractIpcError(error)?.code;
// Cancelling the install confirmation is not a failure.
if (code !== 'MUTATION_CANCELLED') {
toast.error(t(userBrowserPlugin ? ghostInstallErrorKey(code) : pluginMarketErrorKey(error)));
}
} finally {
setUserBrowserSetupBusy(false);
}
}, [browserBackendHealth?.reason, navigate, refreshUserBrowserHealth, t, userBrowserPlugin]);
// While "My browser" still lacks its plugin or extension, check again every few seconds so the
// guidance turns into "connected" as soon as the user finishes a step elsewhere.
useEffect(() => {
if (browserBackendKind !== 'user-browser' || browserBackendHealth?.status !== 'error') return;
// Schedule the next check only after the previous one finished, so slow reads never pile up.
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
await refreshUserBrowserHealth();
if (!stopped) timer = setTimeout(() => void tick(), 3000);
};
timer = setTimeout(() => void tick(), 3000);
return () => {
stopped = true;
clearTimeout(timer);
};
}, [browserBackendKind, browserBackendHealth?.status, refreshUserBrowserHealth]);
const [useRealProfilePending, setUseRealProfilePending] = useState(false);
const confirmDialog = useOptionalConfirmDialog();
useEffect(() => {
let cancelled = false;
setAndroidStatus(null);
setAndroidStatusPending(true);
void window.electronAPI.maker.android
.getConfig()
.then((config) => {
if (!cancelled) {
setAndroidConfig(config);
}
})
.catch((err) => {
log.warn('android.getConfig failed', err);
});
void window.electronAPI.maker.plugins
.getState(ANDROID_PLUGIN_ID)
.then((state) => {
if (cancelled) return;
setAndroidEnabled(state.effectiveEnabled);
// 插件禁用时 mount 不做任何 adb 探测:status() 会跑 `adb devices -l`,
// 5037 上没有 server 时会顺手 fork 一个 daemon(#1806)。禁用态只展示
// 提示文案;探测留到用户开启开关或手动点「刷新」时进行。
if (!state.effectiveEnabled) {
setAndroidStatusPending(false);
return;
}
setAndroidPreparePending(true);
void window.electronAPI.maker.android
.prepareAdb()
.then(() => (cancelled ? undefined : window.electronAPI.maker.android.status()))
.then((status) => {
if (!cancelled && status) setAndroidStatus(status);
})
.catch((err) => {
// 这个 catch 同时兜 prepareAdb 与后续 status 的失败,文案别写死单边。
log.warn('android adb probe (prepareAdb/status) failed', err);
if (!cancelled) setAndroidStatus(androidStatusFallback(err));
})
.finally(() => {
if (!cancelled) {
setAndroidPreparePending(false);
setAndroidStatusPending(false);
}
});
})
.catch((err) => {
log.warn('plugins.getState(android) failed', err);
if (!cancelled) {
setAndroidEnabled(false);
setAndroidStatusPending(false);
}
});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
if (androidAdbPathEdited) return;
const overridePath = androidConfig?.value.adbPathOverride?.trim();
setAndroidAdbPathDraft(
overridePath || androidStatus?.adb_path || androidStatus?.adb_preparation?.path || '',
);
}, [
androidAdbPathEdited,
androidConfig?.value.adbPathOverride,
androidStatus?.adb_path,
androidStatus?.adb_preparation?.path,
]);
useEffect(() => {
let cancelled = false;
// Machine-wide status is independent of workingDir and may include slow
// daemon recovery / TCC probes. Never make it a prerequisite for this page.
void window.electronAPI.maker.computer
.status({
refreshPermissionGuide: false,
forcePermissionProbe: true,
bypassPermissionProbeCache: true,
passivePermissionProbeOnly: true,
})
.catch((err) => {
log.warn('computer.status failed', err);
return {
installed: false,
executablePath: null,
version: null,
daemonRunning: false,
installCommand: 'cua-driver install instructions: https://cua.ai/docs/cua-driver',
docsUrl: 'https://cua.ai/docs/cua-driver',
error: String(err),
} as ComputerDriverStatus;
})
.then((computer) => {
if (cancelled) return;
// A native permission-guide event may already have supplied newer state.
setComputerStatus((current) => current ?? computer);
log.debug('computer initial status loaded', getComputerPermissionLogSummary(computer));
});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
let cancelled = false;
const backendHealthSeq = ++browserBackendHealthSeqRef.current;
setBrowserBackendHealth(null);
if (browserBackendKind === null || browserBackendPending) return;
// Runtime health depends only on the loaded backend, never other settings.
// Wait for a switch to finish before probing its authoritative backend.
void (async () => {
try {
const health = await (window.electronAPI.browserBackend?.getHealth?.() ?? null);
if (cancelled || browserBackendHealthSeqRef.current !== backendHealthSeq) return;
setBrowserBackendHealth(health?.active === browserBackendKind ? health : null);
} catch (error) {
log.warn('browserBackend.getHealth failed', error);
if (cancelled || browserBackendHealthSeqRef.current !== backendHealthSeq) return;
setBrowserBackendHealth(browserBackendHealthFallback(browserBackendKind));
}
})();
return () => {
cancelled = true;
};
}, [browserBackendKind, browserBackendPending]);
// Phase 5: 用户点 segmented chip 切换 backend。乐观更新 + IPC 失败回滚。
const handleSelectBackend = useCallback(
async (kind: 'external' | 'rsb-webview' | 'user-browser') => {
if (browserBackendPending) return;
if (browserBackendKind === kind) return;
const prev = browserBackendKind;
// Results of reads started for the previous browser no longer apply.
browserBackendHealthSeqRef.current += 1;
setBrowserBackendKind(kind);
setBrowserBackendPending(true);
try {
const res = await window.electronAPI.browserBackend.setKind(kind);
// main 返回 active 是权威 — 万一同一次 swap 失败 router 拒了我们 fallback
// 到 main 端的真实值。
setBrowserBackendKind(res.active);
} catch (err) {
log.error('browserBackend.setKind failed', err);
setBrowserBackendKind(prev);
toast.error(t('settings.computerUse.browserBackend.toggleFailed'));
} finally {
setBrowserBackendPending(false);
}
},
[browserBackendKind, browserBackendPending, setBrowserBackendKind, t],
);
const handleToggleRealProfile = useCallback(
async (next: boolean) => {
if (useRealProfilePending) return;
if (next) {
const confirmed = await confirmEnableRealProfile({
platform: window.electronAPI.platform,
t,
confirm: confirmDialog?.confirm,
openExternal: window.electronAPI.openExternal,
onOpenSettingsFailed: (result) => {
log.warn('open Full Disk Access settings failed', result);
},
hasDiskAccess: async () => {
try {
const result = await window.electronAPI.browserBackend.probeSourceRead?.();
return result?.readable === true;
} catch (error) {
log.warn('browserBackend.probeSourceRead failed', error);
return false;
}
},
});
if (!confirmed) return;
}
setUseRealProfilePending(true);
try {
const res = await window.electronAPI.browserBackend.setUseRealProfile(next);
setUseRealProfile(res.enabled);
toast.success(
res.enabled
? t('settings.computerUse.realProfile.toast.enabled')
: t('settings.computerUse.realProfile.toast.disabled'),
);
} catch (err) {
log.error('browserBackend.setUseRealProfile failed', err);
const errorCode = browserOpenForLoginErrorCode(err);
toast.error(
t(
errorCode
? browserOpenForLoginToastKey(errorCode, 'settings.computerUse.realProfile.toast.failed')
: 'settings.computerUse.realProfile.toast.failed',
),
);
} finally {
setUseRealProfilePending(false);
}
},
[confirmDialog, setUseRealProfile, t, useRealProfilePending],
);
const handleRecoverBrowserBackend = useCallback(async () => {
if (browserBackendPending || browserBackendRecovering) return;
setBrowserBackendRecovering(true);
try {
const result = await window.electronAPI.browserBackend.recover();
browserBackendHealthSeqRef.current += 1;
setBrowserBackendKind(result.health.active);
setBrowserBackendHealth(result.health);
if (result.ok) {
toast.success(t('settings.computerUse.browserBackend.health.recovered'));
} else if (result.health.status === 'error') {
toast.error(t('settings.computerUse.browserBackend.health.recoverFailed'));
}
} catch (err) {
log.error('browserBackend.recover failed', err);
browserBackendHealthSeqRef.current += 1;
setBrowserBackendHealth(browserBackendHealthFallback('rsb-webview'));
toast.error(t('settings.computerUse.browserBackend.health.recoverFailed'));
} finally {
setBrowserBackendRecovering(false);
}
}, [browserBackendPending, browserBackendRecovering, setBrowserBackendKind, t]);
// 更新期间订阅 main 广播的下载进度;phase='done' 或组件卸载时清空。
useEffect(() => {
if (!driverUpdatePending) {
setDriverUpdateProgress(null);
return;
}
const unsubscribe = window.electronAPI.maker.computer.onUpdateProgress((progress) => {
setDriverUpdateProgress(progress.phase === 'done' ? null : progress);
});
return unsubscribe;
}, [driverUpdatePending]);
const refreshDriverUpdateCheck = useCallback(async (force = false) => {
setDriverCheckPending(true);
setDriverCheckFailed(false);
try {
const result = await window.electronAPI.maker.computer.checkUpdate(
force ? { force: true } : undefined,
);
if (!computerUseSectionMountedRef.current) return null;
setDriverUpdate(result);
// Older peers have no checkStatus. A missing latestVersion still means
// that a successful check cannot be established, never “up to date”.
setDriverCheckFailed(
result.checkStatus === 'error' || !result.currentVersion || !result.latestVersion,
);
if (result.currentVersion) {
setComputerStatus((current) =>
current?.installed ? { ...current, version: result.currentVersion } : current,
);
}
return result;
} catch (err) {
log.warn('computer.checkUpdate failed', err);
if (computerUseSectionMountedRef.current) setDriverCheckFailed(true);
return null;
} finally {
if (computerUseSectionMountedRef.current) setDriverCheckPending(false);
}
}, []);
// 等待 main 侧更新安装完成并刷新本地展示。更新的 in-flight 托管在 main:
// 面板关闭它照常跑完;面板重开后本函数 join 同一个安装 Promise。
// resume 路径传 joinOnly:若 main 侧安装在 IPC 到达前恰好完成,只读状态
// 刷新,绝不误起一次新安装(用户没点按钮不该有安装发生)。
const joinDriverUpdate = useCallback(
async (joinOnly: boolean) => {
try {
let nextStatus: ComputerDriverStatus | null = null;
let updateSucceeded = false;
try {
const result = await window.electronAPI.maker.computer.updateDriver(
joinOnly ? { joinOnly: true } : undefined,
);
nextStatus = result.status;
updateSucceeded = true;
} catch (err) {
log.warn('computer driver update failed', err);
if (!computerUseSectionMountedRef.current) return;
toast.error(t('settings.computerUse.directControl.update.toast.failed'));
// A nonzero installer exit does not mean the old binary is still on disk.
try {
nextStatus = await window.electronAPI.maker.computer.status({
skipPermissionProbe: true,
});
} catch (refreshErr) {
log.warn('computer.status after failed update failed', refreshErr);
}
}
if (!computerUseSectionMountedRef.current) return;
if (nextStatus) setComputerStatus(nextStatus);
// Publish the installed version and remove the old offer before probing
// permissions. A slow/failed permission probe must not retain old versions.
setDriverUpdate(null);
if (!nextStatus?.installed || !computerUseSectionMountedRef.current) return;
if (nextStatus.permissionState?.platform === 'macos') {
const previousPermissionState = nextStatus.permissionState;
try {
const permissions = await window.electronAPI.maker.computer.status({
forcePermissionProbe: true,
freshPermissionProbe: true,
});
// Keep the independently verified version if the permission status
// request could not even read the binary during daemon recovery.
nextStatus = {
...permissions,
installed: true,
version: nextStatus.version,
executablePath: nextStatus.executablePath,
};
} catch (err) {
log.warn('computer permission check after update failed', err);
nextStatus = {
...nextStatus,
permissions: undefined,
permissionState: {
...previousPermissionState,
status: 'unknown',
accessibility: 'unknown',
screenRecording: 'unknown',
screenRecordingCapturable: 'unknown',
},
};
}
}
if (!computerUseSectionMountedRef.current) return;
setComputerStatus(nextStatus);
if (!isComputerPermissionReady(nextStatus)) {
setComputerPermissionPending(false);
try {
// Unknown opt-in may still be enabled in main. Only publish off
// after persisting it, keeping the initial read alive on failure.
await window.electronAPI.maker.plugins.setEnabled(COMPUTER_PLUGIN_ID, false);
if (computerUseSectionMountedRef.current) setComputerEnabled(false);
} catch (error) {
log.warn('disabling computer after permission reset failed', error);
}
toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
}
if (updateSucceeded && isComputerPermissionReady(nextStatus)) {
toast.success(t('settings.computerUse.directControl.update.toast.success'));
}
} finally {
if (computerUseSectionMountedRef.current) {
setDriverUpdatePending(false);
// Finish local permission recovery before starting the network check.
void refreshDriverUpdateCheck();
}
}
},
[refreshDriverUpdateCheck, setComputerEnabled, t],
);
useEffect(() => {
if (!computerStatus?.installed || driverUpdateCheckedRef.current) return;
driverUpdateCheckedRef.current = true;
let cancelled = false;
let settled = false;
void refreshDriverUpdateCheck()
.then((result) => {
settled = true;
if (cancelled || !result) return;
if (result.updating) {
// 上次面板关闭前发起的更新还在 main 侧跑:恢复「更新中」态并以
// join-only 语义重挂结果(安装恰好已完成时只读状态,不起新安装)。
setDriverUpdatePending(true);
void joinDriverUpdate(true);
}
})
.catch((err) => {
settled = true;
log.warn('computer.checkUpdate failed', err);
});
return () => {
cancelled = true;
// Loading the opt-in state can replace joinDriverUpdate before this
// request settles. Let the next effect consume the shared main check.
if (!settled) driverUpdateCheckedRef.current = false;
};
}, [computerStatus?.installed, joinDriverUpdate, refreshDriverUpdateCheck]);
const handleUpdateDriver = useCallback(() => {
if (driverUpdatePending || driverCheckPending) return;
setDriverUpdatePending(true);
void joinDriverUpdate(false);
}, [driverUpdatePending, driverCheckPending, joinDriverUpdate]);
const persistComputerEnabled = useCallback(
async (next: boolean) => {
const result = await window.electronAPI.maker.plugins.setEnabled(COMPUTER_PLUGIN_ID, next);
setComputerEnabled(next);
if (result.codexMcpRefreshed === false) {
toast.warning(t('settings.computerUse.codexRefreshDeferred'));
return;
}
toast.success(
next
? t('settings.computerUse.directControl.toast.enabled')
: t('settings.computerUse.directControl.toast.disabled'),
);
},
[setComputerEnabled, t],
);
// CLI-only CuaDriver installs use the legacy `permissions grant` process and
// have no native-guide broadcasts. Keep checking that live permission state
// while the shared pending UI is visible. The completion ref also prevents a
// native broadcast and this fallback poll from enabling the plugin twice.
useEffect(() => {
if (!computerPermissionPending) {
if (computerPermissionPollTimerRef.current !== null) {
window.clearTimeout(computerPermissionPollTimerRef.current);
computerPermissionPollTimerRef.current = null;
}
return;
}
let cancelled = false;
const deadline = Date.now() + COMPUTER_PERMISSION_POLL_TIMEOUT_MS;
const poll = async () => {
try {
if (!computerPermissionGrantInProgressRef.current) {
const status = await refreshComputerPermissionStatus('permission-poll', {
bypassCache: true,
});
if (cancelled) return;
if (isComputerPermissionReady(status)) {
if (computerPermissionCompletionInFlightRef.current) return;
computerPermissionCompletionInFlightRef.current = true;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
cancelNativeComputerPermissionGrant();
try {
if (computerEnableIntentRef.current || computerEnabled) {
await persistComputerEnabled(true);
}
} finally {
computerPermissionCompletionInFlightRef.current = false;
}
return;
}
}
} catch (err) {
log.warn('computer permission poll failed', err);
}
if (cancelled) return;
if (Date.now() >= deadline) {
setComputerPermissionPending(false);
resetComputerPermissionFlow();
cancelNativeComputerPermissionGrant();
if (!computerEnabled) computerEnableIntentRef.current = false;
toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
return;
}
computerPermissionPollTimerRef.current = window.setTimeout(
poll,
COMPUTER_PERMISSION_POLL_INTERVAL_MS,
);
};
void poll();
return () => {
cancelled = true;
if (computerPermissionPollTimerRef.current !== null) {
window.clearTimeout(computerPermissionPollTimerRef.current);
computerPermissionPollTimerRef.current = null;
}
};
}, [
cancelNativeComputerPermissionGrant,
computerEnabled,
computerPermissionPending,
persistComputerEnabled,
refreshComputerPermissionStatus,
resetComputerPermissionFlow,
t,
]);
const handleToggleBrowser = useCallback(
async (next: boolean) => {
setTogglePending(true);
try {
if (workingDir) {
await window.electronAPI.maker.plugins.setProjectEnabled(
workingDir,
BROWSER_PLUGIN_ID,
next,
);
} else {
await window.electronAPI.maker.plugins.setEnabled(BROWSER_PLUGIN_ID, next);
}
setBrowserEnabled(next);
toast.success(
next
? t('settings.computerUse.browser.toast.enabled')
: t('settings.computerUse.browser.toast.disabled'),
);
} catch (err) {
log.warn('set browser plugin enabled failed', err);
toast.error(t('settings.computerUse.browser.toast.toggleFailed'));
} finally {
setTogglePending(false);
}
},
[setBrowserEnabled, t, workingDir],
);
const handleRefreshAndroidStatus = useCallback(
async (showErrorToast = true) => {
setAndroidStatusPending(true);
try {
const status = await window.electronAPI.maker.android.status();
setAndroidStatus(status);
} catch (err) {
log.warn('android.status refresh failed', err);
setAndroidStatus(androidStatusFallback(err));
if (showErrorToast) {
toast.error(t('settings.computerUse.android.toast.statusFailed'));
}
} finally {
setAndroidStatusPending(false);
}
},
[t],
);
const handleSelectAndroidDevice = useCallback(
async (value: string) => {
const serial = value === ANDROID_AUTO_DEVICE_VALUE ? null : value;
setAndroidDevicePending(true);
try {
const config = await window.electronAPI.maker.android.setDefaultDevice(serial);
setAndroidConfig(config);
await handleRefreshAndroidStatus(false);
} catch (err) {
log.warn('android.setDefaultDevice failed', err);
toast.error(t('settings.computerUse.android.toast.deviceFailed'));
} finally {
setAndroidDevicePending(false);
}
},
[handleRefreshAndroidStatus, t],
);
const handleSaveAndroidAdbPath = useCallback(async () => {
const nextAdbPath = androidAdbPathDraft.trim();
setAndroidAdbPathPending(true);
try {
const config = await window.electronAPI.maker.android.setAdbPath(nextAdbPath);
setAndroidConfig(config);
setAndroidAdbPathDraft(config.value.adbPathOverride ?? nextAdbPath);
setAndroidAdbPathEdited(false);
if (androidEnabled) {
setAndroidPreparePending(true);
await window.electronAPI.maker.android.prepareAdb();
}
await handleRefreshAndroidStatus(false);
} catch (err) {
log.warn('android.setAdbPath failed', err);
toast.error(t('settings.computerUse.android.toast.adbPathFailed'));
} finally {
setAndroidPreparePending(false);
setAndroidAdbPathPending(false);
}
}, [androidAdbPathDraft, androidEnabled, handleRefreshAndroidStatus, t]);
const handleUseDefaultAndroidAdbPath = useCallback(async () => {
setAndroidAdbPathPending(true);
try {
const config = await window.electronAPI.maker.android.setAdbPath(null);
if (androidEnabled) {
setAndroidPreparePending(true);
await window.electronAPI.maker.android.prepareAdb();
}
await handleRefreshAndroidStatus(false);
setAndroidConfig(config);
setAndroidAdbPathEdited(false);
} catch (err) {
log.warn('android.useDefaultAdbPath failed', err);
toast.error(t('settings.computerUse.android.toast.adbPathFailed'));
} finally {
setAndroidPreparePending(false);
setAndroidAdbPathPending(false);
}
}, [androidEnabled, handleRefreshAndroidStatus, t]);
const handleToggleAndroid = useCallback(
async (next: boolean) => {
setAndroidTogglePending(true);
try {
const result = await window.electronAPI.maker.plugins.setEnabled(ANDROID_PLUGIN_ID, next);
setAndroidEnabled(next);
if (next) {
setAndroidPreparePending(true);
await window.electronAPI.maker.android.prepareAdb();
await handleRefreshAndroidStatus(false);
} else {
// 关闭时清掉旧探测结果:状态区回到禁用提示,设备选择入口一并禁用,
// 不再展示已过时的就绪/设备状态(#1829 review)。
setAndroidStatus(null);
}
toast.success(
next
? t('settings.computerUse.android.toast.enabled')
: t('settings.computerUse.android.toast.disabled'),
);
if (result.codexMcpRefreshed === false) {
toast.warning(t('settings.computerUse.codexRefreshDeferred'));
}
} catch (err) {
log.warn('plugins.setEnabled(android) failed', err);
toast.error(t('settings.computerUse.android.toast.toggleFailed'));
} finally {
setAndroidPreparePending(false);
setAndroidTogglePending(false);
}
},
[handleRefreshAndroidStatus, t],
);
const handleToggleComputer = useCallback(
async (next: boolean) => {
const flowSeq = computerPermissionFlowSeqRef.current;
const isCurrentFlow = () =>
computerUseSectionMountedRef.current && computerPermissionFlowSeqRef.current === flowSeq;
computerTogglePendingRef.current = true;
setComputerTogglePending(true);
computerEnableIntentRef.current = next;
if (next) computerPermissionCompletionInFlightRef.current = false;
let nextStatus = computerStatus;
try {
if (next && !nextStatus?.installed) {
setComputerInstallPending(true);
const installResult = await window.electronAPI.maker.computer.installDriver();
if (!isCurrentFlow()) return;
nextStatus = installResult.status;
setComputerStatus(installResult.status);
if (!installResult.status.installed) {
throw new Error(
installResult.status.error ??
'cua-driver install did not produce an installed driver',
);
}
}
if (next && nextStatus?.permissionState?.platform === 'macos') {
nextStatus = await refreshComputerPermissionStatus('toggle-fresh-preflight', {
fresh: true,
bypassCache: true,
});
if (!isCurrentFlow()) return;
}
if (next && isComputerPermissionPreflightInconclusive(nextStatus)) {
computerEnableIntentRef.current = false;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
toast.error(t('settings.computerUse.directControl.toast.permissionFailed'));
return;
}
if (shouldStartComputerPermissionGuide(next, nextStatus)) {
if (!isCurrentFlow()) return;
setComputerPermissionPending(true);
nextStatus = await requestComputerPermissionGrant('toggle');
// 用户在 grant 等待期间点了引导弹窗的「取消」:整个流程已终止,
// 不再打开系统设置/弹提示。
if (computerPermissionFlowSeqRef.current !== flowSeq) return;
if (!isComputerPermissionReady(nextStatus)) {
toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
return;
}
setComputerPermissionPending(false);
resetComputerPermissionFlow();
}
if (next && isComputerPermissionReady(nextStatus)) {
// The early status card may have been shown while a fresh check was
// in flight; close it when that check proves permissions are already
// complete.
setComputerPermissionPending(false);
resetComputerPermissionFlow();
}
if (!isCurrentFlow()) return;
await persistComputerEnabled(next);
if (!next) {
computerEnableIntentRef.current = false;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
}
if (nextStatus !== computerStatus) {
setComputerStatus(nextStatus);
}
} catch (err) {
if (!isCurrentFlow()) return;
log.warn('setProjectEnabled(computer) failed', err);
computerEnableIntentRef.current = false;
setComputerPermissionPending(false);
resetComputerPermissionFlow();
cancelNativeComputerPermissionGrant();
toast.error(
next && !nextStatus?.installed
? t('settings.computerUse.directControl.toast.installFailed')
: next && !isComputerPermissionReady(nextStatus)
? t('settings.computerUse.directControl.toast.permissionFailed')
: t('settings.computerUse.directControl.toast.toggleFailed'),
);
} finally {
computerTogglePendingRef.current = false;
if (computerUseSectionMountedRef.current) {
setComputerInstallPending(false);
setComputerTogglePending(false);
}
}
},
[
computerStatus,
cancelNativeComputerPermissionGrant,
persistComputerEnabled,
refreshComputerPermissionStatus,
requestComputerPermissionGrant,
resetComputerPermissionFlow,
t,
],
);
const handleDownload = useCallback(() => {
void window.electronAPI.openExternal(CHROME_DOWNLOAD_URL);
}, []);
const handleOpenCuaProject = useCallback(() => {
void window.electronAPI.openExternal(CUA_GITHUB_URL);
}, []);
// Launch the headed automation browser so the user can log into sites once;
// logins persist in the managed profile across sessions.
const handleOpenForLogin = useCallback(async () => {
try {
await window.electronAPI.maker.browser.openForLogin();
toast.success(t('settings.computerUse.browser.toast.openedForLogin'));
} catch (err) {
log.warn('browser.openForLogin failed', err);
const errorCode = browserOpenForLoginErrorCode(err);
if (errorCode === REAL_PROFILE_READ_DENIED) {
if (!confirmDialog) {
toast.error(t('settings.computerUse.realProfile.readDeniedDescription'));
}
await guideFullDiskAccessAfterReadDenied({
platform: window.electronAPI.platform,
t,
confirm: confirmDialog?.confirm,
openExternal: window.electronAPI.openExternal,
onOpenSettingsFailed: (result) => {
log.warn('open Full Disk Access settings failed', result);
},
});
return;
}
toast.error(
t(
errorCode
? browserOpenForLoginToastKey(errorCode)
: 'settings.computerUse.browser.toast.openForLoginFailed',
),
);
}
}, [confirmDialog, t]);
const handleOpenComputerPermission = useCallback(
async (url: string, granted: boolean) => {
if (computerPermissionPending) return;
const flowSeq = computerPermissionFlowSeqRef.current;
// Open the exact System Settings pane before starting native onboarding.
// The old order waited for the paused grant flow first, so the user saw
// no feedback while the guide was preparing and the pane could open late.
const opened = await openComputerPermissionSettings(
url,
granted ? 'badge-granted' : 'badge-missing',
);
if (
!computerUseSectionMountedRef.current ||
computerPermissionFlowSeqRef.current !== flowSeq
) {
return;
}
if (!opened) return;
if (granted) {
return;
}
setComputerPermissionPending(true);
const initialStatus = computerStatus;
try {
// Page entry/Recheck already supplied the source-of-truth snapshot.
// Pass it straight into the guide so its first frame chooses the
// current missing step without another probe or a driver restart.
if (isComputerPermissionReady(initialStatus)) {
setComputerPermissionPending(false);
resetComputerPermissionFlow();
if (computerEnableIntentRef.current || computerEnabled) {
await persistComputerEnabled(true);
}
return;
}
const status = await requestComputerPermissionGrant('badge', url);
if (computerPermissionFlowSeqRef.current !== flowSeq) return;
if (isComputerPermissionReady(status)) {
setComputerPermissionPending(false);
resetComputerPermissionFlow();
if (computerEnableIntentRef.current || computerEnabled) {
await persistComputerEnabled(true);
}
return;
}
log.debug(
'computer permission grant still pending after badge action',
getComputerPermissionLogSummary(status),
);
// The System Settings pane is already open. Keep the guide alive and
// let its native observer complete the remaining step.
toast.warning(t('settings.computerUse.directControl.toast.permissionPending'));
} catch (err) {
if (
!computerUseSectionMountedRef.current ||
computerPermissionFlowSeqRef.current !== flowSeq
) {
return;
}
log.warn('computer permission grant failed', err);
setComputerPermissionPending(false);
resetComputerPermissionFlow();
cancelNativeComputerPermissionGrant();
toast.error(t('settings.computerUse.directControl.toast.permissionFailed'));
}
},
[
computerEnabled,
computerStatus,
computerPermissionPending,
cancelNativeComputerPermissionGrant,
openComputerPermissionSettings,
persistComputerEnabled,
requestComputerPermissionGrant,
resetComputerPermissionFlow,
t,
],
);
// Recheck restarts the daemon so it picks up revoked permissions that a
// running daemon cannot detect (AX revoke is invisible to the live process;
// Screen Recording removal may not kill the daemon on all macOS versions).
// fresh=true is required: passiveOnly kept the old daemon alive and its
// stale TCC preflight kept reporting "granted" even after the user removed
// CuaDriver from Screen Recording.
const handleRecheckComputerStatus = useCallback(async () => {
setComputerPermissionRecheckPending(true);
try {
const status = await refreshComputerPermissionStatus('recheck', {
fresh: true,
bypassCache: true,
});
if (!status.installed || !isComputerPermissionReady(status)) {
log.debug(
'computer permission recheck found missing permissions',
getComputerPermissionLogSummary(status),
);
}
} catch (err) {
log.warn('computer.status refresh failed', err);
toast.error(t('settings.computerUse.directControl.toast.toggleFailed'));
} finally {
setComputerPermissionRecheckPending(false);
}
}, [refreshComputerPermissionStatus, t]);
const computerAccessibilityGranted = isComputerAccessibilityPermissionReady(computerStatus);
const computerScreenRecordingGranted = isComputerScreenRecordingPermissionReady(computerStatus);
const computerAccessibilityPending = computerPermissionPending && !computerAccessibilityGranted;
const computerScreenRecordingPending =
computerPermissionPending && computerAccessibilityGranted && !computerScreenRecordingGranted;
const computerReady = computerStatus?.installed && isComputerPermissionReady(computerStatus);
// Persisted opt-in and runtime readiness are separate states. Keeping an
// unavailable enabled configuration checked lets the user turn it off
// instead of forcing the only interaction back into onboarding.
const computerSwitchChecked = getComputerPermissionSwitchChecked(
computerEnabled ?? false,
computerTogglePending,
computerEnableIntentRef.current,
);
const computerSwitchDisabled =
computerEnabled === null ||
computerStatus === null ||
computerTogglePending ||
computerInstallPending ||
computerPermissionPending;
const configuredDefaultAndroidDevice =
androidConfig?.value.defaultDeviceSerial ??
androidStatus?.configured_default_device_serial ??
null;
const androidDevices = androidStatus?.devices ?? [];
const selectedAndroidDevice = configuredDefaultAndroidDevice
? androidDevices.find((device) => device.device_serial === configuredDefaultAndroidDevice)
: undefined;
const androidDeviceTriggerLabel = configuredDefaultAndroidDevice
? androidDeviceLabel(selectedAndroidDevice) || configuredDefaultAndroidDevice
: t('settings.computerUse.android.device.auto');
const hasStaleConfiguredAndroidDevice = Boolean(
configuredDefaultAndroidDevice &&
!androidDevices.some((device) => device.device_serial === configuredDefaultAndroidDevice),
);
// 禁用且尚无任何探测结果时显示禁用提示,避免落在 describeAndroidDeviceStatus
// 的「正在检查…」上(禁用态 mount 不探测,#1806)。用户手动「刷新」拿到结果后
// 仍按真实 status 展示。
const androidDeviceStatusText =
androidEnabled === false && !androidStatus
? t('settings.computerUse.android.status.disabled')
: describeAndroidDeviceStatus(androidStatus, t);
const androidConnectionGuideKind = getAndroidConnectionGuideKind(androidStatus);
const androidAdbSource =
androidStatus?.adb_path_source ?? androidStatus?.adb_preparation?.source ?? null;
const androidAdbSourceText = androidPreparePending
? t('settings.computerUse.android.adb.preparing')
: androidStatus?.adb_available && androidStatus.adb_path
? t('settings.computerUse.android.adb.ready', {
source: t(androidSourceLabelKey(androidAdbSource)),
})
: androidStatus?.adb_preparation?.error
? t('settings.computerUse.android.adb.prepareFailed', {
message: androidStatus.adb_preparation.error,
})
: t('settings.computerUse.android.adb.auto');
const androidAdbPersistedOverride = androidConfig?.value.adbPathOverride?.trim() ?? '';
const androidAdbActivePath =
androidStatus?.adb_path ?? androidStatus?.adb_preparation?.path ?? '';
const androidAdbBaselinePath = androidAdbPersistedOverride || androidAdbActivePath;
const androidAdbPathTrimmed = androidAdbPathDraft.trim();
const androidAdbPathDirty =
androidAdbPathEdited && androidAdbPathTrimmed !== androidAdbBaselinePath.trim();
const androidAdbPathCanSave = androidAdbPathDirty && androidAdbPathTrimmed.length > 0;
const androidAdbPathBusy = androidAdbPathPending || androidPreparePending;
return (
<div className="flex flex-col gap-[14px]">
<div className="flex flex-col gap-1 min-w-0">
<h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">
{t('settings.computerUse.title')}
</h2>
<p className="text-13 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.description')}
</p>
</div>
<div
id="automation-browser"
className={cn(
'flex flex-col overflow-hidden rounded-xl',
'bg-[var(--settings-theme-card-bg)]',
'border border-[var(--settings-theme-card-border)]',
)}
>
<div className="flex items-center justify-between gap-3 px-4 py-[14px]">
<div className="flex min-w-0 items-center gap-3">
<div
className={cn(
'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg',
'bg-[var(--settings-input-bg)]',
)}
>
<Globe size={16} className="text-[var(--settings-section-title)]" />
</div>
<div className="flex min-w-0 flex-col gap-[8px]">
<p
id="settings-search-settings-computerUse-browser-title"
className="truncate text-14 font-medium leading-none text-[var(--settings-section-title)]"
>
{t('settings.computerUse.browser.title')}
</p>
<p className="truncate text-12 leading-none text-[var(--settings-section-desc)]">
{t('settings.computerUse.browser.description')}
</p>
</div>
</div>
<Switch
checked={browserEnabled ?? false}
disabled={browserEnabled === null || togglePending}
onCheckedChange={handleToggleBrowser}
aria-label={t('settings.computerUse.browser.toggleAria')}
/>
</div>
<ConfigurationReadStatus
label={t('settings.computerUse.browser.title')}
status={browserRead.status}
retry={browserRead.retry}
/>
<ConfigurationReadStatus
label={t('settings.computerUse.browserBackend.title')}
status={backendRead.status}
retry={backendRead.retry}
/>
{/* Phase 5: backend 切换 segmented control,排在 enable toggle 紧下方 —
「使用哪个浏览器」是控制 toggle 之后用户首先需要回答的问题,所以放在
探测 / 登录 cell 之前。state 还没拉到时不渲染。 */}
{browserBackendKind !== null ? (
<BrowserBackendSubsection
active={browserBackendKind}
pending={browserBackendPending || browserBackendRecovering}
recovering={browserBackendRecovering}
health={browserBackendHealth}
onSelect={(kind) => void handleSelectBackend(kind)}
onRecover={() => void handleRecoverBrowserBackend()}
userBrowserPluginState={
userBrowserPlugin === null
? 'not-installed'
: userBrowserPlugin.enabled
? 'enabled'
: 'disabled'
}
userBrowserSetupBusy={userBrowserSetupBusy}
onSetUpUserBrowser={() => void handleSetUpUserBrowser()}
/>
) : null}
{/* 拷贝登录文件只对独立浏览器有用;别的浏览器下隐藏,但已经开着时仍要能关掉并删除拷贝。 */}
{browserBackendKind === 'external' || (browserBackendKind !== null && useRealProfile) ? (
<BrowserRealProfileSubsection
enabled={useRealProfile}
pending={useRealProfilePending}
available={browserBackendKind === 'external'}
onToggle={(next) => void handleToggleRealProfile(next)}
/>
) : null}
{/* 只在 backend === 'external' 时展示 Chrome 探测 + 登录入口。内置 webview
backend 用 Electron 自带 Chromium,这些 UI 对它都没有意义。 */}
{browserBackendKind === 'external' ? (
<ConfigurationReadStatus
label={t('settings.computerUse.configurationRead.browserDetection')}
status={availabilityRead.status}
retry={availabilityRead.retry}
/>
) : null}
{browserBackendKind === 'external' && availability !== null ? (
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-[14px]">
<p className="min-w-0 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{availability.detected
? t('settings.computerUse.browser.detected', {
browser: (availability.browserKind ?? 'chromium').replace(/^./, (c) =>
c.toUpperCase(),
),
})
: t('settings.computerUse.browser.notDetected')}
</p>
{availability.detected ? (
<Button
variant="secondary"
size="sm"
className="px-3"
type="button"
onClick={handleOpenForLogin}
>
<LogIn size={12} className="shrink-0" />
{t('settings.computerUse.browser.openForLogin')}
</Button>
) : (
<Button
variant="secondary"
size="sm"
className="px-3"
type="button"
onClick={handleDownload}
>
<Download size={12} className="shrink-0" />
{t('settings.computerUse.browser.download')}
</Button>
)}
</div>
) : null}
</div>
{browserBackendKind === 'external' && availability?.detected ? (
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.browser.openForLoginHint')}
</p>
) : null}
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.browser.toggleHint')}
</p>
<div aria-hidden="true" className="h-px bg-[var(--settings-theme-card-border)]" />
<div
id="automation-computer"
className={cn(
'flex flex-col overflow-hidden rounded-xl',
'bg-[var(--settings-theme-card-bg)]',
'border border-[var(--settings-theme-card-border)]',
)}
>
<div className="flex items-center justify-between gap-3 px-4 py-[14px]">
<div className="flex min-w-0 items-center gap-3">
<div
className={cn(
'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg',
'bg-[var(--settings-input-bg)]',
)}
>
<MonitorCog size={16} className="text-[var(--settings-section-title)]" />
</div>
<div className="flex min-w-0 flex-col gap-[8px]">
<p
id="settings-search-settings-computerUse-directControl-title"
className="truncate text-14 font-medium leading-none text-[var(--settings-section-title)]"
>
{t('settings.computerUse.directControl.title')}
</p>
<p className="truncate text-12 leading-none text-[var(--settings-section-desc)]">
{t('settings.computerUse.directControl.description')}
</p>
</div>
</div>
<Switch
checked={computerSwitchChecked}
disabled={computerSwitchDisabled}
onCheckedChange={handleToggleComputer}
aria-label={t('settings.computerUse.directControl.toggleAria')}
/>
</div>
<ConfigurationReadStatus
label={t('settings.computerUse.directControl.title')}
status={computerRead.status}
retry={computerRead.retry}
/>
{computerStatus === null ? (
<div
role="status"
className="flex items-center gap-2 border-t border-[var(--settings-theme-card-border)] px-4 py-4 text-12 text-[var(--settings-section-desc)]"
>
<Spinner size={12} />
{t('settings.computerUse.directControl.update.readingVersion')}
</div>
) : (
<>
{/* Windows/Linux 没有 macOS TCC 权限,整块隐藏;安装进度改在下方状态行展示。 */}
{window.electronAPI.platform === 'darwin' ? (
<div className="border-t border-[var(--settings-theme-card-border)] px-4 py-4">
<div className="flex items-center justify-between gap-3">
<p
id="settings-search-settings-computerUse-directControl-permissions-title"
className="text-13 font-medium text-[var(--settings-section-title)]"
>
{t('settings.computerUse.directControl.permissions.title')}
</p>
{computerInstallPending || computerPermissionPending ? (
<span className="inline-flex items-center gap-1.5 text-12 text-[var(--settings-section-desc)]">
<Spinner size={12} />
{computerInstallPending
? t('settings.computerUse.directControl.installing')
: t('settings.computerUse.directControl.authorizing')}
</span>
) : (
<Button
variant="secondary"
size="sm"
className="px-2.5"
loading={computerPermissionRecheckPending}
type="button"
onClick={() => void handleRecheckComputerStatus()}
disabled={computerPermissionRecheckPending}
>
<RefreshCw size={12} className="shrink-0" />
{t('settings.computerUse.directControl.permissions.recheck')}
</Button>
)}
</div>
<div
id="settings-search-settings-computerUse-directControl-permissions-accessibilityLabel"
className="mt-3 grid gap-2.5 sm:grid-cols-2"
>
<ComputerPermissionRow
label={t('settings.computerUse.directControl.permissions.accessibilityLabel')}
iconSrc={accessibilityPermissionIcon}
granted={computerAccessibilityGranted}
pending={computerAccessibilityPending}
actionLabel={
computerAccessibilityPending
? t('settings.computerUse.directControl.permissionGuide.waiting')
: computerAccessibilityGranted
? t('settings.computerUse.directControl.permissions.granted')
: t('settings.computerUse.directControl.permissions.grant')
}
onAction={() =>
void (computerStatus.installed
? handleOpenComputerPermission(
MAC_ACCESSIBILITY_SETTINGS_URL,
computerAccessibilityGranted,
)
: handleToggleComputer(true))
}
/>
<div id="settings-search-settings-computerUse-directControl-permissions-screenRecordingLabel">
<ComputerPermissionRow
label={t(
'settings.computerUse.directControl.permissions.screenRecordingLabel',
)}
iconSrc={screenRecordingPermissionIcon}
granted={computerScreenRecordingGranted}
pending={computerScreenRecordingPending}
actionLabel={
computerScreenRecordingPending
? t('settings.computerUse.directControl.permissionGuide.waiting')
: computerScreenRecordingGranted
? t('settings.computerUse.directControl.permissions.granted')
: t('settings.computerUse.directControl.permissions.grant')
}
onAction={() =>
void (computerStatus.installed
? handleOpenComputerPermission(
MAC_SCREEN_RECORDING_SETTINGS_URL,
computerScreenRecordingGranted,
)
: handleToggleComputer(true))
}
/>
</div>
</div>
</div>
) : null}
<div className="relative border-t border-[var(--settings-theme-card-border)] px-4 py-2.5">
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
<span className="text-11 text-[var(--settings-section-desc)]">
{computerStatus.installed
? t('settings.computerUse.directControl.status.version', {
version: computerStatus.version ?? 'cua-driver',
})
: t('settings.computerUse.directControl.notDetected')}
</span>
{window.electronAPI.platform !== 'darwin' && computerInstallPending ? (
<>
<span
aria-hidden="true"
className="text-11 text-[var(--settings-theme-card-border)]"
>
·
</span>
<span className="inline-flex items-center gap-1.5 text-11 text-[var(--settings-section-desc)]">
<Spinner size={12} />
{t('settings.computerUse.directControl.installing')}
</span>
</>
) : null}
{computerStatus.installed ? (
<>
{!driverUpdate?.updateAvailable ||
driverCheckPending ||
driverUpdatePending ||
driverCheckFailed ? (
<>
<span
aria-hidden="true"
className="text-11 text-[var(--settings-theme-card-border)]"
>
·
</span>
<span
role="status"
className="text-11 text-[var(--settings-section-desc)]"
>
{driverCheckPending
? t('settings.computerUse.directControl.update.checking')
: driverUpdatePending
? driverUpdateProgress?.phase === 'installing'
? t('settings.computerUse.directControl.update.installing')
: t('settings.computerUse.directControl.update.updating')
: driverCheckFailed
? t('settings.computerUse.directControl.update.checkFailed')
: driverUpdate
? t('settings.computerUse.directControl.update.upToDate')
: t('settings.computerUse.directControl.update.notChecked')}
</span>
</>
) : null}
{driverUpdate?.checkedAt && !driverUpdatePending ? (
<span className="text-11 text-[var(--settings-section-desc)]">
{t('settings.computerUse.directControl.update.lastChecked', {
time: new Date(driverUpdate.checkedAt).toLocaleString(i18n?.language, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}),
})}
</span>
) : null}
</>
) : null}
{computerStatus.installed &&
driverUpdate?.updateAvailable &&
driverUpdate.latestVersion &&
!driverUpdatePending ? (
<>
<span
aria-hidden="true"
className="text-11 text-[var(--settings-theme-card-border)]"
>
·
</span>
<span className="text-11 text-[var(--settings-section-desc)]">
{t(
driverCheckFailed
? 'settings.computerUse.directControl.update.previouslyAvailable'
: 'settings.computerUse.directControl.update.available',
{
version: driverUpdate.latestVersion,
},
)}
</span>
<Button
variant="secondary"
size="sm"
className="px-2.5"
type="button"
onClick={() => void handleUpdateDriver()}
disabled={driverCheckPending || computerInstallPending}
>
<Download size={12} className="shrink-0" />
{t('settings.computerUse.directControl.update.action')}
</Button>
</>
) : null}
{computerStatus.installed ? (
<Button
variant="secondary"
size="sm"
className="px-2.5"
type="button"
loading={driverCheckPending}
disabled={driverCheckPending || driverUpdatePending || computerInstallPending}
onClick={() => void refreshDriverUpdateCheck(true)}
>
<RefreshCw size={12} className="shrink-0" />
{driverCheckFailed
? t('settings.computerUse.directControl.update.retry')
: t('settings.computerUse.directControl.update.check')}
</Button>
) : null}
</div>
<button
type="button"
onClick={() => setComputerDetailsOpen((open) => !open)}
aria-expanded={computerDetailsOpen}
className={cn(
'inline-flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5',
'text-11 font-medium text-[var(--settings-section-desc)]',
'transition-colors hover:bg-[var(--settings-input-bg)] hover:text-[var(--settings-section-title)]',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
)}
>
{computerDetailsOpen
? t('settings.computerUse.directControl.permissions.hideDetails')
: t('settings.computerUse.directControl.permissions.moreDetails')}
<ChevronDown
size={12}
className={cn(
'transition-transform duration-200',
computerDetailsOpen && 'rotate-180',
)}
/>
</button>
</div>
{driverUpdatePending &&
driverUpdateProgress?.phase === 'downloading' &&
driverUpdateProgress.downloadedBytes !== null &&
driverUpdateProgress.totalBytes ? (
<div className="absolute inset-x-0 bottom-0 h-[2px] bg-[var(--settings-input-bg)]">
<div
className="h-full bg-[var(--settings-section-title)] transition-[width] duration-500"
style={{
width: `${Math.min(
100,
(driverUpdateProgress.downloadedBytes / driverUpdateProgress.totalBytes) *
100,
)}%`,
}}
/>
</div>
) : null}
</div>
{computerDetailsOpen ? (
<div className="flex flex-col gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-3.5">
<div className="flex flex-col gap-2">
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.directControl.driverInfo')}
</p>
{window.electronAPI.platform === 'darwin' ? (
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{computerReady
? t('settings.computerUse.directControl.permissions.runtimeConfirmations')
: t('settings.computerUse.directControl.permissions.macosHint')}
</p>
) : null}
</div>
<div>
<Button
variant="secondary"
size="sm"
className="px-3"
type="button"
onClick={handleOpenCuaProject}
>
<ExternalLink size={12} className="shrink-0" />
{t('settings.computerUse.directControl.openSourceProject')}
</Button>
</div>
</div>
) : null}
</>
)}
</div>
<div aria-hidden="true" className="h-px bg-[var(--settings-theme-card-border)]" />
<div
id="automation-android"
className={cn(
'flex flex-col overflow-hidden rounded-xl',
'bg-[var(--settings-theme-card-bg)]',
'border border-[var(--settings-theme-card-border)]',
)}
>
<div className="flex items-center justify-between gap-3 px-4 py-[14px]">
<div className="flex min-w-0 items-center gap-3">
<div
className={cn(
'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg',
'bg-[var(--settings-input-bg)]',
)}
>
<Smartphone size={16} className="text-[var(--settings-section-title)]" />
</div>
<div className="flex min-w-0 flex-col gap-[8px]">
<p
id="settings-search-settings-computerUse-android-title"
className="truncate text-14 font-medium leading-none text-[var(--settings-section-title)]"
>
{t('settings.computerUse.android.title')}
</p>
<p className="truncate text-12 leading-none text-[var(--settings-section-desc)]">
{t('settings.computerUse.android.description')}
</p>
</div>
</div>
<Switch
checked={androidEnabled ?? false}
disabled={androidEnabled === null || androidTogglePending}
onCheckedChange={handleToggleAndroid}
aria-label={t('settings.computerUse.android.toggleAria')}
/>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-[14px]">
<div className="flex min-w-0 flex-col gap-1">
<p className="text-12 font-medium leading-[1.5] text-[var(--settings-section-title)]">
{t('settings.computerUse.android.device.title')}
</p>
<p className="min-w-0 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{androidDeviceStatusText}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
disabled={androidDevicePending || !androidStatus}
className={cn(ACTION_BUTTON_CLASS, 'max-w-[260px] px-2.5')}
aria-label={t('settings.computerUse.android.device.ariaLabel')}
title={configuredDefaultAndroidDevice ?? undefined}
>
<Smartphone size={12} className="shrink-0" />
<span className="truncate">{androidDeviceTriggerLabel}</span>
<ChevronDown size={12} className="shrink-0 opacity-60" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-[260px] max-w-[360px]">
<DropdownMenuItem
onClick={() => void handleSelectAndroidDevice(ANDROID_AUTO_DEVICE_VALUE)}
className="flex items-start gap-2"
>
<Check
size={14}
className={cn(
'mt-0.5 shrink-0',
!configuredDefaultAndroidDevice ? 'opacity-100' : 'opacity-0',
)}
/>
<div className="flex min-w-0 flex-col gap-0.5">
<span className="truncate">
{t('settings.computerUse.android.device.auto')}
</span>
<span className="truncate text-12 leading-[1.33] text-[var(--cmd-palette-item-meta)]">
{t('settings.computerUse.android.device.autoHint')}
</span>
</div>
</DropdownMenuItem>
{hasStaleConfiguredAndroidDevice ? (
<DropdownMenuItem
onClick={() =>
void handleSelectAndroidDevice(configuredDefaultAndroidDevice ?? '')
}
className="flex items-start gap-2"
>
<Check size={14} className="mt-0.5 shrink-0 opacity-100" />
<div className="flex min-w-0 flex-col gap-0.5">
<span className="truncate">{configuredDefaultAndroidDevice}</span>
<span className="truncate text-12 leading-[1.33] text-[var(--cmd-palette-item-meta)]">
{t('settings.computerUse.android.device.unavailable')}
</span>
</div>
</DropdownMenuItem>
) : null}
{androidDevices.length === 0 ? (
<div className="px-2 py-2 text-12 text-[var(--settings-section-desc)]">
{t('settings.computerUse.android.device.none')}
</div>
) : (
androidDevices.map((device) => {
const selected = configuredDefaultAndroidDevice === device.device_serial;
const ready = device.state === 'device';
return (
<DropdownMenuItem
key={device.device_serial}
disabled={!ready}
onClick={() => void handleSelectAndroidDevice(device.device_serial)}
className="flex items-start gap-2"
>
<Check
size={14}
className={cn('mt-0.5 shrink-0', selected ? 'opacity-100' : 'opacity-0')}
/>
<div className="flex min-w-0 flex-col gap-0.5">
<span className="truncate">{androidDeviceLabel(device)}</span>
<span className="truncate text-12 leading-[1.33] text-[var(--cmd-palette-item-meta)]">
{ready
? t('settings.computerUse.android.device.ready')
: t('settings.computerUse.android.device.state', {
state: device.state,
})}
</span>
</div>
</DropdownMenuItem>
);
})
)}
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="secondary"
size="sm"
className="px-3"
loading={androidStatusPending}
type="button"
onClick={() => void handleRefreshAndroidStatus()}
disabled={androidStatusPending}
>
<RefreshCw size={12} className="shrink-0" />
{t('settings.computerUse.android.refresh')}
</Button>
</div>
</div>
{androidConnectionGuideKind ? (
<div className="border-t border-[var(--settings-theme-card-border)] px-4 py-3">
<div className="rounded-xl bg-[var(--settings-input-bg)] px-3 py-3">
<p className="text-12 font-medium leading-[1.5] text-[var(--settings-section-title)]">
{t(
`settings.computerUse.android.connectionGuide.${androidConnectionGuideKind}.title`,
)}
</p>
{androidConnectionGuideKind === 'connect' ? (
<>
<p className="mt-1.5 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.android.connectionGuide.connect.adbNote')}
</p>
<ol className="mt-2 list-decimal space-y-1 pl-4 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{[1, 2, 3, 4].map((step) => (
<li key={step}>
{t(`settings.computerUse.android.connectionGuide.connect.step${step}`)}
</li>
))}
</ol>
</>
) : (
<p className="mt-1.5 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t(
`settings.computerUse.android.connectionGuide.${androidConnectionGuideKind}.body`,
)}
</p>
)}
</div>
</div>
) : null}
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--settings-theme-card-border)] px-4 py-[14px]">
<div className="flex min-w-0 flex-col gap-1">
<p
id="settings-search-settings-computerUse-android-adb-title"
className="text-12 font-medium leading-[1.5] text-[var(--settings-section-title)]"
>
{t('settings.computerUse.android.adb.title')}
</p>
<p className="min-w-0 break-all text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{androidAdbSourceText}
</p>
</div>
<div className="flex min-w-[240px] flex-1 flex-wrap items-center justify-end gap-2">
<input
value={androidAdbPathDraft}
onChange={(event) => {
setAndroidAdbPathDraft(event.target.value);
setAndroidAdbPathEdited(true);
}}
disabled={androidAdbPathBusy}
placeholder={t('settings.computerUse.android.adb.placeholder')}
aria-label={t('settings.computerUse.android.adb.pathAria')}
className={cn(
'h-8 min-w-[220px] flex-1 rounded-full px-3 text-12 outline-none',
'border border-[var(--settings-input-border)]',
'bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',
'placeholder:text-[var(--settings-input-placeholder)]',
'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
'disabled:opacity-50',
)}
/>
<Button
variant="secondary"
size="sm"
className="px-3"
type="button"
onClick={() => void handleSaveAndroidAdbPath()}
disabled={!androidAdbPathCanSave || androidAdbPathBusy}
>
{t('settings.computerUse.android.adb.save')}
</Button>
<Button
variant="secondary"
size="sm"
className="px-3"
type="button"
onClick={() => void handleUseDefaultAndroidAdbPath()}
disabled={androidAdbPathBusy}
>
{t('settings.computerUse.android.adb.useDefault')}
</Button>
</div>
</div>
</div>
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.android.toggleHint')}
</p>
</div>
);
}