Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(settings): 修复自动操作页面读取阻塞导致的空白

Dash5dafe7946f50
diff --git a/apps/desktop/scripts/fixtures/automation-settings/fixture.tsx b/apps/desktop/scripts/fixtures/automation-settings/fixture.tsx
new file mode 100644
index 0000000000..1486c6d5d2
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/automation-settings/fixture.tsx
@@ -0,0 +1,49 @@
+import { ComputerUseSection } from '../../../src/renderer/components/settings/ComputerUseSection';
+import { mountPage, subscription } from '../../ui-page/harness';
+
+void mountPage({
+ host: (ctx) => ({
+ maker: {
+ plugins: {
+ getState: async (id: string) => {
+ if (ctx.case === 'loading' && id === 'computer') return new Promise(() => {});
+ return { effectiveEnabled: id === 'browser' };
+ },
+ },
+ browser: {
+ status: async () => {
+ if (ctx.case === 'loading') return new Promise(() => {});
+ return { detected: true, browserKind: 'chrome', executablePath: '/chrome' };
+ },
+ },
+ computer: {
+ status: async () => ({
+ installed: false,
+ executablePath: null,
+ version: null,
+ daemonRunning: false,
+ }),
+ onPermissionGuideStatusChanged: subscription('permissionStatus'),
+ onPermissionGuideCancelled: subscription('permissionCancelled'),
+ onUpdateProgress: subscription('updateProgress'),
+ },
+ android: {
+ getConfig: async () => ({
+ value: { defaultDeviceSerial: null, adbPathOverride: null },
+ }),
+ },
+ },
+ browserBackend: {
+ getState: async () => {
+ if (ctx.case === 'error') throw new Error('Configuration unavailable');
+ return { active: 'external', useRealProfile: false };
+ },
+ getHealth: async () => ({ active: 'external', status: 'ready', canRecover: false }),
+ },
+ }),
+ render: () => (
+ <div className="p-4">
+ <ComputerUseSection workingDir="/project" />
+ </div>
+ ),
+});
diff --git a/apps/desktop/scripts/fixtures/automation-settings/ui-page.mjs b/apps/desktop/scripts/fixtures/automation-settings/ui-page.mjs
new file mode 100644
index 0000000000..d7fdda92d6
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/automation-settings/ui-page.mjs
@@ -0,0 +1,56 @@
+import assert from 'node:assert/strict';
+
+export default {
+ name: 'automation-settings',
+ entry: './fixture.tsx',
+ viewport: { width: 720, height: 1000 },
+ real: 'ComputerUseSection, independent configuration reads, localized loading/error rows and existing browser/computer/Android controls',
+ notCovered:
+ 'Real IPC, browser discovery and device permissions; timeout and stale response behavior is covered by ComputerUseSection.browserHealth.test.tsx',
+ cases: {
+ default: { about: 'All settings loaded' },
+ loading: {
+ about:
+ 'Browser detection and computer configuration remain pending; other controls stay usable',
+ },
+ error: {
+ about:
+ 'Backend configuration fails twice, showing localized recovery inside the browser card',
+ },
+ },
+ async check(page, ui) {
+ const browser = page.getByRole('switch', {
+ name: await ui.t('settings.computerUse.browser.toggleAria'),
+ });
+ await browser.waitFor();
+ await page.waitForFunction(
+ () => !document.querySelector('#automation-browser button[role="switch"]')?.disabled,
+ );
+ assert.ok(await browser.isEnabled());
+ assert.ok(
+ await page
+ .getByText(await ui.t('settings.computerUse.android.title'), { exact: true })
+ .isVisible(),
+ );
+ if (ui.case === 'error') {
+ await page
+ .getByRole('button', { name: await ui.t('settings.computerUse.configurationRead.retry') })
+ .waitFor();
+ }
+ if (ui.case === 'loading') {
+ assert.ok(
+ await page
+ .getByRole('switch', {
+ name: await ui.t('settings.computerUse.directControl.toggleAria'),
+ })
+ .isDisabled(),
+ );
+ assert.equal(
+ await page
+ .getByText(await ui.t('settings.computerUse.browser.notDetected'), { exact: true })
+ .count(),
+ 0,
+ );
+ }
+ },
+};
diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
index 850eab33ac..5353aa0506 100644
--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx
@@ -11,7 +11,7 @@
* - mount → 并行拉 plugins.getState('browser', workingDir) (取 browser 开关态)
* + browser.status()。注意 browser 是 HOSTED_ELSEWHERE, 不在 plugins.list()
* 里, 必须按 id 直接读单个状态, 否则 find() 永远 undefined。
- * - 基础配置到位后渲染;电脑权限与浏览器健康检测独立补齐,不阻塞整页。
+ * - 各项配置独立加载;慢请求只影响对应控件,不阻塞整页。
* 浏览器开关读写完全复用 builtin plugin IPC, 不新造持久化通道。
*/
@@ -45,6 +45,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { createLogger } from '@/lib/logger';
import { BrowserBackendSubsection } from './BrowserBackendSubsection';
+import { useAutomationSettingsRead } from './useAutomationSettingsRead';
import { ComputerPermissionRow } from './ComputerPermissionRow';
import { BrowserRealProfileSubsection } from './BrowserRealProfileSubsection';
import {
@@ -94,9 +95,7 @@ const ACTION_BUTTON_CLASS = cn(
);
const ANDROID_AUTO_DEVICE_VALUE = '__auto__';
-function browserBackendHealthFallback(
- active: 'external' | 'rsb-webview',
-): BrowserBackendHealth {
+function browserBackendHealthFallback(active: 'external' | 'rsb-webview'): BrowserBackendHealth {
return {
active,
status: 'error',
@@ -158,16 +157,61 @@ interface ComputerUseSectionProps {
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) {
+export function ComputerUseSection({ workingDir }: ComputerUseSectionProps) {
const { t, i18n } = useTranslation();
- // null = not loaded yet (blank, no flash). After load, all resolve.
- const [browserEnabled, setBrowserEnabled] = useState<boolean | null>(null);
+ 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 [computerEnabled, setComputerEnabled] = useState<boolean | null>(null);
- const [availability, setAvailability] = useState<BrowserAvailability | 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('');
@@ -226,11 +270,10 @@ export function ComputerUseSection({
computerPermissionFlowSeqRef.current += 1;
computerEnableIntentRef.current = false;
computerPermissionCompletionInFlightRef.current = false;
- const hadActivePermissionFlow = (
- computerTogglePendingRef.current
- || computerPermissionPendingRef.current
- || computerPermissionGrantInProgressRef.current
- );
+ const hadActivePermissionFlow =
+ computerTogglePendingRef.current ||
+ computerPermissionPendingRef.current ||
+ computerPermissionGrantInProgressRef.current;
resetComputerPermissionFlow();
if (hadActivePermissionFlow) {
cancelNativeComputerPermissionGrant();
@@ -281,7 +324,8 @@ export function ComputerUseSection({
resetComputerPermissionFlow();
cancelNativeComputerPermissionGrant();
if (computerEnableIntentRef.current || computerEnabled) {
- void window.electronAPI.maker.plugins.setEnabled(COMPUTER_PLUGIN_ID, true)
+ void window.electronAPI.maker.plugins
+ .setEnabled(COMPUTER_PLUGIN_ID, true)
.then((result) => {
setComputerEnabled(true);
if (result.codexMcpRefreshed === false) {
@@ -305,57 +349,61 @@ export function ComputerUseSection({
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 } : {}),
+ 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 grant result', {
+ log.debug('computer permission status refreshed', {
flowReason: reason,
- ok: result.ok,
- ...getComputerPermissionLogSummary(result.status),
+ fresh: options?.fresh === true,
+ bypassCache: options?.bypassCache === true,
+ passiveOnly: options?.passiveOnly === true,
+ ...getComputerPermissionLogSummary(status),
});
- setComputerStatus(result.status);
- return result.status;
- } finally {
- computerPermissionGrantInProgressRef.current = false;
- }
- }, []);
+ 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(() => {
@@ -367,18 +415,38 @@ export function ComputerUseSection({
// 用 ref 防止重复触发网络请求。
const driverUpdateCheckedRef = useRef(false);
- // Phase 5: agent automation 实际驱动哪个浏览器 — 'external' 时这张卡片底下
- // 「Chrome 探测 / 下载 Chrome / 打开 Agent 专用浏览器」整套 UI 才有意义;
- // 'rsb-webview' 时全部隐藏(内置 Electron Chromium 永远可用,不需要装 Chrome
- // 也没有"专用 profile 登录"概念)。null = 还没拉到,跟其它 state 一样不渲染
- // 任何 backend-dependent UI(规则 7: 不要 loading 闪屏)。
- const [browserBackendKind, setBrowserBackendKind] = useState<
- 'external' | 'rsb-webview' | null
- >(null);
+ 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' | 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, setUseRealProfile] = 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 [useRealProfilePending, setUseRealProfilePending] = useState(false);
const confirmDialog = useOptionalConfirmDialog();
// Health can include an automatic embedded-browser recovery and therefore
@@ -390,7 +458,8 @@ export function ComputerUseSection({
let cancelled = false;
setAndroidStatus(null);
setAndroidStatusPending(true);
- void window.electronAPI.maker.android.getConfig()
+ void window.electronAPI.maker.android
+ .getConfig()
.then((config) => {
if (!cancelled) {
setAndroidConfig(config);
@@ -399,7 +468,8 @@ export function ComputerUseSection({
.catch((err) => {
log.warn('android.getConfig failed', err);
});
- void window.electronAPI.maker.plugins.getState(ANDROID_PLUGIN_ID)
+ void window.electronAPI.maker.plugins
+ .getState(ANDROID_PLUGIN_ID)
.then((state) => {
if (cancelled) return;
setAndroidEnabled(state.effectiveEnabled);
@@ -411,7 +481,8 @@ export function ComputerUseSection({
return;
}
setAndroidPreparePending(true);
- void window.electronAPI.maker.android.prepareAdb()
+ void window.electronAPI.maker.android
+ .prepareAdb()
.then(() => (cancelled ? undefined : window.electronAPI.maker.android.status()))
.then((status) => {
if (!cancelled && status) setAndroidStatus(status);
@@ -457,28 +528,31 @@ export function ComputerUseSection({
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));
- });
+ 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;
};
@@ -487,70 +561,25 @@ export function ComputerUseSection({
useEffect(() => {
let cancelled = false;
const backendHealthSeq = ++browserBackendHealthSeqRef.current;
- // Start the slow health/recovery path alongside the base reads, but do not
- // include it in their render gate. The Automation cards are useful while
- // this result is pending and BrowserBackendSubsection already supports a
- // null health state.
- const backendHealthPromise = (async () => {
+ 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 {
- return {
- health: await (window.electronAPI.browserBackend?.getHealth?.() ?? null),
- error: null,
- };
+ 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);
- return { health: null, error };
+ if (cancelled || browserBackendHealthSeqRef.current !== backendHealthSeq) return;
+ setBrowserBackendHealth(browserBackendHealthFallback(browserBackendKind));
}
})();
- void (async () => {
- const [browserState, computerState, avail, backendState] = await Promise.all([
- // `browser` is hidden from plugins.list() (HOSTED_ELSEWHERE), so read its
- // enable state directly by id — list().find() would always be undefined
- // and the toggle would wrongly reset to enabled on every remount.
- window.electronAPI.maker.plugins.getState(BROWSER_PLUGIN_ID, workingDir).catch((err) => {
- log.warn('plugins.getState(browser) failed', err);
- return null;
- }),
- window.electronAPI.maker.plugins.getState(COMPUTER_PLUGIN_ID).catch((err) => {
- log.warn('plugins.getState(computer) failed', err);
- return null;
- }),
- window.electronAPI.maker.browser.status().catch((err) => {
- log.warn('browser.status failed', err);
- return { detected: false, browserKind: null, executablePath: null } as BrowserAvailability;
- }),
- window.electronAPI.browserBackend?.getState?.().catch((err) => {
- log.warn('browserBackend.getState failed', err);
- return null;
- }) ?? Promise.resolve(null),
- ]);
- if (cancelled) return;
- // Browser keeps the builtin default-on behavior. Direct computer control
- // reflects the persisted machine-wide opt-in; readiness is shown separately.
- setBrowserEnabled(browserState ? browserState.effectiveEnabled : true);
- const effectiveComputerEnabled = computerState ? computerState.effectiveEnabled : false;
- setComputerEnabled(effectiveComputerEnabled);
- setAvailability(avail);
- // Phase 5: backend kind 拉不到时(老版本 preload / IPC 缺失)安全 fallback
- // 到 'external',保持现有 Chrome 探测 / 登录 UI 可见 — 总比因为 IPC 失败
- // 让卡片整张瘫成内置态强。
- const activeBackend = backendState?.active ?? 'external';
- setBrowserBackendKind(activeBackend);
- setUseRealProfile(backendState?.useRealProfile === true);
- const { health: backendHealth, error: backendHealthError } = await backendHealthPromise;
- if (cancelled || browserBackendHealthSeqRef.current !== backendHealthSeq) return;
- setBrowserBackendHealth(
- backendHealth?.active === activeBackend
- ? backendHealth
- : backendHealthError
- ? browserBackendHealthFallback(activeBackend)
- : null,
- );
- })();
return () => {
cancelled = true;
};
- }, [workingDir]);
+ }, [browserBackendKind, browserBackendPending]);
// Phase 5: 用户点 segmented chip 切换 backend。乐观更新 + IPC 失败回滚。
const handleSelectBackend = useCallback(
@@ -565,18 +594,6 @@ export function ComputerUseSection({
// main 返回 active 是权威 — 万一同一次 swap 失败 router 拒了我们 fallback
// 到 main 端的真实值。
setBrowserBackendKind(res.active);
- const backendHealthSeq = ++browserBackendHealthSeqRef.current;
- try {
- const health = await window.electronAPI.browserBackend.getHealth();
- if (browserBackendHealthSeqRef.current === backendHealthSeq) {
- setBrowserBackendHealth(health);
- }
- } catch (healthErr) {
- log.warn('browserBackend.getHealth after setKind failed', healthErr);
- if (browserBackendHealthSeqRef.current === backendHealthSeq) {
- setBrowserBackendHealth(browserBackendHealthFallback(res.active));
- }
- }
} catch (err) {
log.error('browserBackend.setKind failed', err);
setBrowserBackendKind(prev);
@@ -585,7 +602,7 @@ export function ComputerUseSection({
setBrowserBackendPending(false);
}
},
- [browserBackendKind, browserBackendPending, t],
+ [browserBackendKind, browserBackendPending, setBrowserBackendKind, t],
);
const handleToggleRealProfile = useCallback(
@@ -628,7 +645,7 @@ export function ComputerUseSection({
setUseRealProfilePending(false);
}
},
- [confirmDialog, t, useRealProfilePending],
+ [confirmDialog, setUseRealProfile, t, useRealProfilePending],
);
const handleRecoverBrowserBackend = useCallback(async () => {
@@ -652,7 +669,7 @@ export function ComputerUseSection({
} finally {
setBrowserBackendRecovering(false);
}
- }, [browserBackendPending, browserBackendRecovering, t]);
+ }, [browserBackendPending, browserBackendRecovering, setBrowserBackendKind, t]);
// 更新期间订阅 main 广播的下载进度;phase='done' 或组件卸载时清空。
useEffect(() => {
@@ -670,16 +687,20 @@ export function ComputerUseSection({
setDriverCheckPending(true);
setDriverCheckFailed(false);
try {
- const result = await window.electronAPI.maker.computer.checkUpdate(force ? { force: true } : undefined);
+ 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);
+ setDriverCheckFailed(
+ result.checkStatus === 'error' || !result.currentVersion || !result.latestVersion,
+ );
if (result.currentVersion) {
- setComputerStatus((current) => current?.installed
- ? { ...current, version: result.currentVersion }
- : current);
+ setComputerStatus((current) =>
+ current?.installed ? { ...current, version: result.currentVersion } : current,
+ );
}
return result;
} catch (err) {
@@ -695,85 +716,93 @@ export function ComputerUseSection({
// 面板关闭它照常跑完;面板重开后本函数 join 同一个安装 Promise。
// resume 路径传 joinOnly:若 main 侧安装在 IPC 到达前恰好完成,只读状态
// 刷新,绝不误起一次新安装(用户没点按钮不该有安装发生)。
- const joinDriverUpdate = useCallback(async (joinOnly: boolean) => {
- try {
- let nextStatus: ComputerDriverStatus | null = null;
- let updateSucceeded = false;
+ const joinDriverUpdate = useCallback(
+ async (joinOnly: boolean) => {
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.
+ let nextStatus: ComputerDriverStatus | null = null;
+ let updateSucceeded = false;
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,
- };
+ const result = await window.electronAPI.maker.computer.updateDriver(
+ joinOnly ? { joinOnly: true } : undefined,
+ );
+ nextStatus = result.status;
+ updateSucceeded = true;
} 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',
- },
- };
+ 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;
- setComputerStatus(nextStatus);
- if (!isComputerPermissionReady(nextStatus)) {
- setComputerPermissionPending(false);
- setComputerEnabled(false);
- if (computerEnabled) {
- await window.electronAPI.maker.plugins.setEnabled(COMPUTER_PLUGIN_ID, false)
- .catch((error) => log.warn('disabling computer after permission reset failed', error));
+ 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);
+ setComputerEnabled(false);
+ if (computerEnabled) {
+ await window.electronAPI.maker.plugins
+ .setEnabled(COMPUTER_PLUGIN_ID, 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();
}
- 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();
}
- }
- }, [computerEnabled, refreshDriverUpdateCheck, t]);
+ },
+ [computerEnabled, refreshDriverUpdateCheck, setComputerEnabled, t],
+ );
useEffect(() => {
if (!computerStatus?.installed || driverUpdateCheckedRef.current) return;
@@ -809,19 +838,22 @@ export function ComputerUseSection({
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'),
- );
- }, [t]);
+ 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
@@ -903,7 +935,11 @@ export function ComputerUseSection({
setTogglePending(true);
try {
if (workingDir) {
- await window.electronAPI.maker.plugins.setProjectEnabled(workingDir, BROWSER_PLUGIN_ID, next);
+ await window.electronAPI.maker.plugins.setProjectEnabled(
+ workingDir,
+ BROWSER_PLUGIN_ID,
+ next,
+ );
} else {
await window.electronAPI.maker.plugins.setEnabled(BROWSER_PLUGIN_ID, next);
}
@@ -920,39 +956,45 @@ export function ComputerUseSection({
setTogglePending(false);
}
},
- [t, workingDir],
+ [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'));
+ 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);
}
- } finally {
- setAndroidStatusPending(false);
- }
- }, [t]);
+ },
+ [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 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();
@@ -1033,10 +1075,8 @@ export function ComputerUseSection({
const handleToggleComputer = useCallback(
async (next: boolean) => {
const flowSeq = computerPermissionFlowSeqRef.current;
- const isCurrentFlow = () => (
- computerUseSectionMountedRef.current
- && computerPermissionFlowSeqRef.current === flowSeq
- );
+ const isCurrentFlow = () =>
+ computerUseSectionMountedRef.current && computerPermissionFlowSeqRef.current === flowSeq;
computerTogglePendingRef.current = true;
setComputerTogglePending(true);
computerEnableIntentRef.current = next;
@@ -1050,7 +1090,10 @@ export function ComputerUseSection({
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');
+ throw new Error(
+ installResult.status.error ??
+ 'cua-driver install did not produce an installed driver',
+ );
}
}
if (next && nextStatus?.permissionState?.platform === 'macos') {
@@ -1111,7 +1154,7 @@ export function ComputerUseSection({
? t('settings.computerUse.directControl.toast.installFailed')
: next && !isComputerPermissionReady(nextStatus)
? t('settings.computerUse.directControl.toast.permissionFailed')
- : t('settings.computerUse.directControl.toast.toggleFailed'),
+ : t('settings.computerUse.directControl.toast.toggleFailed'),
);
} finally {
computerTogglePendingRef.current = false;
@@ -1186,8 +1229,8 @@ export function ComputerUseSection({
granted ? 'badge-granted' : 'badge-missing',
);
if (
- !computerUseSectionMountedRef.current
- || computerPermissionFlowSeqRef.current !== flowSeq
+ !computerUseSectionMountedRef.current ||
+ computerPermissionFlowSeqRef.current !== flowSeq
) {
return;
}
@@ -1222,14 +1265,17 @@ export function ComputerUseSection({
return;
}
- log.debug('computer permission grant still pending after badge action', getComputerPermissionLogSummary(status));
+ 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
+ !computerUseSectionMountedRef.current ||
+ computerPermissionFlowSeqRef.current !== flowSeq
) {
return;
}
@@ -1267,7 +1313,10 @@ export function ComputerUseSection({
bypassCache: true,
});
if (!status.installed || !isComputerPermissionReady(status)) {
- log.debug('computer permission recheck found missing permissions', getComputerPermissionLogSummary(status));
+ log.debug(
+ 'computer permission recheck found missing permissions',
+ getComputerPermissionLogSummary(status),
+ );
}
} catch (err) {
log.warn('computer.status refresh failed', err);
@@ -1277,40 +1326,31 @@ export function ComputerUseSection({
}
}, [refreshComputerPermissionStatus, t]);
- const automationViewLoading =
- browserEnabled === null
- || computerEnabled === null
- || availability === null;
-
- // Only base configuration gates the page; runtime probes update independently.
- if (automationViewLoading) {
- return null;
- }
-
const computerAccessibilityGranted = isComputerAccessibilityPermissionReady(computerStatus);
const computerScreenRecordingGranted = isComputerScreenRecordingPermissionReady(computerStatus);
const computerAccessibilityPending = computerPermissionPending && !computerAccessibilityGranted;
const computerScreenRecordingPending =
- computerPermissionPending &&
- computerAccessibilityGranted &&
- !computerScreenRecordingGranted;
- const computerReady =
- computerStatus?.installed && isComputerPermissionReady(computerStatus);
+ 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,
+ computerEnabled ?? false,
computerTogglePending,
computerEnableIntentRef.current,
);
const computerSwitchDisabled =
- computerStatus === null || computerTogglePending || computerInstallPending || computerPermissionPending;
+ computerEnabled === null ||
+ computerStatus === null ||
+ computerTogglePending ||
+ computerInstallPending ||
+ computerPermissionPending;
const configuredDefaultAndroidDevice =
- androidConfig?.value.defaultDeviceSerial
- ?? androidStatus?.configured_default_device_serial
- ?? null;
+ androidConfig?.value.defaultDeviceSerial ??
+ androidStatus?.configured_default_device_serial ??
+ null;
const androidDevices = androidStatus?.devices ?? [];
const selectedAndroidDevice = configuredDefaultAndroidDevice
? androidDevices.find((device) => device.device_serial === configuredDefaultAndroidDevice)
@@ -1319,17 +1359,19 @@ export function ComputerUseSection({
? androidDeviceLabel(selectedAndroidDevice) || configuredDefaultAndroidDevice
: t('settings.computerUse.android.device.auto');
const hasStaleConfiguredAndroidDevice = Boolean(
- configuredDefaultAndroidDevice
- && !androidDevices.some((device) => device.device_serial === configuredDefaultAndroidDevice),
+ 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 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 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
@@ -1342,10 +1384,12 @@ export function ComputerUseSection({
})
: t('settings.computerUse.android.adb.auto');
const androidAdbPersistedOverride = androidConfig?.value.adbPathOverride?.trim() ?? '';
- const androidAdbActivePath = androidStatus?.adb_path ?? androidStatus?.adb_preparation?.path ?? '';
+ const androidAdbActivePath =
+ androidStatus?.adb_path ?? androidStatus?.adb_preparation?.path ?? '';
const androidAdbBaselinePath = androidAdbPersistedOverride || androidAdbActivePath;
const androidAdbPathTrimmed = androidAdbPathDraft.trim();
- const androidAdbPathDirty = androidAdbPathEdited && androidAdbPathTrimmed !== androidAdbBaselinePath.trim();
+ const androidAdbPathDirty =
+ androidAdbPathEdited && androidAdbPathTrimmed !== androidAdbBaselinePath.trim();
const androidAdbPathCanSave = androidAdbPathDirty && androidAdbPathTrimmed.length > 0;
const androidAdbPathBusy = androidAdbPathPending || androidPreparePending;
@@ -1379,7 +1423,10 @@ export function ComputerUseSection({
<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)]">
+ <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)]">
@@ -1388,12 +1435,22 @@ export function ComputerUseSection({
</div>
</div>
<Switch
- checked={browserEnabled}
- disabled={togglePending}
+ 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 还没拉到时不渲染。 */}
@@ -1418,11 +1475,20 @@ export function ComputerUseSection({
{/* 只在 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()),
+ browser: (availability.browserKind ?? 'chromium').replace(/^./, (c) =>
+ c.toUpperCase(),
+ ),
})
: t('settings.computerUse.browser.notDetected')}
</p>
@@ -1438,7 +1504,13 @@ export function ComputerUseSection({
{t('settings.computerUse.browser.openForLogin')}
</Button>
) : (
- <Button variant="secondary" size="sm" className="px-3" type="button" onClick={handleDownload}>
+ <Button
+ variant="secondary"
+ size="sm"
+ className="px-3"
+ type="button"
+ onClick={handleDownload}
+ >
<Download size={12} className="shrink-0" />
{t('settings.computerUse.browser.download')}
</Button>
@@ -1447,7 +1519,7 @@ export function ComputerUseSection({
) : null}
</div>
- {browserBackendKind === 'external' && availability.detected ? (
+ {browserBackendKind === 'external' && availability?.detected ? (
<p className="text-12 leading-[1.5] text-[var(--settings-section-desc)]">
{t('settings.computerUse.browser.openForLoginHint')}
</p>
@@ -1477,7 +1549,10 @@ export function ComputerUseSection({
<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)]">
+ <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)]">
@@ -1492,8 +1567,16 @@ export function ComputerUseSection({
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)]">
+ <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>
@@ -1503,7 +1586,10 @@ export function ComputerUseSection({
{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)]">
+ <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 ? (
@@ -1529,7 +1615,10 @@ export function ComputerUseSection({
)}
</div>
- <div id="settings-search-settings-computerUse-directControl-permissions-accessibilityLabel" className="mt-3 grid gap-2.5 sm:grid-cols-2">
+ <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}
@@ -1543,40 +1632,38 @@ export function ComputerUseSection({
: t('settings.computerUse.directControl.permissions.grant')
}
onAction={() =>
- void (
- computerStatus.installed
- ? handleOpenComputerPermission(
- MAC_ACCESSIBILITY_SETTINGS_URL,
- computerAccessibilityGranted,
- )
- : handleToggleComputer(true)
- )
+ 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
+ <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)
- )
- }
- />
+ : handleToggleComputer(true))
+ }
+ />
</div>
</div>
</div>
@@ -1594,7 +1681,10 @@ export function ComputerUseSection({
</span>
{window.electronAPI.platform !== 'darwin' && computerInstallPending ? (
<>
- <span aria-hidden="true" className="text-11 text-[var(--settings-theme-card-border)]">
+ <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)]">
@@ -1605,10 +1695,21 @@ export function ComputerUseSection({
) : null}
{computerStatus.installed ? (
<>
- {(!driverUpdate?.updateAvailable || driverCheckPending || driverUpdatePending || driverCheckFailed) ? (
+ {!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)]">
+ <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
@@ -1627,24 +1728,36 @@ export function ComputerUseSection({
<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',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
}),
})}
</span>
) : null}
</>
) : null}
- {computerStatus.installed && driverUpdate?.updateAvailable && driverUpdate.latestVersion && !driverUpdatePending ? (
+ {computerStatus.installed &&
+ driverUpdate?.updateAvailable &&
+ driverUpdate.latestVersion &&
+ !driverUpdatePending ? (
<>
- <span aria-hidden="true" className="text-11 text-[var(--settings-theme-card-border)]">
+ <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,
- })}
+ {t(
+ driverCheckFailed
+ ? 'settings.computerUse.directControl.update.previouslyAvailable'
+ : 'settings.computerUse.directControl.update.available',
+ {
+ version: driverUpdate.latestVersion,
+ },
+ )}
</span>
<Button
variant="secondary"
@@ -1709,7 +1822,8 @@ export function ComputerUseSection({
style={{
width: `${Math.min(
100,
- (driverUpdateProgress.downloadedBytes / driverUpdateProgress.totalBytes) * 100,
+ (driverUpdateProgress.downloadedBytes / driverUpdateProgress.totalBytes) *
+ 100,
)}%`,
}}
/>
@@ -1770,7 +1884,10 @@ export function ComputerUseSection({
<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)]">
+ <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)]">
@@ -1809,17 +1926,17 @@ export function ComputerUseSection({
<ChevronDown size={12} className="shrink-0 opacity-60" />
</button>
</DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="min-w-[260px] max-w-[360px]"
- >
+ <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')}
+ 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">
@@ -1832,14 +1949,14 @@ export function ComputerUseSection({
</DropdownMenuItem>
{hasStaleConfiguredAndroidDevice ? (
<DropdownMenuItem
- onClick={() => void handleSelectAndroidDevice(configuredDefaultAndroidDevice ?? '')}
+ 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">{configuredDefaultAndroidDevice}</span>
<span className="truncate text-12 leading-[1.33] text-[var(--cmd-palette-item-meta)]">
{t('settings.computerUse.android.device.unavailable')}
</span>
@@ -1866,13 +1983,13 @@ export function ComputerUseSection({
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">{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 })}
+ : t('settings.computerUse.android.device.state', {
+ state: device.state,
+ })}
</span>
</div>
</DropdownMenuItem>
@@ -1906,16 +2023,12 @@ export function ComputerUseSection({
{androidConnectionGuideKind === 'connect' ? (
<>
<p className="mt-1.5 text-12 leading-[1.5] text-[var(--settings-section-desc)]">
- {t(
- 'settings.computerUse.android.connectionGuide.connect.adbNote',
- )}
+ {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}`,
- )}
+ {t(`settings.computerUse.android.connectionGuide.connect.step${step}`)}
</li>
))}
</ol>
@@ -1932,7 +2045,10 @@ export function ComputerUseSection({
) : 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)]">
+ <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)]">
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx
index 4d3c03954f..f3e2b1af00 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx
@@ -126,9 +126,161 @@ beforeEach(() => {
});
});
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
describe('ComputerUseSection browser backend health loading', () => {
+ // Regression: the four base reads used to gate the entire page via Promise.all.
+ // Existing tests cover slow runtime probes only. A never-settling base read
+ // must leave the other cards and their loaded controls usable (unit/jsdom).
+ it.each(['browser', 'computer', 'availability', 'backend'])(
+ 'keeps other settings usable while %s configuration never returns',
+ async (pending) => {
+ const never = new Promise<never>(() => {});
+ if (pending === 'availability') api.getBrowserStatus.mockReturnValue(never);
+ else if (pending === 'backend') api.getBackendState.mockReturnValue(never);
+ else
+ api.getPluginState.mockImplementation(async (id: string) =>
+ id === pending ? never : { effectiveEnabled: id === 'browser' },
+ );
+
+ await act(async () => {
+ render(<ComputerUseSection workingDir="/tmp/project" />);
+ });
+
+ expect(screen.getByText('settings.computerUse.title')).toBeTruthy();
+ expect(screen.getByText('settings.computerUse.android.title')).toBeTruthy();
+ const browserSwitch = screen.getByRole('switch', {
+ name: 'settings.computerUse.browser.toggleAria',
+ }) as HTMLButtonElement;
+ expect(browserSwitch.disabled).toBe(pending === 'browser');
+ expect(
+ (
+ screen.getByRole('switch', {
+ name: 'settings.computerUse.android.toggleAria',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
+ if (pending !== 'backend') {
+ expect(
+ screen.getByRole('radio', {
+ name: 'settings.computerUse.browserBackend.rsbWebview.title',
+ }),
+ ).toBeTruthy();
+ }
+ },
+ );
+
+ it('automatically recovers a failed read without presenting a default as persisted state', async () => {
+ vi.useFakeTimers();
+ let failed = false;
+ api.getPluginState.mockImplementation((id: string) => {
+ if (id === 'browser' && !failed) {
+ failed = true;
+ throw new Error('bridge unavailable');
+ }
+ return Promise.resolve({ effectiveEnabled: id === 'browser' });
+ });
+ await act(async () => {
+ render(<ComputerUseSection workingDir="/tmp/project" />);
+ });
+ const toggle = screen.getByRole('switch', {
+ name: 'settings.computerUse.browser.toggleAria',
+ }) as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ expect(screen.getByText('settings.computerUse.configurationRead.retrying')).toBeTruthy();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_000);
+ });
+
+ expect(toggle.disabled).toBe(false);
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ expect(screen.queryByText('settings.computerUse.configurationRead.retrying')).toBeNull();
+ });
+
+ it('bounds timeout retries, allows manual recovery, and ignores a late timed-out result', async () => {
+ vi.useFakeTimers();
+ const initialDetection = deferred<BrowserAvailability>();
+ api.getBackendState.mockResolvedValue({ active: 'external' });
+ api.getBrowserStatus.mockReturnValue(initialDetection.promise);
+ await act(async () => {
+ render(<ComputerUseSection workingDir="/tmp/project" />);
+ });
+ expect(screen.queryByText('settings.computerUse.browser.notDetected')).toBeNull();
+ expect(screen.queryByText('settings.computerUse.browser.download')).toBeNull();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(21_000);
+ });
+ expect(screen.getByText('settings.computerUse.configurationRead.error')).toBeTruthy();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(api.getBrowserStatus).toHaveBeenCalledTimes(2);
+ expect(
+ (
+ screen.getByRole('switch', {
+ name: 'settings.computerUse.browser.toggleAria',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
+
+ api.getBrowserStatus.mockResolvedValue({
+ detected: true,
+ browserKind: 'chrome',
+ executablePath: '/chrome',
+ });
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole('button', { name: 'settings.computerUse.configurationRead.retry' }),
+ );
+ });
+ expect(screen.getByText('settings.computerUse.browser.openForLogin')).toBeTruthy();
+ await act(async () => {
+ initialDetection.resolve({ detected: false, browserKind: null, executablePath: null });
+ });
+ expect(screen.getByText('settings.computerUse.browser.openForLogin')).toBeTruthy();
+ expect(screen.queryByText('settings.computerUse.browser.download')).toBeNull();
+ });
+
+ it('ignores the previous project read after switching projects', async () => {
+ const previous = deferred<{ effectiveEnabled: boolean }>();
+ api.getPluginState.mockImplementation(async (id: string, directory?: string) =>
+ id === 'browser' && directory === '/tmp/previous'
+ ? previous.promise
+ : { effectiveEnabled: false },
+ );
+ const { rerender } = render(<ComputerUseSection workingDir="/tmp/previous" />);
+ await act(async () => {
+ rerender(<ComputerUseSection workingDir="/tmp/current" />);
+ });
+ const toggle = screen.getByRole('switch', {
+ name: 'settings.computerUse.browser.toggleAria',
+ }) as HTMLButtonElement;
+ expect(toggle.disabled).toBe(false);
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ await act(async () => {
+ previous.resolve({ effectiveEnabled: true });
+ });
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('cancels pending recovery when the panel is closed', async () => {
+ vi.useFakeTimers();
+ api.getBackendState.mockRejectedValue(new Error('unavailable'));
+ const { unmount } = render(<ComputerUseSection workingDir="/tmp/project" />);
+ await act(async () => {});
+ expect(screen.getByText('settings.computerUse.configurationRead.retrying')).toBeTruthy();
+ unmount();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+ expect(api.getBackendState).toHaveBeenCalledTimes(1);
+ });
+
it('renders other settings while computer permission detection is pending', async () => {
const initialComputer = deferred<ComputerDriverStatus>();
api.getComputerStatus.mockReturnValueOnce(initialComputer.promise);
@@ -140,7 +292,9 @@ describe('ComputerUseSection browser backend health loading', () => {
name: 'settings.computerUse.directControl.toggleAria',
});
expect((computerToggle as HTMLButtonElement).disabled).toBe(true);
- expect(screen.getByText('settings.computerUse.directControl.update.readingVersion')).toBeTruthy();
+ expect(
+ screen.getByText('settings.computerUse.directControl.update.readingVersion'),
+ ).toBeTruthy();
expect(screen.queryByText('settings.computerUse.directControl.notDetected')).toBeNull();
expect(api.getComputerStatus).toHaveBeenCalledWith({
refreshPermissionGuide: false,
@@ -149,26 +303,40 @@ describe('ComputerUseSection browser backend health loading', () => {
passivePermissionProbeOnly: true,
});
- fireEvent.click(screen.getByRole('radio', {
- name: 'settings.computerUse.browserBackend.external.title',
- }));
+ fireEvent.click(
+ await screen.findByRole('radio', {
+ name: 'settings.computerUse.browserBackend.external.title',
+ }),
+ );
await waitFor(() => expect(api.setBackendKind).toHaveBeenCalledWith('external'));
rerender(<ComputerUseSection workingDir="/tmp/other-project" />);
expect(api.getComputerStatus).toHaveBeenCalledTimes(1);
- await act(async () => { initialComputer.resolve(computerUnavailable); });
+ await act(async () => {
+ initialComputer.resolve(computerUnavailable);
+ });
expect((computerToggle as HTMLButtonElement).disabled).toBe(false);
- expect(screen.queryByText('settings.computerUse.directControl.update.readingVersion')).toBeNull();
+ expect(
+ screen.queryByText('settings.computerUse.directControl.update.readingVersion'),
+ ).toBeNull();
});
it('settles a failed computer probe without hiding the settings', async () => {
api.getComputerStatus.mockRejectedValueOnce(new Error('probe failed'));
- render(<ComputerUseSection workingDir="/tmp/project" />);
+ await act(async () => {
+ render(<ComputerUseSection workingDir="/tmp/project" />);
+ });
expect(await screen.findByText('settings.computerUse.title')).toBeTruthy();
- expect(screen.queryByText('settings.computerUse.directControl.update.readingVersion')).toBeNull();
- expect((screen.getByRole('switch', {
- name: 'settings.computerUse.directControl.toggleAria',
- }) as HTMLButtonElement).disabled).toBe(false);
+ expect(
+ screen.queryByText('settings.computerUse.directControl.update.readingVersion'),
+ ).toBeNull();
+ expect(
+ (
+ screen.getByRole('switch', {
+ name: 'settings.computerUse.directControl.toggleAria',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(false);
});
it('preserves a newer native status when the initial probe returns late', async () => {
@@ -176,8 +344,9 @@ describe('ComputerUseSection browser backend health loading', () => {
// Use the real IPC business handler: forced reads normally broadcast before
// resolving, which must not overwrite a newer guide event for page entry.
const broadcast = vi.fn((status: ComputerDriverStatus) => {
- vi.mocked(window.electronAPI.maker.computer.onPermissionGuideStatusChanged)
- .mock.calls.at(-1)![0](status);
+ vi.mocked(window.electronAPI.maker.computer.onPermissionGuideStatusChanged).mock.calls.at(
+ -1,
+ )![0](status);
});
api.getComputerStatus.mockImplementationOnce((options) =>
readComputerStatusForSettings(options, {
@@ -193,13 +362,16 @@ describe('ComputerUseSection browser backend health loading', () => {
});
render(<ComputerUseSection workingDir="/tmp/project" />);
await screen.findByText('settings.computerUse.title');
- const onStatus = vi.mocked(window.electronAPI.maker.computer.onPermissionGuideStatusChanged)
+ const onStatus = vi
+ .mocked(window.electronAPI.maker.computer.onPermissionGuideStatusChanged)
.mock.calls.at(-1)![0];
await act(async () => {
onStatus({ ...computerUnavailable, installed: true, version: '0.12.2' });
});
expect(screen.getByText('settings.computerUse.directControl.status.version')).toBeTruthy();
- await act(async () => { initialComputer.resolve(computerUnavailable); });
+ await act(async () => {
+ initialComputer.resolve(computerUnavailable);
+ });
expect(broadcast).not.toHaveBeenCalled();
expect(screen.getByText('settings.computerUse.directControl.status.version')).toBeTruthy();
});
diff --git a/apps/desktop/src/renderer/components/settings/useAutomationSettingsRead.ts b/apps/desktop/src/renderer/components/settings/useAutomationSettingsRead.ts
new file mode 100644
index 0000000000..a1056a975b
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/useAutomationSettingsRead.ts
@@ -0,0 +1,89 @@
+import { useCallback, useEffect, useRef, useState, type SetStateAction } from 'react';
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('AutomationSettingsRead');
+const READ_TIMEOUT_MS = 10_000;
+const RETRY_DELAY_MS = 1_000;
+type ReadStatus = 'loading' | 'retrying' | 'error' | 'ready';
+
+/** Independent, bounded reads for the Automation panel's initial configuration.
+ * IPC cannot be cancelled: obsolete attempts may finish, but never commit state.
+ * Each load gets one automatic retry; leaving the panel clears its timers.
+ */
+export function useAutomationSettingsRead<T>(name: string, load: () => Promise<T>) {
+ const [state, setState] = useState<{
+ owner: typeof load;
+ value: T | null;
+ status: ReadStatus;
+ }>({ owner: load, value: null, status: 'loading' });
+ const [revision, setRevision] = useState(0);
+ const cancelRef = useRef(() => {});
+
+ useEffect(() => {
+ let cancelled = false;
+ let attempt = 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const cancel = () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ cancelRef.current = cancel;
+ setState({ owner: load, value: null, status: 'loading' });
+
+ const run = (isRetry: boolean) => {
+ if (cancelled) return;
+ const currentAttempt = ++attempt;
+ const fail = (error: unknown) => {
+ if (cancelled || currentAttempt !== attempt) return;
+ ++attempt;
+ clearTimeout(timer);
+ log.warn('initial configuration read failed', { name, isRetry, error });
+ setState({ owner: load, value: null, status: isRetry ? 'error' : 'retrying' });
+ if (!isRetry) timer = setTimeout(() => run(true), RETRY_DELAY_MS);
+ };
+ timer = setTimeout(() => fail(new Error('SETTINGS_READ_TIMEOUT')), READ_TIMEOUT_MS);
+ // Capture synchronous bridge errors as well as rejected IPC promises.
+ void Promise.resolve()
+ .then(() => (cancelled ? null : load()))
+ .then((value) => {
+ if (cancelled || currentAttempt !== attempt) return;
+ clearTimeout(timer);
+ setState({ owner: load, value, status: 'ready' });
+ }, fail);
+ };
+ run(false);
+ return cancel;
+ }, [load, name, revision]);
+
+ const retry = useCallback(() => {
+ cancelRef.current();
+ setState({ owner: load, value: null, status: 'loading' });
+ setRevision((current) => current + 1);
+ }, [load]);
+
+ // A successful user action owns the value from here; an older initial read
+ // or scheduled retry must not revert it.
+ const setValue = useCallback(
+ (next: SetStateAction<T | null>) => {
+ cancelRef.current();
+ setState((current) => ({
+ owner: load,
+ value:
+ typeof next === 'function'
+ ? (next as (previous: T | null) => T | null)(
+ current.owner === load ? current.value : null,
+ )
+ : next,
+ status: 'ready',
+ }));
+ },
+ [load],
+ );
+
+ return {
+ value: state.owner === load ? state.value : null,
+ status: state.owner === load ? state.status : ('loading' as ReadStatus),
+ setValue,
+ retry,
+ };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b0b00f41e8..b43638b513 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5170,6 +5170,13 @@
}
},
"computerUse": {
+ "configurationRead": {
+ "loading": "Loading {{section}}…",
+ "retrying": "Could not load {{section}}. Retrying automatically…",
+ "error": "Could not load {{section}}.",
+ "retry": "Reload Settings",
+ "browserDetection": "Browser detection"
+ },
"title": "Automation",
"description": "Let agents use your computer and connected devices to get things done for you. Browser automation uses an isolated browser; Android automation uses ADB; computer automation relies on a local driver.",
"codexRefreshDeferred": "Setting saved, but Codex is busy. Restart the app to apply it to new Codex sessions.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 298dcea952..9073c9dfbf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5139,6 +5139,13 @@
}
},
"computerUse": {
+ "configurationRead": {
+ "loading": "{{section}}を読み込み中…",
+ "retrying": "{{section}}を読み込めませんでした。自動で再試行中…",
+ "error": "{{section}}を読み込めませんでした。",
+ "retry": "設定を再読み込み",
+ "browserDetection": "ブラウザの検出結果"
+ },
"title": "自動操作",
"description": "エージェントがコンピュータと接続済みデバイスを使ってあなたの代わりに作業します。ブラウザ自動操作は独立したブラウザを使い、Android 自動操作は ADB を使い、コンピュータ自動操作はローカルドライバーに依存します。",
"codexRefreshDeferred": "設定は保存されましたが、Codex が使用中です。アプリを再起動すると、新しい Codex セッションに反映されます。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 536991f92d..e1f3a90202 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5139,6 +5139,13 @@
}
},
"computerUse": {
+ "configurationRead": {
+ "loading": "{{section}} 불러오는 중…",
+ "retrying": "{{section}} 불러오기에 실패했습니다. 자동으로 다시 시도하는 중…",
+ "error": "{{section}} 불러오기에 실패했습니다.",
+ "retry": "설정 다시 불러오기",
+ "browserDetection": "브라우저 감지 결과"
+ },
"title": "자동 조작",
"description": "에이전트가 컴퓨터와 연결된 기기를 사용해 사용자를 대신해 작업합니다. 브라우저 자동화는 독립 브라우저를 사용하고, Android 자동화는 ADB를 사용하며, 컴퓨터 자동화는 로컬 드라이버에 의존합니다.",
"codexRefreshDeferred": "설정은 저장되었지만 Codex가 사용 중입니다. 앱을 다시 시작하면 새 Codex 세션에 적용됩니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 24bd342bc9..49f4207b70 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5139,6 +5139,13 @@
}
},
"computerUse": {
+ "configurationRead": {
+ "loading": "正在读取{{section}}…",
+ "retrying": "未能读取{{section}},正在自动重试…",
+ "error": "未能读取{{section}}",
+ "retry": "重新读取设置",
+ "browserDetection": "浏览器检测结果"
+ },
"title": "自动操作",
"description": "让 Agent 使用电脑和已连接设备替你完成任务。浏览器自动化使用独立浏览器;Android 自动化使用 ADB;电脑自动化依赖本机 driver。",
"codexRefreshDeferred": "设置已保存,但 Codex 正忙;重启应用后将对新的 Codex Agent 会话生效",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 4c7c0c0d1d..f4aabd8d22 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5139,6 +5139,13 @@
}
},
"computerUse": {
+ "configurationRead": {
+ "loading": "正在讀取{{section}}…",
+ "retrying": "未能讀取{{section}},正在自動重試…",
+ "error": "未能讀取{{section}}",
+ "retry": "重新讀取設定",
+ "browserDetection": "瀏覽器偵測結果"
+ },
"title": "自動操作",
"description": "讓 Agent 使用電腦和已連線裝置替你完成任務。瀏覽器自動化使用獨立瀏覽器;Android 自動化使用 ADB;電腦自動化依賴本機 driver。",
"codexRefreshDeferred": "設定已儲存,但 Codex 正忙;重啟應用後將對新的 Codex Agent 會話生效",