π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(desktop): stop browser tools hanging on, or misreporting, page loads (#20414)
Arvin Xuf0289f7ef62a
diff --git a/apps/desktop/src/main/controllers/BrowserControlCtr.ts b/apps/desktop/src/main/controllers/BrowserControlCtr.tsindex 493f0d699f7..9a42f149687 100644--- a/apps/desktop/src/main/controllers/BrowserControlCtr.ts+++ b/apps/desktop/src/main/controllers/BrowserControlCtr.ts@@ -89,6 +89,15 @@ export const captureGuest = async (guest: WebContents): Promise<NativeImage> =>}};+/**+ * `WebContents.executeJavaScript` defers the script until the main frame stops+ * loading, so on a page that never finishes (a pending image, long-poll, dev+ * proxy) every snapshot/readPage/click hung until the caller timed out. The+ * main frame's own `executeJavaScript` runs against the current document now.+ */+const evaluate = (guest: WebContents, code: string): Promise<any> =>+ guest.mainFrame.executeJavaScript(code);+/*** Runs inside the guest page. Builds a compact interactive-element snapshot and* caches the elements on `window.__lobeBrowserRefs` so later actions can@@ -289,7 +298,7 @@ export default class BrowserControlCtr extends ControllerModule {@IpcMethod()async snapshot(params: BrowserControlParams): Promise<BrowserControlSnapshotResult> {return this.withGuest(params.sessionId, async (guest) => {- const raw = await guest.executeJavaScript(SNAPSHOT_SCRIPT);+ const raw = await evaluate(guest, SNAPSHOT_SCRIPT);const parsed = JSON.parse(raw);return { success: true, ...parsed };});@@ -301,7 +310,7 @@ export default class BrowserControlCtr extends ControllerModule {let { x, y } = params;if (params.ref) {- const raw = await guest.executeJavaScript(resolveRefScript(params.ref));+ const raw = await evaluate(guest, resolveRefScript(params.ref));const resolved = JSON.parse(raw);if (resolved.error) return { error: resolved.error, success: false };x = resolved.x;@@ -331,7 +340,7 @@ export default class BrowserControlCtr extends ControllerModule {async fill(params: BrowserControlFillParams): Promise<BrowserControlResult> {return this.withGuest(params.sessionId, async (guest) => {this.markControlling(params.sessionId, guest);- const raw = await guest.executeJavaScript(fillScript(params.ref, params.text));+ const raw = await evaluate(guest, fillScript(params.ref, params.text));const result = JSON.parse(raw);if (result.error) return { error: result.error, success: false };@@ -357,7 +366,8 @@ export default class BrowserControlCtr extends ControllerModule {async scroll(params: BrowserControlScrollParams): Promise<BrowserControlResult> {return this.withGuest(params.sessionId, async (guest) => {this.markControlling(params.sessionId, guest);- await guest.executeJavaScript(+ await evaluate(+ guest,`window.scrollBy({ behavior: 'smooth', left: ${Number(params.dx) || 0}, top: ${Number(params.dy) || 0} })`,);await sleep(350);@@ -370,7 +380,7 @@ export default class BrowserControlCtr extends ControllerModule {return this.withGuest(params.sessionId, async (guest) => {// Strip the agent cursor/chip first β otherwise the model sees its own// overlay in the frame it just asked for.- await guest.executeJavaScript(OVERLAY_REMOVE_SCRIPT).catch(() => {});+ await evaluate(guest, OVERLAY_REMOVE_SCRIPT).catch(() => {});let image = await captureGuest(guest);const size = image.getSize();@@ -384,7 +394,7 @@ export default class BrowserControlCtr extends ControllerModule {@IpcMethod()async readPage(params: BrowserControlParams): Promise<BrowserControlReadPageResult> {return this.withGuest(params.sessionId, async (guest) => {- const raw = await guest.executeJavaScript(READ_PAGE_SCRIPT);+ const raw = await evaluate(guest, READ_PAGE_SCRIPT);return { success: true, ...JSON.parse(raw) };});}@@ -401,7 +411,7 @@ export default class BrowserControlCtr extends ControllerModule {while (Date.now() < deadline) {if (guest.isDestroyed()) return { error: 'Browser page was closed', success: false };- const found = await guest.executeJavaScript(containsTextScript(params.text));+ const found = await evaluate(guest, containsTextScript(params.text));if (found) return { success: true };await sleep(250);}@@ -445,7 +455,7 @@ export default class BrowserControlCtr extends ControllerModule {* The overlay is injected into the guest so it follows page scrolling and zoom.*/private inject(guest: WebContents, script: string) {- guest.executeJavaScript(script).catch((error: Error) => {+ evaluate(guest, script).catch((error: Error) => {logger.debug(`Agent overlay injection failed: ${error.message}`);});}diff --git a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts b/apps/desktop/src/main/controllers/BrowserSidebarCtr.tsindex ad362228fa4..76220feb503 100644--- a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts+++ b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts@@ -36,6 +36,10 @@ const DEFAULT_BROWSER_URL = 'about:blank';const HTTP_URL_PATTERN = /^https?:\/\//i;const LOCAL_URL_PATTERN = /^(?:localhost|127(?:\.\d{1,3}){3}|\[?::1\]?)(?::\d+)?(?:[/?#].*)?$/i;const SUPPORTED_PROTOCOLS = new Set(['about:', 'http:', 'https:']);+/** How long `navigate` waits for the load to finish before reporting it as still loading. */+const NAVIGATION_SETTLE_TIMEOUT_MS = 15_000;+/** net::ERR_ABORTED β the navigation was superseded rather than failed. */+const NAVIGATION_ABORTED_ERRNO = -3;const DEFAULT_OVERLAY_LABELS: AgentOverlayLabels = {controlling: 'Agent is controlling this page',@@ -296,13 +300,61 @@ export default class BrowserSidebarCtr extends ControllerModule {page.url = url;page.error = undefined;- await webContents.loadURL(url).catch((error: Error) => {- // A superseded navigation rejects here; the did-fail-load handler already- // records anything worth surfacing.- logger.debug(`Navigation to ${url} did not settle cleanly: ${error.message}`);+ // `loadURL` only settles once every subresource has loaded, which never+ // happens on pages with a hanging request β the tool call then sat until+ // the gateway timeout. Past the cap, report the page as still loading, but+ // only once the requested document has committed: before that, getURL()+ // and the main frame still belong to the previous page. Only a cross-document+ // commit counts: `did-navigate-in-page` also fires for hash changes and+ // pushState on the old page, and a same-document target settles loadURL+ // right away anyway.+ let committed = false;+ const onNavigate = () => {+ committed = true;+ };+ webContents.on('did-navigate', onNavigate);+ let settleTimer: ReturnType<typeof setTimeout> | undefined;+ const outcome = await Promise.race([+ webContents.loadURL(url).then(+ () => ({ status: 'loaded' as const }),+ (error: Error & { errno?: number }) => ({ error, status: 'failed' as const }),+ ),+ new Promise<{ status: 'pending' }>((resolve) => {+ settleTimer = setTimeout(+ () => resolve({ status: 'pending' }),+ NAVIGATION_SETTLE_TIMEOUT_MS,+ );+ }),+ ]).finally(() => {+ clearTimeout(settleTimer);+ webContents.removeListener('did-navigate', onNavigate);});this.updateSnapshot(params.sessionId);++ // ERR_ABORTED means another navigation took over (a redirect or a newer+ // load); the page that replaced it is the real outcome. Anything else β+ // connection refused, a 204 or a download β left the requested page+ // unopened, so say so instead of reporting whatever page is still showing.+ if (outcome.status === 'failed' && outcome.error.errno !== NAVIGATION_ABORTED_ERRNO) {+ logger.debug(`Navigation to ${url} failed: ${outcome.error.message}`);+ const current = webContents.getURL();+ // A refused connection commits Chromium's error page under the requested URL.+ const showing =+ current === url ? 'showing its error page' : `still showing ${current || 'a blank page'}`;+ return {+ error: `Could not open ${url}: ${outcome.error.message}. The browser is ${showing}.`,+ success: false,+ };+ }++ if (outcome.status === 'pending' && !committed) {+ return {+ error: `${url} has not responded within ${NAVIGATION_SETTLE_TIMEOUT_MS / 1000}s, so the browser is still showing ${webContents.getURL() || 'a blank page'}. The load continues in the background β check with readPage or snapshot before acting on the page, or navigate again.`,+ success: false,+ };+ }+return { success: true };}diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.pageLoad.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.pageLoad.test.tsnew file mode 100644index 00000000000..d634b3e3a06--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.pageLoad.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import BrowserControlCtr from '../BrowserControlCtr';++vi.mock('electron', () => ({+ ipcMain: { handle: vi.fn() },+}));++/**+ * Electron's `WebContents.executeJavaScript` waits for the main frame to stop+ * loading. On a page with a request that never finishes it never runs, so the+ * fake mirrors that: it only settles via `mainFrame.executeJavaScript`.+ */+const createStillLoadingGuest = () => ({+ executeJavaScript: vi.fn(() => new Promise(() => {})),+ isDestroyed: () => false,+ mainFrame: {+ executeJavaScript: vi.fn(async (code: string) => {+ if (code.includes('__lobeBrowserRefs = refs'))+ return JSON.stringify({+ snapshot: '- heading "Hello" [ref=e1]',+ title: 'Slow',+ url: 'http://x/',+ });+ if (code.includes('innerText'))+ return JSON.stringify({+ content: 'Hello',+ selectedText: '',+ title: 'Slow',+ url: 'http://x/',+ });+ return undefined;+ }),+ },+});++describe('BrowserControlCtr on a page that is still loading', () => {+ const setup = () => {+ const guest = createStillLoadingGuest();+ const controller = new BrowserControlCtr({+ getController: () => ({ getSessionWebContents: () => guest }),+ } as unknown as App);+ return { controller, guest };+ };++ it('snapshots the current document instead of waiting for load to finish', async () => {+ const { controller, guest } = setup();++ await expect(controller.snapshot({ sessionId: 'topic:a' })).resolves.toMatchObject({+ snapshot: '- heading "Hello" [ref=e1]',+ success: true,+ });+ expect(guest.executeJavaScript).not.toHaveBeenCalled();+ });++ it('reads the page while it is still loading', async () => {+ const { controller } = setup();++ await expect(controller.readPage({ sessionId: 'topic:a' })).resolves.toMatchObject({+ content: 'Hello',+ success: true,+ });+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.tsindex 4c1b1526020..52cb01730e9 100644--- a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts@@ -119,6 +119,141 @@ describe('BrowserSidebarCtr retained webview registration', () => {);});+ describe('navigate outcome', () => {+ const register = async (guest: FakeWebContents) => {+ fromIdMock.mockImplementation((id: number) => (id === guest.id ? guest : undefined));+ await invokeIpc('browserSidebar.registerWebview', {+ sessionId: 'topic:a',+ webContentsId: guest.id,+ });+ };++ it('stops waiting for a page whose load never finishes', async () => {+ vi.useFakeTimers();+ const guest = createWebContents(7);+ // The document commits, but a request on it never completes: loadURL+ // never settles.+ guest.loadURL = vi.fn((nextUrl: string) => {+ guest.getURL.mockReturnValue(nextUrl);+ guest.emit('did-navigate', {}, nextUrl);+ return new Promise(() => {});+ });+ await register(guest);++ const pending = invokeIpc('browserSidebar.navigate', {+ sessionId: 'topic:a',+ url: 'http://127.0.0.1:9876/',+ });+ await vi.advanceTimersByTimeAsync(15_000);++ await expect(pending).resolves.toEqual({ success: true });+ vi.useRealTimers();+ });++ it('does not report success while the requested document has not committed', async () => {+ vi.useFakeTimers();+ const guest = createWebContents(7);+ guest.getURL.mockReturnValue('http://127.0.0.1:16001/');+ // The server has not answered yet: nothing commits, loadURL never settles.+ guest.loadURL = vi.fn(() => new Promise(() => {}));+ await register(guest);++ const pending = invokeIpc('browserSidebar.navigate', {+ sessionId: 'topic:a',+ url: 'http://127.0.0.1:18748/',+ });+ await vi.advanceTimersByTimeAsync(15_000);++ await expect(pending).resolves.toEqual({+ error:+ 'http://127.0.0.1:18748/ has not responded within 15s, so the browser is still showing http://127.0.0.1:16001/. The load continues in the background β check with readPage or snapshot before acting on the page, or navigate again.',+ success: false,+ });+ expect(guest.listenerCount('did-navigate')).toBe(1);+ vi.useRealTimers();+ });++ it('ignores in-page navigations of the old page while the requested one is pending', async () => {+ vi.useFakeTimers();+ const guest = createWebContents(7);+ guest.getURL.mockReturnValue('http://127.0.0.1:16001/');+ // The old SPA changes its hash / pushState while the new server is still+ // silent: that is not the requested document committing.+ guest.loadURL = vi.fn(() => {+ guest.emit('did-navigate-in-page', {}, 'http://127.0.0.1:16001/#tab', true);+ return new Promise(() => {});+ });+ await register(guest);++ const pending = invokeIpc('browserSidebar.navigate', {+ sessionId: 'topic:a',+ url: 'http://127.0.0.1:18748/',+ });+ await vi.advanceTimersByTimeAsync(15_000);++ await expect(pending).resolves.toMatchObject({ success: false });+ vi.useRealTimers();+ });++ it('reports a navigation that left the requested page unopened', async () => {+ const guest = createWebContents(7);+ guest.getURL.mockReturnValue('http://127.0.0.1:16001/');+ // A 204 / download / refused connection rejects without committing.+ guest.loadURL = vi.fn(async () => {+ throw Object.assign(new Error("ERR_FAILED (-2) loading 'http://127.0.0.1:18748/'"), {+ errno: -2,+ });+ });+ await register(guest);++ await expect(+ invokeIpc('browserSidebar.navigate', {+ sessionId: 'topic:a',+ url: 'http://127.0.0.1:18748/',+ }),+ ).resolves.toEqual({+ error:+ "Could not open http://127.0.0.1:18748/: ERR_FAILED (-2) loading 'http://127.0.0.1:18748/'. The browser is still showing http://127.0.0.1:16001/.",+ success: false,+ });+ });++ it('says an error page is showing when the failed URL committed', async () => {+ const guest = createWebContents(7);+ guest.loadURL = vi.fn(async (nextUrl: string) => {+ guest.getURL.mockReturnValue(nextUrl);+ throw Object.assign(new Error('ERR_CONNECTION_REFUSED (-102)'), { errno: -102 });+ });+ await register(guest);++ await expect(+ invokeIpc('browserSidebar.navigate', {+ sessionId: 'topic:a',+ url: 'http://127.0.0.1:18748/',+ }),+ ).resolves.toEqual({+ error:+ 'Could not open http://127.0.0.1:18748/: ERR_CONNECTION_REFUSED (-102). The browser is showing its error page.',+ success: false,+ });+ });++ it('treats a superseded navigation (ERR_ABORTED) as settled', async () => {+ const guest = createWebContents(7);+ guest.loadURL = vi.fn(async () => {+ throw Object.assign(new Error('ERR_ABORTED (-3)'), { errno: -3 });+ });+ await register(guest);++ await expect(+ invokeIpc('browserSidebar.navigate', {+ sessionId: 'topic:a',+ url: 'https://example.com/redirects',+ }),+ ).resolves.toEqual({ success: true });+ });+ });+it('keeps sessions isolated and activates the most recently registered host', async () => {const oldGuest = createWebContents(1);const newGuest = createWebContents(2);diff --git a/packages/builtin-tool-browser/src/client/executor/index.ts b/packages/builtin-tool-browser/src/client/executor/index.tsindex c7e710236a4..ffe495729d1 100644--- a/packages/builtin-tool-browser/src/client/executor/index.ts+++ b/packages/builtin-tool-browser/src/client/executor/index.ts@@ -50,10 +50,16 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {// Let the page settle before reporting where we landed.await this.waitForLoad(sessionId);const next = await electronBrowserSidebarService.getState({ sessionId });- return this.success(`Opened ${next.url}${next.title ? ` β "${next.title}"` : ''}`, {- title: next.title,- url: next.url,- });+ const loading = next.isLoading+ ? ' The page is still loading (some requests have not finished); its content may be incomplete, but snapshot/readPage work now.'+ : '';+ return this.success(+ `Opened ${next.url}${next.title ? ` β "${next.title}"` : ''}.${loading}`,+ {+ title: next.title,+ url: next.url,+ },+ );} catch (error) {return this.errorResult(error);}