An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(page): register the new tools and enrich page info and screenshots
Shahriar2fbecd897bc9
diff --git a/lib/actions/page/click-element.ts b/lib/actions/page/click-element.tsindex f049a42..2e897b9 100644--- a/lib/actions/page/click-element.ts+++ b/lib/actions/page/click-element.ts@@ -1,6 +1,6 @@import { z } from 'zod';import { defineAction } from '../core';-import { describeElement, resolveTarget, targetSchema } from './dom';+import { describeElement, resolveTarget, submitsOnClick, targetSchema } from './dom';export const clickElement = defineAction({name: 'page.clickElement',@@ -16,10 +16,7 @@ export const clickElement = defineAction({el.focus({ preventScroll: true });} catch {}- const submits =- !!el.closest('form') &&- ((el instanceof HTMLButtonElement && el.type === 'submit') ||- (el instanceof HTMLInputElement && (el.type === 'submit' || el.type === 'image')));+ const submits = submitsOnClick(el);const init = { bubbles: true, cancelable: true, composed: true };el.dispatchEvent(new PointerEvent('pointerdown', init));el.dispatchEvent(new MouseEvent('mousedown', init));diff --git a/lib/actions/page/dom.ts b/lib/actions/page/dom.tsindex a04416e..85ccb2f 100644--- a/lib/actions/page/dom.ts+++ b/lib/actions/page/dom.ts@@ -23,11 +23,55 @@ const ROLE_TAGS: Record<string, string[]> = {heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],};+const ROLE_BY_INPUT_TYPE: Record<string, string> = {+ button: 'button',+ submit: 'button',+ reset: 'button',+ image: 'button',+ file: 'button',+ checkbox: 'checkbox',+ radio: 'radio',+ range: 'slider',+ number: 'spinbutton',+ search: 'searchbox',+};++const ROLE_BY_TAG: Record<string, string> = {+ button: 'button',+ select: 'combobox',+ textarea: 'textbox',+ summary: 'button',+ option: 'option',+ h1: 'heading',+ h2: 'heading',+ h3: 'heading',+ h4: 'heading',+ h5: 'heading',+ h6: 'heading',+ nav: 'navigation',+ main: 'main',+ header: 'banner',+ footer: 'contentinfo',+ aside: 'complementary',+ form: 'form',+ dialog: 'dialog',+};++const VALUELESS_INPUT = new Set(['button', 'submit', 'reset', 'image', 'checkbox', 'radio', 'file']);++export function computedRole(el: Element): string | undefined {+ const explicit = el.getAttribute('role')?.trim().split(/\s+/)[0];+ if (explicit) return explicit.toLowerCase();+ if (el instanceof HTMLInputElement) return ROLE_BY_INPUT_TYPE[el.type] ?? 'textbox';+ if (el instanceof HTMLAnchorElement) return el.getAttribute('href') === null ? undefined : 'link';+ return ROLE_BY_TAG[el.tagName.toLowerCase()];+}+function matchesRole(el: Element, role: string): boolean {const wanted = role.toLowerCase();const tag = el.tagName.toLowerCase();if (tag === wanted) return true;- if (el.getAttribute('role')?.toLowerCase() === wanted) return true;+ if (computedRole(el) === wanted) return true;return ROLE_TAGS[wanted]?.includes(tag) ?? false;}@@ -86,6 +130,60 @@ export function isVisible(el: Element): boolean {return style.visibility !== 'hidden' && style.display !== 'none';}+export function isExposed(el: Element): boolean {+ return isVisible(el) && !el.closest('[aria-hidden="true"],[inert]');+}++function ariaFlag(el: Element, name: string): boolean | undefined {+ const value = el.getAttribute(name);+ return value === 'true' ? true : value === 'false' ? false : undefined;+}++export interface ElementState {+ disabled?: boolean;+ checked?: boolean;+ expanded?: boolean;+ selected?: boolean;+ current?: string;+ required?: boolean;+ invalid?: boolean;+ filled?: boolean;+ value?: string;+}++export function elementState(el: Element): ElementState | undefined {+ const state: ElementState = {};+ if (el.matches(':disabled') || ariaFlag(el, 'aria-disabled')) state.disabled = true;++ const checked =+ el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')+ ? el.checked+ : ariaFlag(el, 'aria-checked');+ if (checked !== undefined) state.checked = checked;++ const expanded = ariaFlag(el, 'aria-expanded');+ if (expanded !== undefined) state.expanded = expanded;++ const selected = el instanceof HTMLOptionElement ? el.selected : ariaFlag(el, 'aria-selected');+ if (selected !== undefined) state.selected = selected;++ const current = el.getAttribute('aria-current');+ if (current && current !== 'false') state.current = current;++ if (el.matches(':required') || ariaFlag(el, 'aria-required')) state.required = true;+ if (ariaFlag(el, 'aria-invalid')) state.invalid = true;++ if (el instanceof HTMLSelectElement) {+ state.value = el.selectedOptions[0]?.text.replace(/\s+/g, ' ').trim().slice(0, 60) || undefined;+ } else if (el instanceof HTMLTextAreaElement) {+ state.filled = el.value.length > 0;+ } else if (el instanceof HTMLInputElement && !VALUELESS_INPUT.has(el.type)) {+ state.filled = el.value.length > 0;+ }++ return Object.values(state).some((value) => value !== undefined) ? state : undefined;+}+export function cssPath(el: Element): string {const path: string[] = [];for (let node: Element | null = el; node && node !== document.documentElement; node = node.parentElement) {@@ -116,8 +214,16 @@ export function describeElement(el: Element) {const text = accessibleText(el).slice(0, 80);return {tag: el.tagName.toLowerCase(),+ role: computedRole(el),selector: cssPath(el),text: text || undefined,+ state: elementState(el),bounds: documentBounds(el),};}++export function submitsOnClick(el: Element): boolean {+ if (!el.closest('form')) return false;+ if (el instanceof HTMLButtonElement) return el.type === 'submit';+ return el instanceof HTMLInputElement && (el.type === 'submit' || el.type === 'image');+}diff --git a/lib/actions/page/extract-text.ts b/lib/actions/page/extract-text.tsindex 9154c65..2115bff 100644--- a/lib/actions/page/extract-text.ts+++ b/lib/actions/page/extract-text.ts@@ -9,7 +9,13 @@ export const extractText = defineAction({description: 'Read the rendered text or raw HTML of an element or the whole page.',input: z.object({target: targetSchema.optional().describe('Element to read; defaults to the whole page'),- format: z.enum(['text', 'html']).default('text').describe('Plain rendered text or raw HTML'),+ format: z+ .enum(['text', 'html'])+ .default('text')+ .describe(+ 'Plain rendered text, or raw HTML. HTML is denied by default — it carries comments and hidden nodes ' ++ 'the reader never sees — and needs "raw-html-read": "allow" in the guardrail config.',+ ),maxLength: z.number().int()diff --git a/lib/actions/page/get-page-info.ts b/lib/actions/page/get-page-info.tsindex 29adcb5..3eb4de0 100644--- a/lib/actions/page/get-page-info.ts+++ b/lib/actions/page/get-page-info.ts@@ -1,12 +1,19 @@import { z } from 'zod';import { defineAction } from '../core';-import { accessibleText, cssPath, describeElement, documentBounds, isVisible } from './dom';+import { accessibleText, cssPath, describeElement, documentBounds, isExposed } from './dom';++interface Tally {+ links: number;+ buttons: number;+ fields: number;+}interface Region {role: string;label?: string;selector: string;bounds: { x: number; y: number; width: number; height: number };+ contains: Tally;children: Region[];}@@ -36,7 +43,7 @@ const LANDMARK_ROLES = new Set([export const getPageInfo = defineAction({name: 'page.getPageInfo',description:- 'Snapshot the current page: document metadata, viewport and scroll state, a semantic layout tree with a text diagram, the heading outline, and an inventory of interactive elements.',+ 'Snapshot the current page: document metadata, viewport and scroll state, a semantic layout tree with a text diagram, the heading outline, and an inventory of interactive elements — each carrying its ARIA role, its live state (disabled, checked, expanded, filled, aria-current) and the landmark region it sits in.',input: z.object({maxPerKind: z.number()@@ -46,7 +53,9 @@ export const getPageInfo = defineAction({.describe('Cap on links, buttons, fields, and forms listed per kind'),}),execute({ maxPerKind }) {- const regions = layoutTree();+ const { regions, owners } = layoutTree();+ const found = collect();+ tally(found, owners);return {document: {url: location.href,@@ -66,13 +75,13 @@ export const getPageInfo = defineAction({selection: getSelection()?.toString().slice(0, 500) || undefined,layout: { regions, diagram: renderDiagram(regions) },outline: [...document.querySelectorAll<HTMLElement>('h1,h2,h3,h4,h5,h6')]- .filter(isVisible)+ .filter(isExposed).slice(0, 60).map((heading) => ({level: Number(heading.tagName[1]),text: accessibleText(heading).slice(0, 120),})),- interactive: inventory(maxPerKind),+ interactive: inventory(found, owners, maxPerKind),};},});@@ -93,29 +102,42 @@ function regionLabel(el: HTMLElement): string | undefined {return heading?.textContent?.replace(/\s+/g, ' ').trim().slice(0, 60) || undefined;}-function layoutTree(): Region[] {+function layoutTree(): { regions: Region[]; owners: Map<HTMLElement, Region> } {const candidates = [...document.querySelectorAll<HTMLElement>('header,nav,main,aside,footer,form,section,dialog,[role]'),]- .filter((el) => regionRole(el) && isVisible(el))+ .filter((el) => regionRole(el) && isExposed(el)).slice(0, 40);- const roots: Region[] = [];- const known = new Map<HTMLElement, Region>();+ const regions: Region[] = [];+ const owners = new Map<HTMLElement, Region>();for (const el of candidates) {const region: Region = {role: regionRole(el)!,label: regionLabel(el),selector: cssPath(el),bounds: documentBounds(el),+ contains: { links: 0, buttons: 0, fields: 0 },children: [],};- known.set(el, region);+ owners.set(el, region);let ancestor = el.parentElement;- while (ancestor && !known.has(ancestor)) ancestor = ancestor.parentElement;- (ancestor ? known.get(ancestor)!.children : roots).push(region);+ while (ancestor && !owners.has(ancestor)) ancestor = ancestor.parentElement;+ (ancestor ? owners.get(ancestor)!.children : regions).push(region);+ }+ return { regions, owners };+}++function regionName(region: Region): string {+ return region.label ? `${region.role} “${region.label}”` : region.role;+}++function ownerOf(el: HTMLElement, owners: Map<HTMLElement, Region>): Region | undefined {+ for (let node = el.parentElement; node; node = node.parentElement) {+ const region = owners.get(node);+ if (region) return region;}- return roots;+ return undefined;}function renderDiagram(regions: Region[]): string {@@ -126,9 +148,13 @@ function renderDiagram(regions: Region[]): string {const walk = (nodes: Region[], indent: string) => {nodes.forEach((region, i) => {const last = i === nodes.length - 1;- const { role, label, bounds } = region;+ const { bounds, contains } = region;+ const counts = (['links', 'buttons', 'fields'] as const)+ .filter((kind) => contains[kind] > 0)+ .map((kind) => ` · ${contains[kind]} ${kind}`)+ .join('');lines.push(- `${indent}${last ? '└' : '├'} ${role}${label ? ` “${label}”` : ''} · ${bounds.width}×${bounds.height} @ (${bounds.x},${bounds.y})`,+ `${indent}${last ? '└' : '├'} ${regionName(region)} · ${bounds.width}×${bounds.height} @ (${bounds.x},${bounds.y})${counts}`,);walk(region.children, indent + (last ? ' ' : '│ '));});@@ -137,32 +163,63 @@ function renderDiagram(regions: Region[]): string {return lines.join('\n');}-function inventory(cap: number) {- const visible = (selector: string) =>- [...document.querySelectorAll<HTMLElement>(selector)].filter(isVisible);+function collect() {+ const exposed = <T extends HTMLElement>(selector: string) =>+ [...document.querySelectorAll<T>(selector)].filter(isExposed);+ return {+ links: exposed<HTMLAnchorElement>('a[href]'),+ buttons: exposed('button,[role="button"],input[type="button"],input[type="submit"]'),+ fields: exposed('input:not([type="hidden"]):not([type="button"]):not([type="submit"]),select,textarea'),+ forms: exposed<HTMLFormElement>('form'),+ };+}++function tally(found: ReturnType<typeof collect>, owners: Map<HTMLElement, Region>) {+ for (const kind of ['links', 'buttons', 'fields'] as const) {+ for (const el of found[kind]) {+ for (let node = el.parentElement; node; node = node.parentElement) {+ const owner = owners.get(node);+ if (owner) owner.contains[kind] += 1;+ }+ }+ }+}++function inventory(+ found: ReturnType<typeof collect>,+ owners: Map<HTMLElement, Region>,+ cap: number,+) {+ const regionFor = (el: HTMLElement) => {+ const owner = ownerOf(el, owners);+ return owner && regionName(owner);+ };return {- links: visible('a[href]')- .slice(0, cap)- .map((link) => ({- text: accessibleText(link).slice(0, 80),- href: (link as HTMLAnchorElement).href,- selector: cssPath(link),- })),- buttons: visible('button,[role="button"],input[type="button"],input[type="submit"]')- .slice(0, cap)- .map(describeElement),- fields: visible('input:not([type="hidden"]):not([type="button"]):not([type="submit"]),select,textarea')- .slice(0, cap)- .map((field) => ({- ...describeElement(field),- kind: field instanceof HTMLInputElement ? field.type : field.tagName.toLowerCase(),- })),- forms: visible('form')- .slice(0, cap)- .map((form) => ({- selector: cssPath(form),- action: form.getAttribute('action') || undefined,- method: (form.getAttribute('method') || 'get').toLowerCase(),- })),+ links: found.links.slice(0, cap).map((link) => ({+ ...describeElement(link),+ href: link.href,+ region: regionFor(link),+ })),+ buttons: found.buttons.slice(0, cap).map((button) => ({+ ...describeElement(button),+ region: regionFor(button),+ })),+ fields: found.fields.slice(0, cap).map((field) => ({+ ...describeElement(field),+ kind: field instanceof HTMLInputElement ? field.type : field.tagName.toLowerCase(),+ region: regionFor(field),+ })),+ forms: found.forms.slice(0, cap).map((form) => ({+ selector: cssPath(form),+ action: form.getAttribute('action') || undefined,+ method: (form.getAttribute('method') || 'get').toLowerCase(),+ region: regionFor(form),+ })),+ counts: {+ links: found.links.length,+ buttons: found.buttons.length,+ fields: found.fields.length,+ forms: found.forms.length,+ },};}diff --git a/lib/actions/page/screenshot.ts b/lib/actions/page/screenshot.tsindex 44230b6..756bea7 100644--- a/lib/actions/page/screenshot.ts+++ b/lib/actions/page/screenshot.ts@@ -5,37 +5,43 @@ import { documentBounds, resolveTarget, targetSchema } from './dom';export const screenshot = defineAction({name: 'page.screenshot',description:- 'Capture the tab as a PNG/JPEG image — the full scroll view, the current viewport, or a single targeted element. The image is saved under ~/browsentic/screenshot/ and the result reports the path as savedTo; pass save: false to capture without writing a file.',+ 'Capture the tab as a JPEG/PNG image — the current viewport by default, or the full scroll view, or a single targeted element. The viewport capture is the fast one: it is a single grab that returns in well under a second. fullPage: true has to scroll the page in viewport-sized steps and wait out the browser’s capture rate limit between each, so it costs a second or more per screenful — ask for it only when you need what is below the fold. Nothing is written to disk unless you pass save: true — the image comes back in the result either way, so a capture you take to look at the page for yourself leaves no file behind.',input: z.object({target: targetSchema.optional().describe('Capture only this element’s box (a specific block). When set, fullPage is ignored.'),fullPage: z.boolean()- .default(true)- .describe('With no target: true captures the entire scroll view, false only the current viewport.'),+ .default(false)+ .describe(+ 'With no target: false (the default) captures only the current viewport and is much faster; true captures the entire scroll view by tiling, which costs roughly a second per screenful.',+ ),format: z.enum(['png', 'jpeg'])- .default('png')- .describe('Image format. PNG is lossless; JPEG is smaller with slight artifacts and no transparency.'),+ .default('jpeg')+ .describe(+ 'Image format. JPEG (the default) is far smaller and quicker to encode; PNG is lossless and keeps transparency, at several times the size and time.',+ ),quality: z.number().int().min(1).max(100).optional()- .describe('JPEG quality, 1–100. Only valid when format is "jpeg".'),+ .describe('JPEG quality, 1–100, defaulting to 80. Only valid when format is "jpeg".'),maxLongSide: z.number().int().positive()- .default(4000)- .describe('Downscale the result so its longest side is at most this many pixels.'),+ .default(1600)+ .describe(+ 'Downscale the result so its longest side is at most this many pixels. The default is sized for reading a page, not for pixel-level inspection — raise it when fine detail matters.',+ ),save: z.boolean()- .default(true)+ .default(false).describe(- 'Write the image to ~/browsentic/screenshot/ (done by the local Browsentic daemon, which adds savedTo to the result). Set false to capture without touching the disk.',+ 'Write the image to ~/browsentic/screenshot/ and report the path as savedTo. Off by default: a capture you take to see the page for yourself is handed to you in the result and should leave nothing behind. Set true only when the user asked for a picture they can keep.',),filename: z.string()diff --git a/lib/actions/registry.ts b/lib/actions/registry.tsindex 96ad9e7..6967232 100644--- a/lib/actions/registry.ts+++ b/lib/actions/registry.ts@@ -1,12 +1,15 @@import { z } from 'zod';import type { AnyAction } from './core';import type { ToolDescriptor } from './manifest';+import { applyTheme } from './page/apply-theme';import { attachFile } from './page/attach-file';+import { auditContrast } from './page/audit-contrast';import { awaitMonitor } from './page/await-monitor';import { clickElement } from './page/click-element';import { closeTab } from './page/close-tab';import { extractText } from './page/extract-text';import { fillInput } from './page/fill-input';+import { findCaptcha } from './page/find-captcha';import { findProgress } from './page/find-progress';import { focusInput } from './page/focus-input';import { getPageInfo } from './page/get-page-info';@@ -19,14 +22,17 @@ import { navigate } from './page/navigate';import { openTab } from './page/open-tab';import { pressKey } from './page/press-key';import { readRecording } from './page/read-recording';+import { readTheme } from './page/read-theme';import { screenshot } from './page/screenshot';import { scrollTo } from './page/scroll-to';import { selectOption } from './page/select-option';import { selectText } from './page/select-text';+import { solveCaptcha } from './page/solve-captcha';import { startMonitor } from './page/start-monitor';import { stopMonitor } from './page/stop-monitor';import { submitForm } from './page/submit-form';import { switchTab } from './page/switch-tab';+import { trustedClick } from './page/trusted-click';import { typeText } from './page/type-text';import { waitForElement } from './page/wait-for-element';@@ -36,6 +42,9 @@ export const actions: ReadonlyMap<string, AnyAction> = new Map(getPageInfo,scrollTo,clickElement,+ trustedClick,+ findCaptcha,+ solveCaptcha,hoverElement,focusInput,fillInput,@@ -47,6 +56,9 @@ export const actions: ReadonlyMap<string, AnyAction> = new Map(submitForm,waitForElement,findProgress,+ readTheme,+ auditContrast,+ applyTheme,startMonitor,monitorStatus,awaitMonitor,diff --git a/lib/bridge/invoke.ts b/lib/bridge/invoke.tsindex 0918756..46d07a7 100644--- a/lib/bridge/invoke.ts+++ b/lib/bridge/invoke.ts@@ -5,6 +5,7 @@ import { ActionError } from '@/lib/actions/core';import { attachFile } from '@/lib/actions/page/attach-file';import { awaitMonitor } from '@/lib/actions/page/await-monitor';import { closeTab } from '@/lib/actions/page/close-tab';+import { findCaptcha } from '@/lib/actions/page/find-captcha';import { listFiles } from '@/lib/actions/page/list-files';import { listRecordings } from '@/lib/actions/page/list-recordings';import { monitorStatus } from '@/lib/actions/page/monitor-status';@@ -12,14 +13,18 @@ import { navigate, resolveNavigation, type NavigateInput } from '@/lib/actions/pimport { openTab } from '@/lib/actions/page/open-tab';import { readRecording } from '@/lib/actions/page/read-recording';import { screenshot } from '@/lib/actions/page/screenshot';+import { solveCaptcha } from '@/lib/actions/page/solve-captcha';import { startMonitor } from '@/lib/actions/page/start-monitor';import { stopMonitor } from '@/lib/actions/page/stop-monitor';import { switchTab } from '@/lib/actions/page/switch-tab';+import { trustedClick } from '@/lib/actions/page/trusted-click';import { failure, success, type ActionResult } from '@/lib/actions/protocol';+import { findCaptchaInTab, solveCaptchaInTab } from '@/lib/bridge/captcha';import { listMeta, readBytes } from '@/lib/bridge/file-store';import { awaitMonitorDone, monitorStatusFor, startTabMonitor, stopTabMonitor } from '@/lib/bridge/monitor';import { listRecordings as listStoredMeta, readRecordingBody } from '@/lib/bridge/recording-store';import { screenshotTab } from '@/lib/bridge/screenshot';+import { trustedClickInTab } from '@/lib/bridge/trusted-input';import { closeOpenTab, openNewTab, switchToTab, watchForLoad } from '@/lib/bridge/tabs';export async function invokeForHarness(action: string, input?: unknown, tabId?: number): Promise<ActionResult> {@@ -43,6 +48,9 @@ export async function invokeForHarness(action: string, input?: unknown, tabId?:if (action === closeTab.name) return closeOpenTab({ id: tab.id, windowId: tab.windowId }, input);if (action === screenshot.name) return screenshotTab({ id: tab.id, windowId: tab.windowId }, input);if (action === attachFile.name) return attachStoredFile(tab.id, input);+ if (action === trustedClick.name) return trustedClickInTab(tab.id, input);+ if (action === findCaptcha.name) return findCaptchaInTab(tab.id);+ if (action === solveCaptcha.name) return solveCaptchaInTab(tab.id, input);return invokeInTab(tab.id, action, input);}diff --git a/lib/bridge/screenshot.ts b/lib/bridge/screenshot.tsindex 923f674..e92a0bb 100644--- a/lib/bridge/screenshot.ts+++ b/lib/bridge/screenshot.ts@@ -30,9 +30,9 @@ export async function screenshotTab(const plan = planned.data as CapturePlan;try {- const { thumbnail, ...data } = await capture(tab, plan);- await publishScreenshot({ ...data, thumbnail }).catch(() => {});- return success(data);+ const shot = await capture(tab, plan);+ void publishCapture(shot);+ return success(shot);} catch (error) {if (error instanceof ActionError) return failure(error.code, error.message);return failure('CAPTURE_FAILED', error instanceof Error ? error.message : String(error));@@ -44,17 +44,21 @@ export async function screenshotTab(}}-async function capture(- tab: { id: number; windowId?: number },- plan: CapturePlan,-): Promise<{+interface Shot {format: string;width: number;height: number;dataUrl: string;truncated?: boolean;- thumbnail: string;-}> {+}++async function publishCapture(shot: Shot): Promise<void> {+ try {+ await publishScreenshot({ ...shot, thumbnail: await thumbnailOf(shot.dataUrl) });+ } catch {}+}++async function capture(tab: { id: number; windowId?: number }, plan: CapturePlan): Promise<Shot> {const { viewport, format, quality, maxLongSide } = plan;const region = { ...plan.region };@@ -73,12 +77,14 @@ async function capture(const xs = tileStarts(region.x, region.w, viewport.w);const ys = tileStarts(region.y, region.h, viewport.h);+ const singleTile = xs.length === 1 && ys.length === 1 && plan.mode === 'viewport';+let ctx: OffscreenCanvasRenderingContext2D | null = null;let out: OffscreenCanvas | null = null;let scale = 1;let outScale = 1;+ let lastCaptureAt = 0;- let first = true;for (const y of ys) {for (const x of xs) {const scrolled = await invokeInTab(tab.id, 'page.scrollTo', {@@ -88,15 +94,24 @@ async function capture(if (!scrolled.ok) throw new ActionError(scrolled.error.message, scrolled.error.code);const at = scrolled.data as { scrollX: number; scrollY: number };- if (!first) await delay(CAPTURE_INTERVAL_MS);- first = false;+ const sinceLast = Date.now() - lastCaptureAt;+ if (lastCaptureAt && sinceLast < CAPTURE_INTERVAL_MS) await delay(CAPTURE_INTERVAL_MS - sinceLast);- const bitmap = await captureViewport(tab.windowId, format, quality);+ const shot = await captureViewport(tab.windowId, format, quality);+ lastCaptureAt = Date.now();+ const bitmap = shot.bitmap;if (!out) {const capScale = bitmap.width / viewport.w || plan.dpr || 1;outScale = fitScale(region.w * capScale, region.h * capScale, maxLongSide);scale = capScale * outScale;++ if (singleTile && outScale === 1) {+ const { width, height } = bitmap;+ bitmap.close();+ return { format, width, height, dataUrl: shot.dataUrl, ...(truncated ? { truncated } : {}) };+ }+out = new OffscreenCanvas(Math.max(1, Math.round(region.w * scale)),Math.max(1, Math.round(region.h * scale)),@@ -120,33 +135,40 @@ async function capture(}if (!out) throw new ActionError('Nothing was captured', 'CAPTURE_FAILED');- return { ...(await encode(out, format, quality, truncated)), thumbnail: await thumbnail(out) };+ return encode(out, format, quality, truncated);}const THUMB_MAX_SIDE = 640;const THUMB_QUALITY = 0.6;-async function thumbnail(source: OffscreenCanvas): Promise<string> {+async function thumbnailOf(dataUrl: string): Promise<string> {+ const source = await createImageBitmap(await (await fetch(dataUrl)).blob());const scale = Math.min(1, THUMB_MAX_SIDE / Math.max(source.width, source.height, 1));const small = new OffscreenCanvas(Math.max(1, Math.round(source.width * scale)),Math.max(1, Math.round(source.height * scale)),);const ctx = small.getContext('2d');- if (!ctx) return '';+ if (!ctx) {+ source.close();+ return '';+ }ctx.drawImage(source, 0, 0, small.width, small.height);+ source.close();return blobToDataUrl(await small.convertToBlob({ type: 'image/jpeg', quality: THUMB_QUALITY }), 'image/jpeg');}+const DEFAULT_JPEG_QUALITY = 80;+async function encode(canvas: OffscreenCanvas,format: 'png' | 'jpeg',quality: number | undefined,truncated: boolean,-): Promise<{ format: string; width: number; height: number; dataUrl: string; truncated?: boolean }> {+): Promise<Shot> {const mime = format === 'jpeg' ? 'image/jpeg' : 'image/png';const blob = await canvas.convertToBlob(- format === 'jpeg' ? { type: mime, quality: (quality ?? 90) / 100 } : { type: mime },+ format === 'jpeg' ? { type: mime, quality: (quality ?? DEFAULT_JPEG_QUALITY) / 100 } : { type: mime },);const dataUrl = await blobToDataUrl(blob, mime);return { format, width: canvas.width, height: canvas.height, dataUrl, ...(truncated ? { truncated } : {}) };@@ -163,14 +185,15 @@ async function captureViewport(windowId: number | undefined,format: 'png' | 'jpeg',quality: number | undefined,-): Promise<ImageBitmap> {+): Promise<{ dataUrl: string; bitmap: ImageBitmap }> {+ const grade = format === 'jpeg' ? (quality ?? DEFAULT_JPEG_QUALITY) : undefined;for (let attempt = 0; ; attempt++) {try {const dataUrl =windowId == null- ? await browser.tabs.captureVisibleTab({ format, quality })- : await browser.tabs.captureVisibleTab(windowId, { format, quality });- return createImageBitmap(await (await fetch(dataUrl)).blob());+ ? await browser.tabs.captureVisibleTab({ format, quality: grade })+ : await browser.tabs.captureVisibleTab(windowId, { format, quality: grade });+ return { dataUrl, bitmap: await createImageBitmap(await (await fetch(dataUrl)).blob()) };} catch (error) {const message = error instanceof Error ? error.message : String(error);if (attempt < 2 && /MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND/i.test(message)) {