mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 15:58:53 +00:00
The headless browser was found only through the "DevTools listening on ws://..." line on the launched process's stderr. A Chrome or Edge that was updated while it kept running (a newer version folder than its launcher, until the browser is restarted) starts a new process and the launched one exits with code 0 after about 60 ms, so the session failed with "Google Chrome exited early (code 0)" although the browser was running. The browser always writes DevToolsActivePort into its profile folder, so that file is now read too (every 100 ms); an exit with code 0 is a hand-over and the port file or the 15 s timeout decides, any other exit code still fails at once. Closing is unchanged (Browser.close over CDP first). Tests: readDevToolsPortFile cases in tests/visual-browser.test.mjs; the real browser test of that file passes on the PC where it failed (Chrome 158, update 8127.89 installed beside the running 8127.37).
1095 lines
43 KiB
JavaScript
1095 lines
43 KiB
JavaScript
/**
|
||
* Zero-dependency Chrome DevTools Protocol (CDP) controller for Strata's Live Sidebar Visual Browser.
|
||
*
|
||
* Launches installed Chrome, Microsoft Edge, or Chromium headless (`--headless=new`), streams live
|
||
* viewport frames (`Page.startScreencast` + explicit post-action captures), animates virtual cursor
|
||
* movements and `@eN` element inspection highlights over SSE (`event: browser-view`), and hosts a
|
||
* stateless sandboxed HTML stage so the assistant can visually inspect and iterate on websites and
|
||
* local HTML deliverables right inside the right-hand sidebar.
|
||
*/
|
||
|
||
import { spawn, spawnSync } from 'node:child_process';
|
||
import { randomBytes, randomUUID } from 'node:crypto';
|
||
import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||
import { request as httpRequest } from 'node:http';
|
||
import { tmpdir } from 'node:os';
|
||
import { extname, join, resolve, sep } from 'node:path';
|
||
import { pathToFileURL } from 'node:url';
|
||
import { findBrowser } from './agent/browser-probe.mjs';
|
||
import { createDuckDuckGoSearch } from './web-search-ddg.mjs';
|
||
import {
|
||
DESIGN_AUDIT_EXPRESSION,
|
||
SNAPSHOT_EXPRESSION,
|
||
formatDesignAuditForModel,
|
||
formatSnapshotForModel,
|
||
renderSearchResultsHtml,
|
||
resolveRefExpression,
|
||
} from './visual-browser-snapshot.mjs';
|
||
|
||
export const VIEWPORT_PRESETS = Object.freeze({
|
||
desktop: { width: 1280, height: 800, mobile: false, preset: 'desktop' },
|
||
tablet: { width: 820, height: 1080, mobile: true, preset: 'tablet' },
|
||
mobile: { width: 390, height: 844, mobile: true, preset: 'mobile' },
|
||
});
|
||
|
||
export const MAX_SESSIONS = 2;
|
||
export const SCREENCAST_IDLE_MS = 10_000;
|
||
export const TEMP_DIR_MAX_AGE_MS = 2 * 3600_000;
|
||
const IDLE_TTL_MS = 5 * 60 * 1000;
|
||
|
||
/** The browser's DevTools address from the `DevToolsActivePort` file in its profile folder (line 1 the port, line 2 the path), or null while it is not there. */
|
||
export function readDevToolsPortFile(profileDir) {
|
||
try {
|
||
const [port, path] = readFileSync(join(profileDir, 'DevToolsActivePort'), 'utf8').split(/\r?\n/);
|
||
return /^\d{2,5}$/.test(port ?? '') && /^\/devtools\/browser\/[\w-]+$/.test(path ?? '') ? `ws://127.0.0.1:${port}${path}` : null;
|
||
} catch { return null; }
|
||
}
|
||
|
||
/** Delete stale `strata-vbrowser-*` folders in `tmpdir()` older than `maxAgeMs` (default 2 hours). */
|
||
export function sweepTempDirs({ baseDir = tmpdir(), maxAgeMs = TEMP_DIR_MAX_AGE_MS, now = Date.now } = {}) {
|
||
let swept = 0;
|
||
let entries = [];
|
||
try { entries = readdirSync(baseDir, { withFileTypes: true }); } catch { return 0; }
|
||
const cutoff = now() - maxAgeMs;
|
||
for (const entry of entries) {
|
||
if (!entry.isDirectory() || !entry.name.startsWith('strata-vbrowser-')) continue;
|
||
const full = join(baseDir, entry.name);
|
||
try {
|
||
if (statSync(full).mtimeMs <= cutoff) {
|
||
rmSync(full, { recursive: true, force: true });
|
||
swept++;
|
||
}
|
||
} catch { /* in use or already gone */ }
|
||
}
|
||
return swept;
|
||
}
|
||
const BLOCKED_HOSTS = new Set([
|
||
'169.254.169.254',
|
||
'100.100.100.200',
|
||
'metadata.google.internal',
|
||
'metadata.internal',
|
||
'[fd00:ec2::254]',
|
||
]);
|
||
|
||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||
|
||
/** Minimal RFC-6455 loopback WebSocket fallback in case `globalThis.WebSocket` is absent on older Node builds. */
|
||
function connectWebSocket(wsUrl) {
|
||
if (typeof globalThis.WebSocket === 'function') {
|
||
return new Promise((resolvePromise, rejectPromise) => {
|
||
const ws = new globalThis.WebSocket(wsUrl);
|
||
const onOpen = () => {
|
||
ws.removeEventListener('error', onErr);
|
||
resolvePromise({
|
||
send: text => ws.send(text),
|
||
onMessage: fn => ws.addEventListener('message', e => fn(typeof e.data === 'string' ? e.data : Buffer.from(e.data).toString('utf8'))),
|
||
onClose: fn => ws.addEventListener('close', fn),
|
||
close: () => { try { ws.close(); } catch {} },
|
||
});
|
||
};
|
||
const onErr = err => rejectPromise(err?.error ?? new Error(`WebSocket connection failed: ${wsUrl}`));
|
||
ws.addEventListener('open', onOpen, { once: true });
|
||
ws.addEventListener('error', onErr, { once: true });
|
||
});
|
||
}
|
||
return new Promise((resolvePromise, rejectPromise) => {
|
||
const parsed = new URL(wsUrl);
|
||
const key = randomBytes(16).toString('base64');
|
||
const req = httpRequest({
|
||
hostname: parsed.hostname,
|
||
port: Number(parsed.port),
|
||
path: parsed.pathname + parsed.search,
|
||
headers: {
|
||
Connection: 'Upgrade',
|
||
Upgrade: 'websocket',
|
||
'Sec-WebSocket-Version': '13',
|
||
'Sec-WebSocket-Key': key,
|
||
},
|
||
});
|
||
req.on('error', rejectPromise);
|
||
req.on('upgrade', (_res, socket) => {
|
||
const listeners = [];
|
||
const closeListeners = [];
|
||
let buf = Buffer.alloc(0);
|
||
let frag = [];
|
||
socket.on('data', chunk => {
|
||
buf = Buffer.concat([buf, chunk]);
|
||
while (buf.length >= 2) {
|
||
const b0 = buf[0], b1 = buf[1];
|
||
const fin = (b0 & 0x80) !== 0;
|
||
const opcode = b0 & 0x0f;
|
||
const masked = (b1 & 0x80) !== 0;
|
||
let len = b1 & 0x7f;
|
||
let offset = 2;
|
||
if (len === 126) {
|
||
if (buf.length < 4) return;
|
||
len = buf.readUInt16BE(2);
|
||
offset = 4;
|
||
} else if (len === 127) {
|
||
if (buf.length < 10) return;
|
||
len = Number(buf.readBigUInt64BE(2));
|
||
offset = 10;
|
||
}
|
||
const maskLen = masked ? 4 : 0;
|
||
if (buf.length < offset + maskLen + len) return;
|
||
const payload = Buffer.from(buf.subarray(offset + maskLen, offset + maskLen + len));
|
||
if (masked) {
|
||
const mask = buf.subarray(offset, offset + 4);
|
||
for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
|
||
}
|
||
buf = buf.subarray(offset + maskLen + len);
|
||
if (opcode === 0x8) { socket.end(); return; }
|
||
if (opcode === 0x9) {
|
||
const pong = Buffer.alloc(2 + payload.length);
|
||
pong[0] = 0x8a;
|
||
pong[1] = payload.length;
|
||
payload.copy(pong, 2);
|
||
socket.write(pong);
|
||
continue;
|
||
}
|
||
frag.push(payload);
|
||
if (fin) {
|
||
const full = Buffer.concat(frag).toString('utf8');
|
||
frag = [];
|
||
for (const fn of listeners) fn(full);
|
||
}
|
||
}
|
||
});
|
||
socket.on('close', () => closeListeners.forEach(fn => fn()));
|
||
const send = text => {
|
||
const data = Buffer.from(text, 'utf8');
|
||
const mask = randomBytes(4);
|
||
let head;
|
||
if (data.length < 126) {
|
||
head = Buffer.from([0x81, 0x80 | data.length]);
|
||
} else if (data.length < 65536) {
|
||
head = Buffer.alloc(4);
|
||
head[0] = 0x81;
|
||
head[1] = 0x80 | 126;
|
||
head.writeUInt16BE(data.length, 2);
|
||
} else {
|
||
head = Buffer.alloc(10);
|
||
head[0] = 0x81;
|
||
head[1] = 0x80 | 127;
|
||
head.writeBigUInt64BE(BigInt(data.length), 2);
|
||
}
|
||
const maskedData = Buffer.alloc(data.length);
|
||
for (let i = 0; i < data.length; i++) maskedData[i] = data[i] ^ mask[i & 3];
|
||
socket.write(Buffer.concat([head, mask, maskedData]));
|
||
};
|
||
resolvePromise({
|
||
send,
|
||
onMessage: fn => listeners.push(fn),
|
||
onClose: fn => closeListeners.push(fn),
|
||
close: () => { try { socket.destroy(); } catch {} },
|
||
});
|
||
});
|
||
req.end();
|
||
});
|
||
}
|
||
|
||
/** Validate that a target URL cannot SSRF internal Strata ports, cloud metadata, or files outside the chat workspace. */
|
||
export function validateBrowserTarget(rawUrl, { hostPort, forbiddenPorts = [], workspacePath = null } = {}) {
|
||
const input = String(rawUrl ?? '').trim();
|
||
if (!input) throw new Error('Provide a URL or HTML file path to open.');
|
||
|
||
if (workspacePath && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(input) && !input.startsWith('//')) {
|
||
const root = realpathSync(workspacePath);
|
||
const full = resolve(root, input);
|
||
if (existsSync(full)) {
|
||
const real = realpathSync(full);
|
||
const inside = real === root || real.startsWith(root + sep);
|
||
if (!inside) throw new Error('Browser access outside the current workspace folder is blocked.');
|
||
return { url: pathToFileURL(real).href, displayUrl: input, localFile: real };
|
||
}
|
||
}
|
||
|
||
let parsed;
|
||
try {
|
||
parsed = new URL(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(input) ? input : `https://${input}`);
|
||
} catch {
|
||
throw new Error(`Invalid browser URL: ${input}`);
|
||
}
|
||
|
||
if (parsed.protocol === 'file:') {
|
||
if (!workspacePath) throw new Error('Local file:// URLs require an active workspace folder.');
|
||
const root = realpathSync(workspacePath);
|
||
let targetPath;
|
||
try { targetPath = realpathSync(new URL(parsed.href)); } catch { throw new Error('That local file does not exist.'); }
|
||
if (targetPath !== root && !targetPath.startsWith(root + sep)) {
|
||
throw new Error('Browser file:// access outside the chat workspace folder is blocked.');
|
||
}
|
||
return { url: parsed.href, displayUrl: targetPath.slice(root.length + 1).replace(/\\/g, '/') || parsed.pathname, localFile: targetPath };
|
||
}
|
||
|
||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||
throw new Error(`Unsupported browser protocol "${parsed.protocol}" (use https://, http://, or a workspace HTML file).`);
|
||
}
|
||
|
||
const host = parsed.hostname.toLowerCase();
|
||
if (BLOCKED_HOSTS.has(host) || /^169\.254\./.test(host)) {
|
||
throw new Error('Access to cloud metadata addresses is blocked.');
|
||
}
|
||
|
||
const isLoopback = host === '127.0.0.1' || host === 'localhost' || host === '[::1]' || host === '::1';
|
||
if (isLoopback) {
|
||
const port = Number(parsed.port || (parsed.protocol === 'https:' ? 443 : 80));
|
||
if (forbiddenPorts.includes(port)) {
|
||
throw new Error('Access to internal Strata engine or bridge ports is blocked.');
|
||
}
|
||
if (hostPort && port === Number(hostPort) && !parsed.pathname.startsWith('/api/visual-browser/stage/')) {
|
||
throw new Error('Access to Strata internal API routes from the visual browser is blocked.');
|
||
}
|
||
}
|
||
|
||
return { url: parsed.href, displayUrl: parsed.href, localFile: null };
|
||
}
|
||
|
||
class CdpConnection {
|
||
constructor(ws) {
|
||
this.ws = ws;
|
||
this.seq = 0;
|
||
this.pending = new Map();
|
||
this.events = new Map();
|
||
this.closed = false;
|
||
|
||
ws.onMessage(raw => {
|
||
let msg;
|
||
try { msg = JSON.parse(raw); } catch { return; }
|
||
if (msg.id) {
|
||
const entry = this.pending.get(msg.id);
|
||
if (!entry) return;
|
||
clearTimeout(entry.timer);
|
||
this.pending.delete(msg.id);
|
||
if (msg.error) entry.reject(new Error(msg.error.message || 'CDP command failed'));
|
||
else entry.resolve(msg.result ?? {});
|
||
return;
|
||
}
|
||
if (msg.method) {
|
||
const list = this.events.get(msg.method);
|
||
if (list) for (const fn of list) { try { fn(msg.params ?? {}); } catch {} }
|
||
}
|
||
});
|
||
|
||
ws.onClose(() => {
|
||
this.closed = true;
|
||
for (const p of this.pending.values()) {
|
||
clearTimeout(p.timer);
|
||
p.reject(new Error('Browser connection closed.'));
|
||
}
|
||
this.pending.clear();
|
||
});
|
||
}
|
||
|
||
send(method, params = {}, timeoutMs = 20_000) {
|
||
if (this.closed) return Promise.reject(new Error('Browser connection closed.'));
|
||
const id = ++this.seq;
|
||
return new Promise((resolvePromise, rejectPromise) => {
|
||
const timer = setTimeout(() => {
|
||
this.pending.delete(id);
|
||
rejectPromise(new Error(`Browser action timed out (${method}).`));
|
||
}, timeoutMs);
|
||
this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
|
||
this.ws.send(JSON.stringify({ id, method, params }));
|
||
});
|
||
}
|
||
|
||
call(method, params = {}, timeoutMs = 20_000) {
|
||
return this.send(method, params, timeoutMs);
|
||
}
|
||
|
||
on(method, fn) {
|
||
const list = this.events.get(method) ?? [];
|
||
list.push(fn);
|
||
this.events.set(method, list);
|
||
}
|
||
|
||
close() {
|
||
this.closed = true;
|
||
this.ws.close();
|
||
}
|
||
}
|
||
|
||
function keySpec(key) {
|
||
const map = {
|
||
Enter: { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r' },
|
||
Tab: { key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 },
|
||
Escape: { key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
|
||
Backspace: { key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 },
|
||
Delete: { key: 'Delete', code: 'Delete', windowsVirtualKeyCode: 46 },
|
||
ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40 },
|
||
ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', windowsVirtualKeyCode: 38 },
|
||
ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 },
|
||
ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 },
|
||
PageDown: { key: 'PageDown', code: 'PageDown', windowsVirtualKeyCode: 34 },
|
||
PageUp: { key: 'PageUp', code: 'PageUp', windowsVirtualKeyCode: 33 },
|
||
Space: { key: ' ', code: 'Space', windowsVirtualKeyCode: 32, text: ' ' },
|
||
};
|
||
return map[key] ?? { key: String(key), code: String(key), windowsVirtualKeyCode: String(key).toUpperCase().charCodeAt(0) || 0 };
|
||
}
|
||
|
||
export function createVisualBrowserManager({
|
||
hostPort = () => 8787,
|
||
forbiddenPorts = () => [],
|
||
publish = () => {},
|
||
findBrowserImpl = findBrowser,
|
||
searcher = createDuckDuckGoSearch(),
|
||
animationDelayMs = 560,
|
||
maxSessions = MAX_SESSIONS,
|
||
screencastIdleMs = SCREENCAST_IDLE_MS,
|
||
sweepOnInit = true,
|
||
} = {}) {
|
||
if (sweepOnInit) {
|
||
try { sweepTempDirs(); } catch { /* best effort */ }
|
||
}
|
||
/** @type {Map<string, any>} */
|
||
const sessions = new Map();
|
||
/** @type {Map<string, { sessionId: string, html: string, title: string }>} */
|
||
const stagePages = new Map();
|
||
|
||
function publicView(sess, includeFrame = true) {
|
||
return {
|
||
sessionId: sess.sessionId,
|
||
active: sess.active,
|
||
status: sess.status,
|
||
url: sess.url,
|
||
displayUrl: sess.displayUrl,
|
||
title: sess.title,
|
||
isLocalStage: sess.isLocalStage,
|
||
stageHtml: sess.isLocalStage ? sess.stageHtml : null,
|
||
viewport: sess.viewport,
|
||
cursor: sess.cursor,
|
||
highlight: sess.highlight,
|
||
steps: sess.steps.slice(-12),
|
||
consoleErrors: sess.consoleErrors.slice(-6),
|
||
updatedAt: sess.updatedAt,
|
||
...(includeFrame && sess.frame ? { frame: sess.frame } : {}),
|
||
};
|
||
}
|
||
|
||
function emit(sess, includeFrame = true) {
|
||
sess.updatedAt = Date.now();
|
||
publish(publicView(sess, includeFrame));
|
||
}
|
||
|
||
function touchIdle(sess) {
|
||
if (sess.idleTimer) clearTimeout(sess.idleTimer);
|
||
sess.idleTimer = setTimeout(() => { void closeSession(sess.sessionId); }, IDLE_TTL_MS);
|
||
sess.idleTimer.unref?.();
|
||
}
|
||
|
||
function armScreencastIdle(sess) {
|
||
if (sess.screencastTimer) clearTimeout(sess.screencastTimer);
|
||
if (!(screencastIdleMs > 0)) return;
|
||
sess.screencastTimer = setTimeout(() => {
|
||
sess.screencastTimer = null;
|
||
if (!sess.active || !sess.cdp || sess.cdp.closed || !sess.screencastActive) return;
|
||
sess.screencastActive = false;
|
||
sess.cdp.send('Page.stopScreencast', {}, 2000).catch(() => {});
|
||
}, screencastIdleMs);
|
||
sess.screencastTimer.unref?.();
|
||
}
|
||
|
||
async function ensureScreencast(sess) {
|
||
if (!sess.cdp || sess.cdp.closed) return;
|
||
if (!sess.screencastActive) {
|
||
sess.screencastActive = true;
|
||
await sess.cdp.send('Page.startScreencast', {
|
||
format: 'jpeg',
|
||
quality: 74,
|
||
maxWidth: 1280,
|
||
maxHeight: 900,
|
||
everyNthFrame: 1,
|
||
}, 4000).catch(() => { sess.screencastActive = false; });
|
||
}
|
||
armScreencastIdle(sess);
|
||
}
|
||
|
||
function addStep(sess, kind, label, detail = '') {
|
||
sess.steps.push({ id: randomUUID().slice(0, 8), at: Date.now(), kind, label, ...(detail ? { detail } : {}) });
|
||
if (sess.steps.length > 24) sess.steps.shift();
|
||
}
|
||
|
||
async function spawnCdpSession(sess) {
|
||
const found = findBrowserImpl();
|
||
if (!found.found || !found.path) {
|
||
throw new Error('No Chrome, Microsoft Edge, or Chromium browser was found on this computer.');
|
||
}
|
||
const profileDir = mkdtempSync(join(tmpdir(), 'strata-vbrowser-'));
|
||
sess.profileDir = profileDir;
|
||
const args = [
|
||
'--headless=new',
|
||
'--remote-debugging-port=0',
|
||
'--remote-allow-origins=*',
|
||
`--user-data-dir=${profileDir}`,
|
||
`--window-size=${sess.viewport.width},${sess.viewport.height}`,
|
||
'--no-first-run',
|
||
'--no-default-browser-check',
|
||
'--disable-background-networking',
|
||
'--disable-sync',
|
||
'--disable-extensions',
|
||
'--disable-default-apps',
|
||
'--disable-popup-blocking',
|
||
'--mute-audio',
|
||
'--hide-scrollbars',
|
||
'--disable-gpu-sandbox',
|
||
'about:blank',
|
||
];
|
||
const proc = spawn(found.path, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
sess.proc = proc;
|
||
|
||
const browserWsUrl = await new Promise((resolvePromise, rejectPromise) => {
|
||
let stderr = '', settled = false;
|
||
const finish = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); clearInterval(poll); proc.stderr.off('data', onData); fn(value); };
|
||
const timer = setTimeout(() => finish(rejectPromise, new Error(`${found.name} did not open its DevTools port in time.`)), 15_000);
|
||
const onData = chunk => {
|
||
stderr += chunk.toString('utf8');
|
||
const m = stderr.match(/DevTools listening on (ws:\/\/127\.0\.0\.1:\d+\/[^\r\n]+)/i);
|
||
if (m) finish(resolvePromise, m[1].trim());
|
||
};
|
||
/* A browser with a pending update (Chrome or Edge that was updated while it kept running) hands the start over to a new process and the first one
|
||
* exits with code 0, so its stderr never says "DevTools listening". The browser always writes DevToolsActivePort into its profile folder: read that too. */
|
||
const poll = setInterval(() => { const url = readDevToolsPortFile(profileDir); if (url) finish(resolvePromise, url); }, 100);
|
||
proc.stderr.on('data', onData);
|
||
proc.once('error', err => finish(rejectPromise, err));
|
||
proc.once('exit', code => {
|
||
if (code === 0) return; /* a hand-over, not a failure: the port file or the timeout decides */
|
||
finish(rejectPromise, new Error(`${found.name} exited early (code ${code}).`));
|
||
});
|
||
});
|
||
|
||
const cdpOrigin = new URL(browserWsUrl).origin.replace(/^ws:/i, 'http:');
|
||
let pageWsUrl = null;
|
||
for (let attempt = 0; attempt < 20; attempt++) {
|
||
try {
|
||
const res = await fetch(`${cdpOrigin}/json/list`, { signal: AbortSignal.timeout(2500) });
|
||
if (res.ok) {
|
||
const targets = await res.json();
|
||
const page = Array.isArray(targets) ? targets.find(t => t.type === 'page' && t.webSocketDebuggerUrl) : null;
|
||
if (page) { pageWsUrl = page.webSocketDebuggerUrl; break; }
|
||
}
|
||
} catch { /* wait for target */ }
|
||
await sleep(120);
|
||
}
|
||
if (!pageWsUrl) {
|
||
const res = await fetch(`${cdpOrigin}/json/new?about:blank`, { method: 'PUT', signal: AbortSignal.timeout(3000) });
|
||
const created = await res.json();
|
||
pageWsUrl = created.webSocketDebuggerUrl;
|
||
}
|
||
|
||
const ws = await connectWebSocket(pageWsUrl);
|
||
const cdp = new CdpConnection(ws);
|
||
sess.cdp = cdp;
|
||
|
||
await cdp.send('Page.enable');
|
||
await cdp.send('Runtime.enable');
|
||
await cdp.send('DOM.enable');
|
||
await cdp.send('Emulation.setDeviceMetricsOverride', {
|
||
width: sess.viewport.width,
|
||
height: sess.viewport.height,
|
||
deviceScaleFactor: 1,
|
||
mobile: sess.viewport.preset !== 'desktop',
|
||
});
|
||
|
||
cdp.on('Runtime.consoleAPICalled', params => {
|
||
if (params.type === 'error') {
|
||
const text = (params.args ?? []).map(a => a.value ?? a.description ?? '').filter(Boolean).join(' ').slice(0, 220);
|
||
if (text) {
|
||
sess.consoleErrors.push(text);
|
||
if (sess.consoleErrors.length > 20) sess.consoleErrors.shift();
|
||
}
|
||
}
|
||
});
|
||
cdp.on('Runtime.exceptionThrown', params => {
|
||
const desc = params.exceptionDetails?.exception?.description || params.exceptionDetails?.text || '';
|
||
if (desc) {
|
||
sess.consoleErrors.push(String(desc).split('\n')[0].slice(0, 220));
|
||
if (sess.consoleErrors.length > 20) sess.consoleErrors.shift();
|
||
}
|
||
});
|
||
cdp.on('Page.screencastFrame', params => {
|
||
if (params.sessionId !== undefined) {
|
||
cdp.send('Page.screencastFrameAck', { sessionId: params.sessionId }).catch(() => {});
|
||
}
|
||
if (params.data) {
|
||
const now = Date.now();
|
||
sess.frame = `data:image/jpeg;base64,${params.data}`;
|
||
if (now - (sess.lastFrameEmitAt ?? 0) >= 90) {
|
||
sess.lastFrameEmitAt = now;
|
||
emit(sess, true);
|
||
}
|
||
}
|
||
});
|
||
|
||
await ensureScreencast(sess);
|
||
}
|
||
|
||
async function ensureSession(sessionId) {
|
||
const id = String(sessionId || 'default');
|
||
let sess = sessions.get(id);
|
||
if (!sess) {
|
||
while (sessions.size >= maxSessions) {
|
||
const oldest = [...sessions.values()].sort((a, b) => a.updatedAt - b.updatedAt)[0];
|
||
if (!oldest) break;
|
||
await closeSession(oldest.sessionId);
|
||
}
|
||
const stageToken = randomBytes(16).toString('hex');
|
||
sess = {
|
||
sessionId: id,
|
||
stageToken,
|
||
active: true,
|
||
status: 'browsing',
|
||
url: 'about:blank',
|
||
displayUrl: '',
|
||
title: 'Live Browser',
|
||
isLocalStage: false,
|
||
stageHtml: null,
|
||
viewport: { ...VIEWPORT_PRESETS.desktop },
|
||
cursor: { x: 640, y: 360, visible: false, label: null, clicking: false, clickSeq: 0 },
|
||
highlight: null,
|
||
frame: null,
|
||
steps: [],
|
||
consoleErrors: [],
|
||
updatedAt: Date.now(),
|
||
lastFrameEmitAt: 0,
|
||
cdp: null,
|
||
proc: null,
|
||
profileDir: null,
|
||
idleTimer: null,
|
||
screencastTimer: null,
|
||
screencastActive: false,
|
||
starting: null,
|
||
};
|
||
sessions.set(id, sess);
|
||
}
|
||
sess.active = true;
|
||
touchIdle(sess);
|
||
if (!sess.cdp || sess.cdp.closed) {
|
||
if (!sess.starting) {
|
||
sess.starting = spawnCdpSession(sess).finally(() => { sess.starting = null; });
|
||
}
|
||
await sess.starting;
|
||
} else {
|
||
await ensureScreencast(sess);
|
||
}
|
||
return sess;
|
||
}
|
||
|
||
async function captureFrame(sess) {
|
||
if (!sess.cdp || sess.cdp.closed) return null;
|
||
try {
|
||
const shot = await sess.cdp.send('Page.captureScreenshot', { format: 'jpeg', quality: 78 }, 8000);
|
||
if (shot?.data) {
|
||
sess.frame = `data:image/jpeg;base64,${shot.data}`;
|
||
sess.lastFrameEmitAt = Date.now();
|
||
return sess.frame;
|
||
}
|
||
} catch { /* ignore transient navigation frame miss */ }
|
||
return sess.frame;
|
||
}
|
||
|
||
async function captureLlmFrame(sess) {
|
||
if (!sess.cdp || sess.cdp.closed) return sess.frame;
|
||
try {
|
||
const vw = Math.max(320, sess.viewport?.width || 1280);
|
||
const vh = Math.max(320, sess.viewport?.height || 800);
|
||
const scale = vw > 800 ? Math.round((800 / vw) * 100) / 100 : 1;
|
||
const shot = await sess.cdp.send('Page.captureScreenshot', {
|
||
format: 'jpeg',
|
||
quality: 62,
|
||
clip: { x: 0, y: 0, width: vw, height: vh, scale },
|
||
}, 6000);
|
||
if (shot?.data) return `data:image/jpeg;base64,${shot.data}`;
|
||
} catch { /* fall back to standard frame */ }
|
||
return sess.frame;
|
||
}
|
||
|
||
async function evaluate(sess, expression) {
|
||
const res = await sess.cdp.send('Runtime.evaluate', {
|
||
expression,
|
||
returnByValue: true,
|
||
awaitPromise: true,
|
||
});
|
||
if (res?.exceptionDetails) {
|
||
throw new Error(res.exceptionDetails.text || 'Script evaluation error in browser.');
|
||
}
|
||
return res?.result?.value;
|
||
}
|
||
|
||
async function takeSnapshot(sess) {
|
||
const snap = await evaluate(sess, SNAPSHOT_EXPRESSION);
|
||
if (snap) {
|
||
sess.title = snap.title || sess.title;
|
||
if (!sess.isLocalStage) {
|
||
sess.url = snap.url || sess.url;
|
||
sess.displayUrl = snap.url || sess.displayUrl;
|
||
}
|
||
}
|
||
await captureFrame(sess);
|
||
emit(sess, true);
|
||
return snap;
|
||
}
|
||
|
||
async function waitForLoad(sess, timeoutMs = 8000) {
|
||
const start = Date.now();
|
||
await sleep(180);
|
||
while (Date.now() - start < timeoutMs) {
|
||
try {
|
||
const state = await evaluate(sess, 'document.readyState');
|
||
if (state === 'complete' || state === 'interactive') break;
|
||
} catch { /* navigation in flight */ }
|
||
await sleep(140);
|
||
}
|
||
await sleep(220);
|
||
}
|
||
|
||
async function resolveTarget(sess, { ref, x, y }) {
|
||
if (ref) {
|
||
const info = await evaluate(sess, resolveRefExpression(ref));
|
||
if (!info) throw new Error(`Element @${String(ref).replace(/^@/, '')} is no longer on the page. Call browser_snapshot to refresh refs.`);
|
||
return info;
|
||
}
|
||
if (typeof x === 'number' && typeof y === 'number') {
|
||
return {
|
||
ref: null,
|
||
tag: 'point',
|
||
type: '',
|
||
label: `(${Math.round(x)}, ${Math.round(y)})`,
|
||
rect: { x: Math.round(x - 14), y: Math.round(y - 14), width: 28, height: 28 },
|
||
center: { x: Math.round(x), y: Math.round(y) },
|
||
};
|
||
}
|
||
throw new Error('Provide either an element `ref` (e.g. "e2") from browser_snapshot or `x` and `y` coordinates.');
|
||
}
|
||
|
||
async function glideCursor(sess, target, actionLabel, tone = 'inspect') {
|
||
const cx = Math.max(4, Math.min(sess.viewport.width - 4, target.center.x));
|
||
const cy = Math.max(4, Math.min(sess.viewport.height - 4, target.center.y));
|
||
const dist = sess.cursor.visible ? Math.hypot(cx - sess.cursor.x, cy - sess.cursor.y) : 0;
|
||
if (!sess.cursor.visible || dist < 56) {
|
||
const startX = Math.max(24, Math.min(sess.viewport.width - 24, cx > sess.viewport.width * 0.5 ? cx - 140 : cx + 140));
|
||
const startY = Math.max(24, Math.min(sess.viewport.height - 24, cy > sess.viewport.height * 0.35 ? cy - 95 : cy + 95));
|
||
sess.cursor = { ...sess.cursor, x: startX, y: startY, visible: true, label: null, clicking: false };
|
||
emit(sess, false);
|
||
if (animationDelayMs > 0) await sleep(Math.min(animationDelayMs, 130));
|
||
}
|
||
sess.cursor = {
|
||
...sess.cursor,
|
||
x: cx,
|
||
y: cy,
|
||
visible: true,
|
||
label: actionLabel,
|
||
clicking: false,
|
||
};
|
||
sess.highlight = target.rect ? { ...target.rect, label: actionLabel, tone } : null;
|
||
emit(sess, false);
|
||
await sess.cdp.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: cx, y: cy, button: 'none' }).catch(() => {});
|
||
if (animationDelayMs > 0) await sleep(animationDelayMs);
|
||
return { cx, cy };
|
||
}
|
||
|
||
function stageUrlFor(sess, title = 'Design Preview') {
|
||
const port = Number(typeof hostPort === 'function' ? hostPort() : hostPort);
|
||
return `http://127.0.0.1:${port}/api/visual-browser/stage/${sess.stageToken}?t=${Date.now()}#${encodeURIComponent(title)}`;
|
||
}
|
||
|
||
async function scanLoadedPage(sess, snap, label = 'Reading page') {
|
||
const vw = sess.viewport.width || 1280;
|
||
const vh = sess.viewport.height || 800;
|
||
await captureFrame(sess);
|
||
sess.cursor = {
|
||
...sess.cursor,
|
||
x: Math.round(vw * 0.16),
|
||
y: Math.round(vh * 0.14),
|
||
visible: true,
|
||
label,
|
||
clicking: false,
|
||
};
|
||
emit(sess, true);
|
||
if (animationDelayMs > 0) await sleep(Math.min(animationDelayMs, 140));
|
||
|
||
const visibleEls = Array.isArray(snap?.elements)
|
||
? snap.elements.filter(e => e.inViewport && e.rect?.width > 8 && e.rect?.height > 8)
|
||
: [];
|
||
const waypoints = [];
|
||
waypoints.push({ x: Math.round(vw * 0.42), y: Math.round(vh * 0.25), label });
|
||
const secondary = visibleEls.length >= 2 ? visibleEls[1] : null;
|
||
if (secondary?.rect) {
|
||
waypoints.push({
|
||
x: Math.round(secondary.rect.x + Math.min(secondary.rect.width, 160) / 2),
|
||
y: Math.round(secondary.rect.y + Math.min(secondary.rect.height, 44) / 2),
|
||
label,
|
||
});
|
||
}
|
||
for (const wp of waypoints) {
|
||
sess.cursor = {
|
||
...sess.cursor,
|
||
x: Math.max(16, Math.min(vw - 16, wp.x)),
|
||
y: Math.max(16, Math.min(vh - 16, wp.y)),
|
||
visible: true,
|
||
label: wp.label,
|
||
clicking: false,
|
||
};
|
||
emit(sess, false);
|
||
if (animationDelayMs > 0) await sleep(Math.min(animationDelayMs, 340));
|
||
}
|
||
}
|
||
|
||
async function openStageHtml(sess, { html, title = 'HTML Preview', filePath = null, stepLabel = 'Loaded HTML preview' }) {
|
||
stagePages.set(sess.stageToken, { sessionId: sess.sessionId, html: String(html), title });
|
||
sess.isLocalStage = true;
|
||
sess.stageHtml = String(html);
|
||
sess.displayUrl = filePath ? String(filePath) : `${title}.html`;
|
||
sess.title = title;
|
||
sess.status = 'browsing';
|
||
sess.consoleErrors = [];
|
||
sess.highlight = null;
|
||
const url = stageUrlFor(sess, title);
|
||
sess.url = url;
|
||
addStep(sess, 'open', stepLabel, sess.displayUrl);
|
||
emit(sess, false);
|
||
await sess.cdp.send('Page.navigate', { url });
|
||
await waitForLoad(sess, 6000);
|
||
const snap = await evaluate(sess, SNAPSHOT_EXPRESSION);
|
||
await scanLoadedPage(sess, snap, `Viewing ${title}`);
|
||
return snap;
|
||
}
|
||
|
||
async function closeSession(sessionId) {
|
||
const sess = sessions.get(String(sessionId));
|
||
if (!sess) return;
|
||
sessions.delete(String(sessionId));
|
||
stagePages.delete(sess.stageToken);
|
||
if (sess.idleTimer) clearTimeout(sess.idleTimer);
|
||
if (sess.screencastTimer) clearTimeout(sess.screencastTimer);
|
||
sess.screencastActive = false;
|
||
sess.active = false;
|
||
sess.status = 'idle';
|
||
sess.highlight = null;
|
||
sess.cursor = { ...sess.cursor, visible: false, clicking: false, label: null };
|
||
if (sess.cdp && !sess.cdp.closed) {
|
||
try { await sess.cdp.call('Browser.close', {}, 400); } catch {}
|
||
}
|
||
try { sess.cdp?.close(); } catch {}
|
||
if (sess.proc) {
|
||
const pid = sess.proc.pid;
|
||
try { sess.proc.kill(); } catch {}
|
||
if (process.platform === 'win32' && Number.isInteger(pid) && pid > 0 && sess.proc.exitCode === null) {
|
||
let alive = false;
|
||
try { process.kill(pid, 0); alive = true; } catch { alive = false; }
|
||
if (alive) {
|
||
try { spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 5000 }); } catch {}
|
||
}
|
||
}
|
||
}
|
||
if (sess.profileDir) {
|
||
const userDataDir = sess.profileDir;
|
||
setTimeout(() => { try { rmSync(userDataDir, { recursive: true, force: true }); } catch {} }, 800).unref?.();
|
||
setTimeout(() => { try { rmSync(userDataDir, { recursive: true, force: true }); } catch {} }, 3000).unref?.();
|
||
}
|
||
emit(sess, false);
|
||
}
|
||
|
||
return {
|
||
available() {
|
||
return findBrowserImpl();
|
||
},
|
||
|
||
getStagePage(stageToken) {
|
||
return stagePages.get(String(stageToken)) ?? null;
|
||
},
|
||
|
||
getState(sessionId) {
|
||
const sess = sessions.get(String(sessionId));
|
||
return sess ? publicView(sess, true) : null;
|
||
},
|
||
|
||
async close(sessionId) {
|
||
if (sessionId) await closeSession(sessionId);
|
||
else await Promise.allSettled([...sessions.keys()].map(id => closeSession(id)));
|
||
},
|
||
|
||
async search(sessionId, { query, maxResults = 8 }, signal) {
|
||
const q = String(query ?? '').trim();
|
||
if (!q) throw new Error('Provide a search query.');
|
||
const sess = await ensureSession(sessionId);
|
||
sess.status = 'browsing';
|
||
addStep(sess, 'search', `Searching "${q.slice(0, 48)}"`);
|
||
emit(sess, false);
|
||
const found = await searcher.search({ query: q, maxResults }, signal);
|
||
const sources = found.sources ?? [];
|
||
const html = renderSearchResultsHtml(q, sources);
|
||
stagePages.set(sess.stageToken, { sessionId: sess.sessionId, html, title: `${q} — Search` });
|
||
sess.isLocalStage = false;
|
||
sess.stageHtml = null;
|
||
sess.displayUrl = `search://${q}`;
|
||
sess.title = `${q} — Web Search`;
|
||
sess.consoleErrors = [];
|
||
await sess.cdp.send('Page.navigate', { url: stageUrlFor(sess, q) });
|
||
await waitForLoad(sess, 4000);
|
||
const snap = await evaluate(sess, SNAPSHOT_EXPRESSION);
|
||
await scanLoadedPage(sess, snap, `Results for "${q.slice(0, 28)}"`);
|
||
return {
|
||
query: q,
|
||
sources,
|
||
snapshot: snap,
|
||
text: formatSnapshotForModel(snap, sess.consoleErrors),
|
||
};
|
||
},
|
||
|
||
async open(sessionId, { url, html, title, workspacePath = null }) {
|
||
const sess = await ensureSession(sessionId);
|
||
if (typeof html === 'string' && html.trim()) {
|
||
const snap = await openStageHtml(sess, { html, title: title || 'HTML Design', stepLabel: `Opened ${title || 'HTML preview'}` });
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
}
|
||
const raw = String(url ?? '').trim();
|
||
if (workspacePath && raw && !/^https?:\/\//i.test(raw)) {
|
||
const root = realpathSync(workspacePath);
|
||
const candidate = resolve(root, raw);
|
||
if (existsSync(candidate)) {
|
||
const real = realpathSync(candidate);
|
||
if ((real === root || real.startsWith(root + sep)) && /\.html?$/i.test(extname(real))) {
|
||
const fileHtml = readFileSync(real, 'utf8');
|
||
const snap = await openStageHtml(sess, { html: fileHtml, title: title || raw, filePath: raw, stepLabel: `Opened ${raw}` });
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
}
|
||
}
|
||
}
|
||
const checked = validateBrowserTarget(raw, {
|
||
hostPort: typeof hostPort === 'function' ? hostPort() : hostPort,
|
||
forbiddenPorts: typeof forbiddenPorts === 'function' ? forbiddenPorts() : forbiddenPorts,
|
||
workspacePath,
|
||
});
|
||
sess.isLocalStage = false;
|
||
sess.stageHtml = null;
|
||
sess.url = checked.url;
|
||
sess.displayUrl = checked.displayUrl;
|
||
sess.status = 'browsing';
|
||
sess.consoleErrors = [];
|
||
sess.highlight = null;
|
||
addStep(sess, 'open', `Opening ${checked.displayUrl.slice(0, 60)}`);
|
||
emit(sess, false);
|
||
await sess.cdp.send('Page.navigate', { url: checked.url });
|
||
await waitForLoad(sess, 9000);
|
||
const snap = await evaluate(sess, SNAPSHOT_EXPRESSION);
|
||
if (snap) {
|
||
sess.title = snap.title || sess.title;
|
||
sess.url = snap.url || sess.url;
|
||
sess.displayUrl = snap.url || sess.displayUrl;
|
||
}
|
||
await scanLoadedPage(sess, snap, 'Reading page');
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async snapshot(sessionId) {
|
||
const sess = await ensureSession(sessionId);
|
||
const snap = await takeSnapshot(sess);
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors), frame: sess.frame };
|
||
},
|
||
|
||
async hover(sessionId, { ref, x, y }) {
|
||
const sess = await ensureSession(sessionId);
|
||
sess.status = 'inspecting';
|
||
const target = await resolveTarget(sess, { ref, x, y });
|
||
const desc = target.label ? `"${target.label.slice(0, 32)}"` : `@${target.ref}`;
|
||
addStep(sess, 'hover', `Checking ${desc}`);
|
||
await glideCursor(sess, target, `Checking ${desc}${target.ref ? ` · @${target.ref}` : ''}`, 'inspect');
|
||
const snap = await takeSnapshot(sess);
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async click(sessionId, { ref, x, y, mode = 'manual' }) {
|
||
const sess = await ensureSession(sessionId);
|
||
sess.status = 'browsing';
|
||
const target = await resolveTarget(sess, { ref, x, y });
|
||
if (mode === 'plan' && (target.tag === 'button' || target.type === 'submit') && !sess.isLocalStage) {
|
||
throw new Error('Plan (read-only) mode blocks submitting external buttons or forms.');
|
||
}
|
||
const prevUrl = sess.url;
|
||
const desc = target.label ? `"${target.label.slice(0, 32)}"` : `@${target.ref}`;
|
||
addStep(sess, 'click', `Clicking ${desc}`);
|
||
const { cx, cy } = await glideCursor(sess, target, `Clicking ${desc}${target.ref ? ` · @${target.ref}` : ''}`, 'inspect');
|
||
sess.cursor = { ...sess.cursor, clicking: true, clickSeq: (sess.cursor.clickSeq ?? 0) + 1 };
|
||
emit(sess, false);
|
||
await sess.cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: cx, y: cy, button: 'left', clickCount: 1 });
|
||
await sleep(90);
|
||
await sess.cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: cx, y: cy, button: 'left', clickCount: 1 });
|
||
if (animationDelayMs > 50) await sleep(Math.min(animationDelayMs, 260));
|
||
sess.cursor = { ...sess.cursor, clicking: false };
|
||
await waitForLoad(sess, 4500);
|
||
const snap = await takeSnapshot(sess);
|
||
if (snap?.url && snap.url !== prevUrl && !sess.isLocalStage) {
|
||
sess.highlight = null;
|
||
await scanLoadedPage(sess, snap, null);
|
||
}
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async type(sessionId, { ref, text, submit = false, clear = true, mode = 'manual' }) {
|
||
const sess = await ensureSession(sessionId);
|
||
if (mode === 'plan' && !sess.isLocalStage) {
|
||
throw new Error('Plan (read-only) mode blocks typing into external web forms.');
|
||
}
|
||
sess.status = 'browsing';
|
||
const target = await resolveTarget(sess, { ref });
|
||
if (target.type === 'password') {
|
||
throw new Error('Typing into password fields is blocked for safety.');
|
||
}
|
||
const desc = target.label ? `"${target.label.slice(0, 28)}"` : `@${target.ref}`;
|
||
addStep(sess, 'type', `Typing into ${desc}`);
|
||
const { cx, cy } = await glideCursor(sess, target, `Typing in ${desc}`, 'inspect');
|
||
await sess.cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: cx, y: cy, button: 'left', clickCount: 1 });
|
||
await sess.cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: cx, y: cy, button: 'left', clickCount: 1 });
|
||
if (clear && target.ref) {
|
||
await evaluate(sess, `(() => {
|
||
const el = document.querySelector('[data-strata-ref="${target.ref}"]');
|
||
if (el && ('value' in el)) { el.focus(); el.value = ''; el.dispatchEvent(new Event('input', { bubbles: true })); }
|
||
})()`);
|
||
}
|
||
await sess.cdp.send('Input.insertText', { text: String(text ?? '') });
|
||
if (submit) {
|
||
const enter = keySpec('Enter');
|
||
await sess.cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', ...enter });
|
||
await sess.cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', ...enter });
|
||
await waitForLoad(sess, 5000);
|
||
} else {
|
||
await sleep(160);
|
||
}
|
||
const snap = await takeSnapshot(sess);
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async press(sessionId, { key }) {
|
||
const sess = await ensureSession(sessionId);
|
||
const spec = keySpec(key);
|
||
if (/^(PageDown|PageUp|ArrowDown|ArrowUp|Home|End| )$/i.test(spec.key)) {
|
||
sess.highlight = null;
|
||
}
|
||
addStep(sess, 'press', `Pressing ${spec.key}`);
|
||
await sess.cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', ...spec });
|
||
await sess.cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', ...spec });
|
||
await sleep(220);
|
||
const snap = await takeSnapshot(sess);
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async scroll(sessionId, { direction = 'down', amount = 520, ref = null }) {
|
||
const sess = await ensureSession(sessionId);
|
||
if (ref) {
|
||
const target = await resolveTarget(sess, { ref });
|
||
addStep(sess, 'scroll', `Scrolling to @${target.ref}`);
|
||
await glideCursor(sess, target, `Scrolled to @${target.ref}`, 'inspect');
|
||
} else {
|
||
sess.highlight = null;
|
||
const dy = direction === 'up' ? -Math.abs(amount) : direction === 'top' ? -999999 : direction === 'bottom' ? 999999 : Math.abs(amount);
|
||
addStep(sess, 'scroll', `Scrolling ${direction}`);
|
||
await evaluate(sess, `window.scrollBy({ top: ${Number(dy)}, behavior: 'instant' })`);
|
||
await sleep(200);
|
||
}
|
||
const snap = await takeSnapshot(sess);
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async setViewport(sessionId, { preset = 'desktop', width, height }) {
|
||
const sess = await ensureSession(sessionId);
|
||
const base = VIEWPORT_PRESETS[preset] ?? VIEWPORT_PRESETS.desktop;
|
||
const w = Number.isInteger(width) && width >= 320 && width <= 1920 ? width : base.width;
|
||
const h = Number.isInteger(height) && height >= 320 && height <= 1600 ? height : base.height;
|
||
sess.viewport = { width: w, height: h, preset: VIEWPORT_PRESETS[preset] ? preset : 'custom' };
|
||
addStep(sess, 'viewport', `Viewport ${w}×${h} (${sess.viewport.preset})`);
|
||
await sess.cdp.send('Emulation.setDeviceMetricsOverride', {
|
||
width: w,
|
||
height: h,
|
||
deviceScaleFactor: 1,
|
||
mobile: preset === 'mobile' || preset === 'tablet' || w < 768,
|
||
});
|
||
await sleep(220);
|
||
const snap = await takeSnapshot(sess);
|
||
return { snapshot: snap, text: formatSnapshotForModel(snap, sess.consoleErrors) };
|
||
},
|
||
|
||
async inspectDesign(sessionId) {
|
||
const sess = await ensureSession(sessionId);
|
||
sess.status = 'inspecting';
|
||
addStep(sess, 'inspect', `Auditing layout & contrast (${sess.viewport.width}×${sess.viewport.height})`);
|
||
emit(sess, false);
|
||
await evaluate(sess, SNAPSHOT_EXPRESSION);
|
||
const audit = await evaluate(sess, DESIGN_AUDIT_EXPRESSION);
|
||
const sweepTargets = [
|
||
...(audit?.issues ?? []).slice(0, 3).map(i => ({
|
||
label: i.kind === 'low-contrast' ? 'Contrast issue' : i.kind === 'horizontal-overflow' ? 'Overflow detected' : 'Checking issue',
|
||
tone: 'warn',
|
||
rect: i.rect,
|
||
})),
|
||
...(audit?.regions ?? []).slice(0, 3).map(r => ({
|
||
label: `Checking ${r.label.toLowerCase()}`,
|
||
tone: 'inspect',
|
||
rect: r.rect,
|
||
})),
|
||
].slice(0, 4);
|
||
|
||
for (const item of sweepTargets) {
|
||
if (!item.rect) continue;
|
||
const center = {
|
||
x: Math.round(item.rect.x + item.rect.width / 2),
|
||
y: Math.round(item.rect.y + Math.min(item.rect.height, 140) / 2),
|
||
};
|
||
await glideCursor(sess, { rect: item.rect, center }, item.label, item.tone);
|
||
}
|
||
|
||
sess.highlight = audit?.issues?.[0]?.rect
|
||
? { ...audit.issues[0].rect, label: audit.issues[0].summary.slice(0, 48), tone: 'warn' }
|
||
: { x: 16, y: 16, width: sess.viewport.width - 32, height: Math.min(80, sess.viewport.height - 32), label: 'Visual audit passed', tone: 'ok' };
|
||
|
||
await captureFrame(sess);
|
||
const llmFrame = await captureLlmFrame(sess);
|
||
emit(sess, true);
|
||
return {
|
||
audit,
|
||
frame: sess.frame,
|
||
llmFrame,
|
||
text: formatDesignAuditForModel(audit, sess.consoleErrors),
|
||
};
|
||
},
|
||
|
||
async updateHtml(sessionId, { html, title = 'Improved Design', filePath = null, workspacePath = null, mode = 'manual' }) {
|
||
const content = String(html ?? '');
|
||
if (!content.trim()) throw new Error('Provide the updated HTML content.');
|
||
const sess = await ensureSession(sessionId);
|
||
sess.status = 'updating';
|
||
let savedRelative = null;
|
||
if (filePath && workspacePath && mode !== 'plan') {
|
||
const root = realpathSync(workspacePath);
|
||
const full = resolve(root, String(filePath));
|
||
const parent = resolve(full, '..');
|
||
if ((full === root || full.startsWith(root + sep)) && existsSync(parent)) {
|
||
writeFileSync(full, content, 'utf8');
|
||
savedRelative = String(filePath);
|
||
}
|
||
}
|
||
const snap = await openStageHtml(sess, {
|
||
html: content,
|
||
title,
|
||
filePath: savedRelative,
|
||
stepLabel: `Updated ${savedRelative || title}`,
|
||
});
|
||
const audit = await evaluate(sess, DESIGN_AUDIT_EXPRESSION);
|
||
await captureFrame(sess);
|
||
emit(sess, true);
|
||
return {
|
||
snapshot: snap,
|
||
audit,
|
||
savedFile: savedRelative,
|
||
frame: sess.frame,
|
||
text: [
|
||
`Live HTML updated in sidebar (${title}${savedRelative ? ` -> ${savedRelative}` : ''}).`,
|
||
formatDesignAuditForModel(audit, sess.consoleErrors),
|
||
'',
|
||
formatSnapshotForModel(snap, sess.consoleErrors),
|
||
].join('\n'),
|
||
};
|
||
},
|
||
};
|
||
}
|