Files
Strata/app/host/server/visual-browser-tools.mjs
T

271 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Shared tool schemas, dispatcher, intent detector, and verb labels for Strata's Live Sidebar Visual Browser.
*
* Used identically by:
* 1. `visual-agent-loop.mjs` (standalone local/API chat turns when Harness is not installed)
* 2. `agent/visual-browser-mcp.mjs` -> `/api/visual-browser/call` (Agent Harness MCP turns)
*/
export const VISUAL_BROWSER_TOOLS = Object.freeze([
{
name: 'browser_search',
description: 'Search the web in the live sidebar browser and display clickable @e1..@eN results so you can open and verify sources visually.',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Search query words.' },
},
required: ['query'],
additionalProperties: false,
},
},
{
name: 'browser_open',
description: 'Open a URL (https://..., http://localhost:...), a workspace HTML file path, or "current_html" (loads the latest HTML page from this conversation) in the live sidebar browser.',
parameters: {
type: 'object',
properties: {
url: { type: 'string', description: 'URL to open, workspace relative .html path, or "current_html" to load the chat’s latest HTML page.' },
html: { type: 'string', description: 'Optional raw HTML document to load directly into the live browser stage.' },
title: { type: 'string', description: 'Optional title when loading raw HTML.' },
},
additionalProperties: false,
},
},
{
name: 'browser_snapshot',
description: 'Read the current page title, URL, @e1..@eN interactive elements with (x,y,w,h) coordinates, console errors, and visible text.',
parameters: {
type: 'object',
properties: {},
additionalProperties: false,
},
},
{
name: 'browser_click',
description: 'Move the visible mouse cursor smoothly to element @ref (e.g. "e2") or (x, y) and click it.',
parameters: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Element ref from browser_snapshot, such as "e1" or "e4".' },
x: { type: 'number', description: 'Optional viewport X coordinate if no ref is used.' },
y: { type: 'number', description: 'Optional viewport Y coordinate if no ref is used.' },
},
additionalProperties: false,
},
},
{
name: 'browser_hover',
description: 'Move the visible mouse cursor to element @ref (or x, y) to hover and highlight it in the sidebar.',
parameters: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Element ref from browser_snapshot, such as "e3".' },
x: { type: 'number', description: 'Optional viewport X coordinate.' },
y: { type: 'number', description: 'Optional viewport Y coordinate.' },
},
additionalProperties: false,
},
},
{
name: 'browser_type',
description: 'Click an input/textarea @ref, type text into it live, and optionally press Enter to submit.',
parameters: {
type: 'object',
properties: {
ref: { type: 'string', description: 'Input element ref from browser_snapshot, such as "e1".' },
text: { type: 'string', description: 'Text to type.' },
submit: { type: 'boolean', description: 'Press Enter after typing.' },
},
required: ['ref', 'text'],
additionalProperties: false,
},
},
{
name: 'browser_press',
description: 'Press a keyboard key in the live browser (Enter, Tab, Escape, ArrowDown, ArrowUp, PageDown, Space).',
parameters: {
type: 'object',
properties: {
key: { type: 'string', description: 'Key name such as Enter, Escape, Tab, ArrowDown, PageDown.' },
},
required: ['key'],
additionalProperties: false,
},
},
{
name: 'browser_scroll',
description: 'Scroll the live browser page up, down, top, bottom, or bring element @ref into view.',
parameters: {
type: 'object',
properties: {
direction: { type: 'string', enum: ['down', 'up', 'top', 'bottom'], description: 'Scroll direction.' },
amount: { type: 'number', description: 'Pixels to scroll (default 520).' },
ref: { type: 'string', description: 'Optional element ref to scroll into view.' },
},
additionalProperties: false,
},
},
{
name: 'browser_set_viewport',
description: 'Switch the live browser viewport size between desktop (1280x800), tablet (820x1080), and mobile (390x844) to verify responsive design.',
parameters: {
type: 'object',
properties: {
preset: { type: 'string', enum: ['desktop', 'tablet', 'mobile'], description: 'Viewport preset.' },
},
required: ['preset'],
additionalProperties: false,
},
},
{
name: 'browser_inspect_design',
description: 'Visually audit the open page in the sidebar: sweeps the cursor across key sections and checks WCAG text contrast, horizontal overflow, small tap targets, broken images, and console errors.',
parameters: {
type: 'object',
properties: {},
additionalProperties: false,
},
},
{
name: 'browser_update_html',
description: 'Render new or improved HTML live in the sidebar browser, run an instant visual layout/contrast check, and attach the updated HTML to the Preview panel.',
parameters: {
type: 'object',
properties: {
html: { type: 'string', description: 'Complete <!doctype html>...</html> document.' },
title: { type: 'string', description: 'Short title for the preview tab (e.g. "Refined Landing Page").' },
filePath: { type: 'string', description: 'Optional relative .html file path inside the workspace folder to save.' },
},
required: ['html'],
additionalProperties: false,
},
},
]);
export const VISUAL_BROWSER_VERBS = Object.freeze({
browser_search: ['Searching in the browser', 'Searched in the browser', "Couldn't search in the browser"],
browser_open: ['Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"],
browser_snapshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"],
browser_click: ['Clicking on the page', 'Clicked on the page', "Couldn't click on the page"],
browser_hover: ['Pointing at the page', 'Pointed at the page', "Couldn't point at the page"],
browser_type: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"],
browser_press: ['Pressing a key on the page', 'Pressed a key on the page', "Couldn't press the key"],
browser_scroll: ['Scrolling the page', 'Scrolled the page', "Couldn't scroll the page"],
browser_set_viewport: ['Resizing browser viewport', 'Resized browser viewport', "Couldn't resize viewport"],
browser_inspect_design: ['Inspecting page design', 'Inspected page design', "Couldn't inspect page design"],
browser_update_html: ['Updating live HTML preview', 'Updated live HTML preview', "Couldn't update HTML preview"],
});
export function visualToolLabel(name, args = {}, state = 'running') {
const tuple = VISUAL_BROWSER_VERBS[name] ?? ['Using the browser', 'Used the browser', 'The browser step failed'];
const verb = state === 'error' ? tuple[2] : state === 'done' ? tuple[1] : tuple[0];
const rawTarget = args.query ?? args.url ?? args.title ?? (args.ref ? `@${String(args.ref).replace(/^@/, '')}` : '') ?? args.preset ?? args.direction ?? args.key ?? '';
const target = String(rawTarget ?? '').trim().slice(0, 120);
return { verb, target };
}
/** Extract the newest complete HTML document from chat history (`\`\`\`html ... \`\`\`` or raw `<!doctype html>`) when `url === "current_html"`. */
export function extractLatestHtmlFromHistory(history = [], currentStageHtml = null) {
if (typeof currentStageHtml === 'string' && currentStageHtml.trim()) return currentStageHtml;
const items = Array.isArray(history) ? [...history].reverse() : [];
for (const msg of items) {
const text = typeof msg?.content === 'string'
? msg.content
: Array.isArray(msg?.content)
? msg.content.map(p => (typeof p?.text === 'string' ? p.text : '')).join('\n')
: '';
if (!text) continue;
const blocks = [...text.matchAll(/```(?:html|htm)\s*\n([\s\S]*?)```/gi)];
if (blocks.length) {
const candidate = blocks.at(-1)[1].trim();
if (candidate.includes('<')) return candidate;
}
const rawDoc = text.match(/(<!doctype html[\s\S]*<\/html>)/i);
if (rawDoc) return rawDoc[1].trim();
}
return null;
}
/**
* Decide whether a standalone turn (when Harness is not installed) should engage the visual browser tool loop.
* Keeps ordinary Q&A turns zero-overhead while activating automatically on web search, URL browsing,
* or visual HTML/website inspection & design iteration requests.
*/
export function shouldUseVisualBrowser({ message = '', history = [], hasActiveBrowser = false, explicit = false } = {}) {
if (explicit) return true;
const text = String(message ?? '').trim();
if (!text || text.startsWith('/')) return false;
if (/https?:\/\/[^\s)]+/i.test(text)) return true;
if (/\b(search\s+(for|the\s+web|online|on\s+the\s+web)|look\s+up\s+online|browse\s+to|go\s+to\s+[a-z0-9.-]+\.[a-z]{2,}|open\s+(the\s+)?(website|webpage|page|url|browser|in\s+sidebar)|in\s+the\s+browser)\b/i.test(text)) {
return true;
}
if (/\b(visually\s+(improve|check|inspect|test|audit|fix|refine|redesign|review)|improve\s+(the\s+|this\s+)?(website|html|page|ui|landing\s+page|design)|redesign\s+(the\s+|this\s+)?(html|page|website)|check\s+(the\s+)?(contrast|layout|mobile\s+view|responsive|design)\s+(in|of|on))\b/i.test(text)) {
return true;
}
if (hasActiveBrowser && /\b(click|scroll|hover|type|mobile|desktop|tablet|contrast|header|button|hero|navbar|footer|page|link|tab|result|design|html|css|layout)\b/i.test(text)) {
return true;
}
const hasPriorHtml = Boolean(extractLatestHtmlFromHistory(history));
if (hasPriorHtml && /\b(visual|sidebar|preview|inspect|browser|responsive|mobile|contrast|redesign|make\s+it\s+look\s+better|improve\s+the\s+design)\b/i.test(text)) {
return true;
}
return false;
}
/** Execute one `browser_*` tool call against `visualBrowser` manager. */
export async function executeVisualBrowserTool(visualBrowser, {
sessionId,
name,
args = {},
workspacePath = null,
mode = 'manual',
history = [],
savedHtml = null,
signal,
}) {
const cleanName = String(name ?? '').replace(/^mcp__(?:strata-visual-browser|browser)__/, '');
switch (cleanName) {
case 'browser_search':
return visualBrowser.search(sessionId, { query: args.query, maxResults: 8 }, signal);
case 'browser_open':
case 'browser_navigate': {
const rawUrl = String(args.url ?? '').trim();
if ((rawUrl === 'current_html' || (!rawUrl && !args.html)) && !args.html) {
const existingState = visualBrowser.getState(sessionId);
const latestHtml = extractLatestHtmlFromHistory(history, existingState?.stageHtml ?? savedHtml ?? null);
if (!latestHtml) throw new Error('No HTML page was found in this conversation yet. Pass `url` or `html`, or use `browser_update_html` to create one.');
return visualBrowser.open(sessionId, { html: latestHtml, title: args.title || 'Current HTML Design', workspacePath });
}
return visualBrowser.open(sessionId, { url: rawUrl, html: args.html, title: args.title, workspacePath });
}
case 'browser_snapshot':
return visualBrowser.snapshot(sessionId);
case 'browser_click':
return visualBrowser.click(sessionId, { ref: args.ref, x: args.x, y: args.y, mode });
case 'browser_hover':
return visualBrowser.hover(sessionId, { ref: args.ref, x: args.x, y: args.y });
case 'browser_type':
return visualBrowser.type(sessionId, { ref: args.ref, text: args.text, submit: args.submit === true, mode });
case 'browser_press':
case 'browser_press_key':
return visualBrowser.press(sessionId, { key: args.key });
case 'browser_scroll':
return visualBrowser.scroll(sessionId, { direction: args.direction, amount: args.amount, ref: args.ref });
case 'browser_set_viewport':
return visualBrowser.setViewport(sessionId, { preset: args.preset });
case 'browser_inspect_design':
return visualBrowser.inspectDesign(sessionId);
case 'browser_update_html':
return visualBrowser.updateHtml(sessionId, {
html: args.html,
title: args.title || 'Improved HTML Design',
filePath: args.filePath ?? null,
workspacePath,
mode,
});
default:
throw new Error(`Unknown visual browser tool: ${cleanName}`);
}
}