61c7eee2b0
"Open in new window" sits beside Float: the chat pane and chat list row menus, a floating chat window's title bar, the terminal options menu and the diff bar, plus Alt+Shift+Y for the chat with the keyboard (listed in the shortcut help). Once the window opens the item leaves the main window as Float takes a pane out of the tiling. The window is its own app instance at /window/chat/<id>, /window/terminal?tab=<key> or /window/diff/<token>: only that item, named after it, with "Bring back to main window". It has its own connection and writes no shared layout (no open-chat workspace, window store or terminal layout) and posts no notifications, so they stay the main window's. Web opens a popup window (a blocked popup offers a tab); Linux and macOS start a second process with --detached (Flutter's multi-window API is still experimental); Android and iOS hide the action. The capture kit gains a follow step for windows a page opens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
152 lines
7.2 KiB
JavaScript
152 lines
7.2 KiB
JavaScript
// Headless Chrome over the DevTools protocol: launch a private instance (fresh
|
|
// profile, remote debugging on an OS-assigned port) or attach to a running one
|
|
// via `--cdp http://127.0.0.1:<port>`. Either way the kit works in its own page
|
|
// target, and close() removes everything it created.
|
|
import { spawn } from 'node:child_process';
|
|
import { mkdtemp, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
|
|
const CALL_TIMEOUT_MS = 30000;
|
|
const DEFAULT_CHROME ='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
|
|
|
async function launch(chromePath, gpu, args = []) {
|
|
const profile = await mkdtemp(join(tmpdir(), 'pipelines-capture-chrome-'));
|
|
const chrome = spawn(chromePath, [
|
|
// CAPTURE_HEADED=1 opens a real X11 window (under xvfb-run) instead.
|
|
...(process.env.CAPTURE_HEADED === '1' ? ['--ozone-platform=x11'] : ['--headless=new']), '--no-first-run', '--no-default-browser-check',
|
|
// Without a GPU CanvasKit rasterises on the CPU; `gpu` keeps WebGL (Metal
|
|
// through ANGLE on a Mac) for benches that measure raster time.
|
|
// Linux keeps the GPU through ANGLE on Vulkan.
|
|
...(gpu ? [process.platform === 'darwin' ? '--use-angle=metal' : '--use-angle=vulkan',
|
|
...(process.platform === 'darwin' ? [] : ['--enable-features=Vulkan']),
|
|
'--enable-gpu-rasterization', '--ignore-gpu-blocklist'] : ['--disable-gpu']),
|
|
'--hide-scrollbars', '--mute-audio', ...args,
|
|
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
|
|
], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
let stderr = '';
|
|
chrome.stderr.on('data', (d) => { stderr += d; });
|
|
const exited = new Promise((done) => chrome.once('exit', done));
|
|
const cleanup = async () => {
|
|
if (chrome.exitCode === null && chrome.signalCode === null) {
|
|
chrome.kill('SIGTERM');
|
|
const timedOut = await Promise.race([exited.then(() => false), delay(3000, true)]);
|
|
if (timedOut) { chrome.kill('SIGKILL'); await exited; }
|
|
}
|
|
await rm(profile, { recursive: true, force: true }).catch(() => {});
|
|
};
|
|
for (let i = 0; i < 150; i++) {
|
|
const ws = stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1];
|
|
if (ws) return { ws, cleanup };
|
|
if (chrome.exitCode !== null) break;
|
|
await delay(100);
|
|
}
|
|
await cleanup();
|
|
throw new Error(`Chrome did not start (${chromePath}): ${stderr.slice(-800)}`);
|
|
}
|
|
|
|
async function attach(cdp) {
|
|
const version = await (await fetch(new URL('/json/version', cdp))).json();
|
|
return { ws: version.webSocketDebuggerUrl, cleanup: async () => {} };
|
|
}
|
|
|
|
/**
|
|
* Opens a page target. Returns `{ send, on, close }`: `send(method, params)`
|
|
* talks to the page session; `on(method, fn)` subscribes to its events and
|
|
* returns the unsubscribe function; `newPage()` opens a scratch page.
|
|
*/
|
|
export async function openBrowser({ cdp, gpu = false, args = [], chromePath = process.env.CHROME_PATH ?? DEFAULT_CHROME } = {}) {
|
|
const { ws: endpoint, cleanup } = cdp ? await attach(cdp) : await launch(chromePath, gpu, args);
|
|
const ws = new WebSocket(endpoint);
|
|
try {
|
|
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = () => fail(new Error(`Cannot open ${endpoint}`)); });
|
|
} catch (error) { await cleanup(); throw error; }
|
|
let nextId = 0;
|
|
const pending = new Map();
|
|
const listeners = new Map();
|
|
let sessionId;
|
|
ws.onmessage = (event) => {
|
|
const m = JSON.parse(event.data);
|
|
if (m.id && pending.has(m.id)) {
|
|
const { ok, fail, method } = pending.get(m.id);
|
|
pending.delete(m.id);
|
|
return m.error ? fail(new Error(`${method}: ${m.error.message}`)) : ok(m.result ?? {});
|
|
}
|
|
if (m.method && m.sessionId === sessionId) for (const fn of listeners.get(m.method) ?? []) fn(m.params);
|
|
};
|
|
// Every call is bounded: an unresponsive page (for example a navigation to a
|
|
// server that never answers) fails the step instead of hanging the kit.
|
|
const raw = (method, params = {}, session) => new Promise((ok, fail) => {
|
|
const id = ++nextId;
|
|
const timer = setTimeout(() => {
|
|
pending.delete(id);
|
|
fail(new Error(`${method}: no reply within ${CALL_TIMEOUT_MS} ms`));
|
|
}, CALL_TIMEOUT_MS);
|
|
const settle = (fn) => (value) => { clearTimeout(timer); fn(value); };
|
|
pending.set(id, { ok: settle(ok), fail: settle(fail), method });
|
|
ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }));
|
|
});
|
|
let targetId;
|
|
let main;
|
|
try {
|
|
({ targetId } = await raw('Target.createTarget', { url: 'about:blank' }));
|
|
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
|
|
} catch (error) { ws.close(); await cleanup(); throw error; }
|
|
return {
|
|
send: (method, params) => raw(method, params, sessionId),
|
|
/** A browser-level call (no page session), e.g. `Browser.grantPermissions`. */
|
|
sendBrowser: (method, params) => raw(method, params),
|
|
on: (method, fn) => {
|
|
listeners.set(method, [...(listeners.get(method) ?? []), fn]);
|
|
return () => listeners.set(method, listeners.get(method).filter((f) => f !== fn));
|
|
},
|
|
/** Every open page target (tabs a link opened included): `{ url, type }`. */
|
|
targets: async () => (await raw('Target.getTargets')).targetInfos
|
|
.filter((t) => t.type === 'page').map((t) => ({ url: t.url, type: t.type })),
|
|
newPage: async () => {
|
|
const page = await raw('Target.createTarget', { url: 'about:blank' });
|
|
const { sessionId: sid } = await raw('Target.attachToTarget', { targetId: page.targetId, flatten: true });
|
|
return {
|
|
send: (method, params) => raw(method, params, sid),
|
|
targetId: page.targetId,
|
|
close: () => raw('Target.closeTarget', { targetId: page.targetId }).catch(() => {}),
|
|
};
|
|
},
|
|
/** Brings the kit's own page to the front again (after a scratch page). */
|
|
front: () => raw('Target.activateTarget', { targetId }),
|
|
/**
|
|
* Moves the kit's page session to another page target: the first one
|
|
* whose URL contains [match] (a window the page opened with
|
|
* `window.open`), waited for up to [timeout] ms; `main` returns to the
|
|
* page the kit opened. Resolves to the target's URL.
|
|
*/
|
|
follow: async (match, timeout = 10000) => {
|
|
main ??= { targetId, sessionId };
|
|
if (match === 'main') {
|
|
({ targetId, sessionId } = main);
|
|
await raw('Target.activateTarget', { targetId });
|
|
return (await raw('Target.getTargets')).targetInfos.find((t) => t.targetId === targetId)?.url;
|
|
}
|
|
const end = Date.now() + timeout;
|
|
for (;;) {
|
|
const hit = (await raw('Target.getTargets')).targetInfos
|
|
.find((t) => t.type === 'page' && t.targetId !== main.targetId && t.url.includes(match));
|
|
if (hit) {
|
|
targetId = hit.targetId;
|
|
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
|
|
await raw('Target.activateTarget', { targetId });
|
|
return hit.url;
|
|
}
|
|
if (Date.now() > end) throw new Error(`no page whose URL contains ${JSON.stringify(match)} within ${timeout} ms`);
|
|
await new Promise((ok) => setTimeout(ok, 100));
|
|
}
|
|
},
|
|
close: async () => {
|
|
await raw('Target.closeTarget', { targetId }).catch(() => {});
|
|
ws.close();
|
|
await cleanup();
|
|
},
|
|
};
|
|
}
|