@midscene/web 1.15.5-beta-20261015030228.0 → 1.15.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/agent-tools-puppeteer.mjs +26 -2
- package/dist/es/agent-tools-puppeteer.mjs.map +1 -1
- package/dist/es/bridge-mode/io-client.mjs +1 -1
- package/dist/es/bridge-mode/io-server.mjs +2 -2
- package/dist/es/bridge-mode/io-server.mjs.map +1 -1
- package/dist/es/bridge-mode/page-browser-side.mjs +1 -1
- package/dist/es/bridge-mode/page-browser-side.mjs.map +1 -1
- package/dist/es/cli.mjs +1 -1
- package/dist/es/{playwright → common}/test-runner/cookies.mjs +56 -79
- package/dist/es/common/test-runner/cookies.mjs.map +1 -0
- package/dist/es/common/test-runner/driver.mjs +0 -0
- package/dist/es/common/test-runner/nodes.mjs +139 -0
- package/dist/es/common/test-runner/nodes.mjs.map +1 -0
- package/dist/es/common/test-runner/utils.mjs +24 -0
- package/dist/es/common/test-runner/utils.mjs.map +1 -0
- package/dist/es/playwright/test-runner/agent-nodes.mjs +3 -10
- package/dist/es/playwright/test-runner/agent-nodes.mjs.map +1 -1
- package/dist/es/playwright/test-runner/driver.mjs +42 -0
- package/dist/es/playwright/test-runner/driver.mjs.map +1 -0
- package/dist/es/playwright/test-runner/index.mjs +1 -4
- package/dist/es/playwright/test-runner/utils.mjs +1 -21
- package/dist/es/playwright/test-runner/utils.mjs.map +1 -1
- package/dist/es/puppeteer/browser-agent.mjs +9 -1
- package/dist/es/puppeteer/browser-agent.mjs.map +1 -1
- package/dist/es/puppeteer/page-agent.mjs +19 -1
- package/dist/es/puppeteer/page-agent.mjs.map +1 -1
- package/dist/es/puppeteer/test-runner/agent-nodes.mjs +6 -0
- package/dist/es/puppeteer/test-runner/agent-nodes.mjs.map +1 -0
- package/dist/es/puppeteer/test-runner/driver.mjs +62 -0
- package/dist/es/puppeteer/test-runner/driver.mjs.map +1 -0
- package/dist/es/puppeteer/test-runner/index.mjs +3 -0
- package/dist/es/puppeteer/test-runner/types.mjs +0 -0
- package/dist/es/puppeteer/test-runner/utils.mjs +8 -0
- package/dist/es/puppeteer/test-runner/utils.mjs.map +1 -0
- package/dist/lib/agent-tools-puppeteer.js +26 -2
- package/dist/lib/agent-tools-puppeteer.js.map +1 -1
- package/dist/lib/bridge-mode/io-client.js +1 -1
- package/dist/lib/bridge-mode/io-server.js +2 -2
- package/dist/lib/bridge-mode/io-server.js.map +1 -1
- package/dist/lib/bridge-mode/page-browser-side.js +1 -1
- package/dist/lib/bridge-mode/page-browser-side.js.map +1 -1
- package/dist/lib/cli.js +1 -1
- package/dist/lib/{playwright → common}/test-runner/cookies.js +58 -81
- package/dist/lib/common/test-runner/cookies.js.map +1 -0
- package/dist/lib/common/test-runner/driver.js +20 -0
- package/dist/lib/common/test-runner/driver.js.map +1 -0
- package/dist/lib/common/test-runner/nodes.js +185 -0
- package/dist/lib/common/test-runner/nodes.js.map +1 -0
- package/dist/lib/common/test-runner/utils.js +61 -0
- package/dist/lib/common/test-runner/utils.js.map +1 -0
- package/dist/lib/playwright/test-runner/agent-nodes.js +3 -10
- package/dist/lib/playwright/test-runner/agent-nodes.js.map +1 -1
- package/dist/lib/playwright/test-runner/driver.js +76 -0
- package/dist/lib/playwright/test-runner/driver.js.map +1 -0
- package/dist/lib/playwright/test-runner/index.js +5 -8
- package/dist/lib/playwright/test-runner/utils.js +4 -24
- package/dist/lib/playwright/test-runner/utils.js.map +1 -1
- package/dist/lib/puppeteer/browser-agent.js +9 -1
- package/dist/lib/puppeteer/browser-agent.js.map +1 -1
- package/dist/lib/puppeteer/page-agent.js +19 -1
- package/dist/lib/puppeteer/page-agent.js.map +1 -1
- package/dist/lib/puppeteer/test-runner/agent-nodes.js +40 -0
- package/dist/lib/puppeteer/test-runner/agent-nodes.js.map +1 -0
- package/dist/lib/puppeteer/test-runner/driver.js +96 -0
- package/dist/lib/puppeteer/test-runner/driver.js.map +1 -0
- package/dist/lib/puppeteer/test-runner/index.js +51 -0
- package/dist/lib/puppeteer/test-runner/index.js.map +1 -0
- package/dist/lib/puppeteer/test-runner/types.js +20 -0
- package/dist/lib/puppeteer/test-runner/types.js.map +1 -0
- package/dist/lib/puppeteer/test-runner/utils.js +48 -0
- package/dist/lib/puppeteer/test-runner/utils.js.map +1 -0
- package/dist/types/agent-tools-puppeteer.d.ts +1 -0
- package/dist/types/agent-tools-puppeteer.d.ts.map +1 -1
- package/dist/types/common/test-runner/cookies.d.ts +52 -0
- package/dist/types/common/test-runner/cookies.d.ts.map +1 -0
- package/dist/types/common/test-runner/driver.d.ts +38 -0
- package/dist/types/common/test-runner/driver.d.ts.map +1 -0
- package/dist/types/common/test-runner/nodes.d.ts +38 -0
- package/dist/types/common/test-runner/nodes.d.ts.map +1 -0
- package/dist/types/common/test-runner/utils.d.ts +3 -0
- package/dist/types/common/test-runner/utils.d.ts.map +1 -0
- package/dist/types/playwright/test-runner/agent-nodes.d.ts +1 -2
- package/dist/types/playwright/test-runner/agent-nodes.d.ts.map +1 -1
- package/dist/types/playwright/test-runner/driver.d.ts +4 -0
- package/dist/types/playwright/test-runner/driver.d.ts.map +1 -0
- package/dist/types/playwright/test-runner/index.d.ts +2 -8
- package/dist/types/playwright/test-runner/index.d.ts.map +1 -1
- package/dist/types/playwright/test-runner/types.d.ts +5 -14
- package/dist/types/playwright/test-runner/types.d.ts.map +1 -1
- package/dist/types/playwright/test-runner/utils.d.ts +1 -2
- package/dist/types/playwright/test-runner/utils.d.ts.map +1 -1
- package/dist/types/puppeteer/browser-agent.d.ts +5 -0
- package/dist/types/puppeteer/browser-agent.d.ts.map +1 -1
- package/dist/types/puppeteer/index.d.ts +1 -1
- package/dist/types/puppeteer/index.d.ts.map +1 -1
- package/dist/types/puppeteer/page-agent.d.ts +8 -1
- package/dist/types/puppeteer/page-agent.d.ts.map +1 -1
- package/dist/types/puppeteer/test-runner/agent-nodes.d.ts +2 -0
- package/dist/types/puppeteer/test-runner/agent-nodes.d.ts.map +1 -0
- package/dist/types/puppeteer/test-runner/driver.d.ts +4 -0
- package/dist/types/puppeteer/test-runner/driver.d.ts.map +1 -0
- package/dist/types/puppeteer/test-runner/index.d.ts +5 -0
- package/dist/types/puppeteer/test-runner/index.d.ts.map +1 -0
- package/dist/types/puppeteer/test-runner/types.d.ts +18 -0
- package/dist/types/puppeteer/test-runner/types.d.ts.map +1 -0
- package/dist/types/puppeteer/test-runner/utils.d.ts +4 -0
- package/dist/types/puppeteer/test-runner/utils.d.ts.map +1 -0
- package/package.json +9 -4
- package/dist/es/playwright/test-runner/clear-cookies.mjs +0 -45
- package/dist/es/playwright/test-runner/clear-cookies.mjs.map +0 -1
- package/dist/es/playwright/test-runner/cookies.mjs.map +0 -1
- package/dist/es/playwright/test-runner/goto-url.mjs +0 -60
- package/dist/es/playwright/test-runner/goto-url.mjs.map +0 -1
- package/dist/es/playwright/test-runner/viewport.mjs +0 -35
- package/dist/es/playwright/test-runner/viewport.mjs.map +0 -1
- package/dist/lib/playwright/test-runner/clear-cookies.js +0 -82
- package/dist/lib/playwright/test-runner/clear-cookies.js.map +0 -1
- package/dist/lib/playwright/test-runner/cookies.js.map +0 -1
- package/dist/lib/playwright/test-runner/goto-url.js +0 -97
- package/dist/lib/playwright/test-runner/goto-url.js.map +0 -1
- package/dist/lib/playwright/test-runner/viewport.js +0 -72
- package/dist/lib/playwright/test-runner/viewport.js.map +0 -1
- package/dist/types/playwright/test-runner/clear-cookies.d.ts +0 -17
- package/dist/types/playwright/test-runner/clear-cookies.d.ts.map +0 -1
- package/dist/types/playwright/test-runner/cookies.d.ts +0 -33
- package/dist/types/playwright/test-runner/cookies.d.ts.map +0 -1
- package/dist/types/playwright/test-runner/goto-url.d.ts +0 -26
- package/dist/types/playwright/test-runner/goto-url.d.ts.map +0 -1
- package/dist/types/playwright/test-runner/viewport.d.ts +0 -14
- package/dist/types/playwright/test-runner/viewport.d.ts.map +0 -1
|
@@ -302,7 +302,7 @@ class WebPuppeteerMidsceneTools extends BaseMidsceneTools {
|
|
|
302
302
|
let page;
|
|
303
303
|
if (navigateToUrl) {
|
|
304
304
|
page = await browser.newPage();
|
|
305
|
-
if (this.viewport) await
|
|
305
|
+
if (this.viewport) await this.resizePersistentViewport(page);
|
|
306
306
|
await page.goto(navigateToUrl, {
|
|
307
307
|
timeout: 30000,
|
|
308
308
|
waitUntil: 'domcontentloaded'
|
|
@@ -313,7 +313,7 @@ class WebPuppeteerMidsceneTools extends BaseMidsceneTools {
|
|
|
313
313
|
const webPages = pages.filter((p)=>/^https?:\/\//.test(p.url()));
|
|
314
314
|
page = matchedPage ?? (webPages.length > 0 ? webPages[webPages.length - 1] : pages[pages.length - 1] || await browser.newPage());
|
|
315
315
|
if (reused) await page.bringToFront();
|
|
316
|
-
if (this.viewport) await
|
|
316
|
+
if (this.viewport) await this.resizePersistentViewport(page);
|
|
317
317
|
}
|
|
318
318
|
const targetId = getTargetId(page);
|
|
319
319
|
if (!targetId) throw new Error('Failed to persist Puppeteer page session because Puppeteer did not expose a Chrome targetId.');
|
|
@@ -326,6 +326,30 @@ class WebPuppeteerMidsceneTools extends BaseMidsceneTools {
|
|
|
326
326
|
this.lastInitArgsSignature = nextSignature;
|
|
327
327
|
return this.agent;
|
|
328
328
|
}
|
|
329
|
+
async resizePersistentViewport(page) {
|
|
330
|
+
const viewport = this.viewport;
|
|
331
|
+
if (!viewport) return;
|
|
332
|
+
await page.setViewport(null);
|
|
333
|
+
const client = await page.createCDPSession();
|
|
334
|
+
try {
|
|
335
|
+
const { windowId, bounds } = await client.send('Browser.getWindowForTarget');
|
|
336
|
+
const content = await page.evaluate('({ width: window.innerWidth, height: window.innerHeight })');
|
|
337
|
+
if (void 0 === bounds.width || void 0 === bounds.height) throw new Error('Chrome did not return window dimensions');
|
|
338
|
+
await client.send('Browser.setWindowBounds', {
|
|
339
|
+
windowId,
|
|
340
|
+
bounds: {
|
|
341
|
+
width: bounds.width + viewport.width - content.width,
|
|
342
|
+
height: bounds.height + viewport.height - content.height
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
await page.waitForFunction(`window.innerWidth === ${JSON.stringify(viewport.width)} && window.innerHeight === ${JSON.stringify(viewport.height)}`, {
|
|
346
|
+
timeout: 10000
|
|
347
|
+
});
|
|
348
|
+
} finally{
|
|
349
|
+
await client.detach();
|
|
350
|
+
}
|
|
351
|
+
await page.setViewport(viewport);
|
|
352
|
+
}
|
|
329
353
|
async destroy() {
|
|
330
354
|
await super.destroy();
|
|
331
355
|
this.browserManager.disconnect();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-tools-puppeteer.mjs","sources":["../../src/agent-tools-puppeteer.ts"],"sourcesContent":["import { type ChildProcess, spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, open, readFile, unlink, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { ScreenshotItem } from '@midscene/core';\nimport {\n extractAgentBehaviorInitArgs,\n getAgentInitArgsSignature,\n shouldRebuildAgentForInitArgs,\n} from '@midscene/shared/agent-tools/agent-behavior-init-args';\nimport {\n BaseMidsceneTools,\n type InitArgSpec,\n} from '@midscene/shared/agent-tools/base-tools';\nimport { resolveChromePath } from '@midscene/shared/agent-tools/chrome-path';\nimport type { ToolDefinition } from '@midscene/shared/agent-tools/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport type { Page as PuppeteerPage } from 'puppeteer';\nimport puppeteer from 'puppeteer-core';\nimport type { Browser, Page } from 'puppeteer-core';\nimport {\n type WebAgentInitArgs,\n adaptWebAgentInitArgs,\n webAgentInitArgShape,\n} from './agent-init-args';\nimport {\n type ViewportSize,\n defaultPuppeteerWindowViewportSize,\n defaultStaticPageViewportSize,\n} from './common/viewport';\nimport { PuppeteerAgent } from './puppeteer';\nimport { StaticPage } from './static';\n\nconst ENDPOINT_FILE = join(tmpdir(), 'midscene-puppeteer-endpoint');\nconst USER_DATA_DIR = join(tmpdir(), 'midscene-puppeteer-profile');\nconst TARGET_ID_FILE = join(tmpdir(), 'midscene-puppeteer-target-id');\nconst DETACHED_CHROME_LAUNCH_TIMEOUT_MS = 30_000;\nconst DETACHED_CHROME_ENDPOINT_POLL_INTERVAL_MS = 25;\nconst debug = getDebug('agent-tools:puppeteer');\n\nexport const PUPPETEER_ENDPOINT_FILE = ENDPOINT_FILE;\n\nexport interface PuppeteerPersistenceOptions {\n endpointFile?: string;\n userDataDir?: string;\n targetIdFile?: string;\n}\n\nexport interface WebPuppeteerMidsceneToolsOptions {\n persistence?: PuppeteerPersistenceOptions;\n}\n\nexport function buildDetachedChromeArgs(options: {\n userDataDir: string;\n viewport?: ViewportSize;\n}): string[] {\n const viewport = options.viewport ?? defaultPuppeteerWindowViewportSize;\n\n return [\n '--headless=new',\n `--user-data-dir=${options.userDataDir}`,\n '--remote-debugging-port=0',\n '--no-first-run',\n '--no-default-browser-check',\n '--disable-extensions',\n '--disable-default-apps',\n '--disable-sync',\n '--disable-background-networking',\n '--password-store=basic',\n '--use-mock-keychain',\n `--window-size=${viewport.width},${viewport.height}`,\n '--force-color-profile=srgb',\n ];\n}\n\nfunction terminateDetachedChrome(proc: ChildProcess): void {\n if (proc.killed || proc.exitCode !== null || proc.signalCode !== null) {\n return;\n }\n\n if (process.platform !== 'win32' && proc.pid) {\n try {\n process.kill(-proc.pid, 'SIGKILL');\n return;\n } catch {}\n }\n\n try {\n proc.kill('SIGKILL');\n } catch {}\n}\n\nfunction getTargetId(page: Page): string | undefined {\n return (page.target() as unknown as { _targetId?: string })._targetId;\n}\n\nexport function waitForDetachedChromeEndpoint(\n proc: ChildProcess,\n stderrFile: string,\n timeoutMs = DETACHED_CHROME_LAUNCH_TIMEOUT_MS,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let output = '';\n let settled = false;\n let exited = false;\n let pollTimer: NodeJS.Timeout | undefined;\n const cleanup = () => {\n clearTimeout(timeout);\n if (pollTimer) {\n clearTimeout(pollTimer);\n }\n proc.removeListener('exit', onExit);\n proc.removeListener('error', onError);\n };\n const resolveOnce = (value: string) => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(value);\n };\n const rejectOnce = (error: Error, terminate = false) => {\n if (settled) return;\n settled = true;\n if (terminate) {\n terminateDetachedChrome(proc);\n }\n cleanup();\n reject(error);\n };\n const onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n exited = true;\n void readFile(stderrFile, 'utf-8')\n .catch(() => output)\n .then((latestOutput) => {\n output = latestOutput;\n rejectOnce(\n new Error(\n `Chrome exited with code ${code ?? signal} before DevTools was ready.\\nChrome stderr: ${output}\\nTip: if running in a container, launch Chrome with sandbox-compatible arguments.`,\n ),\n );\n });\n };\n const onError = (error: Error) => {\n rejectOnce(\n new Error(`Failed to launch Chrome. Stderr log: \"${stderrFile}\".`, {\n cause: error,\n }),\n true,\n );\n };\n const pollForEndpoint = async (): Promise<void> => {\n if (settled || exited) return;\n try {\n output = await readFile(stderrFile, 'utf-8');\n } catch (error) {\n rejectOnce(\n new Error(`Failed to read Chrome stderr log \"${stderrFile}\".`, {\n cause: error,\n }),\n true,\n );\n return;\n }\n\n if (settled || exited) return;\n const match = output.match(/DevTools listening on (ws:\\/\\/[^\\s]+)/);\n if (match) {\n resolveOnce(match[1]);\n return;\n }\n pollTimer = setTimeout(\n () => void pollForEndpoint(),\n DETACHED_CHROME_ENDPOINT_POLL_INTERVAL_MS,\n );\n };\n const timeout = setTimeout(\n () =>\n rejectOnce(\n new Error(\n `Chrome launch timeout.\\nChrome stderr: ${output}\\nTip: if running in a container, launch Chrome with sandbox-compatible arguments.`,\n ),\n true,\n ),\n timeoutMs,\n );\n\n proc.on('exit', onExit);\n proc.on('error', onError);\n void pollForEndpoint();\n });\n}\n\n/**\n * Persistent Puppeteer browser manager.\n * Launches a detached Chrome and persists the WS endpoint across CLI calls.\n */\nclass PuppeteerBrowserManager {\n activeBrowser: Browser | null = null;\n\n constructor(private readonly persistence: PuppeteerPersistenceOptions = {}) {}\n\n private get endpointFile() {\n return this.persistence.endpointFile || ENDPOINT_FILE;\n }\n\n private get userDataDir() {\n return this.persistence.userDataDir || USER_DATA_DIR;\n }\n\n private get targetIdFile() {\n return this.persistence.targetIdFile || TARGET_ID_FILE;\n }\n\n private get chromeStderrFile() {\n return join(this.userDataDir, 'chrome-stderr.log');\n }\n\n async readSavedTargetId(): Promise<string | null> {\n let content: string;\n try {\n content = await readFile(this.targetIdFile, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw new Error(\n `Failed to read Puppeteer targetId from \"${this.targetIdFile}\".`,\n { cause: error },\n );\n }\n\n const targetId = content.trim();\n if (!targetId) {\n throw new Error(\n `Puppeteer targetId file \"${this.targetIdFile}\" is empty.`,\n );\n }\n return targetId;\n }\n\n async saveTargetId(targetId: string): Promise<void> {\n try {\n await writeFile(this.targetIdFile, targetId, 'utf-8');\n debug('Saved Puppeteer targetId: %s', targetId);\n } catch (error) {\n throw new Error(\n `Failed to save Puppeteer targetId to \"${this.targetIdFile}\".`,\n { cause: error },\n );\n }\n }\n\n async cleanupTargetIdFile(): Promise<void> {\n try {\n await unlink(this.targetIdFile);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw new Error(\n `Failed to remove Puppeteer targetId file \"${this.targetIdFile}\".`,\n { cause: error },\n );\n }\n }\n\n async cleanupChromeStderrFile(): Promise<void> {\n try {\n await unlink(this.chromeStderrFile);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n debug('Failed to clean Chrome stderr log: %s', error);\n }\n }\n }\n\n async getOrLaunch(\n viewport?: ViewportSize,\n ): Promise<{ browser: Browser; reused: boolean }> {\n const endpointFile = this.endpointFile;\n if (existsSync(endpointFile)) {\n try {\n const endpoint = (await readFile(endpointFile, 'utf-8')).trim();\n const browser = await puppeteer.connect({\n browserWSEndpoint: endpoint,\n defaultViewport: null,\n });\n return { browser, reused: true };\n } catch (error) {\n debug('Failed to reuse persisted Puppeteer endpoint: %s', error);\n try {\n await unlink(endpointFile);\n } catch {}\n await this.cleanupTargetIdFile();\n }\n }\n\n await this.cleanupTargetIdFile();\n const wsEndpoint = await this.launchDetachedChrome(viewport);\n await writeFile(endpointFile, wsEndpoint);\n\n const browser = await puppeteer.connect({\n browserWSEndpoint: wsEndpoint,\n defaultViewport: null,\n });\n return { browser, reused: false };\n }\n\n async closeBrowser(): Promise<void> {\n const endpointFile = this.endpointFile;\n if (existsSync(endpointFile)) {\n try {\n const endpoint = (await readFile(endpointFile, 'utf-8')).trim();\n const browser = await puppeteer.connect({\n browserWSEndpoint: endpoint,\n });\n await browser.close();\n } catch (error) {\n debug('Failed to close persisted Puppeteer browser: %s', error);\n }\n }\n try {\n if (existsSync(endpointFile)) {\n await unlink(endpointFile);\n }\n } catch {}\n await this.cleanupTargetIdFile();\n await this.cleanupChromeStderrFile();\n }\n\n disconnect(): void {\n if (this.activeBrowser) {\n this.activeBrowser.disconnect();\n this.activeBrowser = null;\n }\n }\n\n async launchDetachedChrome(viewport?: ViewportSize): Promise<string> {\n const chromePath = resolveChromePath();\n const userDataDir = this.userDataDir;\n\n await mkdir(userDataDir, { recursive: true });\n\n const args = buildDetachedChromeArgs({\n userDataDir,\n viewport,\n });\n\n const stderrFile = this.chromeStderrFile;\n const stderrHandle = await open(stderrFile, 'w');\n let proc: ChildProcess;\n try {\n proc = spawn(chromePath, args, {\n detached: true,\n stdio: ['ignore', 'ignore', stderrHandle.fd],\n });\n } catch (error) {\n await stderrHandle.close();\n throw error;\n }\n const endpointPromise = waitForDetachedChromeEndpoint(proc, stderrFile);\n proc.unref();\n try {\n await stderrHandle.close();\n } catch (error) {\n terminateDetachedChrome(proc);\n await endpointPromise.catch(() => undefined);\n throw new Error(`Failed to close Chrome stderr log \"${stderrFile}\".`, {\n cause: error,\n });\n }\n\n return endpointPromise;\n }\n}\n\nconst defaultBrowserManager = new PuppeteerBrowserManager();\n\n/**\n * Tools manager for Web Puppeteer mode.\n * Uses a persistent headless Chrome browser that survives across CLI calls.\n */\nexport class WebPuppeteerMidsceneTools extends BaseMidsceneTools<\n PuppeteerAgent,\n WebAgentInitArgs\n> {\n private readonly viewport?: ViewportSize;\n private readonly browserManager: PuppeteerBrowserManager;\n private lastInitArgsSignature?: string;\n\n constructor(\n viewport?: ViewportSize,\n options: WebPuppeteerMidsceneToolsOptions = {},\n ) {\n super();\n this.viewport = viewport ? { ...viewport } : undefined;\n this.browserManager = options.persistence\n ? new PuppeteerBrowserManager(options.persistence)\n : defaultBrowserManager;\n }\n\n protected getCliReportSessionName() {\n return 'midscene-web';\n }\n\n protected readonly initArgSpec: InitArgSpec<WebAgentInitArgs> = {\n namespace: 'web',\n shape: webAgentInitArgShape,\n cli: {\n preferBareKeys: true,\n },\n adapt: adaptWebAgentInitArgs,\n };\n\n protected createTemporaryDevice() {\n return new StaticPage({\n screenshot: ScreenshotItem.create('', Date.now()),\n shotSize: this.viewport ?? defaultStaticPageViewportSize,\n shrunkShotToLogicalRatio: 1,\n });\n }\n\n protected async ensureAgent(\n initArgs?: WebAgentInitArgs,\n ): Promise<PuppeteerAgent> {\n const navigateToUrl = initArgs?.url;\n const nextSignature = getAgentInitArgsSignature(initArgs);\n const shouldOpenUrl = typeof navigateToUrl === 'string';\n\n if (\n this.agent &&\n (shouldOpenUrl ||\n shouldRebuildAgentForInitArgs(\n this.lastInitArgsSignature,\n nextSignature,\n ))\n ) {\n try {\n await this.agent?.destroy?.();\n } catch {}\n this.agent = undefined;\n }\n\n if (this.agent) return this.agent;\n\n const { browser, reused } = await this.browserManager.getOrLaunch(\n this.viewport,\n );\n this.browserManager.activeBrowser = browser;\n\n const pages = await browser.pages();\n let page: Page;\n\n if (navigateToUrl) {\n page = await browser.newPage();\n if (this.viewport) {\n await page.setViewport(this.viewport);\n }\n await page.goto(navigateToUrl, {\n timeout: 30000,\n waitUntil: 'domcontentloaded',\n });\n } else {\n const savedTargetId = await this.browserManager.readSavedTargetId();\n const matchedPage = savedTargetId\n ? pages.find((candidate) => getTargetId(candidate) === savedTargetId)\n : undefined;\n const webPages = pages.filter((p) => /^https?:\\/\\//.test(p.url()));\n page =\n matchedPage ??\n (webPages.length > 0\n ? webPages[webPages.length - 1]\n : pages[pages.length - 1] || (await browser.newPage()));\n\n if (reused) {\n await page.bringToFront();\n }\n if (this.viewport) {\n await page.setViewport(this.viewport);\n }\n }\n\n const targetId = getTargetId(page);\n if (!targetId) {\n throw new Error(\n 'Failed to persist Puppeteer page session because Puppeteer did not expose a Chrome targetId.',\n );\n }\n await this.browserManager.saveTargetId(targetId);\n\n const reportOptions = this.readCliReportAgentOptions();\n this.agent = new PuppeteerAgent(page as unknown as PuppeteerPage, {\n ...(extractAgentBehaviorInitArgs(initArgs) ?? {}),\n ...(reportOptions ?? {}),\n });\n this.lastInitArgsSignature = nextSignature;\n return this.agent;\n }\n\n public async destroy(): Promise<void> {\n await super.destroy();\n this.browserManager.disconnect();\n }\n\n protected preparePlatformTools(): ToolDefinition[] {\n return [\n {\n name: 'web_connect',\n description:\n 'Connect to a web page. Opens a new tab with the given URL, or reuses the current page.',\n schema: this.getAgentInitArgSchema(),\n cli: this.getAgentInitArgCliMetadata(),\n handler: async (args) => {\n const initArgs = this.extractAgentInitParam(args);\n const url = initArgs?.url;\n\n // Explicit connect always starts a fresh page session.\n if (this.agent) {\n try {\n await this.agent.destroy?.();\n } catch {}\n this.agent = undefined;\n this.lastInitArgsSignature = undefined;\n }\n\n const reportSession = this.createNewCliReportSession(\n url ?? 'current-page',\n );\n this.commitCliReportSession(reportSession);\n this.agent = await this.ensureAgent(initArgs);\n\n const screenshot = await this.agent.page?.screenshotBase64();\n const label = url ?? 'current page';\n\n return {\n content: [\n { type: 'text', text: `Connected to: ${label}` },\n ...(screenshot ? this.buildScreenshotContent(screenshot) : []),\n ],\n };\n },\n },\n {\n name: 'web_disconnect',\n description:\n 'Disconnect from current web page. The browser stays running for future calls.',\n schema: {},\n handler: async () => {\n if (this.agent) {\n try {\n await this.agent.destroy?.();\n } catch {}\n this.agent = undefined;\n this.lastInitArgsSignature = undefined;\n }\n this.browserManager.disconnect();\n await this.browserManager.cleanupTargetIdFile();\n return this.buildTextResult(\n 'Disconnected from web page (browser still running)',\n );\n },\n },\n {\n name: 'web_close',\n description: 'Close the browser completely and release all resources.',\n schema: {},\n handler: async () => {\n if (this.agent) {\n try {\n await this.agent.destroy?.();\n } catch {}\n this.agent = undefined;\n this.lastInitArgsSignature = undefined;\n }\n await this.browserManager.closeBrowser();\n return this.buildTextResult('Browser closed');\n },\n },\n ];\n }\n}\n"],"names":["ENDPOINT_FILE","join","tmpdir","USER_DATA_DIR","TARGET_ID_FILE","DETACHED_CHROME_LAUNCH_TIMEOUT_MS","DETACHED_CHROME_ENDPOINT_POLL_INTERVAL_MS","debug","getDebug","PUPPETEER_ENDPOINT_FILE","buildDetachedChromeArgs","options","viewport","defaultPuppeteerWindowViewportSize","terminateDetachedChrome","proc","process","getTargetId","page","waitForDetachedChromeEndpoint","stderrFile","timeoutMs","Promise","resolve","reject","output","settled","exited","pollTimer","cleanup","clearTimeout","timeout","onExit","onError","resolveOnce","value","rejectOnce","error","terminate","code","signal","readFile","latestOutput","Error","pollForEndpoint","match","setTimeout","PuppeteerBrowserManager","content","targetId","writeFile","unlink","endpointFile","existsSync","endpoint","browser","puppeteer","wsEndpoint","chromePath","resolveChromePath","userDataDir","mkdir","args","stderrHandle","open","spawn","endpointPromise","undefined","persistence","defaultBrowserManager","WebPuppeteerMidsceneTools","BaseMidsceneTools","StaticPage","ScreenshotItem","Date","defaultStaticPageViewportSize","initArgs","navigateToUrl","nextSignature","getAgentInitArgsSignature","shouldOpenUrl","shouldRebuildAgentForInitArgs","reused","pages","savedTargetId","matchedPage","candidate","webPages","p","reportOptions","PuppeteerAgent","extractAgentBehaviorInitArgs","url","reportSession","screenshot","label","webAgentInitArgShape","adaptWebAgentInitArgs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAMA,gBAAgBC,KAAKC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QAAQ;QAAC,IAAIuD;QAC7C,IAAI,CAAC,cAAc,GAAGxD,QAAQ,WAAW,GACrC,IAAIoC,wBAAwBpC,QAAQ,WAAW,IAC/C0D;IACN;AAqLF"}
|
|
1
|
+
{"version":3,"file":"agent-tools-puppeteer.mjs","sources":["../../src/agent-tools-puppeteer.ts"],"sourcesContent":["import { type ChildProcess, spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, open, readFile, unlink, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { ScreenshotItem } from '@midscene/core';\nimport {\n extractAgentBehaviorInitArgs,\n getAgentInitArgsSignature,\n shouldRebuildAgentForInitArgs,\n} from '@midscene/shared/agent-tools/agent-behavior-init-args';\nimport {\n BaseMidsceneTools,\n type InitArgSpec,\n} from '@midscene/shared/agent-tools/base-tools';\nimport { resolveChromePath } from '@midscene/shared/agent-tools/chrome-path';\nimport type { ToolDefinition } from '@midscene/shared/agent-tools/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport type { Page as PuppeteerPage } from 'puppeteer';\nimport puppeteer from 'puppeteer-core';\nimport type { Browser, Page } from 'puppeteer-core';\nimport {\n type WebAgentInitArgs,\n adaptWebAgentInitArgs,\n webAgentInitArgShape,\n} from './agent-init-args';\nimport {\n type ViewportSize,\n defaultPuppeteerWindowViewportSize,\n defaultStaticPageViewportSize,\n} from './common/viewport';\nimport { PuppeteerAgent } from './puppeteer';\nimport { StaticPage } from './static';\n\nconst ENDPOINT_FILE = join(tmpdir(), 'midscene-puppeteer-endpoint');\nconst USER_DATA_DIR = join(tmpdir(), 'midscene-puppeteer-profile');\nconst TARGET_ID_FILE = join(tmpdir(), 'midscene-puppeteer-target-id');\nconst DETACHED_CHROME_LAUNCH_TIMEOUT_MS = 30_000;\nconst DETACHED_CHROME_ENDPOINT_POLL_INTERVAL_MS = 25;\nconst debug = getDebug('agent-tools:puppeteer');\n\nexport const PUPPETEER_ENDPOINT_FILE = ENDPOINT_FILE;\n\nexport interface PuppeteerPersistenceOptions {\n endpointFile?: string;\n userDataDir?: string;\n targetIdFile?: string;\n}\n\nexport interface WebPuppeteerMidsceneToolsOptions {\n persistence?: PuppeteerPersistenceOptions;\n}\n\nexport function buildDetachedChromeArgs(options: {\n userDataDir: string;\n viewport?: ViewportSize;\n}): string[] {\n const viewport = options.viewport ?? defaultPuppeteerWindowViewportSize;\n\n return [\n '--headless=new',\n `--user-data-dir=${options.userDataDir}`,\n '--remote-debugging-port=0',\n '--no-first-run',\n '--no-default-browser-check',\n '--disable-extensions',\n '--disable-default-apps',\n '--disable-sync',\n '--disable-background-networking',\n '--password-store=basic',\n '--use-mock-keychain',\n `--window-size=${viewport.width},${viewport.height}`,\n '--force-color-profile=srgb',\n ];\n}\n\nfunction terminateDetachedChrome(proc: ChildProcess): void {\n if (proc.killed || proc.exitCode !== null || proc.signalCode !== null) {\n return;\n }\n\n if (process.platform !== 'win32' && proc.pid) {\n try {\n process.kill(-proc.pid, 'SIGKILL');\n return;\n } catch {}\n }\n\n try {\n proc.kill('SIGKILL');\n } catch {}\n}\n\nfunction getTargetId(page: Page): string | undefined {\n return (page.target() as unknown as { _targetId?: string })._targetId;\n}\n\nexport function waitForDetachedChromeEndpoint(\n proc: ChildProcess,\n stderrFile: string,\n timeoutMs = DETACHED_CHROME_LAUNCH_TIMEOUT_MS,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let output = '';\n let settled = false;\n let exited = false;\n let pollTimer: NodeJS.Timeout | undefined;\n const cleanup = () => {\n clearTimeout(timeout);\n if (pollTimer) {\n clearTimeout(pollTimer);\n }\n proc.removeListener('exit', onExit);\n proc.removeListener('error', onError);\n };\n const resolveOnce = (value: string) => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(value);\n };\n const rejectOnce = (error: Error, terminate = false) => {\n if (settled) return;\n settled = true;\n if (terminate) {\n terminateDetachedChrome(proc);\n }\n cleanup();\n reject(error);\n };\n const onExit = (code: number | null, signal: NodeJS.Signals | null) => {\n exited = true;\n void readFile(stderrFile, 'utf-8')\n .catch(() => output)\n .then((latestOutput) => {\n output = latestOutput;\n rejectOnce(\n new Error(\n `Chrome exited with code ${code ?? signal} before DevTools was ready.\\nChrome stderr: ${output}\\nTip: if running in a container, launch Chrome with sandbox-compatible arguments.`,\n ),\n );\n });\n };\n const onError = (error: Error) => {\n rejectOnce(\n new Error(`Failed to launch Chrome. Stderr log: \"${stderrFile}\".`, {\n cause: error,\n }),\n true,\n );\n };\n const pollForEndpoint = async (): Promise<void> => {\n if (settled || exited) return;\n try {\n output = await readFile(stderrFile, 'utf-8');\n } catch (error) {\n rejectOnce(\n new Error(`Failed to read Chrome stderr log \"${stderrFile}\".`, {\n cause: error,\n }),\n true,\n );\n return;\n }\n\n if (settled || exited) return;\n const match = output.match(/DevTools listening on (ws:\\/\\/[^\\s]+)/);\n if (match) {\n resolveOnce(match[1]);\n return;\n }\n pollTimer = setTimeout(\n () => void pollForEndpoint(),\n DETACHED_CHROME_ENDPOINT_POLL_INTERVAL_MS,\n );\n };\n const timeout = setTimeout(\n () =>\n rejectOnce(\n new Error(\n `Chrome launch timeout.\\nChrome stderr: ${output}\\nTip: if running in a container, launch Chrome with sandbox-compatible arguments.`,\n ),\n true,\n ),\n timeoutMs,\n );\n\n proc.on('exit', onExit);\n proc.on('error', onError);\n void pollForEndpoint();\n });\n}\n\n/**\n * Persistent Puppeteer browser manager.\n * Launches a detached Chrome and persists the WS endpoint across CLI calls.\n */\nclass PuppeteerBrowserManager {\n activeBrowser: Browser | null = null;\n\n constructor(private readonly persistence: PuppeteerPersistenceOptions = {}) {}\n\n private get endpointFile() {\n return this.persistence.endpointFile || ENDPOINT_FILE;\n }\n\n private get userDataDir() {\n return this.persistence.userDataDir || USER_DATA_DIR;\n }\n\n private get targetIdFile() {\n return this.persistence.targetIdFile || TARGET_ID_FILE;\n }\n\n private get chromeStderrFile() {\n return join(this.userDataDir, 'chrome-stderr.log');\n }\n\n async readSavedTargetId(): Promise<string | null> {\n let content: string;\n try {\n content = await readFile(this.targetIdFile, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw new Error(\n `Failed to read Puppeteer targetId from \"${this.targetIdFile}\".`,\n { cause: error },\n );\n }\n\n const targetId = content.trim();\n if (!targetId) {\n throw new Error(\n `Puppeteer targetId file \"${this.targetIdFile}\" is empty.`,\n );\n }\n return targetId;\n }\n\n async saveTargetId(targetId: string): Promise<void> {\n try {\n await writeFile(this.targetIdFile, targetId, 'utf-8');\n debug('Saved Puppeteer targetId: %s', targetId);\n } catch (error) {\n throw new Error(\n `Failed to save Puppeteer targetId to \"${this.targetIdFile}\".`,\n { cause: error },\n );\n }\n }\n\n async cleanupTargetIdFile(): Promise<void> {\n try {\n await unlink(this.targetIdFile);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw new Error(\n `Failed to remove Puppeteer targetId file \"${this.targetIdFile}\".`,\n { cause: error },\n );\n }\n }\n\n async cleanupChromeStderrFile(): Promise<void> {\n try {\n await unlink(this.chromeStderrFile);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n debug('Failed to clean Chrome stderr log: %s', error);\n }\n }\n }\n\n async getOrLaunch(\n viewport?: ViewportSize,\n ): Promise<{ browser: Browser; reused: boolean }> {\n const endpointFile = this.endpointFile;\n if (existsSync(endpointFile)) {\n try {\n const endpoint = (await readFile(endpointFile, 'utf-8')).trim();\n const browser = await puppeteer.connect({\n browserWSEndpoint: endpoint,\n defaultViewport: null,\n });\n return { browser, reused: true };\n } catch (error) {\n debug('Failed to reuse persisted Puppeteer endpoint: %s', error);\n try {\n await unlink(endpointFile);\n } catch {}\n await this.cleanupTargetIdFile();\n }\n }\n\n await this.cleanupTargetIdFile();\n const wsEndpoint = await this.launchDetachedChrome(viewport);\n await writeFile(endpointFile, wsEndpoint);\n\n const browser = await puppeteer.connect({\n browserWSEndpoint: wsEndpoint,\n defaultViewport: null,\n });\n return { browser, reused: false };\n }\n\n async closeBrowser(): Promise<void> {\n const endpointFile = this.endpointFile;\n if (existsSync(endpointFile)) {\n try {\n const endpoint = (await readFile(endpointFile, 'utf-8')).trim();\n const browser = await puppeteer.connect({\n browserWSEndpoint: endpoint,\n });\n await browser.close();\n } catch (error) {\n debug('Failed to close persisted Puppeteer browser: %s', error);\n }\n }\n try {\n if (existsSync(endpointFile)) {\n await unlink(endpointFile);\n }\n } catch {}\n await this.cleanupTargetIdFile();\n await this.cleanupChromeStderrFile();\n }\n\n disconnect(): void {\n if (this.activeBrowser) {\n this.activeBrowser.disconnect();\n this.activeBrowser = null;\n }\n }\n\n async launchDetachedChrome(viewport?: ViewportSize): Promise<string> {\n const chromePath = resolveChromePath();\n const userDataDir = this.userDataDir;\n\n await mkdir(userDataDir, { recursive: true });\n\n const args = buildDetachedChromeArgs({\n userDataDir,\n viewport,\n });\n\n const stderrFile = this.chromeStderrFile;\n const stderrHandle = await open(stderrFile, 'w');\n let proc: ChildProcess;\n try {\n proc = spawn(chromePath, args, {\n detached: true,\n stdio: ['ignore', 'ignore', stderrHandle.fd],\n });\n } catch (error) {\n await stderrHandle.close();\n throw error;\n }\n const endpointPromise = waitForDetachedChromeEndpoint(proc, stderrFile);\n proc.unref();\n try {\n await stderrHandle.close();\n } catch (error) {\n terminateDetachedChrome(proc);\n await endpointPromise.catch(() => undefined);\n throw new Error(`Failed to close Chrome stderr log \"${stderrFile}\".`, {\n cause: error,\n });\n }\n\n return endpointPromise;\n }\n}\n\nconst defaultBrowserManager = new PuppeteerBrowserManager();\n\n/**\n * Tools manager for Web Puppeteer mode.\n * Uses a persistent headless Chrome browser that survives across CLI calls.\n */\nexport class WebPuppeteerMidsceneTools extends BaseMidsceneTools<\n PuppeteerAgent,\n WebAgentInitArgs\n> {\n private readonly viewport?: ViewportSize;\n private readonly browserManager: PuppeteerBrowserManager;\n private lastInitArgsSignature?: string;\n\n constructor(\n viewport?: ViewportSize,\n options: WebPuppeteerMidsceneToolsOptions = {},\n ) {\n super();\n this.viewport = viewport ? { ...viewport } : undefined;\n this.browserManager = options.persistence\n ? new PuppeteerBrowserManager(options.persistence)\n : defaultBrowserManager;\n }\n\n protected getCliReportSessionName() {\n return 'midscene-web';\n }\n\n protected readonly initArgSpec: InitArgSpec<WebAgentInitArgs> = {\n namespace: 'web',\n shape: webAgentInitArgShape,\n cli: {\n preferBareKeys: true,\n },\n adapt: adaptWebAgentInitArgs,\n };\n\n protected createTemporaryDevice() {\n return new StaticPage({\n screenshot: ScreenshotItem.create('', Date.now()),\n shotSize: this.viewport ?? defaultStaticPageViewportSize,\n shrunkShotToLogicalRatio: 1,\n });\n }\n\n protected async ensureAgent(\n initArgs?: WebAgentInitArgs,\n ): Promise<PuppeteerAgent> {\n const navigateToUrl = initArgs?.url;\n const nextSignature = getAgentInitArgsSignature(initArgs);\n const shouldOpenUrl = typeof navigateToUrl === 'string';\n\n if (\n this.agent &&\n (shouldOpenUrl ||\n shouldRebuildAgentForInitArgs(\n this.lastInitArgsSignature,\n nextSignature,\n ))\n ) {\n try {\n await this.agent?.destroy?.();\n } catch {}\n this.agent = undefined;\n }\n\n if (this.agent) return this.agent;\n\n const { browser, reused } = await this.browserManager.getOrLaunch(\n this.viewport,\n );\n this.browserManager.activeBrowser = browser;\n\n const pages = await browser.pages();\n let page: Page;\n\n if (navigateToUrl) {\n page = await browser.newPage();\n if (this.viewport) {\n await this.resizePersistentViewport(page);\n }\n await page.goto(navigateToUrl, {\n timeout: 30000,\n waitUntil: 'domcontentloaded',\n });\n } else {\n const savedTargetId = await this.browserManager.readSavedTargetId();\n const matchedPage = savedTargetId\n ? pages.find((candidate) => getTargetId(candidate) === savedTargetId)\n : undefined;\n const webPages = pages.filter((p) => /^https?:\\/\\//.test(p.url()));\n page =\n matchedPage ??\n (webPages.length > 0\n ? webPages[webPages.length - 1]\n : pages[pages.length - 1] || (await browser.newPage()));\n\n if (reused) {\n await page.bringToFront();\n }\n if (this.viewport) {\n await this.resizePersistentViewport(page);\n }\n }\n\n const targetId = getTargetId(page);\n if (!targetId) {\n throw new Error(\n 'Failed to persist Puppeteer page session because Puppeteer did not expose a Chrome targetId.',\n );\n }\n await this.browserManager.saveTargetId(targetId);\n\n const reportOptions = this.readCliReportAgentOptions();\n this.agent = new PuppeteerAgent(page as unknown as PuppeteerPage, {\n ...(extractAgentBehaviorInitArgs(initArgs) ?? {}),\n ...(reportOptions ?? {}),\n });\n this.lastInitArgsSignature = nextSignature;\n return this.agent;\n }\n\n private async resizePersistentViewport(page: Page): Promise<void> {\n const viewport = this.viewport;\n if (!viewport) return;\n\n // Emulation is scoped to the CDP connection. Resize the actual content area\n // so the requested dimensions also survive CLI disconnect and reconnect.\n await page.setViewport(null);\n const client = await page.createCDPSession();\n try {\n const { windowId, bounds } = await client.send(\n 'Browser.getWindowForTarget',\n );\n // Browser snippets must remain free of Node-side coverage counters.\n const content = (await page.evaluate(\n '({ width: window.innerWidth, height: window.innerHeight })',\n )) as { width: number; height: number };\n if (bounds.width === undefined || bounds.height === undefined) {\n throw new Error('Chrome did not return window dimensions');\n }\n await client.send('Browser.setWindowBounds', {\n windowId,\n bounds: {\n width: bounds.width + viewport.width - content.width,\n height: bounds.height + viewport.height - content.height,\n },\n });\n await page.waitForFunction(\n `window.innerWidth === ${JSON.stringify(viewport.width)} && window.innerHeight === ${JSON.stringify(viewport.height)}`,\n { timeout: 10_000 },\n );\n } finally {\n await client.detach();\n }\n await page.setViewport(viewport);\n }\n\n public async destroy(): Promise<void> {\n await super.destroy();\n this.browserManager.disconnect();\n }\n\n protected preparePlatformTools(): ToolDefinition[] {\n return [\n {\n name: 'web_connect',\n description:\n 'Connect to a web page. Opens a new tab with the given URL, or reuses the current page.',\n schema: this.getAgentInitArgSchema(),\n cli: this.getAgentInitArgCliMetadata(),\n handler: async (args) => {\n const initArgs = this.extractAgentInitParam(args);\n const url = initArgs?.url;\n\n // Explicit connect always starts a fresh page session.\n if (this.agent) {\n try {\n await this.agent.destroy?.();\n } catch {}\n this.agent = undefined;\n this.lastInitArgsSignature = undefined;\n }\n\n const reportSession = this.createNewCliReportSession(\n url ?? 'current-page',\n );\n this.commitCliReportSession(reportSession);\n this.agent = await this.ensureAgent(initArgs);\n\n const screenshot = await this.agent.page?.screenshotBase64();\n const label = url ?? 'current page';\n\n return {\n content: [\n { type: 'text', text: `Connected to: ${label}` },\n ...(screenshot ? this.buildScreenshotContent(screenshot) : []),\n ],\n };\n },\n },\n {\n name: 'web_disconnect',\n description:\n 'Disconnect from current web page. The browser stays running for future calls.',\n schema: {},\n handler: async () => {\n if (this.agent) {\n try {\n await this.agent.destroy?.();\n } catch {}\n this.agent = undefined;\n this.lastInitArgsSignature = undefined;\n }\n this.browserManager.disconnect();\n await this.browserManager.cleanupTargetIdFile();\n return this.buildTextResult(\n 'Disconnected from web page (browser still running)',\n );\n },\n },\n {\n name: 'web_close',\n description: 'Close the browser completely and release all resources.',\n schema: {},\n handler: async () => {\n if (this.agent) {\n try {\n await this.agent.destroy?.();\n } catch {}\n this.agent = undefined;\n this.lastInitArgsSignature = undefined;\n }\n await this.browserManager.closeBrowser();\n return this.buildTextResult('Browser closed');\n },\n },\n ];\n }\n}\n"],"names":["ENDPOINT_FILE","join","tmpdir","USER_DATA_DIR","TARGET_ID_FILE","DETACHED_CHROME_LAUNCH_TIMEOUT_MS","DETACHED_CHROME_ENDPOINT_POLL_INTERVAL_MS","debug","getDebug","PUPPETEER_ENDPOINT_FILE","buildDetachedChromeArgs","options","viewport","defaultPuppeteerWindowViewportSize","terminateDetachedChrome","proc","process","getTargetId","page","waitForDetachedChromeEndpoint","stderrFile","timeoutMs","Promise","resolve","reject","output","settled","exited","pollTimer","cleanup","clearTimeout","timeout","onExit","onError","resolveOnce","value","rejectOnce","error","terminate","code","signal","readFile","latestOutput","Error","pollForEndpoint","match","setTimeout","PuppeteerBrowserManager","content","targetId","writeFile","unlink","endpointFile","existsSync","endpoint","browser","puppeteer","wsEndpoint","chromePath","resolveChromePath","userDataDir","mkdir","args","stderrHandle","open","spawn","endpointPromise","undefined","persistence","defaultBrowserManager","WebPuppeteerMidsceneTools","BaseMidsceneTools","StaticPage","ScreenshotItem","Date","defaultStaticPageViewportSize","initArgs","navigateToUrl","nextSignature","getAgentInitArgsSignature","shouldOpenUrl","shouldRebuildAgentForInitArgs","reused","pages","savedTargetId","matchedPage","candidate","webPages","p","reportOptions","PuppeteerAgent","extractAgentBehaviorInitArgs","client","windowId","bounds","JSON","url","reportSession","screenshot","label","webAgentInitArgShape","adaptWebAgentInitArgs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAMA,gBAAgBC,KAAKC,UAAU;AACrC,MAAMC,gBAAgBF,KAAKC,UAAU;AACrC,MAAME,iBAAiBH,KAAKC,UAAU;AACtC,MAAMG,oCAAoC;AAC1C,MAAMC,4CAA4C;AAClD,MAAMC,QAAQC,SAAS;AAEhB,MAAMC,0BAA0BT;AAYhC,SAASU,wBAAwBC,OAGvC;IACC,MAAMC,WAAWD,QAAQ,QAAQ,IAAIE;IAErC,OAAO;QACL;QACA,CAAC,gBAAgB,EAAEF,QAAQ,WAAW,EAAE;QACxC;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,CAAC,cAAc,EAAEC,SAAS,KAAK,CAAC,CAAC,EAAEA,SAAS,MAAM,EAAE;QACpD;KACD;AACH;AAEA,SAASE,wBAAwBC,IAAkB;IACjD,IAAIA,KAAK,MAAM,IAAIA,AAAkB,SAAlBA,KAAK,QAAQ,IAAaA,AAAoB,SAApBA,KAAK,UAAU,EAC1D;IAGF,IAAIC,AAAqB,YAArBA,QAAQ,QAAQ,IAAgBD,KAAK,GAAG,EAC1C,IAAI;QACFC,QAAQ,IAAI,CAAC,CAACD,KAAK,GAAG,EAAE;QACxB;IACF,EAAE,OAAM,CAAC;IAGX,IAAI;QACFA,KAAK,IAAI,CAAC;IACZ,EAAE,OAAM,CAAC;AACX;AAEA,SAASE,YAAYC,IAAU;IAC7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E,IAAI,CAAC,QAAQ,GAAGzF,WAAW;YAAE,GAAGA,QAAQ;QAAC,IAAIuD;QAC7C,IAAI,CAAC,cAAc,GAAGxD,QAAQ,WAAW,GACrC,IAAIoC,wBAAwBpC,QAAQ,WAAW,IAC/C0D;IACN;AAyNF"}
|
|
@@ -101,7 +101,7 @@ class BridgeServer {
|
|
|
101
101
|
logMsg('one client connected');
|
|
102
102
|
this.socket = socket;
|
|
103
103
|
const clientVersion = socket.handshake.query.version;
|
|
104
|
-
logMsg(`Bridge connected, cli-side version v1.15.5
|
|
104
|
+
logMsg(`Bridge connected, cli-side version v1.15.5, browser-side version v${clientVersion}`);
|
|
105
105
|
socket.on(BridgeEvent.CallResponse, (params)=>{
|
|
106
106
|
const id = params.id;
|
|
107
107
|
const response = params.response;
|
|
@@ -125,7 +125,7 @@ class BridgeServer {
|
|
|
125
125
|
setTimeout(()=>{
|
|
126
126
|
this.onConnect?.();
|
|
127
127
|
const payload = {
|
|
128
|
-
version: "1.15.5
|
|
128
|
+
version: "1.15.5"
|
|
129
129
|
};
|
|
130
130
|
socket.emit(BridgeEvent.Connected, payload);
|
|
131
131
|
Promise.resolve().then(()=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-mode/io-server.mjs","sources":["../../../src/bridge-mode/io-server.ts"],"sourcesContent":["import {\n type IncomingMessage,\n type ServerResponse,\n createServer,\n} from 'node:http';\nimport { sleep } from '@midscene/core/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { logMsg } from '@midscene/shared/utils';\nimport { Server, type Socket as ServerSocket } from 'socket.io';\nimport { io as ClientIO } from 'socket.io-client';\n\nimport {\n type BridgeCall,\n type BridgeCallResponse,\n BridgeCallTimeout,\n type BridgeConnectedEventPayload,\n BridgeErrorCodeNoClientConnected,\n BridgeEvent,\n BridgeSignalKill,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n} from './common';\n\nconst debug = getDebug('web:bridge:io-server');\n\ndeclare const __VERSION__: string;\n\n/**\n * Returns true if the given Origin header value is allowed to connect\n * to the bridge server. Trusted origins are:\n * - No Origin header (local Node.js processes like killRunningServer)\n * - chrome-extension:// origins (the Midscene Chrome extension)\n *\n * Browser pages (https://evil.com, etc.) are rejected to prevent\n * Cross-Site WebSocket Hijacking (CSWSH) attacks.\n */\nfunction isTrustedOrigin(origin: string | undefined): boolean {\n if (!origin) return true;\n if (origin.startsWith('chrome-extension://')) return true;\n return false;\n}\n\nexport const killRunningServer = async (\n port?: number,\n host = DefaultBridgeServerHost,\n) => {\n try {\n const client = ClientIO(`ws://${host}:${port || DefaultBridgeServerPort}`, {\n query: {\n [BridgeSignalKill]: 1,\n },\n });\n await sleep(300);\n await client.close();\n } catch (e) {\n debug('failed to kill port: %O', e);\n }\n};\n\n// ws server, this is where the request is sent\nexport class BridgeServer {\n private callId = 0;\n private io: Server | null = null;\n private socket: ServerSocket | null = null;\n private listeningTimeoutId: NodeJS.Timeout | null = null;\n private listeningTimerFlag = false;\n private connectionTipTimer: NodeJS.Timeout | null = null;\n public calls: Record<string, BridgeCall> = {};\n\n private connectionLost = false;\n private connectionLostReason = '';\n\n constructor(\n public host: string,\n public port: number,\n public onConnect?: () => void,\n public onDisconnect?: (reason: string) => void,\n public closeConflictServer?: boolean,\n ) {}\n\n async listen(\n opts: {\n timeout?: number | false;\n } = {},\n ): Promise<void> {\n const { timeout = 30000 } = opts;\n\n if (this.closeConflictServer) {\n await killRunningServer(this.port, this.host);\n }\n\n return new Promise((resolve, reject) => {\n if (this.listeningTimerFlag) {\n return reject(new Error('already listening'));\n }\n this.listeningTimerFlag = true;\n\n this.listeningTimeoutId = timeout\n ? setTimeout(() => {\n reject(\n new Error(\n `no extension connected after ${timeout}ms (${BridgeErrorCodeNoClientConnected})`,\n ),\n );\n }, timeout)\n : null;\n\n this.connectionTipTimer =\n !timeout || timeout > 3000\n ? setTimeout(() => {\n logMsg('waiting for bridge to connect...');\n }, 2000)\n : null;\n\n // Create HTTP server — no /bridge-auth endpoint needed since we use\n // pure Origin checking in the Socket.IO middleware below.\n const httpServer = createServer(\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(404);\n res.end();\n },\n );\n\n // Set up HTTP server event listeners FIRST\n httpServer.once('listening', () => {\n resolve();\n });\n\n httpServer.once('error', (err: Error) => {\n reject(new Error(`Bridge Listening Error: ${err.message}`));\n });\n\n // Always honor the configured interface, including the loopback default.\n httpServer.listen(this.port, this.host);\n\n // Now create Socket.IO Server attached to the already-listening HTTP server\n this.io = new Server(httpServer, {\n maxHttpBufferSize: 100 * 1024 * 1024, // 100MB\n // Increase pingTimeout to tolerate Chrome MV3 Service Worker suspension.\n // The SW keepalive alarm fires every ~24s; default pingTimeout (20s) may\n // be too short if the SW is suspended between alarm pings.\n pingTimeout: 60000,\n });\n\n this.io.use((socket, next) => {\n // Reject connections from untrusted browser origins to prevent\n // Cross-Site WebSocket Hijacking (CSWSH) and unauthorized kill signals.\n // The browser automatically sets the Origin header on WebSocket\n // handshakes, and JavaScript cannot override it.\n const origin = socket.handshake.headers.origin;\n if (!isTrustedOrigin(origin)) {\n debug('connection rejected: untrusted origin=%s', origin);\n return next(new Error('origin not allowed'));\n }\n\n // Allow new connections to replace old ones (reconnection after\n // extension Stop→Start). If the old socket is already disconnected\n // or unresponsive, accept the new connection immediately.\n if (\n socket.handshake.url.includes(BridgeSignalKill) === false &&\n this.socket?.connected\n ) {\n return next(new Error('server already connected by another client'));\n }\n next();\n });\n\n this.io.on('connection', (socket) => {\n // check the connection url\n const url = socket.handshake.url;\n if (url.includes(BridgeSignalKill)) {\n console.warn('kill signal received, closing bridge server');\n return this.close();\n }\n\n this.connectionLost = false;\n this.connectionLostReason = '';\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.listeningTimeoutId = null;\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n this.connectionTipTimer = null;\n if (this.socket?.connected) {\n socket.emit(BridgeEvent.Refused);\n socket.disconnect();\n logMsg(\n 'refused new connection: server already connected by another client',\n );\n return;\n }\n\n // Clean up stale old socket if it exists but is no longer connected\n if (this.socket) {\n try {\n this.socket.disconnect();\n } catch (e) {\n logMsg(`failed to disconnect stale socket: ${e}`);\n }\n this.socket = null;\n }\n\n try {\n logMsg('one client connected');\n this.socket = socket;\n\n const clientVersion = socket.handshake.query.version;\n logMsg(\n `Bridge connected, cli-side version v${__VERSION__}, browser-side version v${clientVersion}`,\n );\n\n socket.on(BridgeEvent.CallResponse, (params: BridgeCallResponse) => {\n const id = params.id;\n const response = params.response;\n const error = params.error;\n\n this.triggerCallResponseCallback(id, error, response);\n });\n\n socket.on('disconnect', (reason: string) => {\n this.connectionLost = true;\n this.connectionLostReason = reason;\n this.socket = null;\n\n // flush all pending calls as error and clean up completed calls\n for (const id in this.calls) {\n const call = this.calls[id];\n\n if (!call.responseTime) {\n const errorMessage = this.connectionLostErrorMsg();\n this.triggerCallResponseCallback(\n id,\n new Error(errorMessage),\n null,\n );\n }\n }\n\n // Clean up completed calls to prevent memory leaks in long-running sessions\n for (const id in this.calls) {\n if (this.calls[id].responseTime) {\n delete this.calls[id];\n }\n }\n\n this.onDisconnect?.(reason);\n });\n\n setTimeout(() => {\n this.onConnect?.();\n\n const payload = {\n version: __VERSION__,\n } as BridgeConnectedEventPayload;\n socket.emit(BridgeEvent.Connected, payload);\n Promise.resolve().then(() => {\n for (const id in this.calls) {\n if (this.calls[id].callTime === 0) {\n this.emitCall(id);\n }\n }\n });\n }, 0);\n } catch (e) {\n logMsg(`failed to handle connection event: ${e}`);\n }\n });\n\n this.io.on('close', () => {\n this.close();\n });\n });\n }\n\n private connectionLostErrorMsg = () => {\n return `Connection lost, reason: ${this.connectionLostReason}`;\n };\n\n private async triggerCallResponseCallback(\n id: string | number,\n error: Error | string | null,\n response: any,\n ) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n // Ensure error is always an Error object (bridge client may send strings)\n if (error) {\n call.error =\n error instanceof Error\n ? error\n : new Error(typeof error === 'string' ? error : String(error));\n } else {\n call.error = undefined;\n }\n call.response = response;\n call.responseTime = Date.now();\n\n call.callback(call.error, response);\n }\n\n private async emitCall(id: string) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n\n if (this.connectionLost) {\n const message = `Connection lost, reason: ${this.connectionLostReason}`;\n call.callback(new Error(message), null);\n return;\n }\n\n if (this.socket) {\n this.socket.emit(BridgeEvent.Call, {\n id,\n method: call.method,\n args: call.args,\n });\n call.callTime = Date.now();\n }\n }\n\n async call<T = any>(\n method: string,\n args: any[],\n timeout = BridgeCallTimeout,\n ): Promise<T> {\n const id = `${this.callId++}`;\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n logMsg(`bridge call timeout, id=${id}, method=${method}, args=`, args);\n this.calls[id].error = new Error(\n `Bridge call timeout after ${timeout}ms: ${method}`,\n );\n reject(this.calls[id].error);\n }, timeout);\n\n this.calls[id] = {\n method,\n args,\n response: null,\n callTime: 0,\n responseTime: 0,\n callback: (error: Error | undefined, response: any) => {\n clearTimeout(timeoutId);\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n },\n };\n\n this.emitCall(id);\n });\n }\n\n // do NOT restart after close\n async close() {\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n const closeProcess = this.io?.close();\n this.io = null;\n\n return closeProcess;\n }\n}\n"],"names":["debug","getDebug","isTrustedOrigin","origin","killRunningServer","port","host","DefaultBridgeServerHost","client","ClientIO","DefaultBridgeServerPort","BridgeSignalKill","sleep","e","BridgeServer","opts","timeout","Promise","resolve","reject","Error","setTimeout","BridgeErrorCodeNoClientConnected","logMsg","httpServer","createServer","_req","res","err","Server","socket","next","url","console","clearTimeout","BridgeEvent","clientVersion","params","id","response","error","reason","call","errorMessage","payload","__VERSION__","String","undefined","Date","message","method","args","BridgeCallTimeout","timeoutId","closeProcess","onConnect","onDisconnect","closeConflictServer"],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R;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAQ,sBAAR;QACA,uBAAO,SAAP;QAEA,uBAAQ,kBAAR;QACA,uBAAQ,wBAAR;QA0MA,uBAAQ,0BAAR;aAvMSnD,IAAI,GAAJA;aACAD,IAAI,GAAJA;aACAkD,SAAS,GAATA;aACAC,YAAY,GAAZA;aACAC,mBAAmB,GAAnBA;aAhBD,MAAM,GAAG;aACT,EAAE,GAAkB;aACpB,MAAM,GAAwB;aAC9B,kBAAkB,GAA0B;aAC5C,kBAAkB,GAAG;aACrB,kBAAkB,GAA0B;aAC7C,KAAK,GAA+B,CAAC;aAEpC,cAAc,GAAG;aACjB,oBAAoB,GAAG;aA0MvB,sBAAsB,GAAG,IACxB,CAAC,yBAAyB,EAAE,IAAI,CAAC,oBAAoB,EAAE;IAnM7D;AAiSL"}
|
|
1
|
+
{"version":3,"file":"bridge-mode/io-server.mjs","sources":["../../../src/bridge-mode/io-server.ts"],"sourcesContent":["import {\n type IncomingMessage,\n type ServerResponse,\n createServer,\n} from 'node:http';\nimport { sleep } from '@midscene/core/utils';\nimport { getDebug } from '@midscene/shared/logger';\nimport { logMsg } from '@midscene/shared/utils';\nimport { Server, type Socket as ServerSocket } from 'socket.io';\nimport { io as ClientIO } from 'socket.io-client';\n\nimport {\n type BridgeCall,\n type BridgeCallResponse,\n BridgeCallTimeout,\n type BridgeConnectedEventPayload,\n BridgeErrorCodeNoClientConnected,\n BridgeEvent,\n BridgeSignalKill,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n} from './common';\n\nconst debug = getDebug('web:bridge:io-server');\n\ndeclare const __VERSION__: string;\n\n/**\n * Returns true if the given Origin header value is allowed to connect\n * to the bridge server. Trusted origins are:\n * - No Origin header (local Node.js processes like killRunningServer)\n * - chrome-extension:// origins (the Midscene Chrome extension)\n *\n * Browser pages (https://evil.com, etc.) are rejected to prevent\n * Cross-Site WebSocket Hijacking (CSWSH) attacks.\n */\nfunction isTrustedOrigin(origin: string | undefined): boolean {\n if (!origin) return true;\n if (origin.startsWith('chrome-extension://')) return true;\n return false;\n}\n\nexport const killRunningServer = async (\n port?: number,\n host = DefaultBridgeServerHost,\n) => {\n try {\n const client = ClientIO(`ws://${host}:${port || DefaultBridgeServerPort}`, {\n query: {\n [BridgeSignalKill]: 1,\n },\n });\n await sleep(300);\n await client.close();\n } catch (e) {\n debug('failed to kill port: %O', e);\n }\n};\n\n// ws server, this is where the request is sent\nexport class BridgeServer {\n private callId = 0;\n private io: Server | null = null;\n private socket: ServerSocket | null = null;\n private listeningTimeoutId: NodeJS.Timeout | null = null;\n private listeningTimerFlag = false;\n private connectionTipTimer: NodeJS.Timeout | null = null;\n public calls: Record<string, BridgeCall> = {};\n\n private connectionLost = false;\n private connectionLostReason = '';\n\n constructor(\n public host: string,\n public port: number,\n public onConnect?: () => void,\n public onDisconnect?: (reason: string) => void,\n public closeConflictServer?: boolean,\n ) {}\n\n async listen(\n opts: {\n timeout?: number | false;\n } = {},\n ): Promise<void> {\n const { timeout = 30000 } = opts;\n\n if (this.closeConflictServer) {\n await killRunningServer(this.port, this.host);\n }\n\n return new Promise((resolve, reject) => {\n if (this.listeningTimerFlag) {\n return reject(new Error('already listening'));\n }\n this.listeningTimerFlag = true;\n\n this.listeningTimeoutId = timeout\n ? setTimeout(() => {\n reject(\n new Error(\n `no extension connected after ${timeout}ms (${BridgeErrorCodeNoClientConnected})`,\n ),\n );\n }, timeout)\n : null;\n\n this.connectionTipTimer =\n !timeout || timeout > 3000\n ? setTimeout(() => {\n logMsg('waiting for bridge to connect...');\n }, 2000)\n : null;\n\n // Create HTTP server — no /bridge-auth endpoint needed since we use\n // pure Origin checking in the Socket.IO middleware below.\n const httpServer = createServer(\n (_req: IncomingMessage, res: ServerResponse) => {\n res.writeHead(404);\n res.end();\n },\n );\n\n // Set up HTTP server event listeners FIRST\n httpServer.once('listening', () => {\n resolve();\n });\n\n httpServer.once('error', (err: Error) => {\n reject(new Error(`Bridge Listening Error: ${err.message}`));\n });\n\n // Always honor the configured interface, including the loopback default.\n httpServer.listen(this.port, this.host);\n\n // Now create Socket.IO Server attached to the already-listening HTTP server\n this.io = new Server(httpServer, {\n maxHttpBufferSize: 100 * 1024 * 1024, // 100MB\n // Increase pingTimeout to tolerate Chrome MV3 Service Worker suspension.\n // The SW keepalive alarm fires every ~24s; default pingTimeout (20s) may\n // be too short if the SW is suspended between alarm pings.\n pingTimeout: 60000,\n });\n\n this.io.use((socket, next) => {\n // Reject connections from untrusted browser origins to prevent\n // Cross-Site WebSocket Hijacking (CSWSH) and unauthorized kill signals.\n // The browser automatically sets the Origin header on WebSocket\n // handshakes, and JavaScript cannot override it.\n const origin = socket.handshake.headers.origin;\n if (!isTrustedOrigin(origin)) {\n debug('connection rejected: untrusted origin=%s', origin);\n return next(new Error('origin not allowed'));\n }\n\n // Allow new connections to replace old ones (reconnection after\n // extension Stop→Start). If the old socket is already disconnected\n // or unresponsive, accept the new connection immediately.\n if (\n socket.handshake.url.includes(BridgeSignalKill) === false &&\n this.socket?.connected\n ) {\n return next(new Error('server already connected by another client'));\n }\n next();\n });\n\n this.io.on('connection', (socket) => {\n // check the connection url\n const url = socket.handshake.url;\n if (url.includes(BridgeSignalKill)) {\n console.warn('kill signal received, closing bridge server');\n return this.close();\n }\n\n this.connectionLost = false;\n this.connectionLostReason = '';\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.listeningTimeoutId = null;\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n this.connectionTipTimer = null;\n if (this.socket?.connected) {\n socket.emit(BridgeEvent.Refused);\n socket.disconnect();\n logMsg(\n 'refused new connection: server already connected by another client',\n );\n return;\n }\n\n // Clean up stale old socket if it exists but is no longer connected\n if (this.socket) {\n try {\n this.socket.disconnect();\n } catch (e) {\n logMsg(`failed to disconnect stale socket: ${e}`);\n }\n this.socket = null;\n }\n\n try {\n logMsg('one client connected');\n this.socket = socket;\n\n const clientVersion = socket.handshake.query.version;\n logMsg(\n `Bridge connected, cli-side version v${__VERSION__}, browser-side version v${clientVersion}`,\n );\n\n socket.on(BridgeEvent.CallResponse, (params: BridgeCallResponse) => {\n const id = params.id;\n const response = params.response;\n const error = params.error;\n\n this.triggerCallResponseCallback(id, error, response);\n });\n\n socket.on('disconnect', (reason: string) => {\n this.connectionLost = true;\n this.connectionLostReason = reason;\n this.socket = null;\n\n // flush all pending calls as error and clean up completed calls\n for (const id in this.calls) {\n const call = this.calls[id];\n\n if (!call.responseTime) {\n const errorMessage = this.connectionLostErrorMsg();\n this.triggerCallResponseCallback(\n id,\n new Error(errorMessage),\n null,\n );\n }\n }\n\n // Clean up completed calls to prevent memory leaks in long-running sessions\n for (const id in this.calls) {\n if (this.calls[id].responseTime) {\n delete this.calls[id];\n }\n }\n\n this.onDisconnect?.(reason);\n });\n\n setTimeout(() => {\n this.onConnect?.();\n\n const payload = {\n version: __VERSION__,\n } as BridgeConnectedEventPayload;\n socket.emit(BridgeEvent.Connected, payload);\n Promise.resolve().then(() => {\n for (const id in this.calls) {\n if (this.calls[id].callTime === 0) {\n this.emitCall(id);\n }\n }\n });\n }, 0);\n } catch (e) {\n logMsg(`failed to handle connection event: ${e}`);\n }\n });\n\n this.io.on('close', () => {\n this.close();\n });\n });\n }\n\n private connectionLostErrorMsg = () => {\n return `Connection lost, reason: ${this.connectionLostReason}`;\n };\n\n private async triggerCallResponseCallback(\n id: string | number,\n error: Error | string | null,\n response: any,\n ) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n // Ensure error is always an Error object (bridge client may send strings)\n if (error) {\n call.error =\n error instanceof Error\n ? error\n : new Error(typeof error === 'string' ? error : String(error));\n } else {\n call.error = undefined;\n }\n call.response = response;\n call.responseTime = Date.now();\n\n call.callback(call.error, response);\n }\n\n private async emitCall(id: string) {\n const call = this.calls[id];\n if (!call) {\n throw new Error(`call ${id} not found`);\n }\n\n if (this.connectionLost) {\n const message = `Connection lost, reason: ${this.connectionLostReason}`;\n call.callback(new Error(message), null);\n return;\n }\n\n if (this.socket) {\n this.socket.emit(BridgeEvent.Call, {\n id,\n method: call.method,\n args: call.args,\n });\n call.callTime = Date.now();\n }\n }\n\n async call<T = any>(\n method: string,\n args: any[],\n timeout = BridgeCallTimeout,\n ): Promise<T> {\n const id = `${this.callId++}`;\n\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n logMsg(`bridge call timeout, id=${id}, method=${method}, args=`, args);\n this.calls[id].error = new Error(\n `Bridge call timeout after ${timeout}ms: ${method}`,\n );\n reject(this.calls[id].error);\n }, timeout);\n\n this.calls[id] = {\n method,\n args,\n response: null,\n callTime: 0,\n responseTime: 0,\n callback: (error: Error | undefined, response: any) => {\n clearTimeout(timeoutId);\n if (error) {\n reject(error);\n } else {\n resolve(response);\n }\n },\n };\n\n this.emitCall(id);\n });\n }\n\n // do NOT restart after close\n async close() {\n this.listeningTimeoutId && clearTimeout(this.listeningTimeoutId);\n this.connectionTipTimer && clearTimeout(this.connectionTipTimer);\n const closeProcess = this.io?.close();\n this.io = null;\n\n return closeProcess;\n }\n}\n"],"names":["debug","getDebug","isTrustedOrigin","origin","killRunningServer","port","host","DefaultBridgeServerHost","client","ClientIO","DefaultBridgeServerPort","BridgeSignalKill","sleep","e","BridgeServer","opts","timeout","Promise","resolve","reject","Error","setTimeout","BridgeErrorCodeNoClientConnected","logMsg","httpServer","createServer","_req","res","err","Server","socket","next","url","console","clearTimeout","BridgeEvent","clientVersion","params","id","response","error","reason","call","errorMessage","payload","__VERSION__","String","undefined","Date","message","method","args","BridgeCallTimeout","timeoutId","closeProcess","onConnect","onDisconnect","closeConflictServer"],"mappings":";;;;;;;;;;;;;;;;;AAuBA,MAAMA,QAAQC,SAAS;AAavB,SAASC,gBAAgBC,MAA0B;IACjD,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAIA,OAAO,UAAU,CAAC,wBAAwB,OAAO;IACrD,OAAO;AACT;AAEO,MAAMC,oBAAoB,OAC/BC,MACAC,OA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AAY,GAAZA;aACAC,mBAAmB,GAAnBA;aAhBD,MAAM,GAAG;aACT,EAAE,GAAkB;aACpB,MAAM,GAAwB;aAC9B,kBAAkB,GAA0B;aAC5C,kBAAkB,GAAG;aACrB,kBAAkB,GAA0B;aAC7C,KAAK,GAA+B,CAAC;aAEpC,cAAc,GAAG;aACjB,oBAAoB,GAAG;aA0MvB,sBAAsB,GAAG,IACxB,CAAC,yBAAyB,EAAE,IAAI,CAAC,oBAAoB,EAAE;IAnM7D;AAiSL"}
|
|
@@ -100,7 +100,7 @@ class ExtensionBridgePageBrowserSide extends page {
|
|
|
100
100
|
throw new Error('Connection denied by user');
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
-
this.onLogMessage(`Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v1.15.5
|
|
103
|
+
this.onLogMessage(`Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v1.15.5`, 'log');
|
|
104
104
|
}
|
|
105
105
|
async connect() {
|
|
106
106
|
return await this.setupBridgeClient();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-mode/page-browser-side.mjs","sources":["../../../src/bridge-mode/page-browser-side.ts"],"sourcesContent":["import { assert } from '@midscene/shared/utils';\nimport ChromeExtensionProxyPage from '../chrome-extension/page';\nimport type {\n ChromePageDestroyOptions,\n KeyboardAction,\n MouseAction,\n} from '../web-page';\nimport {\n type BridgeConnectTabOptions,\n BridgeEvent,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n KeyboardEvent,\n MouseEvent,\n} from './common';\nimport { BridgeClient } from './io-client';\n\ndeclare const __VERSION__: string;\n\nconst NEW_TAB_LOAD_TIMEOUT_MS = 30_000;\n\nfunction isBlankUrl(url: string | undefined): boolean {\n if (!url) return true;\n return url === 'about:blank' || url.startsWith('chrome://newtab');\n}\n\n// Wait until the freshly created tab has navigated away from about:blank\n// and reached `status === 'complete'`. Resolves on timeout instead of\n// throwing so callers degrade to the existing lazy-attach behavior.\nfunction waitForTabNavigationComplete(\n tabId: number,\n targetUrl: string,\n timeoutMs = NEW_TAB_LOAD_TIMEOUT_MS,\n): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n try {\n chrome.tabs.onUpdated.removeListener(onUpdated);\n } catch {}\n clearTimeout(timer);\n resolve();\n };\n\n const isReady = (tab: chrome.tabs.Tab | undefined): boolean => {\n if (!tab) return false;\n if (tab.status !== 'complete') return false;\n const currentUrl = tab.url || tab.pendingUrl || '';\n // Skip the initial about:blank \"complete\" that fires before\n // the target URL navigation kicks in.\n if (isBlankUrl(currentUrl) && !isBlankUrl(targetUrl)) return false;\n return true;\n };\n\n const onUpdated = (\n id: number,\n _info: chrome.tabs.TabChangeInfo,\n tab: chrome.tabs.Tab,\n ) => {\n if (id !== tabId) return;\n if (isReady(tab)) finish();\n };\n\n chrome.tabs.onUpdated.addListener(onUpdated);\n const timer = setTimeout(finish, timeoutMs);\n\n // Handle the race where the tab already finished loading before\n // we registered the listener.\n chrome.tabs\n .get(tabId)\n .then((tab) => {\n if (isReady(tab)) finish();\n })\n .catch(() => {});\n });\n}\n\nexport class ExtensionBridgePageBrowserSide extends ChromeExtensionProxyPage {\n public bridgeClient: BridgeClient | null = null;\n\n private destroyOptions?: ChromePageDestroyOptions;\n\n private newlyCreatedTabIds: number[] = [];\n\n // Connection confirmation state\n private confirmationPromise: Promise<boolean> | null = null;\n\n constructor(\n public serverEndpoint?: string,\n public onDisconnect: () => void = () => {},\n public onLogMessage: (\n message: string,\n type: 'log' | 'status',\n ) => void = () => {},\n forceSameTabNavigation = true,\n public onConnectionRequest?: () => Promise<boolean>,\n ) {\n super(forceSameTabNavigation);\n }\n\n private async setupBridgeClient() {\n const endpoint =\n this.serverEndpoint ||\n `ws://${DefaultBridgeServerHost}:${DefaultBridgeServerPort}`;\n\n // Create confirmation gate BEFORE establishing connection,\n // so that any calls received immediately after connection are blocked\n // until user confirms. This prevents a race condition where server-side\n // queued calls bypass the confirmation dialog.\n let resolveConfirmationGate: (allowed: boolean) => void = () => {};\n if (this.onConnectionRequest) {\n this.confirmationPromise = new Promise<boolean>((resolve) => {\n resolveConfirmationGate = resolve;\n });\n }\n\n this.bridgeClient = new BridgeClient(\n endpoint,\n async (method, args: any[]) => {\n // Wait for user confirmation before processing any commands\n if (this.confirmationPromise) {\n const allowed = await this.confirmationPromise;\n if (!allowed) {\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(`bridge call from cli side: ${method}`, 'log');\n if (method === BridgeEvent.ConnectNewTabWithUrl) {\n return this.connectNewTabWithUrl.apply(\n this,\n args as unknown as [string],\n );\n }\n\n if (method === BridgeEvent.GetBrowserTabList) {\n return this.getBrowserTabList.apply(this, args as any);\n }\n\n if (method === BridgeEvent.SetActiveTabId) {\n return this.setActiveTabId.apply(this, args as any);\n }\n\n if (method === BridgeEvent.ConnectCurrentTab) {\n return this.connectCurrentTab.apply(this, args as any);\n }\n\n if (method === BridgeEvent.UpdateAgentStatus) {\n return this.onLogMessage(args[0] as string, 'status');\n }\n\n const tabId = await this.getActiveTabId();\n if (!tabId || tabId === 0) {\n throw new Error('no tab is connected');\n }\n\n // this.onLogMessage(`calling method: ${method}`);\n\n if (method.startsWith(MouseEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof MouseAction;\n if (actionName === 'drag') {\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n\n if (method.startsWith(KeyboardEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof KeyboardAction;\n if (actionName === 'press') {\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n\n // Generic method lookup. Methods like `setWaterFlowAnimationEnabled`\n // and `getWaterFlowAnimationEnabled` are inherited from\n // ChromeExtensionProxyPage and found via `this[method]`.\n if (!this[method as keyof ChromeExtensionProxyPage]) {\n this.onLogMessage(`method not found: ${method}`, 'log');\n return undefined;\n }\n\n try {\n // @ts-expect-error\n const result = await this[method as keyof ChromeExtensionProxyPage](\n ...args,\n );\n return result;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : 'Unknown error';\n this.onLogMessage(\n `Error calling method: ${method}, ${errorMessage}`,\n 'log',\n );\n throw new Error(errorMessage, { cause: e });\n }\n },\n // on disconnect\n () => {\n return this.destroy();\n },\n );\n await this.bridgeClient.connect();\n\n // Show confirmation dialog after connection is established\n if (this.onConnectionRequest) {\n this.onLogMessage('Waiting for user confirmation...', 'log');\n const allowed = await this.onConnectionRequest();\n resolveConfirmationGate(allowed);\n this.confirmationPromise = null;\n\n if (!allowed) {\n this.onLogMessage('Connection denied by user', 'log');\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(\n `Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v${__VERSION__}`,\n 'log',\n );\n }\n\n public async connect() {\n return await this.setupBridgeClient();\n }\n\n public async connectNewTabWithUrl(\n url: string,\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n // Otherwise the animation gets injected during the connection flow\n // before the CLI side's setWaterFlowAnimationEnabled(false) arrives.\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n // Preserve the historical default: activate the new tab unless the caller opts into background mode.\n const activate = options.activateTab ?? true;\n const tab = await chrome.tabs.create({ url, active: activate });\n const tabId = tab.id;\n assert(tabId, 'failed to get tabId after creating a new tab');\n\n // new tab\n this.onLogMessage(`Creating new tab: ${url}`, 'log');\n this.newlyCreatedTabIds.push(tabId);\n\n if (options?.forceSameTabNavigation) {\n this.forceSameTabNavigation = true;\n }\n\n // chrome.tabs.create returns immediately with an about:blank target,\n // then navigates to `url`. If we attach the debugger during that\n // cross-origin transition Site Isolation will detach it again, leaving\n // the first CDP command to fail with \"Debugger is not attached to the\n // tab\". Wait for navigation to settle so the lazy attach lands on a\n // stable target.\n await waitForTabNavigationComplete(tabId, url);\n\n await this.setActiveTabId(tabId, { activate });\n }\n\n public async connectCurrentTab(\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n const tabs = await chrome.tabs.query({ active: true, currentWindow: true });\n const tabId = tabs[0]?.id;\n assert(tabId, 'failed to get tabId');\n\n this.onLogMessage(`Connected to current tab: ${tabs[0]?.url}`, 'log');\n\n if (options?.forceSameTabNavigation) {\n this.forceSameTabNavigation = true;\n }\n\n await this.setActiveTabId(tabId);\n }\n\n public async setDestroyOptions(options: ChromePageDestroyOptions) {\n this.destroyOptions = options;\n }\n\n async destroy() {\n if (this.destroyOptions?.closeTab && this.newlyCreatedTabIds.length > 0) {\n this.onLogMessage('Closing all newly created tabs by bridge...', 'log');\n for (const tabId of this.newlyCreatedTabIds) {\n await chrome.tabs.remove(tabId);\n }\n this.newlyCreatedTabIds = [];\n }\n\n await super.destroy();\n\n if (this.bridgeClient) {\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n this.onDisconnect();\n }\n }\n}\n"],"names":["NEW_TAB_LOAD_TIMEOUT_MS","isBlankUrl","url","waitForTabNavigationComplete","tabId","targetUrl","timeoutMs","Promise","resolve","settled","finish","chrome","onUpdated","clearTimeout","timer","isReady","tab","currentUrl","id","_info","setTimeout","ExtensionBridgePageBrowserSide","ChromeExtensionProxyPage","endpoint","DefaultBridgeServerHost","DefaultBridgeServerPort","resolveConfirmationGate","BridgeClient","method","args","allowed","Error","BridgeEvent","MouseEvent","actionName","KeyboardEvent","result","e","errorMessage","options","undefined","activate","assert","tabs","serverEndpoint","onDisconnect","onLogMessage","forceSameTabNavigation","onConnectionRequest"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAMA,0BAA0B;AAEhC,SAASC,WAAWC,GAAuB;IACzC,IAAI,CAACA,KAAK,OAAO;IACjB,OAAOA,AAAQ,kBAARA,OAAyBA,IAAI,UAAU,CAAC;AACjD;AAKA,SAASC,6BACPC,KAAa,EACbC,SAAiB,EACjBC,YAAYN,uBAAuB;IAEnC,OAAO,IAAIO,QAAQ,CAACC;QAClB,IAAIC,UAAU;QACd,MAAMC,SAAS;YACb,IAAID,SAAS;YACbA,UAAU;YACV,IAAI;gBACFE,OAAO,IAAI,CAAC,SAAS,CAAC,cAAc,CAACC;YACvC,EAAE,OAAM,CAAC;YACTC,aAAaC;YACbN;QACF;QAEA,MAAMO,UAAU,CAACC;YACf,IAAI,CAACA,KAAK,OAAO;YACjB,IAAIA,AAAe,eAAfA,IAAI,MAAM,EAAiB,OAAO;YACtC,MAAMC,aAAaD,IAAI,GAAG,IAAIA,IAAI,UAAU,IAAI;YAGhD,IAAIf,WAAWgB,eAAe,CAAChB,WAAWI,YAAY,OAAO;YAC7D,OAAO;QACT;QAEA,MAAMO,YAAY,CAChBM,IACAC,OACAH;YAEA,IAAIE,OAAOd,OAAO;YAClB,IAAIW,QAAQC,MAAMN;QACpB;QAEAC,OAAO,IAAI,CAAC,SAAS,CAAC,WAAW,CAACC;QAClC,MAAME,QAAQM,WAAWV,QAAQJ;QAIjCK,OAAO,IAAI,CACR,GAAG,CAACP,OACJ,IAAI,CAAC,CAACY;YACL,IAAID,QAAQC,MAAMN;QACpB,GACC,KAAK,CAAC,KAAO;IAClB;AACF;AAEO,MAAMW,uCAAuCC;IAuBlD,MAAc,oBAAoB;QAChC,MAAMC,WACJ,IAAI,CAAC,cAAc,IACnB,CAAC,KAAK,EAAEC,wBAAwB,CAAC,EAAEC,yBAAyB;QAM9D,IAAIC,0BAAsD,KAAO;QACjE,IAAI,IAA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MAAMnC,SAAS,IAAI,CAAC,kBAAkB,CACzC,MAAMO,OAAO,IAAI,CAAC,MAAM,CAACP;YAE3B,IAAI,CAAC,kBAAkB,GAAG,EAAE;QAC9B;QAEA,MAAM,KAAK,CAAC;QAEZ,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,IAAI,CAAC,YAAY,CAAC,UAAU;YAC5B,IAAI,CAAC,YAAY,GAAG;YACpB,IAAI,CAAC,YAAY;QACnB;IACF;IAjOA,YACSwC,cAAuB,EACvBC,eAA2B,KAAO,CAAC,EACnCC,eAGK,KAAO,CAAC,EACpBC,yBAAyB,IAAI,EACtBC,mBAA4C,CACnD;QACA,KAAK,CAACD,yBAAAA,iBAAAA,IAAAA,EAAAA,kBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,gBAAAA,KAAAA,IAAAA,iBAAAA,IAAAA,EAAAA,uBAAAA,KAAAA,IAnBR,uBAAO,gBAAP,SAEA,uBAAQ,kBAAR,SAEA,uBAAQ,sBAAR,SAGA,uBAAQ,uBAAR,cAGSH,cAAc,GAAdA,gBAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CACAC,YAAY,GAAZA,cAAAA,IAAAA,CAKAE,mBAAmB,GAAnBA,qBAAAA,IAAAA,CAjBF,YAAY,GAAwB,WAInC,kBAAkB,GAAa,EAAE,OAGjC,mBAAmB,GAA4B;IAavD;AAuNF"}
|
|
1
|
+
{"version":3,"file":"bridge-mode/page-browser-side.mjs","sources":["../../../src/bridge-mode/page-browser-side.ts"],"sourcesContent":["import { assert } from '@midscene/shared/utils';\nimport ChromeExtensionProxyPage from '../chrome-extension/page';\nimport type {\n ChromePageDestroyOptions,\n KeyboardAction,\n MouseAction,\n} from '../web-page';\nimport {\n type BridgeConnectTabOptions,\n BridgeEvent,\n DefaultBridgeServerHost,\n DefaultBridgeServerPort,\n KeyboardEvent,\n MouseEvent,\n} from './common';\nimport { BridgeClient } from './io-client';\n\ndeclare const __VERSION__: string;\n\nconst NEW_TAB_LOAD_TIMEOUT_MS = 30_000;\n\nfunction isBlankUrl(url: string | undefined): boolean {\n if (!url) return true;\n return url === 'about:blank' || url.startsWith('chrome://newtab');\n}\n\n// Wait until the freshly created tab has navigated away from about:blank\n// and reached `status === 'complete'`. Resolves on timeout instead of\n// throwing so callers degrade to the existing lazy-attach behavior.\nfunction waitForTabNavigationComplete(\n tabId: number,\n targetUrl: string,\n timeoutMs = NEW_TAB_LOAD_TIMEOUT_MS,\n): Promise<void> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) return;\n settled = true;\n try {\n chrome.tabs.onUpdated.removeListener(onUpdated);\n } catch {}\n clearTimeout(timer);\n resolve();\n };\n\n const isReady = (tab: chrome.tabs.Tab | undefined): boolean => {\n if (!tab) return false;\n if (tab.status !== 'complete') return false;\n const currentUrl = tab.url || tab.pendingUrl || '';\n // Skip the initial about:blank \"complete\" that fires before\n // the target URL navigation kicks in.\n if (isBlankUrl(currentUrl) && !isBlankUrl(targetUrl)) return false;\n return true;\n };\n\n const onUpdated = (\n id: number,\n _info: chrome.tabs.TabChangeInfo,\n tab: chrome.tabs.Tab,\n ) => {\n if (id !== tabId) return;\n if (isReady(tab)) finish();\n };\n\n chrome.tabs.onUpdated.addListener(onUpdated);\n const timer = setTimeout(finish, timeoutMs);\n\n // Handle the race where the tab already finished loading before\n // we registered the listener.\n chrome.tabs\n .get(tabId)\n .then((tab) => {\n if (isReady(tab)) finish();\n })\n .catch(() => {});\n });\n}\n\nexport class ExtensionBridgePageBrowserSide extends ChromeExtensionProxyPage {\n public bridgeClient: BridgeClient | null = null;\n\n private destroyOptions?: ChromePageDestroyOptions;\n\n private newlyCreatedTabIds: number[] = [];\n\n // Connection confirmation state\n private confirmationPromise: Promise<boolean> | null = null;\n\n constructor(\n public serverEndpoint?: string,\n public onDisconnect: () => void = () => {},\n public onLogMessage: (\n message: string,\n type: 'log' | 'status',\n ) => void = () => {},\n forceSameTabNavigation = true,\n public onConnectionRequest?: () => Promise<boolean>,\n ) {\n super(forceSameTabNavigation);\n }\n\n private async setupBridgeClient() {\n const endpoint =\n this.serverEndpoint ||\n `ws://${DefaultBridgeServerHost}:${DefaultBridgeServerPort}`;\n\n // Create confirmation gate BEFORE establishing connection,\n // so that any calls received immediately after connection are blocked\n // until user confirms. This prevents a race condition where server-side\n // queued calls bypass the confirmation dialog.\n let resolveConfirmationGate: (allowed: boolean) => void = () => {};\n if (this.onConnectionRequest) {\n this.confirmationPromise = new Promise<boolean>((resolve) => {\n resolveConfirmationGate = resolve;\n });\n }\n\n this.bridgeClient = new BridgeClient(\n endpoint,\n async (method, args: any[]) => {\n // Wait for user confirmation before processing any commands\n if (this.confirmationPromise) {\n const allowed = await this.confirmationPromise;\n if (!allowed) {\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(`bridge call from cli side: ${method}`, 'log');\n if (method === BridgeEvent.ConnectNewTabWithUrl) {\n return this.connectNewTabWithUrl.apply(\n this,\n args as unknown as [string],\n );\n }\n\n if (method === BridgeEvent.GetBrowserTabList) {\n return this.getBrowserTabList.apply(this, args as any);\n }\n\n if (method === BridgeEvent.SetActiveTabId) {\n return this.setActiveTabId.apply(this, args as any);\n }\n\n if (method === BridgeEvent.ConnectCurrentTab) {\n return this.connectCurrentTab.apply(this, args as any);\n }\n\n if (method === BridgeEvent.UpdateAgentStatus) {\n return this.onLogMessage(args[0] as string, 'status');\n }\n\n const tabId = await this.getActiveTabId();\n if (!tabId || tabId === 0) {\n throw new Error('no tab is connected');\n }\n\n // this.onLogMessage(`calling method: ${method}`);\n\n if (method.startsWith(MouseEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof MouseAction;\n if (actionName === 'drag') {\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n return this.mouse[actionName].apply(this.mouse, args as any);\n }\n\n if (method.startsWith(KeyboardEvent.PREFIX)) {\n const actionName = method.split('.')[1] as keyof KeyboardAction;\n if (actionName === 'press') {\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n return this.keyboard[actionName].apply(this.keyboard, args as any);\n }\n\n // Generic method lookup. Methods like `setWaterFlowAnimationEnabled`\n // and `getWaterFlowAnimationEnabled` are inherited from\n // ChromeExtensionProxyPage and found via `this[method]`.\n if (!this[method as keyof ChromeExtensionProxyPage]) {\n this.onLogMessage(`method not found: ${method}`, 'log');\n return undefined;\n }\n\n try {\n // @ts-expect-error\n const result = await this[method as keyof ChromeExtensionProxyPage](\n ...args,\n );\n return result;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : 'Unknown error';\n this.onLogMessage(\n `Error calling method: ${method}, ${errorMessage}`,\n 'log',\n );\n throw new Error(errorMessage, { cause: e });\n }\n },\n // on disconnect\n () => {\n return this.destroy();\n },\n );\n await this.bridgeClient.connect();\n\n // Show confirmation dialog after connection is established\n if (this.onConnectionRequest) {\n this.onLogMessage('Waiting for user confirmation...', 'log');\n const allowed = await this.onConnectionRequest();\n resolveConfirmationGate(allowed);\n this.confirmationPromise = null;\n\n if (!allowed) {\n this.onLogMessage('Connection denied by user', 'log');\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n throw new Error('Connection denied by user');\n }\n }\n\n this.onLogMessage(\n `Bridge connected, cli-side version v${this.bridgeClient.serverVersion}, browser-side version v${__VERSION__}`,\n 'log',\n );\n }\n\n public async connect() {\n return await this.setupBridgeClient();\n }\n\n public async connectNewTabWithUrl(\n url: string,\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n // Otherwise the animation gets injected during the connection flow\n // before the CLI side's setWaterFlowAnimationEnabled(false) arrives.\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n // Preserve the historical default: activate the new tab unless the caller opts into background mode.\n const activate = options.activateTab ?? true;\n const tab = await chrome.tabs.create({ url, active: activate });\n const tabId = tab.id;\n assert(tabId, 'failed to get tabId after creating a new tab');\n\n // new tab\n this.onLogMessage(`Creating new tab: ${url}`, 'log');\n this.newlyCreatedTabIds.push(tabId);\n\n if (options?.forceSameTabNavigation) {\n this.forceSameTabNavigation = true;\n }\n\n // chrome.tabs.create returns immediately with an about:blank target,\n // then navigates to `url`. If we attach the debugger during that\n // cross-origin transition Site Isolation will detach it again, leaving\n // the first CDP command to fail with \"Debugger is not attached to the\n // tab\". Wait for navigation to settle so the lazy attach lands on a\n // stable target.\n await waitForTabNavigationComplete(tabId, url);\n\n await this.setActiveTabId(tabId, { activate });\n }\n\n public async connectCurrentTab(\n options: BridgeConnectTabOptions = {\n forceSameTabNavigation: true,\n },\n ) {\n // Set the water-flow animation flag BEFORE any debugger commands are\n // sent (which trigger enableWaterFlowAnimation via sendCommandToDebugger).\n if (options.enableWaterFlowAnimation !== undefined) {\n this.waterFlowAnimationEnabled = options.enableWaterFlowAnimation;\n }\n\n const tabs = await chrome.tabs.query({ active: true, currentWindow: true });\n const tabId = tabs[0]?.id;\n assert(tabId, 'failed to get tabId');\n\n this.onLogMessage(`Connected to current tab: ${tabs[0]?.url}`, 'log');\n\n if (options?.forceSameTabNavigation) {\n this.forceSameTabNavigation = true;\n }\n\n await this.setActiveTabId(tabId);\n }\n\n public async setDestroyOptions(options: ChromePageDestroyOptions) {\n this.destroyOptions = options;\n }\n\n async destroy() {\n if (this.destroyOptions?.closeTab && this.newlyCreatedTabIds.length > 0) {\n this.onLogMessage('Closing all newly created tabs by bridge...', 'log');\n for (const tabId of this.newlyCreatedTabIds) {\n await chrome.tabs.remove(tabId);\n }\n this.newlyCreatedTabIds = [];\n }\n\n await super.destroy();\n\n if (this.bridgeClient) {\n this.bridgeClient.disconnect();\n this.bridgeClient = null;\n this.onDisconnect();\n }\n }\n}\n"],"names":["NEW_TAB_LOAD_TIMEOUT_MS","isBlankUrl","url","waitForTabNavigationComplete","tabId","targetUrl","timeoutMs","Promise","resolve","settled","finish","chrome","onUpdated","clearTimeout","timer","isReady","tab","currentUrl","id","_info","setTimeout","ExtensionBridgePageBrowserSide","ChromeExtensionProxyPage","endpoint","DefaultBridgeServerHost","DefaultBridgeServerPort","resolveConfirmationGate","BridgeClient","method","args","allowed","Error","BridgeEvent","MouseEvent","actionName","KeyboardEvent","result","e","errorMessage","options","undefined","activate","assert","tabs","serverEndpoint","onDisconnect","onLogMessage","forceSameTabNavigation","onConnectionRequest"],"mappings":";;;;;;;;;;;;;;AAmBA,MAAMA,0BAA0B;AAEhC,SAASC,WAAWC,GAAuB;IACzC,IAAI,CAACA,KAAK,OAAO;IACjB,OAAOA,AAAQ,kBAARA,OAAyBA,IAAI,UAAU,CAAC;AACjD;AAKA,SAASC,6BACPC,KAAa,EACbC,SAAiB,EACjBC,YAAYN,uBAAuB;IAEnC,OAAO,IAAIO,QAAQ,CAACC;QAClB,IAAIC,UAAU;QACd,MAAMC,SAAS;YACb,IAAID,SAAS;YACbA,UAAU;YACV,IAAI;gBACFE,OAAO,IAAI,CAAC,SAAS,CAAC,cAAc,CAACC;YACvC,EAAE,OAAM,CAAC;YACTC,aAAaC;YACbN;QACF;QAEA,MAAMO,UAAU,CAACC;YACf,IAAI,CAACA,KAAK,OAAO;YACjB,IAAIA,AAAe,eAAfA,IAAI,MAAM,EAAiB,OAAO;YACtC,MAAMC,aAAaD,IAAI,GAAG,IAAIA,IAAI,UAAU,IAAI;YAGhD,IAAIf,WAAWgB,eAAe,CAAChB,WAAWI,YAAY,OAAO;YAC7D,OAAO;QACT;QAEA,MAAMO,YAAY,CAChBM,IACAC,OACAH;YAEA,IAAIE,OAAOd,OAAO;YAClB,IAAIW,QAAQC,MAAMN;QACpB;QAEAC,OAAO,IAAI,CAAC,SAAS,CAAC,WAAW,CAACC;QAClC,MAAME,QAAQM,WAAWV,QAAQJ;QAIjCK,OAAO,IAAI,CACR,GAAG,CAACP,OACJ,IAAI,CAAC,CA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(()=>{
|
|
|
18
18
|
return runToolsCLI(tools, 'midscene-web', {
|
|
19
19
|
stripPrefix: 'web_',
|
|
20
20
|
argv: parsedOptions.argv,
|
|
21
|
-
version: "1.15.5
|
|
21
|
+
version: "1.15.5",
|
|
22
22
|
extraCommands: createReportCliCommands()
|
|
23
23
|
});
|
|
24
24
|
}).catch((e)=>{
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
3
|
import { z } from "zod/v4";
|
|
4
|
-
import {
|
|
4
|
+
import { resolveWebUrl } from "./utils.mjs";
|
|
5
5
|
const setCookiesInputSchema = z.strictObject({
|
|
6
|
-
cookiesEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional().describe('The environment variable containing a Cookie header, cookie array JSON, or
|
|
6
|
+
cookiesEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional().describe('The environment variable containing a Cookie header, cookie array JSON, or browser storage-state JSON.'),
|
|
7
7
|
profile: z.string().regex(/\S/).optional().describe('A cookie profile resolved by getCookieProfile().'),
|
|
8
|
-
storageStatePath: z.string().regex(/\S/).optional().describe('A path to a
|
|
8
|
+
storageStatePath: z.string().regex(/\S/).optional().describe('A path to a browser storage-state JSON file.'),
|
|
9
9
|
url: z.string().url().optional().describe('The HTTP(S) URL used to scope Cookie-header values or cookies without domain/path.')
|
|
10
10
|
}).superRefine((input, ctx)=>{
|
|
11
11
|
const sourceCount = [
|
|
@@ -57,48 +57,6 @@ const parseCookieJson = (raw)=>{
|
|
|
57
57
|
throw new TypeError('setCookies source must contain valid JSON or a Cookie header.');
|
|
58
58
|
}
|
|
59
59
|
};
|
|
60
|
-
const resolveCookieSource = async (reference, defaultUrl, ctx, options)=>{
|
|
61
|
-
switch(reference.kind){
|
|
62
|
-
case 'env':
|
|
63
|
-
{
|
|
64
|
-
let env;
|
|
65
|
-
try {
|
|
66
|
-
env = await options.getEnv?.(ctx) ?? process.env;
|
|
67
|
-
} catch {
|
|
68
|
-
throw new Error(`Failed to resolve cookie environment ${reference.name}; the original error was redacted because it may contain cookie values.`);
|
|
69
|
-
}
|
|
70
|
-
const raw = env[reference.name];
|
|
71
|
-
if (!raw?.trim()) throw new Error(`Environment variable ${reference.name} is missing or blank.`);
|
|
72
|
-
const trimmed = raw.trim();
|
|
73
|
-
return {
|
|
74
|
-
reference,
|
|
75
|
-
cookies: /^[\[{]/.test(trimmed) ? parseCookieJson(trimmed) : parseCookieHeader(trimmed, defaultUrl)
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
case 'profile':
|
|
79
|
-
if (!options.getCookieProfile) throw new Error('setCookies.profile requires a configured getCookieProfile callback.');
|
|
80
|
-
try {
|
|
81
|
-
return {
|
|
82
|
-
reference,
|
|
83
|
-
cookies: await options.getCookieProfile({
|
|
84
|
-
profile: reference.name,
|
|
85
|
-
context: ctx.context,
|
|
86
|
-
signal: ctx.signal
|
|
87
|
-
})
|
|
88
|
-
};
|
|
89
|
-
} catch {
|
|
90
|
-
throw new Error(`Failed to resolve cookie profile ${reference.name}; the original error was redacted because it may contain cookie values.`);
|
|
91
|
-
}
|
|
92
|
-
case 'storage-state':
|
|
93
|
-
{
|
|
94
|
-
const path = options.resolveStorageStatePath ? await options.resolveStorageStatePath(reference.name, ctx) : resolve(process.cwd(), reference.name);
|
|
95
|
-
return {
|
|
96
|
-
reference,
|
|
97
|
-
cookies: parseCookieJson(await readFile(path, 'utf8'))
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
60
|
const normalizeCookie = (candidate, defaultUrl, index)=>{
|
|
103
61
|
if (!candidate || 'object' != typeof candidate || Array.isArray(candidate)) throw new TypeError(`setCookies cookie at index ${index} must be an object.`);
|
|
104
62
|
const cookie = candidate;
|
|
@@ -122,41 +80,60 @@ const normalizeCookies = (source, defaultUrl)=>{
|
|
|
122
80
|
if (0 === candidates.length) throw new TypeError('setCookies source contains no cookies.');
|
|
123
81
|
return candidates.map((cookie, index)=>normalizeCookie(cookie, defaultUrl, index));
|
|
124
82
|
};
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
83
|
+
const resolveCookieInput = async (input, ctx, options)=>{
|
|
84
|
+
const defaultUrl = void 0 === input.url ? void 0 : resolveWebUrl(input.url, void 0, 'setCookies.url');
|
|
85
|
+
const reference = toCookieSourceReference(input);
|
|
86
|
+
let source;
|
|
87
|
+
switch(reference.kind){
|
|
88
|
+
case 'env':
|
|
89
|
+
{
|
|
90
|
+
let env;
|
|
91
|
+
try {
|
|
92
|
+
env = await options.getEnv?.(ctx) ?? process.env;
|
|
93
|
+
} catch {
|
|
94
|
+
throw new Error(`Failed to resolve cookie environment ${reference.name}; the original error was redacted because it may contain cookie values.`);
|
|
95
|
+
}
|
|
96
|
+
const raw = env[reference.name];
|
|
97
|
+
if (!raw?.trim()) throw new Error(`Environment variable ${reference.name} is missing or blank.`);
|
|
98
|
+
const trimmed = raw.trim();
|
|
99
|
+
source = /^[\[{]/.test(trimmed) ? parseCookieJson(trimmed) : parseCookieHeader(trimmed, defaultUrl);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
case 'profile':
|
|
103
|
+
if (!options.getCookieProfile) throw new Error('setCookies.profile requires a configured getCookieProfile callback.');
|
|
104
|
+
try {
|
|
105
|
+
source = await options.getCookieProfile({
|
|
106
|
+
profile: reference.name,
|
|
107
|
+
context: ctx.context,
|
|
108
|
+
signal: ctx.signal
|
|
109
|
+
});
|
|
110
|
+
} catch {
|
|
111
|
+
throw new Error(`Failed to resolve cookie profile ${reference.name}; the original error was redacted because it may contain cookie values.`);
|
|
112
|
+
}
|
|
113
|
+
break;
|
|
114
|
+
case 'storage-state':
|
|
115
|
+
{
|
|
116
|
+
let contents;
|
|
117
|
+
try {
|
|
118
|
+
const path = options.resolveStorageStatePath ? await options.resolveStorageStatePath(reference.name, ctx) : resolve(process.cwd(), reference.name);
|
|
119
|
+
contents = await readFile(path, 'utf8');
|
|
120
|
+
} catch {
|
|
121
|
+
throw new Error(`Failed to read cookie storage state ${reference.name}; the original error was redacted because it may contain cookie values.`);
|
|
122
|
+
}
|
|
123
|
+
source = parseCookieJson(contents);
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
158
126
|
}
|
|
127
|
+
const cookies = normalizeCookies(source, defaultUrl);
|
|
128
|
+
return {
|
|
129
|
+
cookies,
|
|
130
|
+
result: {
|
|
131
|
+
source: reference.kind,
|
|
132
|
+
sourceName: reference.name,
|
|
133
|
+
count: cookies.length
|
|
134
|
+
}
|
|
135
|
+
};
|
|
159
136
|
};
|
|
160
|
-
export {
|
|
137
|
+
export { resolveCookieInput, setCookiesInputSchema };
|
|
161
138
|
|
|
162
139
|
//# sourceMappingURL=cookies.mjs.map
|