Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 避免浏览器健康检查阻塞自动化设置 (#1580)
lilsnakec4520531e1dc
diff --git a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsxindex e02cc11323..c0888e9819 100644--- a/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx@@ -410,6 +410,10 @@ export function ComputerUseSection({const [browserBackendPending, setBrowserBackendPending] = useState(false);const [browserBackendRecovering, setBrowserBackendRecovering] = useState(false);const [browserBackendHealth, setBrowserBackendHealth] = useState<BrowserBackendHealth | null>(null);+ // 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);useEffect(() => {let cancelled = false;@@ -480,9 +484,24 @@ 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 () => {+ try {+ return {+ health: await (window.electronAPI.browserBackend?.getHealth?.() ?? null),+ error: null,+ };+ } catch (error) {+ log.warn('browserBackend.getHealth failed', error);+ return { health: null, error };+ }+ })();void (async () => {- let backendHealthError: unknown;- const [browserState, computerState, avail, computer, backendState, backendHealth] = await Promise.all([+ const [browserState, computerState, avail, computer, 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.@@ -523,11 +542,6 @@ export function ComputerUseSection({log.warn('browserBackend.getState failed', err);return null;}) ?? Promise.resolve(null),- window.electronAPI.browserBackend?.getHealth?.().catch((err) => {- backendHealthError = err;- log.warn('browserBackend.getHealth failed', err);- return null;- }) ?? Promise.resolve(null),]);if (cancelled) return;// Browser keeps the builtin default-on behavior. Direct computer control@@ -543,6 +557,8 @@ export function ComputerUseSection({// 让卡片整张瘫成内置态强。const activeBackend = backendState?.active ?? 'external';setBrowserBackendKind(activeBackend);+ const { health: backendHealth, error: backendHealthError } = await backendHealthPromise;+ if (cancelled || browserBackendHealthSeqRef.current !== backendHealthSeq) return;setBrowserBackendHealth(backendHealth?.active === activeBackend? backendHealth@@ -569,11 +585,17 @@ export function ComputerUseSection({// main 返回 active 是权威 — 万一同一次 swap 失败 router 拒了我们 fallback// 到 main 端的真实值。setBrowserBackendKind(res.active);+ const backendHealthSeq = ++browserBackendHealthSeqRef.current;try {- setBrowserBackendHealth(await window.electronAPI.browserBackend.getHealth());+ const health = await window.electronAPI.browserBackend.getHealth();+ if (browserBackendHealthSeqRef.current === backendHealthSeq) {+ setBrowserBackendHealth(health);+ }} catch (healthErr) {log.warn('browserBackend.getHealth after setKind failed', healthErr);- setBrowserBackendHealth(browserBackendHealthFallback(res.active));+ if (browserBackendHealthSeqRef.current === backendHealthSeq) {+ setBrowserBackendHealth(browserBackendHealthFallback(res.active));+ }}} catch (err) {log.error('browserBackend.setKind failed', err);@@ -591,6 +613,7 @@ export function ComputerUseSection({setBrowserBackendRecovering(true);try {const result = await window.electronAPI.browserBackend.recover();+ browserBackendHealthSeqRef.current += 1;setBrowserBackendKind(result.health.active);setBrowserBackendHealth(result.health);if (result.ok) {@@ -600,6 +623,7 @@ export function ComputerUseSection({}} catch (err) {log.error('browserBackend.recover failed', err);+ browserBackendHealthSeqRef.current += 1;setBrowserBackendHealth(browserBackendHealthFallback('rsb-webview'));toast.error(t('settings.computerUse.browserBackend.health.recoverFailed'));} finally {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.tsxnew file mode 100644index 0000000000..45b2029f03--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/ComputerUseSection.browserHealth.test.tsx@@ -0,0 +1,190 @@+// @vitest-environment jsdom++import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { BrowserBackendHealth } from '../../../../shared/browserBackend';++const api = vi.hoisted(() => ({+ getPluginState: vi.fn(),+ setPluginEnabled: vi.fn(),+ getBrowserStatus: vi.fn(),+ getComputerStatus: vi.fn(),+ getAndroidConfig: vi.fn(),+ getAndroidStatus: vi.fn(),+ getBackendState: vi.fn(),+ getBackendHealth: vi.fn(),+ setBackendKind: vi.fn(),+ recoverBackend: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++import { ComputerUseSection } from '../ComputerUseSection';++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++const computerUnavailable: ComputerDriverStatus = {+ installed: false,+ executablePath: null,+ version: null,+ daemonRunning: false,+ installCommand: 'install cua-driver',+ docsUrl: 'https://cua.ai/docs/cua-driver',+};++const androidUnavailable: AndroidStatusSummary = {+ adb_available: false,+ adb_path: null,+ version: null,+ devices: [],+ issue: 'ADB_NOT_FOUND',+};++beforeEach(() => {+ vi.resetAllMocks();+ api.getPluginState.mockImplementation(async (id: string) => ({+ effectiveEnabled: id === 'browser',+ }));+ api.setPluginEnabled.mockResolvedValue({ codexMcpRefreshed: true });+ api.getBrowserStatus.mockResolvedValue({+ detected: false,+ browserKind: null,+ executablePath: null,+ });+ api.getComputerStatus.mockResolvedValue(computerUnavailable);+ api.getAndroidConfig.mockResolvedValue({+ value: { defaultDeviceSerial: null, adbPathOverride: null },+ defaults: { defaultDeviceSerial: null, adbPathOverride: null },+ isCustomized: false,+ customizedKeys: [],+ });+ api.getAndroidStatus.mockResolvedValue(androidUnavailable);+ api.getBackendState.mockResolvedValue({ active: 'rsb-webview' });+ api.setBackendKind.mockImplementation(async (kind: 'external' | 'rsb-webview') => ({+ active: kind,+ }));+ api.recoverBackend.mockResolvedValue({+ ok: true,+ health: { active: 'rsb-webview', status: 'ready', canRecover: true },+ });++ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'linux',+ openExternal: vi.fn().mockResolvedValue({ success: true }),+ maker: {+ plugins: {+ getState: api.getPluginState,+ setEnabled: api.setPluginEnabled,+ setProjectEnabled: vi.fn(),+ },+ browser: {+ status: api.getBrowserStatus,+ openForLogin: vi.fn(),+ },+ computer: {+ status: api.getComputerStatus,+ cancelPermissionGrant: vi.fn().mockResolvedValue({ cancelled: true }),+ onPermissionGuideStatusChanged: vi.fn(() => () => undefined),+ onPermissionGuideCancelled: vi.fn(() => () => undefined),+ onUpdateProgress: vi.fn(() => () => undefined),+ checkUpdate: vi.fn(),+ },+ android: {+ getConfig: api.getAndroidConfig,+ status: api.getAndroidStatus,+ prepareAdb: vi.fn(),+ },+ },+ browserBackend: {+ getState: api.getBackendState,+ getHealth: api.getBackendHealth,+ setKind: api.setBackendKind,+ recover: api.recoverBackend,+ },+ },+ });+});++afterEach(cleanup);++describe('ComputerUseSection browser backend health loading', () => {+ it('renders the Automation settings while the recoverable health probe is still pending', async () => {+ const initialHealth = deferred<BrowserBackendHealth>();+ api.getBackendHealth.mockReturnValueOnce(initialHealth.promise);++ render(<ComputerUseSection workingDir="/tmp/project" />);++ expect(await screen.findByText('settings.computerUse.title')).toBeTruthy();+ expect(screen.getByRole('tab', {+ name: 'settings.computerUse.browserBackend.rsbWebview.title',+ })).toBeTruthy();+ expect(screen.queryByRole('status')).toBeNull();++ await act(async () => {+ initialHealth.resolve({+ active: 'rsb-webview',+ status: 'ready',+ canRecover: true,+ });+ await initialHealth.promise;+ });++ expect((await screen.findByRole('status')).textContent).toContain(+ 'settings.computerUse.browserBackend.health.ready',+ );+ });++ it('does not let a late initial health result overwrite a newer backend selection', async () => {+ const initialHealth = deferred<BrowserBackendHealth>();+ api.getBackendHealth+ .mockReturnValueOnce(initialHealth.promise)+ .mockResolvedValueOnce({ active: 'external', status: 'ready', canRecover: false })+ .mockResolvedValueOnce({ active: 'rsb-webview', status: 'ready', canRecover: true });++ render(<ComputerUseSection workingDir="/tmp/project" />);++ fireEvent.click(await screen.findByRole('tab', {+ name: 'settings.computerUse.browserBackend.external.title',+ }));+ await waitFor(() => expect(api.setBackendKind).toHaveBeenCalledWith('external'));+ await waitFor(() => expect(+ screen.getByRole('tab', {+ name: 'settings.computerUse.browserBackend.external.title',+ }).getAttribute('aria-selected'),+ ).toBe('true'));++ fireEvent.click(screen.getByRole('tab', {+ name: 'settings.computerUse.browserBackend.rsbWebview.title',+ }));+ await waitFor(() => expect(api.setBackendKind).toHaveBeenCalledWith('rsb-webview'));+ expect((await screen.findByRole('status')).textContent).toContain(+ 'settings.computerUse.browserBackend.health.ready',+ );++ await act(async () => {+ initialHealth.resolve({+ active: 'rsb-webview',+ status: 'error',+ canRecover: true,+ reason: 'disposing',+ });+ await initialHealth.promise;+ });++ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('status').textContent).toContain(+ 'settings.computerUse.browserBackend.health.ready',+ );+ });+});