diff --git a/.memory/browser-react-grab.md b/.memory/browser-react-grab.md new file mode 100644 index 0000000000..e4e0f5c1b7 --- /dev/null +++ b/.memory/browser-react-grab.md @@ -0,0 +1,32 @@ +# Browser Element Grab (React Grab) + +Implemented 2026-11-22 for the embedded desktop Workspace Browser (`Environment → Browser`). + +## Architecture & Decisions + +- **Zero new preload IPC channels:** Reuses `browser:command` (`{ action: "grab", tabId, enabled, accent? }`) and `browser:event` (`grab`, `grab-ended`, `shortcut: "grab"`). +- **Zero Remote protocol revision required:** Stores structured metadata on `ChatMessage.grabbedElements?: GrabbedElementContextV1[]` (`renderer/shared/browser-element-grab.ts`) paired with an optional standard `kind: "image"` attachment whose id is `grab-thumb_`. + - Desktop `MessageAttachments` filters out `grab-thumb_*` via `withoutGrabbedElementThumbnails()`, while `MessageBubble` renders read-only `` pairing each element with its thumbnail by `thumbnailAttachmentId`. + - Paired iOS/Android clients continue to see the user message plus the cropped PNG image attachment without breaking `AttachmentKind`. +- **In-page grab runtime & loopback-only source maps:** + - Injected into the guest `WebContentsView` main world via `executeJavaScript` (works alongside open DevTools, CSP-immune via Closed Shadow DOM + inline `el.style`, zero page-context network calls). + - Supports React 16–19 (including React 19 `_debugStack` + RSC `_debugOwner`), Vue, Svelte, Astro, Preact, Solid, Angular, and plain HTML/CSS via getter-safe `Object.getOwnPropertyDescriptor` reads. + - `ArrowUp`/`ArrowDown` component-tree stepping, `Shift+Click` multi-grab (`keepActive: true`), `F` animation freeze, 2-rAF overlay hide before screenshot capture, and unstoppable Escape via main's `before-input-event`. + - Main-process Base64-VLQ source-map symbolication (`main/services/browser/grab-source-map.ts`) fetches only from the authoritative page's exact loopback origin (scheme, host, port), or `file://` only for a `file://` page with a workspace root and realpath containment, with `redirect: "error"`, 1500ms timeout, and LRU caching (2026-11-24, Pullfrog finding). + - While grabbing, every iframe/frame/embed gets inline `pointer-events: none !important` (`FrameShield` in `grab-runtime/index.ts`) so frame input lands on the top document and is suppressed; hit tests lift the shield synchronously to descend into same-origin frames. Props drop `value`/`defaultValue` always and all text on credential fields (`sensitiveTarget`). + - The shield's `MutationObserver` watches the document and every open shadow root its scans find, so frames added later inside a shadow tree are shielded too. A shadow root attached after the grab starts raises no mutation, so `pointerover`/`pointermove` run `FrameShield.adopt` on the event's innermost target (and the hit-test result) as a backstop: it walks up through shadow hosts and same-origin frames, shields any top-document frame and watches any unwatched open shadow root before the pointer reaches the frame (2026-11-24, Pullfrog finding; E2E in `browser-grab.spec.ts` frames test). + - Each overlay frame wait is capped at 100 ms (`nextFrame` in `overlay.ts`). The cap is a bound on a wait that could otherwise never end on a page that does not paint, not a fix for any observed failure. Grab takes no background-throttling lease of its own (the one added in cf57b0bb4 came from a disproven hypothesis and was removed); thumbnail capture takes its own lease. Region screenshots read the viewport in the isolated CDP world, not the page's main world. + - The service records the page URL when a grab starts (`tab.grab.pageUrl`) and passes it to `sanitizeRawGrabPayload` as `grabPageUrl`. If the page has since moved to another source authority (`sameGrabSourceAuthority` in `grab-source-map.ts`), no source hint is resolved or reported, so a stale stack is never judged against the new origin. A same-origin route change keeps the hints. + - The macOS-only E2E failure of the DevTools step (2026-11-24) was the test clicking #secret-form below the fold on the smaller hosted-runner display (the off-viewport click hit nothing, so the grab stayed active); the E2E now scrolls each target into view first. Reproduce by shrinking the main window to about 560px tall. + - Main-process thumbnail capture (`grab-thumbnail.ts`) clamps to viewport, handles Retina/zoom scaling, masks credential fields (`credential-fields.ts` + `credential-mask.ts`), and resizes to <= 640px / <= 512 KiB. + - In-page highlight color follows active Aiden `--fill-accent` / `--fill-accent-foreground` with automatic `#006AD6` / `#FFFFFF` fallback when accent saturation < 0.12 (`resolveGrabAccent`). +- **Composer & Transcript UI (`renderer/components/grabbed-element-chip.tsx`, `composer.tsx`, `chat-pane.tsx`):** + - Each chip renders two sibling `', + textPreview: "Bearer secret_token_value_12345", + attributes: { + class: "cta-primary", + onclick: "evil()", + value: "my-password", + "data-api-key": "secret-val", + }, + props: { + secretToken: "hidden", + size: "lg", + }, + boundingBox: { x: 10, y: 20, width: 120, height: 40 }, + viewport: { width: 1280, height: 720, devicePixelRatio: 2 }, + }, + { + pageUrl: "https://alice:hunter2@localhost:3000/dashboard?__aiden_preview=1", + pageTitle: "Dashboard", + zoomFactor: 1.25, + id: "fixed_id_1", + capturedAt: 42_000, + sourceMapResolver: resolver, + }, + ); + + assert.equal(sanitized.keepActive, true); + assert.equal(sanitized.element.label, "button.cta-primary"); + assert.equal(sanitized.element.componentName, undefined); + assert.equal(sanitized.element.pageUrl, "https://localhost:3000/dashboard?__aiden_preview=1"); + assert.equal(sanitized.element.attributes?.onclick, undefined); + assert.equal(sanitized.element.attributes?.value, undefined); + assert.equal(sanitized.element.attributes?.["data-api-key"], "[redacted]"); + assert.equal(sanitized.element.props?.secretToken, "[redacted]"); + assert.equal(sanitized.element.props?.size, "lg"); + assert.doesNotMatch(sanitized.element.htmlSnippet, /ghp_/); + assert.match(sanitized.element.htmlSnippet, /\[redacted\]/); + assert.equal(sanitized.element.textPreview, "[redacted]"); + assert.equal(sanitized.element.viewport?.zoomFactor, 1.25); +}); + +test("sanitizeRawGrabPayload prevents remote pages from triggering local fetch or file reads via forged _debugStack", async () => { + let fetchCalls = 0; + let readCalls = 0; + const resolver = new LocalGrabSourceMapResolver({ + fetchImpl: (async () => { + fetchCalls += 1; + return new Response("", { status: 200 }); + }) as typeof fetch, + readFileImpl: async () => { + readCalls += 1; + return Buffer.from(""); + }, + }); + + const remote = await sanitizeRawGrabPayload( + { + framework: "react", + componentName: "SpoofedCard", + componentStack: [ + { + name: "SpoofedCard", + source: { + debugStack: + "Error\n at SpoofedCard (http://127.0.0.1:3000/secret.js:1:1)\n at Leak (file:///etc/passwd:1:1)", + }, + }, + { + name: "StaticSourceFrame", + source: { + fileName: "webpack-internal:///(app-pages-browser)/./src/StaticCard.tsx", + lineNumber: 7, + }, + }, + ], + source: { + debugStack: "Error\n at SpoofedCard (file:///Users/dev/app/dist/bundle.js:1:1)", + }, + tagName: "div", + selector: "div.card", + htmlSnippet: '
Hi
', + boundingBox: { x: 0, y: 0, width: 100, height: 50 }, + viewport: { width: 1280, height: 720, devicePixelRatio: 1 }, + }, + { + pageUrl: "https://evil.example/landing", + workspaceRoot: "/Users/dev/app", + id: "remote_guard_1", + capturedAt: 1000, + sourceMapResolver: resolver, + }, + ); + + assert.equal(fetchCalls, 0, "remote page must never trigger loopback fetch"); + assert.equal(readCalls, 0, "remote page must never trigger local file read"); + assert.equal(remote.element.source?.symbolicated, false); + // Offline static _debugSource.fileName normalization still works cleanly. + assert.deepEqual(remote.element.componentStack?.[1]?.source, { + filePath: "src/StaticCard.tsx", + line: 7, + symbolicated: false, + }); +}); + +test("a grabbed credential field never carries its live value in props, whatever the prop is called", async () => { + function OtpField() {} + const otpFiber = { + type: OtpField, + return: null, + memoizedProps: { value: "493817", autoComplete: "one-time-code", code: "493817", label: "Code" }, + }; + const otp = inspectReactElement({ __reactFiber$otp: { type: "input", return: otpFiber, _debugOwner: otpFiber } }); + assert.deepEqual(otp?.props, { value: "[redacted]", autoComplete: "one-time-code", code: "[redacted]", label: "[redacted]" }); + + // The page reports its own props, so the main process applies the same rule to whatever arrives. + const raw = (props: Record, sensitiveTarget?: boolean) => ({ + framework: "react", + componentStack: [{ name: "PasswordField" }], + props, + ...(sensitiveTarget ? { sensitiveTarget } : {}), + tagName: "input", + selector: "input#password", + htmlSnippet: '', + boundingBox: { x: 0, y: 0, width: 200, height: 30 }, + viewport: { width: 1280, height: 720, devicePixelRatio: 1 }, + }); + const options = { pageUrl: "http://localhost:3000/login", id: "credential_props", capturedAt: 1 }; + + const controlled = await sanitizeRawGrabPayload(raw({ value: "hunter2-secret-pass", placeholder: "Password" }), options); + assert.equal(controlled.element.props?.value, "[redacted]"); + assert.equal(controlled.element.props?.placeholder, "Password"); + + const typed = await sanitizeRawGrabPayload(raw({ type: "password", draft: "hunter2-secret-pass", defaultValue: "x" }), options); + assert.deepEqual(typed.element.props, { type: "password", draft: "[redacted]", defaultValue: "[redacted]" }); + + // A wrapper around a password input is sensitive even when its own props don't say so. + const wrapper = await sanitizeRawGrabPayload(raw({ current: "hunter2-secret-pass", pin: 4321, disabled: false }, true), options); + assert.deepEqual(wrapper.element.props, { current: "[redacted]", pin: "[redacted]", disabled: false }); + assert.doesNotMatch(JSON.stringify([controlled.element, typed.element, wrapper.element]), /hunter2|4321/); +}); + +test("a payload taken before the page moved to another origin carries no source hint and fetches nothing", async () => { + const fetchedUrls: string[] = []; + const sourceMapJson = JSON.stringify({ version: 3, sources: ["src/components/Card.tsx"], mappings: "AAUI" }); + const inlineMap = `data:application/json;base64,${Buffer.from(sourceMapJson, "utf8").toString("base64")}`; + const resolver = new LocalGrabSourceMapResolver({ + fetchImpl: (async (input: RequestInfo | URL) => { + fetchedUrls.push(String(input)); + return new Response(`console.log(1);\n//# sourceMappingURL=${inlineMap}\n`, { status: 200 }); + }) as typeof fetch, + }); + // The stale stack names the new page's origin, so only the grab-start URL can tell it apart. + const raw = { + framework: "react", + componentName: "Card", + componentStack: [ + { name: "Card", source: { debugStack: "Error\n at Card (http://localhost:5173/chunks/card.js:1:1)" } }, + { name: "Shell", source: { fileName: "/Users/dev/app/src/Shell.tsx", lineNumber: 3 } }, + ], + source: { debugStack: "Error\n at Card (http://localhost:5173/chunks/card.js:1:1)" }, + tagName: "div", + selector: "div.card", + htmlSnippet: '
Hi
', + boundingBox: { x: 0, y: 0, width: 100, height: 50 }, + viewport: { width: 1280, height: 720, devicePixelRatio: 1 }, + }; + const base = { workspaceRoot: "/Users/dev/app", capturedAt: 1, sourceMapResolver: resolver }; + + const moved = await sanitizeRawGrabPayload(raw, { + ...base, + id: "moved_origin", + pageUrl: "http://localhost:5173/", + grabPageUrl: "http://localhost:3000/dashboard", + }); + assert.equal(moved.element.source, undefined); + assert.deepEqual(moved.element.componentStack, [{ name: "Card" }, { name: "Shell" }]); + assert.deepEqual(fetchedUrls, []); + + // A same-origin route change during the grab keeps the page's source hints. + const routed = await sanitizeRawGrabPayload(raw, { + ...base, + id: "same_origin", + pageUrl: "http://localhost:5173/settings", + grabPageUrl: "http://localhost:5173/", + }); + assert.deepEqual(routed.element.source, { filePath: "src/components/Card.tsx", line: 11, column: 5, symbolicated: true }); + assert.deepEqual(routed.element.componentStack?.[1]?.source, { filePath: "src/Shell.tsx", line: 3, symbolicated: false }); + assert.deepEqual(fetchedUrls, ["http://localhost:5173/chunks/card.js"]); +}); diff --git a/main/services/browser/grab-sanitize.ts b/main/services/browser/grab-sanitize.ts new file mode 100644 index 0000000000..21fafc4c45 --- /dev/null +++ b/main/services/browser/grab-sanitize.ts @@ -0,0 +1,348 @@ +import { randomUUID } from "node:crypto"; +import { + GRABBED_ELEMENT_FRAMEWORKS, + GRABBED_ELEMENT_SCHEMA_VERSION, + parseGrabbedElements, + type GrabbedElementComponentFrame, + type GrabbedElementContextV1, + type GrabbedElementFramework, +} from "../../../renderer/shared/browser-element-grab.js"; +import { browserDisplayUrl, browserMeasuredViewport } from "./core.js"; +import type { CssRect } from "./credential-fields.js"; +import type { RawGrabComponentFrame, RawGrabSourceHint } from "./grab-runtime/inspect-react.js"; +import { + defaultGrabSourceMapResolver, + sameGrabSourceAuthority, + type LocalGrabSourceMapResolver, +} from "./grab-source-map.js"; + +const FRAMEWORK_SET = new Set(GRABBED_ELEMENT_FRAMEWORKS); +const TAG_NAME_PATTERN = /^[a-z][a-z0-9:_-]{0,63}$/u; +const SECRET_KEY_PATTERN = + /pass|secret|token|auth|api[_-]?key|cookie|session|credit|card|cvv|cvc|ssn|bearer|jwt|private|credential/iu; +/** A field's live contents travel under these keys whatever the field is. */ +const VALUE_KEY_PATTERN = /^(?:default)?value$/iu; +/** On a credential field only these describe the field rather than hold its contents. */ +const SENSITIVE_FIELD_SAFE_KEYS = new Set(["type", "autocomplete", "inputmode"]); +const CREDENTIAL_AUTOCOMPLETE_PATTERN = /(?:^|\s)(?:current-password|new-password|one-time-code|cc-[a-z-]+)(?:\s|$)/iu; +const SECRET_VALUE_PATTERN = + /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|Bearer\s+[A-Za-z0-9._~+/=-]{12,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b/gu; + +export interface SanitizeGrabOptions { + /** Authoritative URL from `webContents.getURL()` — never trust guest `location.href`. */ + pageUrl: string; + /** + * Authoritative URL recorded when the grab started. When the page has since + * moved to another origin, the payload's stack belongs to the old page, so no + * source hint is resolved or reported. + */ + grabPageUrl?: string; + /** Authoritative title from `webContents.getTitle()`. */ + pageTitle?: string; + workspaceRoot?: string; + zoomFactor?: number; + id?: string; + capturedAt?: number; + sourceMapResolver?: LocalGrabSourceMapResolver; +} + +export interface SanitizedGrabResult { + element: GrabbedElementContextV1; + keepActive: boolean; + measuredViewport?: { width: number; height: number }; + sensitiveRects: CssRect[]; +} + +function stripUrlCredentials(rawUrl: string): string { + const display = browserDisplayUrl(rawUrl); + try { + const parsed = new URL(display); + parsed.username = ""; + parsed.password = ""; + return parsed.href.slice(0, 2048); + } catch { + return (display || "about:blank").slice(0, 2048); + } +} + +export function redactGrabSecrets(value: string): string { + return value.replace(SECRET_VALUE_PATTERN, "[redacted]"); +} + +function cleanString(value: unknown, maxChars: number): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = redactGrabSecrets(value).trim(); + return trimmed.length > 0 ? trimmed.slice(0, maxChars) : undefined; +} + +function sanitizeSourceHint(raw: unknown): RawGrabSourceHint | undefined { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; + const rec = raw as Record; + const hint: RawGrabSourceHint = {}; + if (typeof rec.fileName === "string" && rec.fileName.trim()) { + hint.fileName = rec.fileName.trim().slice(0, 512); + } + if (typeof rec.lineNumber === "number" && Number.isSafeInteger(rec.lineNumber) && rec.lineNumber >= 1) { + hint.lineNumber = rec.lineNumber; + } + if (typeof rec.columnNumber === "number" && Number.isSafeInteger(rec.columnNumber) && rec.columnNumber >= 1) { + hint.columnNumber = rec.columnNumber; + } + if (typeof rec.debugStack === "string" && rec.debugStack.length > 0) { + hint.debugStack = rec.debugStack.slice(0, 4096); + } + return hint.fileName || hint.debugStack ? hint : undefined; +} + +function propsDescribeSensitiveField(props: Record): boolean { + const type = props.type; + if (typeof type === "string" && type.trim().toLowerCase() === "password") return true; + return [props.autoComplete, props.autocomplete].some( + (value) => typeof value === "string" && CREDENTIAL_AUTOCOMPLETE_PATTERN.test(value), + ); +} + +function sanitizeProps( + raw: unknown, + sensitiveTarget: boolean, +): Record | undefined { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; + const entries = raw as Record; + // A password, one-time-code or card field keeps only the props that describe it. + const sensitive = sensitiveTarget || propsDescribeSensitiveField(entries); + const out: Record = {}; + let count = 0; + for (const [key, val] of Object.entries(entries)) { + if (count >= 12) break; + if (!key || key.length > 80 || key === "__proto__" || key === "constructor" || key === "prototype") continue; + if ( + SECRET_KEY_PATTERN.test(key) || + VALUE_KEY_PATTERN.test(key) || + (sensitive && (typeof val === "string" || typeof val === "number") && + !SENSITIVE_FIELD_SAFE_KEYS.has(key.toLowerCase())) + ) { + out[key] = "[redacted]"; + count += 1; + continue; + } + if (val === null || typeof val === "boolean") { + out[key] = val; + count += 1; + } else if (typeof val === "number" && Number.isFinite(val)) { + out[key] = val; + count += 1; + } else if (typeof val === "string") { + out[key] = redactGrabSecrets(val).slice(0, 256); + count += 1; + } + } + return count > 0 ? out : undefined; +} + +function sanitizeAttributes(raw: unknown): Record | undefined { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; + const out: Record = {}; + let count = 0; + for (const [key, val] of Object.entries(raw as Record)) { + if (count >= 20) break; + if (!key || key.length > 80 || key === "__proto__" || key === "constructor" || key === "prototype") continue; + const lower = key.toLowerCase(); + if (lower === "value" || /^on[a-z]/u.test(lower)) continue; + if (typeof val !== "string") continue; + out[key] = SECRET_KEY_PATTERN.test(key) ? "[redacted]" : redactGrabSecrets(val).slice(0, 512); + count += 1; + } + return count > 0 ? out : undefined; +} + +function sanitizeComputedStyles(raw: unknown): Record | undefined { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; + const out: Record = {}; + let count = 0; + for (const [key, val] of Object.entries(raw as Record)) { + if (count >= 24) break; + if (!key || key.length > 80 || key === "__proto__" || key === "constructor" || key === "prototype") continue; + if (typeof val !== "string" || !val.trim()) continue; + out[key] = val.trim().slice(0, 256); + count += 1; + } + return count > 0 ? out : undefined; +} + +function sanitizeRect(raw: unknown): CssRect { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + return { x: 0, y: 0, width: 0, height: 0 }; + } + const rec = raw as Record; + const num = (value: unknown, min: number, max: number) => + typeof value === "number" && Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : 0; + return { + x: num(rec.x, -50_000, 50_000), + y: num(rec.y, -50_000, 50_000), + width: num(rec.width, 0, 50_000), + height: num(rec.height, 0, 50_000), + }; +} + +function sanitizeSensitiveRects(raw: unknown): CssRect[] { + if (!Array.isArray(raw)) return []; + const rects: CssRect[] = []; + for (const entry of raw.slice(0, 128)) { + const rect = sanitizeRect(entry); + if (rect.width > 0 && rect.height > 0) rects.push(rect); + } + return rects; +} + +function semanticDomLabel(tagName: string, attributes?: Record): string { + const id = attributes?.id?.trim(); + if (id && id.length <= 40 && !/^\d+$/u.test(id)) { + return `${tagName}#${id}`.slice(0, 120); + } + const cls = attributes?.class?.trim(); + if (cls) { + const tokens = cls + .split(/\s+/u) + .filter((t) => t.length > 0 && t.length <= 40 && !/^(css|sc|emotion)-[a-z0-9]{5,}$/iu.test(t)) + .slice(0, 2); + if (tokens.length > 0) { + return `${tagName}.${tokens.join(".")}`.slice(0, 120); + } + } + return tagName.slice(0, 64); +} + +/** + * Validates, redacts, and locally symbolicates an untrusted guest grab payload into + * a schema-verified `GrabbedElementContextV1`. + */ +export async function sanitizeRawGrabPayload( + raw: unknown, + options: SanitizeGrabOptions, +): Promise { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) { + throw new Error("Invalid browser grab payload."); + } + const rec = raw as Record; + const resolver = options.sourceMapResolver ?? defaultGrabSourceMapResolver; + const pageUrl = stripUrlCredentials(options.pageUrl); + // The resolver binds source-map reads to this authoritative page origin. + const sourceAuthority = { pageUrl: options.pageUrl }; + const sourceHintsTrusted = + options.grabPageUrl === undefined || sameGrabSourceAuthority(options.grabPageUrl, options.pageUrl); + + const rawTag = typeof rec.tagName === "string" ? rec.tagName.trim().toLowerCase() : "div"; + const tagName = TAG_NAME_PATTERN.test(rawTag) ? rawTag : "div"; + const framework: GrabbedElementFramework = + typeof rec.framework === "string" && FRAMEWORK_SET.has(rec.framework) + ? (rec.framework as GrabbedElementFramework) + : "dom"; + + const rawStack = Array.isArray(rec.componentStack) + ? (rec.componentStack.slice(0, 12) as RawGrabComponentFrame[]) + : []; + + const resolvedFrames: GrabbedElementComponentFrame[] = []; + await Promise.all( + rawStack.map(async (frame, index) => { + if (!frame || typeof frame !== "object") return; + const name = cleanString((frame as { name?: unknown }).name, 160); + if (!name) return; + const env = (frame as { environment?: unknown }).environment; + const minified = (frame as { minified?: unknown }).minified === true; + const hint = sourceHintsTrusted ? sanitizeSourceHint((frame as { source?: unknown }).source) : undefined; + // Symbolicate up to the top 5 component frames to stay fast. + const source = + index < 5 && hint + ? await resolver.resolveSourceHint(hint, options.workspaceRoot, sourceAuthority) + : undefined; + const cleanFrame: GrabbedElementComponentFrame = { name }; + if (env === "client" || env === "server") cleanFrame.environment = env; + if (source) cleanFrame.source = source; + if (minified) cleanFrame.minified = true; + resolvedFrames[index] = cleanFrame; + }), + ); + const componentStack = resolvedFrames.filter(Boolean); + + const topSourceHint = sourceHintsTrusted ? sanitizeSourceHint(rec.source) : undefined; + const resolvedTopSource = + (topSourceHint + ? await resolver.resolveSourceHint(topSourceHint, options.workspaceRoot, sourceAuthority) + : undefined) ?? componentStack.find((frame) => !frame.minified && frame.source)?.source; + + const rawComponentName = cleanString(rec.componentName, 160); + const primaryNonMinified = componentStack.find((frame) => !frame.minified)?.name; + const componentName = rawComponentName ?? primaryNonMinified; + + const attributes = sanitizeAttributes(rec.attributes); + const props = sanitizeProps(rec.props, rec.sensitiveTarget === true); + const label = (componentName ? `<${componentName} />` : semanticDomLabel(tagName, attributes)).slice(0, 160); + const selector = cleanString(rec.selector, 1024) ?? tagName; + const htmlSnippet = + typeof rec.htmlSnippet === "string" + ? redactGrabSecrets(rec.htmlSnippet).slice(0, 4096) + : ""; + const boundingBox = sanitizeRect(rec.boundingBox); + + const measuredViewport = browserMeasuredViewport(rec.viewport); + const rawViewport = rec.viewport && typeof rec.viewport === "object" ? (rec.viewport as Record) : undefined; + const rawDpr = rawViewport?.devicePixelRatio; + const devicePixelRatio = + typeof rawDpr === "number" && Number.isFinite(rawDpr) && rawDpr > 0 ? rawDpr : undefined; + const zoomFactor = + typeof options.zoomFactor === "number" && Number.isFinite(options.zoomFactor) && options.zoomFactor > 0 + ? options.zoomFactor + : undefined; + + const id = (options.id ?? randomUUID().replace(/-/gu, "")).slice(0, 64); + const pageTitle = cleanString(options.pageTitle, 256); + + const candidate: GrabbedElementContextV1 = { + version: GRABBED_ELEMENT_SCHEMA_VERSION, + id, + label, + framework, + ...(componentName ? { componentName } : {}), + ...(componentStack.length > 0 ? { componentStack } : {}), + ...(resolvedTopSource ? { source: resolvedTopSource } : {}), + ...(props ? { props } : {}), + tagName, + selector, + ...(cleanString(rec.role, 80) ? { role: cleanString(rec.role, 80) } : {}), + ...(cleanString(rec.accessibleName, 256) ? { accessibleName: cleanString(rec.accessibleName, 256) } : {}), + htmlSnippet, + ...(cleanString(rec.textPreview, 1024) ? { textPreview: cleanString(rec.textPreview, 1024) } : {}), + ...(attributes ? { attributes } : {}), + ...(sanitizeComputedStyles(rec.computedStyles) + ? { computedStyles: sanitizeComputedStyles(rec.computedStyles) } + : {}), + boundingBox, + pageUrl, + ...(pageTitle ? { pageTitle } : {}), + ...(measuredViewport + ? { + viewport: { + width: measuredViewport.width, + height: measuredViewport.height, + ...(devicePixelRatio ? { devicePixelRatio } : {}), + ...(zoomFactor ? { zoomFactor } : {}), + }, + } + : {}), + ...(rec.inIframe === true ? { inIframe: true } : {}), + capturedAt: options.capturedAt ?? Date.now(), + }; + + const validated = parseGrabbedElements([candidate], "append"); + if (!validated || validated.length !== 1) { + throw new Error("Sanitized browser grab failed schema validation."); + } + + return { + element: validated[0]!, + keepActive: rec.keepActive === true, + ...(measuredViewport ? { measuredViewport } : {}), + sensitiveRects: sanitizeSensitiveRects(rec.sensitiveRects), + }; +} diff --git a/main/services/browser/grab-source-map.test.ts b/main/services/browser/grab-source-map.test.ts new file mode 100644 index 0000000000..39eb2f68bb --- /dev/null +++ b/main/services/browser/grab-source-map.test.ts @@ -0,0 +1,275 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { pathToFileURL } from "node:url"; +import { + allowedLocalSourceMapFilePath, + decodeSourceMapMappings, + isAllowedSourceMapUrl, + LocalGrabSourceMapResolver, + lookupOriginalPosition, + normalizeBundlerSourcePath, + parseDebugStackFrames, +} from "./grab-source-map.js"; + +test("decodeSourceMapMappings and lookupOriginalPosition decode standard Source Map v3 VLQ segments", () => { + // Line 1: genCol=0 -> src=0, origLine=10 (U = +10), origCol=4 (I = +4) + // Line 2: genCol=2 (E) -> src=0 (A), origLine=12 (E = +2), origCol=8 (I = +4); genCol=10 (Q = +8) -> src=1 (C), origLine=0 (Z = -12), origCol=0 (R = -8) + const indexed = decodeSourceMapMappings({ + version: 3, + sourceRoot: "webpack-internal:///(app-pages-browser)/./", + sources: ["src/components/Hero.tsx", "src/components/Button.tsx"], + mappings: "AAUI;EAEI,QCZR", + }); + + const pos1 = lookupOriginalPosition(indexed, 1, 1); + assert.deepEqual(pos1, { + source: "webpack-internal:///(app-pages-browser)/./src/components/Hero.tsx", + line: 11, + column: 5, + }); + + const pos2 = lookupOriginalPosition(indexed, 2, 5); + assert.deepEqual(pos2, { + source: "webpack-internal:///(app-pages-browser)/./src/components/Hero.tsx", + line: 13, + column: 9, + }); + + const pos3 = lookupOriginalPosition(indexed, 2, 12); + assert.deepEqual(pos3, { + source: "webpack-internal:///(app-pages-browser)/./src/components/Button.tsx", + line: 1, + column: 1, + }); + + assert.equal(lookupOriginalPosition(indexed, 99, 1), null); +}); + +test("isAllowedSourceMapUrl strictly permits loopback and file URLs while rejecting remote/LAN/credentialed hosts", () => { + assert.equal(isAllowedSourceMapUrl("http://localhost:3000/app.js.map"), true); + assert.equal(isAllowedSourceMapUrl("https://127.0.0.1:8443/chunk.js"), true); + assert.equal(isAllowedSourceMapUrl("http://[::1]:5173/src/main.tsx"), true); + assert.equal(isAllowedSourceMapUrl("file:///Users/dev/app/dist/bundle.js"), true); + + assert.equal(isAllowedSourceMapUrl("https://example.com/app.js.map"), false); + assert.equal(isAllowedSourceMapUrl("http://192.168.1.50:3000/app.js"), false); + assert.equal(isAllowedSourceMapUrl("https://127.0.0.1.evil.test/app.js"), false); + assert.equal(isAllowedSourceMapUrl("http://user:pass@localhost:3000/app.js"), false); + assert.equal(isAllowedSourceMapUrl("javascript:alert(1)"), false); +}); + +test("normalizeBundlerSourcePath strips Webpack, Turbopack, Vite, RSC, and file:// prefixes and relativizes inside workspace", () => { + const root = "/Users/dev/project"; + assert.equal( + normalizeBundlerSourcePath("webpack-internal:///(app-pages-browser)/./src/Hero.tsx?v=12", root), + "src/Hero.tsx", + ); + assert.equal( + normalizeBundlerSourcePath("turbopack:///[project]/app/page.tsx", root), + "app/page.tsx", + ); + assert.equal( + normalizeBundlerSourcePath("rsc://React/Server/webpack-internal:///(rsc)/./app/layout.tsx", root), + "app/layout.tsx", + ); + assert.equal( + normalizeBundlerSourcePath("http://localhost:5173/@fs/Users/dev/project/src/Button.tsx?t=999", root), + "src/Button.tsx", + ); + assert.equal( + normalizeBundlerSourcePath("file:///Users/dev/project/src/Card.tsx", root), + "src/Card.tsx", + ); + // Path outside workspace stays clean without escaping with .. + assert.equal( + normalizeBundlerSourcePath("/tmp/external/Widget.tsx", root), + "/tmp/external/Widget.tsx", + ); +}); + +test("LocalGrabSourceMapResolver symbolicates React 19 _debugStack via loopback inline/external source maps and never fetches remote URLs", async () => { + const fetchedUrls: string[] = []; + const fetchOptions: RequestInit[] = []; + const sourceMapJson = JSON.stringify({ + version: 3, + sources: ["turbopack:///[project]/src/components/LandingHeroClient.tsx"], + mappings: "AAUI", + }); + const inlineData = `data:application/json;base64,${Buffer.from(sourceMapJson, "utf8").toString("base64")}`; + + const resolver = new LocalGrabSourceMapResolver({ + fetchImpl: (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + fetchedUrls.push(url); + if (init) fetchOptions.push(init); + if (url === "http://localhost:3000/chunks/hero.js") { + return new Response(`console.log(1);\n//# sourceMappingURL=${inlineData}\n`, { status: 200 }); + } + return new Response("Not Found", { status: 404 }); + }) as typeof fetch, + }); + + const debugStack = [ + "Error: react-stack-top-frame", + " at jsxDEV (http://localhost:3000/node_modules/react_jsx-dev-runtime.js:12:3)", + " at LandingHeroClient (http://localhost:3000/chunks/hero.js:1:1)", + ].join("\n"); + + const page = { pageUrl: "http://localhost:3000/dashboard" }; + const resolved = await resolver.resolveSourceHint({ debugStack }, "/Users/dev/app", page); + assert.deepEqual(resolved, { + filePath: "src/components/LandingHeroClient.tsx", + line: 11, + column: 5, + symbolicated: true, + }); + assert.deepEqual(fetchedUrls, ["http://localhost:3000/chunks/hero.js"]); + assert.equal(fetchOptions[0]?.redirect, "error"); + + // Second call hits LRU cache without re-fetching. + const cached = await resolver.resolveSourceHint({ debugStack }, "/Users/dev/app", page); + assert.deepEqual(cached, resolved); + assert.equal(fetchedUrls.length, 1); + + // Remote URL must NEVER be fetched; gracefully returns un-symbolicated fallback. + const remoteStack = "Error\n at Widget (https://cdn.example.com/bundle.js:10:5)"; + const remote = await resolver.resolveSourceHint({ debugStack: remoteStack }, undefined, page); + assert.equal(fetchedUrls.length, 1); + assert.deepEqual(remote, { + filePath: "https://cdn.example.com/bundle.js", + line: 10, + column: 5, + symbolicated: false, + }); + + // A forged stack naming another loopback port (or the same port over another scheme) is never fetched. + for (const forged of ["http://localhost:5173/admin.js", "https://localhost:3000/chunk.js", "http://127.0.0.1:3000/chunk.js"]) { + const crossOrigin = await resolver.resolveSourceHint({ debugStack: `Error\n at Probe (${forged}:1:1)` }, "/Users/dev/app", page); + assert.equal(crossOrigin?.symbolicated, false); + } + assert.deepEqual(fetchedUrls, ["http://localhost:3000/chunks/hero.js"]); + + // Without an authoritative page URL nothing local is fetched at all. + const unbound = await new LocalGrabSourceMapResolver({ + fetchImpl: (async (input: RequestInfo | URL) => { + fetchedUrls.push(String(input)); + return new Response("", { status: 404 }); + }) as typeof fetch, + }).resolveSourceHint({ debugStack }, "/Users/dev/app"); + assert.equal(unbound?.symbolicated, false); + assert.deepEqual(fetchedUrls, ["http://localhost:3000/chunks/hero.js"]); +}); + +test("parseDebugStackFrames skips react-dom and node_modules frames", () => { + const stack = [ + "Error", + " at renderWithHooks (http://localhost:3000/node_modules/react-dom.js:100:5)", + " at MyCard (http://localhost:3000/src/MyCard.tsx:24:11)", + ].join("\n"); + assert.deepEqual(parseDebugStackFrames(stack), [ + { url: "http://localhost:3000/src/MyCard.tsx", line: 24, column: 11 }, + ]); +}); + +test("LocalGrabSourceMapResolver restricts file:// reads to script/map extensions inside workspaceRoot", async () => { + const readPaths: string[] = []; + const sourceMapJson = JSON.stringify({ + version: 3, + sources: ["src/Widget.tsx"], + mappings: "AAUI", + }); + const resolver = new LocalGrabSourceMapResolver({ + readFileImpl: async (filePath: string) => { + readPaths.push(filePath); + if (filePath.endsWith(".map")) return Buffer.from(sourceMapJson, "utf8"); + return Buffer.from("//# sourceMappingURL=bundle.js.map\n", "utf8"); + }, + realpathImpl: async (filePath: string) => filePath, + }); + const page = { pageUrl: "file:///Users/dev/app/index.html" }; + + // Non-script/map file extension is rejected before reading disk. + assert.equal(allowedLocalSourceMapFilePath("file:///etc/passwd", "/Users/dev/app"), null); + await resolver.resolveSourceHint( + { debugStack: "Error\n at Evil (file:///etc/passwd:1:1)" }, + "/Users/dev/app", + page, + ); + assert.deepEqual(readPaths, []); + + // Out-of-workspace script is rejected before reading disk. + assert.equal(allowedLocalSourceMapFilePath("file:///Users/other/secret.js", "/Users/dev/app"), null); + assert.equal( + allowedLocalSourceMapFilePath("file:///Users/dev/app/../other/secret.js", "/Users/dev/app"), + null, + ); + await resolver.resolveSourceHint( + { debugStack: "Error\n at Evil (file:///Users/other/secret.js:1:1)" }, + "/Users/dev/app", + page, + ); + assert.deepEqual(readPaths, []); + + // With no workspace root nothing bounds the read, so it is refused. + assert.equal(allowedLocalSourceMapFilePath("file:///Users/dev/app/dist/bundle.js"), null); + await resolver.resolveSourceHint( + { debugStack: "Error\n at Widget (file:///Users/dev/app/dist/bundle.js:1:1)" }, + undefined, + page, + ); + assert.deepEqual(readPaths, []); + + // A loopback page cannot reach workspace files through a forged file:// frame. + await resolver.resolveSourceHint( + { debugStack: "Error\n at Widget (file:///Users/dev/app/dist/bundle.js:1:1)" }, + "/Users/dev/app", + { pageUrl: "http://localhost:3000/" }, + ); + assert.deepEqual(readPaths, []); + + // In-workspace .js + .map succeeds. + const resolved = await resolver.resolveSourceHint( + { debugStack: "Error\n at Widget (file:///Users/dev/app/dist/bundle.js:1:1)" }, + "/Users/dev/app", + page, + ); + assert.deepEqual(resolved, { + filePath: "src/Widget.tsx", + line: 11, + column: 5, + symbolicated: true, + }); + assert.equal(readPaths.length, 2); +}); + +test("LocalGrabSourceMapResolver refuses an in-workspace symlink that points outside the workspace", async () => { + const base = await mkdtemp(path.join(tmpdir(), "aiden-grab-map-")); + try { + const workspace = path.join(base, "app"); + const outside = path.join(base, "outside"); + await mkdir(path.join(workspace, "dist"), { recursive: true }); + await mkdir(outside, { recursive: true }); + const sourceMapJson = JSON.stringify({ version: 3, sources: ["src/Secret.tsx"], mappings: "AAUI" }); + await writeFile(path.join(outside, "bundle.js"), "//# sourceMappingURL=bundle.js.map\n"); + await writeFile(path.join(outside, "bundle.js.map"), sourceMapJson); + await writeFile(path.join(workspace, "dist", "own.js"), "//# sourceMappingURL=own.js.map\n"); + await writeFile(path.join(workspace, "dist", "own.js.map"), JSON.stringify({ version: 3, sources: ["src/Own.tsx"], mappings: "AAUI" })); + await symlink(path.join(outside, "bundle.js"), path.join(workspace, "dist", "linked.js")); + await symlink(path.join(outside, "bundle.js.map"), path.join(workspace, "dist", "linked.js.map")); + + const resolver = new LocalGrabSourceMapResolver(); + const page = { pageUrl: pathToFileURL(path.join(workspace, "index.html")).href }; + const linkedUrl = pathToFileURL(path.join(workspace, "dist", "linked.js")).href; + const escaped = await resolver.resolveSourceHint({ debugStack: `Error\n at Leak (${linkedUrl}:1:1)` }, workspace, page); + assert.equal(escaped?.symbolicated, false); + + const ownUrl = pathToFileURL(path.join(workspace, "dist", "own.js")).href; + const own = await resolver.resolveSourceHint({ debugStack: `Error\n at Own (${ownUrl}:1:1)` }, workspace, page); + assert.deepEqual(own, { filePath: "src/Own.tsx", line: 11, column: 5, symbolicated: true }); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); diff --git a/main/services/browser/grab-source-map.ts b/main/services/browser/grab-source-map.ts new file mode 100644 index 0000000000..488794a713 --- /dev/null +++ b/main/services/browser/grab-source-map.ts @@ -0,0 +1,601 @@ +import { readFile, realpath } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { GrabbedElementSourceLocation } from "../../../renderer/shared/browser-element-grab.js"; +import type { RawGrabSourceHint } from "./grab-runtime/inspect-react.js"; + +const MAX_SOURCE_MAP_BYTES = 10 * 1024 * 1024; +const SOURCE_MAP_TIMEOUT_MS = 1_500; +const SOURCE_MAP_CACHE_LIMIT = 25; + +const VLQ_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +const VLQ_LOOKUP = new Int8Array(128).fill(-1); +for (let i = 0; i < VLQ_CHARS.length; i += 1) { + VLQ_LOOKUP[VLQ_CHARS.charCodeAt(i)] = i; +} + +export interface DecodedSourcePosition { + source: string; + line: number; + column: number; +} + +interface ParsedSourceMapV3 { + version: 3; + sources: string[]; + sourceRoot?: string; + mappings: string; +} + +interface DecodedSegment { + genCol: number; + sourceIdx: number; + origLine: number; + origCol: number; +} + +interface IndexedSourceMap { + sources: string[]; + sourceRoot: string; + lines: DecodedSegment[][]; +} + +/** + * Compact standard Base64-VLQ Source Map v3 decoder (zero external dependencies). + * Produces per-generated-line segment lists sorted by generated column. + */ +export function decodeSourceMapMappings(map: ParsedSourceMapV3): IndexedSourceMap { + const lines: DecodedSegment[][] = []; + let currentLine: DecodedSegment[] = []; + const mappings = map.mappings; + const len = mappings.length; + let index = 0; + + let genCol = 0; + let sourceIdx = 0; + let origLine = 0; + let origCol = 0; + + const decodeVlq = (): number | null => { + let result = 0; + let shift = 0; + while (index < len) { + const code = mappings.charCodeAt(index); + const digit = code < 128 ? VLQ_LOOKUP[code] : -1; + if (digit === -1) return null; + index += 1; + result += (digit & 31) << shift; + shift += 5; + if ((digit & 32) === 0) { + const negative = (result & 1) === 1; + const value = result >> 1; + return negative ? -value : value; + } + if (shift > 30) return null; + } + return null; + }; + + while (index < len) { + const ch = mappings.charCodeAt(index); + if (ch === 59) { + // ';' + lines.push(currentLine); + currentLine = []; + genCol = 0; + index += 1; + continue; + } + if (ch === 44) { + // ',' + index += 1; + continue; + } + const genColDelta = decodeVlq(); + if (genColDelta === null) break; + genCol += genColDelta; + + if (index < len && mappings.charCodeAt(index) !== 44 && mappings.charCodeAt(index) !== 59) { + const srcDelta = decodeVlq(); + const lineDelta = decodeVlq(); + const colDelta = decodeVlq(); + if (srcDelta === null || lineDelta === null || colDelta === null) break; + sourceIdx += srcDelta; + origLine += lineDelta; + origCol += colDelta; + // Optional 5th field: name index delta (skip if present). + if (index < len && mappings.charCodeAt(index) !== 44 && mappings.charCodeAt(index) !== 59) { + decodeVlq(); + } + currentLine.push({ genCol, sourceIdx, origLine, origCol }); + } + } + lines.push(currentLine); + + return { + sources: map.sources, + sourceRoot: typeof map.sourceRoot === "string" ? map.sourceRoot : "", + lines, + }; +} + +/** Looks up a 1-based generated `(line, column)` in an indexed Source Map v3. */ +export function lookupOriginalPosition( + indexed: IndexedSourceMap, + generatedLine: number, + generatedColumn: number, +): DecodedSourcePosition | null { + if (generatedLine < 1 || generatedLine > indexed.lines.length) return null; + const lineSegments = indexed.lines[generatedLine - 1]; + if (!lineSegments || lineSegments.length === 0) return null; + const targetCol = Math.max(0, generatedColumn - 1); + + let lo = 0; + let hi = lineSegments.length - 1; + let best = -1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (lineSegments[mid]!.genCol <= targetCol) { + best = mid; + lo = mid + 1; + } else { + hi = mid - 1; + } + } + const segment = best >= 0 ? lineSegments[best] : lineSegments[0]; + if (!segment) return null; + const rawSource = indexed.sources[segment.sourceIdx]; + if (typeof rawSource !== "string" || !rawSource) return null; + const combined = + indexed.sourceRoot && !rawSource.startsWith("/") && !/^[a-zA-Z][a-zA-Z\d+.-]*:/u.test(rawSource) + ? `${indexed.sourceRoot.replace(/\/+$/u, "")}/${rawSource.replace(/^\/+/u, "")}` + : rawSource; + return { + source: combined, + line: Math.max(1, segment.origLine + 1), + column: Math.max(1, segment.origCol + 1), + }; +} + +const ALLOWED_LOCAL_FILE_EXTENSIONS = /\.(?:js|mjs|cjs|map)$/iu; + +function isStrictlyInside(root: string, file: string): boolean { + const rel = path.relative(root, file); + return Boolean(rel) && !rel.startsWith("..") && !path.isAbsolute(rel); +} + +/** + * Validates that a `file://` URL points to an allowed script/source-map extension + * (`.js`, `.mjs`, `.cjs`, `.map`) that lies lexically inside `workspaceRoot`. + * Without a workspace root there is nothing to contain the read, so it is refused. + */ +export function allowedLocalSourceMapFilePath( + rawUrl: string, + workspaceRoot?: string, +): string | null { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return null; + } + if (parsed.protocol !== "file:") return null; + let filePath: string; + try { + filePath = fileURLToPath(parsed); + } catch { + return null; + } + if (!ALLOWED_LOCAL_FILE_EXTENSIONS.test(filePath)) return null; + if (!workspaceRoot) return null; + const resolvedFile = path.resolve(filePath); + if (!isStrictlyInside(path.resolve(workspaceRoot), resolvedFile)) return null; + return resolvedFile; +} + +/** + * Where a page's own source hints may be read from: its exact loopback HTTP(S) + * origin, or workspace files when the page itself is a `file://` document. + * Any other page gets no local reads at all. + */ +export type GrabSourceAuthority = { kind: "http"; origin: string } | { kind: "file" }; + +export function grabSourceAuthority(pageUrl: string | undefined): GrabSourceAuthority | undefined { + if (!pageUrl) return undefined; + let parsed: URL; + try { + parsed = new URL(pageUrl); + } catch { + return undefined; + } + if (parsed.protocol === "file:") return { kind: "file" }; + parsed.username = ""; + parsed.password = ""; + return isAllowedSourceMapUrl(parsed.href) ? { kind: "http", origin: parsed.origin } : undefined; +} + +/** + * Whether two page URLs grant the same source authority. A grab payload's stack + * belongs to the page it was taken on, so it may only be judged against that + * page's origin. + */ +export function sameGrabSourceAuthority(first: string | undefined, second: string | undefined): boolean { + const a = grabSourceAuthority(first); + const b = grabSourceAuthority(second); + if (!a || !b) return !a && !b; + if (a.kind === "file" || b.kind === "file") return a.kind === b.kind; + return a.origin === b.origin; +} + +/** Whether a guest-supplied script or map URL falls under the page's authority. */ +export function isAuthorizedSourceUrl(rawUrl: string, authority: GrabSourceAuthority | undefined): boolean { + if (!authority || !isAllowedSourceMapUrl(rawUrl)) return false; + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return false; + } + if (authority.kind === "file") return parsed.protocol === "file:"; + return parsed.protocol !== "file:" && parsed.origin === authority.origin; +} + +/** + * Strict loopback-or-file-only URL guard. Never permits remote or LAN source-map fetches. + */ +export function isAllowedSourceMapUrl(rawUrl: string): boolean { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return false; + } + if (parsed.protocol === "file:") return true; + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false; + if (parsed.username || parsed.password) return false; + const host = parsed.hostname.toLowerCase(); + return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1"; +} + +/** + * Normalizes Webpack, Turbopack, Vite, RSC, and file:// bundler paths into clean + * workspace-relative (when inside `workspaceRoot`) or display paths. + */ +export function normalizeBundlerSourcePath(rawPath: string, workspaceRoot?: string): string { + let cleaned = rawPath.trim(); + if (!cleaned) return ""; + + // Strip query strings and fragments. + cleaned = cleaned.replace(/[?#].*$/u, ""); + + // Unwrap RSC server wrappers. + cleaned = cleaned.replace(/^rsc:\/\/React\/Server\//iu, ""); + + // Unwrap webpack-internal and webpack URLs. + cleaned = cleaned.replace( + /^webpack-internal:\/\/\/(?:\([^)]+\)\/)?\.?\//iu, + "", + ); + cleaned = cleaned.replace(/^webpack:\/\/[^/]*\/\.?\//iu, ""); + cleaned = cleaned.replace(/^webpack:\/\/\//iu, ""); + + // Unwrap Turbopack prefixes. + cleaned = cleaned.replace(/^turbopack:\/\/\/\[project\]\//iu, ""); + cleaned = cleaned.replace(/^turbopack:\/\/\//iu, ""); + cleaned = cleaned.replace(/^\[project\]\//iu, ""); + + // Unwrap Vite /@fs/ absolute file prefixes. + if (cleaned.startsWith("/@fs/")) { + cleaned = cleaned.slice(4); + } else { + cleaned = cleaned.replace(/^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?\/@fs\//iu, "/"); + } + + // Decode file:// URLs. + if (cleaned.startsWith("file://")) { + try { + cleaned = fileURLToPath(cleaned); + } catch { + cleaned = cleaned.replace(/^file:\/\//iu, ""); + } + } + + // Strip leading "./" + cleaned = cleaned.replace(/^\.\//u, ""); + + // Relativize against active workspace root when inside it. + if (workspaceRoot && path.isAbsolute(cleaned)) { + const resolvedRoot = path.resolve(workspaceRoot); + const resolvedFile = path.resolve(cleaned); + const rel = path.relative(resolvedRoot, resolvedFile); + if (rel && !rel.startsWith("..") && !path.isAbsolute(rel)) { + cleaned = rel.split(path.sep).join("/"); + } + } + + return cleaned.slice(0, 512); +} + +export interface ParsedStackFrame { + url: string; + line: number; + column: number; +} + +const IGNORED_STACK_URL_PATTERN = + /\/node_modules\/|react-dom|react_jsx|scheduler\.development|webpack\/runtime|__vite\/client|@react-refresh/iu; + +/** Extracts userland `(url, line, column)` frames from a React 19 `_debugStack` string. */ +export function parseDebugStackFrames(debugStack: string): ParsedStackFrame[] { + const frames: ParsedStackFrame[] = []; + for (const rawLine of debugStack.split(/\r?\n/u).slice(0, 30)) { + const line = rawLine.trim(); + if (!line) continue; + // Chrome/V8: "at Component (http://localhost:3000/src/App.tsx:42:13)" or "at http://..." + const match = + /\(([^()]+):(\d+):(\d+)\)\s*$/u.exec(line) ?? + /^\s*at\s+(?:async\s+)?([^\s()]+):(\d+):(\d+)\s*$/u.exec(line) ?? + /@([^\s@]+):(\d+):(\d+)\s*$/u.exec(line); + if (!match) continue; + const url = match[1]!.trim(); + const lineNum = Number(match[2]); + const colNum = Number(match[3]); + if (!url || !Number.isSafeInteger(lineNum) || lineNum < 1 || !Number.isSafeInteger(colNum) || colNum < 1) { + continue; + } + if (IGNORED_STACK_URL_PATTERN.test(url)) continue; + frames.push({ url, line: lineNum, column: colNum }); + } + return frames; +} + +function extractSourceMappingUrl(jsContent: string): string | null { + // Scan only the tail of the bundle where sourceMappingURL pragmas live. + const tail = jsContent.slice(-4096); + const matches = [...tail.matchAll(/\/\/[#@]\s*sourceMappingURL=(\S+)/gu)]; + if (matches.length === 0) return null; + return matches[matches.length - 1]![1] ?? null; +} + +function parseInlineDataSourceMap(dataUrl: string): ParsedSourceMapV3 | null { + const match = /^data:application\/json(?:;charset=[^;,]+)?;base64,([A-Za-z0-9+/=]+)$/iu.exec(dataUrl.trim()); + if (!match) return null; + const base64 = match[1]!; + if (Math.floor((base64.length * 3) / 4) > MAX_SOURCE_MAP_BYTES) return null; + try { + const parsed = JSON.parse(Buffer.from(base64, "base64").toString("utf8")) as Partial; + if (parsed.version === 3 && Array.isArray(parsed.sources) && typeof parsed.mappings === "string") { + return parsed as ParsedSourceMapV3; + } + } catch { + return null; + } + return null; +} + +export interface SourceMapFetcherDeps { + fetchImpl?: typeof fetch; + readFileImpl?: (filePath: string) => Promise; + realpathImpl?: (filePath: string) => Promise; +} + +async function readBoundedResponseText(response: Response): Promise { + if (!response.ok) return null; + const contentLength = Number(response.headers.get("content-length")); + if (Number.isFinite(contentLength) && contentLength > MAX_SOURCE_MAP_BYTES) return null; + if (!response.body) { + const text = await response.text(); + return Buffer.byteLength(text, "utf8") <= MAX_SOURCE_MAP_BYTES ? text : null; + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > MAX_SOURCE_MAP_BYTES) { + await reader.cancel(); + return null; + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks, total).toString("utf8"); +} + +/** + * VLQ source-map resolver bound to the page's own loopback origin (or workspace files for a `file://` page) with 25-entry LRU cache, + * `redirect: "error"`, 1500ms timeout, and 10 MB size cap. + */ +export class LocalGrabSourceMapResolver { + private readonly cache = new Map(); + private readonly fetchImpl: typeof fetch; + private readonly readFileImpl: (filePath: string) => Promise; + private readonly realpathImpl: (filePath: string) => Promise; + + constructor(deps: SourceMapFetcherDeps = {}) { + this.fetchImpl = deps.fetchImpl ?? globalThis.fetch; + this.readFileImpl = deps.readFileImpl ?? ((filePath) => readFile(filePath)); + this.realpathImpl = deps.realpathImpl ?? ((filePath) => realpath(filePath)); + } + + /** Resolves symlinks on both sides so an in-root link cannot reach outside the workspace. */ + private async canonicalWorkspaceFile(url: string, workspaceRoot?: string): Promise { + const lexical = allowedLocalSourceMapFilePath(url, workspaceRoot); + if (!lexical || !workspaceRoot) return null; + try { + const [root, file] = await Promise.all([this.realpathImpl(workspaceRoot), this.realpathImpl(lexical)]); + if (!ALLOWED_LOCAL_FILE_EXTENSIONS.test(file) || !isStrictlyInside(root, file)) return null; + return file; + } catch { + return null; + } + } + + private cacheGet(key: string): IndexedSourceMap | null | undefined { + if (!this.cache.has(key)) return undefined; + const value = this.cache.get(key)!; + this.cache.delete(key); + this.cache.set(key, value); + return value; + } + + private cacheSet(key: string, value: IndexedSourceMap | null): void { + this.cache.delete(key); + this.cache.set(key, value); + while (this.cache.size > SOURCE_MAP_CACHE_LIMIT) { + const oldest = this.cache.keys().next().value; + if (oldest === undefined) break; + this.cache.delete(oldest); + } + } + + private async fetchLocalText( + url: string, + authority: GrabSourceAuthority, + workspaceRoot?: string, + ): Promise { + if (!isAuthorizedSourceUrl(url, authority)) return null; + try { + const parsed = new URL(url); + if (parsed.protocol === "file:") { + const filePath = await this.canonicalWorkspaceFile(url, workspaceRoot); + if (!filePath) return null; + const buf = await this.readFileImpl(filePath); + if (buf.byteLength > MAX_SOURCE_MAP_BYTES) return null; + return buf.toString("utf8"); + } + const response = await this.fetchImpl(url, { + method: "GET", + redirect: "error", + signal: AbortSignal.timeout(SOURCE_MAP_TIMEOUT_MS), + }); + return await readBoundedResponseText(response); + } catch { + return null; + } + } + + private async loadSourceMapForBundle( + bundleUrl: string, + authority: GrabSourceAuthority, + workspaceRoot?: string, + ): Promise { + if (!isAuthorizedSourceUrl(bundleUrl, authority)) { + return null; + } + if (bundleUrl.startsWith("file:") && !allowedLocalSourceMapFilePath(bundleUrl, workspaceRoot)) { + return null; + } + const cacheKey = bundleUrl.startsWith("file:") ? `${workspaceRoot ?? ""}::${bundleUrl}` : bundleUrl; + const cached = this.cacheGet(cacheKey); + if (cached !== undefined) return cached; + + let parsedMap: ParsedSourceMapV3 | null = null; + const jsText = await this.fetchLocalText(bundleUrl, authority, workspaceRoot); + if (jsText) { + const mappingRef = extractSourceMappingUrl(jsText); + if (mappingRef) { + if (mappingRef.startsWith("data:")) { + parsedMap = parseInlineDataSourceMap(mappingRef); + } else { + try { + const mapUrl = new URL(mappingRef, bundleUrl).href; + const mapText = await this.fetchLocalText(mapUrl, authority, workspaceRoot); + if (mapText) { + const json = JSON.parse(mapText) as Partial; + if (json.version === 3 && Array.isArray(json.sources) && typeof json.mappings === "string") { + parsedMap = json as ParsedSourceMapV3; + } + } + } catch { + parsedMap = null; + } + } + } + } + + if (!parsedMap) { + // Fallback: try .map directly if still allowed. + try { + const directMapUrl = `${bundleUrl.split(/[?#]/u)[0]}.map`; + const mapText = await this.fetchLocalText(directMapUrl, authority, workspaceRoot); + if (mapText) { + const json = JSON.parse(mapText) as Partial; + if (json.version === 3 && Array.isArray(json.sources) && typeof json.mappings === "string") { + parsedMap = json as ParsedSourceMapV3; + } + } + } catch { + parsedMap = null; + } + } + + const indexed = parsedMap ? decodeSourceMapMappings(parsedMap) : null; + this.cacheSet(cacheKey, indexed); + return indexed; + } + + async resolveSourceHint( + hint: RawGrabSourceHint | undefined, + workspaceRoot?: string, + options?: { pageUrl?: string }, + ): Promise { + if (!hint) return undefined; + // Only the authoritative page URL grants local reads, never the guest's stack text. + const authority = grabSourceAuthority(options?.pageUrl); + + if (hint.fileName) { + const normalized = normalizeBundlerSourcePath(hint.fileName, workspaceRoot); + if (normalized) { + return { + filePath: normalized, + ...(hint.lineNumber !== undefined ? { line: hint.lineNumber } : {}), + ...(hint.columnNumber !== undefined ? { column: hint.columnNumber } : {}), + symbolicated: false, + }; + } + } + + if (hint.debugStack) { + const frames = parseDebugStackFrames(hint.debugStack); + for (const frame of frames.slice(0, 4)) { + if (authority && isAuthorizedSourceUrl(frame.url, authority)) { + const map = await this.loadSourceMapForBundle(frame.url, authority, workspaceRoot); + if (map) { + const original = lookupOriginalPosition(map, frame.line, frame.column); + if (original) { + const filePath = normalizeBundlerSourcePath(original.source, workspaceRoot); + if (filePath) { + return { + filePath, + line: original.line, + column: original.column, + symbolicated: true, + }; + } + } + } + } + const fallbackPath = normalizeBundlerSourcePath(frame.url, workspaceRoot); + if (fallbackPath) { + return { + filePath: fallbackPath, + line: frame.line, + column: frame.column, + symbolicated: false, + }; + } + } + } + + return undefined; + } +} + +export const defaultGrabSourceMapResolver = new LocalGrabSourceMapResolver(); diff --git a/main/services/browser/grab-thumbnail.test.ts b/main/services/browser/grab-thumbnail.test.ts new file mode 100644 index 0000000000..340b536cf8 --- /dev/null +++ b/main/services/browser/grab-thumbnail.test.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { MAX_GRABBED_ELEMENT_THUMBNAIL_BYTES } from "../../../renderer/shared/browser-element-grab.js"; +import { CREDENTIAL_MASK_GRAY } from "./credential-mask.js"; +import { + computeGrabCropPlan, + computeThumbnailResizeTarget, + finalizeGrabThumbnail, + maskSensitiveFieldsInCroppedBitmap, + type NativeImageFactory, + type NativeImageLike, +} from "./grab-thumbnail.js"; + +test("computeGrabCropPlan pads by 8px CSS, clamps to viewport, scales for responsive letterbox/zoom, and omits off-screen elements", () => { + // Element near top-left edge under 0.5x responsive scaling (pageBounds 640x360 for 1280x720 viewport). + const plan = computeGrabCropPlan( + { x: 2, y: 4, width: 100, height: 50 }, + { width: 1280, height: 720 }, + { x: 0, y: 0, width: 640, height: 360 }, + ); + assert.ok(plan); + assert.deepEqual(plan.cssCrop, { x: 0, y: 0, width: 110, height: 62 }); + assert.deepEqual(plan.captureRect, { x: 0, y: 0, width: 55, height: 31 }); + + // Off-screen element returns null cleanly rather than throwing. + const offScreen = computeGrabCropPlan( + { x: 2000, y: 2000, width: 100, height: 40 }, + { width: 1280, height: 720 }, + { x: 0, y: 0, width: 1280, height: 720 }, + ); + assert.equal(offScreen, null); + + // Collapsed 0x0 element near edge still respects 8px padding if visible; far negative returns null. + const farNegative = computeGrabCropPlan( + { x: -500, y: -500, width: 10, height: 10 }, + { width: 1280, height: 720 }, + { x: 0, y: 0, width: 1280, height: 720 }, + ); + assert.equal(farNegative, null); +}); + +test("maskSensitiveFieldsInCroppedBitmap paints neutral gray over password fields inside Retina crops", () => { + // Crop covers CSS (100, 100, 100, 100) rendered at 2x Retina (200x200 bitmap). + const width = 200; + const height = 200; + const data = new Uint8Array(width * height * 4).fill(0x11); + const masked = maskSensitiveFieldsInCroppedBitmap( + { width, height, data }, + [ + // Inside crop at local CSS (20..60, 30..50) -> Retina pixels (40..120, 60..100) +/- 4px CSS padding. + { x: 120, y: 130, width: 40, height: 20 }, + // Completely outside crop: ignored. + { x: 500, y: 500, width: 80, height: 20 }, + ], + { x: 100, y: 100, width: 100, height: 100 }, + ); + assert.equal(masked, 1); + + // Pixel at center of password field (x=80, y=80) is masked to CREDENTIAL_MASK_GRAY. + const maskedAt = (80 * width + 80) * 4; + assert.equal(data[maskedAt], CREDENTIAL_MASK_GRAY); + assert.equal(data[maskedAt + 1], CREDENTIAL_MASK_GRAY); + assert.equal(data[maskedAt + 2], CREDENTIAL_MASK_GRAY); + assert.equal(data[maskedAt + 3], 0xff); + + // Pixel outside password field (x=4, y=4) stays untouched. + const clearAt = (4 * width + 4) * 4; + assert.equal(data[clearAt], 0x11); +}); + +test("computeThumbnailResizeTarget and finalizeGrabThumbnail cap longest edge at 640px and fall back to JPEG when PNG exceeds 512 KiB", () => { + assert.deepEqual(computeThumbnailResizeTarget(1280, 640), { width: 640, height: 320 }); + assert.deepEqual(computeThumbnailResizeTarget(320, 1280), { width: 160, height: 640 }); + assert.equal(computeThumbnailResizeTarget(400, 300), null); + + let resizeCalledWith: { width?: number; height?: number } | null = null; + let bitmapRecreated = false; + + const makeMockImage = ( + w: number, + h: number, + pngBytes: Buffer, + jpegBytes: Buffer, + ): NativeImageLike => ({ + isEmpty: () => false, + getSize: () => ({ width: w, height: h }), + toBitmap: () => Buffer.alloc(w * h * 4, 0x22), + resize: (opts) => { + resizeCalledWith = opts; + return makeMockImage(opts.width ?? w, opts.height ?? h, pngBytes, jpegBytes); + }, + toPNG: () => pngBytes, + toJPEG: () => jpegBytes, + }); + + const factory: NativeImageFactory = { + createFromBitmap: (_buf, opts) => { + bitmapRecreated = true; + return makeMockImage(opts.width, opts.height, Buffer.alloc(MAX_GRABBED_ELEMENT_THUMBNAIL_BYTES + 100), Buffer.from("/9j/small")); + }, + }; + + const hugePng = Buffer.alloc(MAX_GRABBED_ELEMENT_THUMBNAIL_BYTES + 100); + const smallJpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]); + const initial = makeMockImage(1280, 800, hugePng, smallJpeg); + + const result = finalizeGrabThumbnail( + initial, + factory, + [{ x: 10, y: 10, width: 50, height: 20 }], + { x: 0, y: 0, width: 640, height: 400 }, + ); + + assert.equal(bitmapRecreated, true); + assert.deepEqual(resizeCalledWith, { width: 640, height: 400 }); + assert.ok(result); + assert.equal(result.mimeType, "image/jpeg"); + assert.equal(result.width, 640); + assert.equal(result.height, 400); +}); diff --git a/main/services/browser/grab-thumbnail.ts b/main/services/browser/grab-thumbnail.ts new file mode 100644 index 0000000000..13debeced6 --- /dev/null +++ b/main/services/browser/grab-thumbnail.ts @@ -0,0 +1,196 @@ +import { + MAX_GRABBED_ELEMENT_THUMBNAIL_BYTES, + type GrabbedElementBoundingBox, + type GrabbedElementThumbnail, +} from "../../../renderer/shared/browser-element-grab.js"; +import type { CssRect } from "./credential-fields.js"; +import { cssRectsToImageRects, paintRects, type RawBitmap } from "./credential-mask.js"; + +export const GRAB_THUMBNAIL_PADDING_CSS = 8; +export const GRAB_THUMBNAIL_MAX_EDGE_PX = 640; + +export interface GrabCropPlan { + /** Clamped CSS rect in top-level viewport coordinates. */ + cssCrop: CssRect; + /** Corresponding native capture rectangle inside `pageBounds`. */ + captureRect: { x: number; y: number; width: number; height: number }; +} + +/** + * Pads the grabbed element's bounding box by `paddingCss` CSS pixels, intersects with + * `[0, 0, viewport.width, viewport.height]`, and maps to `pageBounds` capture coordinates + * (automatically handling zoomFactor and responsive letterboxing). + * Returns `null` when the element is collapsed or completely off-screen. + */ +export function computeGrabCropPlan( + boundingBox: GrabbedElementBoundingBox, + viewport: { width: number; height: number }, + pageBounds: { x: number; y: number; width: number; height: number }, + paddingCss = GRAB_THUMBNAIL_PADDING_CSS, +): GrabCropPlan | null { + if ( + !(viewport.width > 0 && viewport.height > 0 && pageBounds.width > 0 && pageBounds.height > 0) + ) { + return null; + } + const left = Math.max(0, boundingBox.x - paddingCss); + const top = Math.max(0, boundingBox.y - paddingCss); + const right = Math.min(viewport.width, boundingBox.x + boundingBox.width + paddingCss); + const bottom = Math.min(viewport.height, boundingBox.y + boundingBox.height + paddingCss); + const cssWidth = right - left; + const cssHeight = bottom - top; + if (!(cssWidth >= 1 && cssHeight >= 1)) return null; + + const scaleX = pageBounds.width / viewport.width; + const scaleY = pageBounds.height / viewport.height; + + const x = Math.max(0, Math.floor(left * scaleX)); + const y = Math.max(0, Math.floor(top * scaleY)); + const captureRight = Math.min(pageBounds.width, Math.ceil(right * scaleX)); + const captureBottom = Math.min(pageBounds.height, Math.ceil(bottom * scaleY)); + const width = captureRight - x; + const height = captureBottom - y; + if (!(width >= 1 && height >= 1)) return null; + + return { + cssCrop: { x: left, y: top, width: cssWidth, height: cssHeight }, + captureRect: { + x: pageBounds.x + x, + y: pageBounds.y + y, + width, + height, + }, + }; +} + +/** + * Translates top-viewport sensitive field CSS rects into crop-local coordinates, + * maps them to bitmap pixels via `credential-mask.ts`, and paints them neutral gray in place. + * Returns the number of masked regions painted. + */ +export function maskSensitiveFieldsInCroppedBitmap( + bitmap: RawBitmap, + sensitiveCssRects: readonly CssRect[], + cssCrop: CssRect, +): number { + if (sensitiveCssRects.length === 0) return 0; + const relative: CssRect[] = []; + for (const rect of sensitiveCssRects) { + const left = Math.max(0, rect.x - cssCrop.x); + const top = Math.max(0, rect.y - cssCrop.y); + const right = Math.min(cssCrop.width, rect.x + rect.width - cssCrop.x); + const bottom = Math.min(cssCrop.height, rect.y + rect.height - cssCrop.y); + if (right > left && bottom > top) { + relative.push({ x: left, y: top, width: right - left, height: bottom - top }); + } + } + if (relative.length === 0) return 0; + const pixelRects = cssRectsToImageRects( + relative, + { width: cssCrop.width, height: cssCrop.height }, + { width: bitmap.width, height: bitmap.height }, + ); + if (pixelRects.length === 0) return 0; + paintRects(bitmap, pixelRects); + return pixelRects.length; +} + +/** Computes target dimensions fitting inside `maxEdge` on the longest side. */ +export function computeThumbnailResizeTarget( + width: number, + height: number, + maxEdge = GRAB_THUMBNAIL_MAX_EDGE_PX, +): { width: number; height: number } | null { + if (!(width > 0 && height > 0)) return null; + if (width <= maxEdge && height <= maxEdge) return null; + if (width >= height) { + return { + width: maxEdge, + height: Math.max(1, Math.round((height * maxEdge) / width)), + }; + } + return { + width: Math.max(1, Math.round((width * maxEdge) / height)), + height: maxEdge, + }; +} + +export interface NativeImageLike { + isEmpty(): boolean; + getSize(): { width: number; height: number }; + toBitmap(): Buffer; + resize(options: { width?: number; height?: number }): NativeImageLike; + toPNG(): Buffer; + toJPEG(quality: number): Buffer; +} + +export interface NativeImageFactory { + createFromBitmap(buffer: Buffer, options: { width: number; height: number }): NativeImageLike; +} + +/** + * Pixel-masks any sensitive fields inside a cropped `NativeImage`, resizes to at most + * 640px on the longest side, and encodes PNG (or JPEG fallback) within 512 KiB. + */ +export function finalizeGrabThumbnail( + captured: NativeImageLike, + factory: NativeImageFactory, + sensitiveCssRects: readonly CssRect[], + cssCrop: CssRect, +): GrabbedElementThumbnail | undefined { + if (captured.isEmpty()) return undefined; + let image = captured; + const initialSize = image.getSize(); + if (!(initialSize.width > 0 && initialSize.height > 0)) return undefined; + + if (sensitiveCssRects.length > 0) { + const raw = Buffer.from(image.toBitmap()); + const maskedCount = maskSensitiveFieldsInCroppedBitmap( + { width: initialSize.width, height: initialSize.height, data: raw }, + sensitiveCssRects, + cssCrop, + ); + if (maskedCount > 0) { + image = factory.createFromBitmap(raw, { + width: initialSize.width, + height: initialSize.height, + }); + } + } + + const resizeTarget = computeThumbnailResizeTarget( + image.getSize().width, + image.getSize().height, + GRAB_THUMBNAIL_MAX_EDGE_PX, + ); + if (resizeTarget) { + image = image.resize(resizeTarget); + } + + const finalSize = image.getSize(); + if (!(finalSize.width > 0 && finalSize.height > 0)) return undefined; + + const png = image.toPNG(); + if (png.byteLength > 0 && png.byteLength <= MAX_GRABBED_ELEMENT_THUMBNAIL_BYTES) { + return { + data: png.toString("base64"), + mimeType: "image/png", + width: finalSize.width, + height: finalSize.height, + }; + } + + for (const quality of [82, 65]) { + const jpeg = image.toJPEG(quality); + if (jpeg.byteLength > 0 && jpeg.byteLength <= MAX_GRABBED_ELEMENT_THUMBNAIL_BYTES) { + return { + data: jpeg.toString("base64"), + mimeType: "image/jpeg", + width: finalSize.width, + height: finalSize.height, + }; + } + } + + return undefined; +} diff --git a/main/services/browser/service.ts b/main/services/browser/service.ts index fdf4ca7bb1..1e72babedc 100644 --- a/main/services/browser/service.ts +++ b/main/services/browser/service.ts @@ -27,6 +27,8 @@ import type { BrowserDiagnostic, BrowserElement, BrowserEvent, + BrowserGrabEndReason, + BrowserGrabSource, BrowserImage, BrowserProfile, BrowserRecording, @@ -68,6 +70,15 @@ import { validBrowserViewport, } from "./preferences.js"; import { playwrightInjectedSource } from "./playwright-source.generated.js"; +import { browserGrabRuntimeSource } from "./grab-runtime.generated.js"; +import { sanitizeRawGrabPayload } from "./grab-sanitize.js"; +import { computeGrabCropPlan, finalizeGrabThumbnail } from "./grab-thumbnail.js"; +import { + resolveGrabAccent, + type GrabbedElementAccent, + type GrabbedElementBoundingBox, + type GrabbedElementThumbnail, +} from "../../../renderer/shared/browser-element-grab.js"; import { browserImportSources, importBrowserCookies } from "./import.js"; import { browserFileService, browserPreviewRequestHeaders, type BrowserFileReservation, type PreparedBrowserFile } from "./files.js"; import type { BrowserApprovalTarget } from "./approval.js"; @@ -96,7 +107,9 @@ import { import { scanSensitiveFieldReach, scanSensitiveFields, + sensitiveFieldBoxes, SensitiveFieldMemory, + type CssRect, type SensitiveFieldReach, } from "./credential-fields.js"; import { configureBrowserPermissionHandlers } from "./permission-policy.js"; @@ -104,6 +117,7 @@ import { loadBrowserUrl } from "./navigation-load.js"; import { configStore } from "../config-store.js"; import { browserRecordingBytesMatch, browserRecordingsFolder, findBrowserRecording } from "./recordings.js"; import { browserRecordingExtension } from "../../../renderer/shared/browser-recording.js"; +import { reportAnalyticsEvent } from "../analytics/analytics-report.js"; import { writeFileAtomic } from "../durable-fs.js"; import { projectDiagnosticError } from "../diagnostics-contract.js"; import { writeDiagnosticEvent } from "../diagnostic-journal.js"; @@ -151,7 +165,7 @@ export interface BrowserHold { const HELD_FIELD_SCAN_MS = 500; /** Actions a Bot's browser port never runs. */ const BOUNDARY_REFUSED_ACTIONS: ReadonlySet = new Set([ - "evaluate", "record_start", "record_stop", "open_file", "annotate", "annotation_preview", "annotation_reset", + "evaluate", "record_start", "record_stop", "open_file", "annotate", "grab", "annotation_preview", "annotation_reset", "annotation_submit", "screenshot", "devtools", ]); interface WorkspaceBrowser { @@ -202,6 +216,8 @@ interface LiveTab { closing: boolean; expectedInputs: Array<{ type: string; key?: string; button?: string; modifiers?: number; expires: number }>; picking?: boolean; + /** `pageUrl` is the page's URL when the grab started; payloads are judged against it. */ + grab?: { token: symbol; accent: GrabbedElementAccent; source: BrowserGrabSource; pageUrl: string }; crashTimes: number[]; crashTimer?: ReturnType; pendingNavigationUrl?: string; @@ -256,7 +272,12 @@ function clone(value: T): T { return structuredClone(value); } function redactBrowserData(value: T): T { - const imagePaths = new Set(["image.data", "snapshot.image.data", "annotation.image.data"]); + const imagePaths = new Set([ + "image.data", + "snapshot.image.data", + "annotation.image.data", + "capture.thumbnail.data", + ]); const visit = (item: unknown, at: string): unknown => { if (typeof item === "string") return imagePaths.has(at) ? item : browserFileService.redactText(item); if (Array.isArray(item)) return item.map((entry, index) => visit(entry, `${at}.${index}`)); @@ -877,6 +898,7 @@ export class BrowserService { wc.on("did-start-navigation", (_event, url, inPlace, isMainFrame) => { if (!inPlace) tab.heldFieldWatch?.invalidate(); if (isMainFrame && !inPlace) { + if (tab.grab) void this.stopGrab(tab, "navigation"); // Capture native state before Electron delivers its queued crash event. // Loading alone cannot distinguish a replacement from a current crash. navigationSupersededCrash = wc.isCrashed(); @@ -948,6 +970,7 @@ export class BrowserService { } }); this.cancelCrashRecovery(tab); + if (tab.grab) void this.stopGrab(tab, "crash"); tab.navigationCommand = undefined; tab.queue.interrupt(); tab.backgroundThrottling.reset(); @@ -991,7 +1014,7 @@ export class BrowserService { }); wc.setIgnoreMenuShortcuts(true); const humanInput = (type: string, key?: string, modifiers?: number, button?: string, nativeModifiers?: number) => { - if (tab.picking) return true; + if (tab.picking || tab.grab) return true; tab.expectedInputs = tab.expectedInputs.filter((expected) => expected.expires > Date.now()); // Pinned Electron 43.1.1 keyboard/generic converter exposes _modifiers: // https://github.com/electron/electron/blob/v43.1.1/shell/common/gin_converters/blink_converter.cc @@ -1016,6 +1039,19 @@ export class BrowserService { return false; }; wc.on("before-input-event", (event, input) => { + // Unstoppable Escape and Shift+Cmd+G while grabbing: page JS cannot hijack them. + if (input.type === "keyDown" && tab.grab) { + if (input.key === "Escape") { + event.preventDefault(); + void this.stopGrab(tab, "escape"); + return; + } + if ((input.meta || input.control) && input.shift && !input.alt && input.key.toLowerCase() === "g") { + event.preventDefault(); + if (!input.isAutoRepeat) void this.stopGrab(tab, "cancelled"); + return; + } + } // A repeated physical key is still user control; only debugger-marked // echoes may consume expectations, regardless of auto-repeat. const modifiers = Number(input.alt) | (Number(input.control) << 1) | (Number(input.meta) << 2) | (Number(input.shift) << 3); @@ -1026,13 +1062,17 @@ export class BrowserService { const shortcut = key === "." ? "annotate" - : key === "l" - ? "focus_address" - : key === "r" - ? input.shift - ? "hard_reload" - : "reload" - : null; + : key === "g" && input.shift + ? input.isAutoRepeat + ? null + : "grab" + : key === "l" + ? "focus_address" + : key === "r" + ? input.shift + ? "hard_reload" + : "reload" + : null; if (shortcut) { event.preventDefault(); this.emit(tab.state.workspaceId, { @@ -1363,6 +1403,7 @@ export class BrowserService { } private close(tab: LiveTab): void { if (tab.closing) return; + if (tab.grab) void this.stopGrab(tab, "closed"); tab.closing = true; this.unwatchHeldFields(tab); this.finishPreviewNavigation(tab); @@ -1639,6 +1680,7 @@ export class BrowserService { let captureBounds = pageBounds; if (bounds) { const region = boundedBounds(bounds); + // Read the size in Aiden's isolated world so page-defined viewport globals can't skew crops. const measured = browserMeasuredViewport( await this.evaluate(tab, "({width:innerWidth,height:innerHeight})", signal, true), ); @@ -1998,6 +2040,7 @@ export class BrowserService { const workspace = this.workspace(tab.state.workspaceId); const previous = workspace.state.activeTabId ? this.tabs.get(workspace.state.activeTabId) : undefined; if (previous && previous !== tab) { + if (previous.grab) void this.stopGrab(previous, "cancelled"); if (previous.state.floating) { this.floating(previous, false, false); this.floating(tab, true, false); @@ -2378,7 +2421,192 @@ export class BrowserService { this.emit(tab.state.workspaceId); } } + private async startGrab( + tab: LiveTab, + accent?: GrabbedElementAccent, + source: BrowserGrabSource = "toolbar", + ): Promise { + const wc = tab.view.webContents; + if (tab.closing || wc.isDestroyed()) return; + // Mutual exclusion with Annotate picker on this tab. + if (tab.picking) { + void wc.executeJavaScript("globalThis.__aidenPickerCancel?.()", true).catch(() => {}); + } + // End any active grab session on this workspace's tabs first. + for (const candidate of this.tabs.values()) { + if (candidate.state.workspaceId === tab.state.workspaceId && candidate.grab) { + await this.stopGrab(candidate, "cancelled"); + } + } + const resolvedAccent = resolveGrabAccent(accent); + const token = Symbol("browser-grab"); + const grabSource: BrowserGrabSource = source === "shortcut" ? "shortcut" : "toolbar"; + tab.grab = { token, accent: resolvedAccent, source: grabSource, pageUrl: wc.getURL() }; + tab.state.grabbing = true; + this.emit(tab.state.workspaceId); + + try { + const injected = await wc.executeJavaScript("typeof globalThis.__aidenGrabStart === 'function'", true); + if (!injected) { + await wc.executeJavaScript(browserGrabRuntimeSource, true); + } + if (tab.grab?.token !== token) return; + await wc.executeJavaScript( + `globalThis.__aidenGrabStart?.(${JSON.stringify({ accent: resolvedAccent })})`, + true, + ); + if (tab.grab?.token !== token) return; + wc.focus(); + void this.runGrabLoop(tab, token); + } catch { + if (tab.grab?.token === token) { + await this.stopGrab(tab, "cancelled"); + } + } + } + + private async stopGrab(tab: LiveTab, reason: BrowserGrabEndReason): Promise { + if (!tab.grab) return; + tab.grab = undefined; + tab.state.grabbing = false; + const wc = tab.view.webContents; + if (!tab.closing && !wc.isDestroyed()) { + void wc.executeJavaScript("globalThis.__aidenGrabStop?.()", true).catch(() => {}); + if ((reason === "picked" || reason === "escape") && wc.isFocused()) { + const owner = this.workspaces.get(tab.state.workspaceId)?.owner; + if (owner && !owner.isDestroyed()) { + const hostWindow = BrowserWindow.getAllWindows().find( + (w) => !w.isDestroyed() && w.webContents.id === owner.id, + ); + hostWindow?.webContents.focus(); + } + } + } + this.emit(tab.state.workspaceId); + this.emit(tab.state.workspaceId, { + type: "grab-ended", + workspaceId: tab.state.workspaceId, + tabId: tab.state.id, + reason, + }); + } + + private async captureGrabThumbnail( + tab: LiveTab, + boundingBox: GrabbedElementBoundingBox, + measuredViewport: { width: number; height: number } | undefined, + domSensitiveRects: readonly CssRect[], + ): Promise { + const wc = tab.view.webContents; + if (tab.closing || wc.isDestroyed()) return undefined; + const viewport = + measuredViewport ?? + browserMeasuredViewport( + await wc + .executeJavaScript("({width:Math.round(innerWidth),height:Math.round(innerHeight)})", true) + .catch(() => undefined), + ); + if (!viewport) return undefined; + const pageBounds = browserPageCaptureBounds( + tab.view.getBounds(), + this.presentationViewport(tab), + ); + const plan = computeGrabCropPlan(boundingBox, viewport, pageBounds); + if (!plan) return undefined; + + const sensitiveRects: CssRect[] = [...domSensitiveRects]; + // Combine with CDP sensitive-field detection when DevTools is closed. + if (!wc.isDevToolsOpened()) { + try { + const pid = wc.mainFrame?.processId; + const remembered = typeof pid === "number" ? tab.sensitiveFields.of(pid) : undefined; + const scan = await sensitiveFieldBoxes(this.cdpPort(tab), viewport, remembered); + for (const field of scan.fields) { + sensitiveRects.push(field.box); + } + } catch { + // DOM-collected sensitive rects still mask password/credential fields. + } + } + + const release = tab.backgroundThrottling.acquire(); + const unhost = this.hostWhileActive(tab); + try { + const captured = await browserDeadline(wc.capturePage(plan.captureRect), 1_200); + return finalizeGrabThumbnail(captured, nativeImage, sensitiveRects, plan.cssCrop); + } finally { + unhost(); + release(); + } + } + + private async runGrabLoop(tab: LiveTab, token: symbol): Promise { + const wc = tab.view.webContents; + while (tab.grab?.token === token && !tab.closing && !wc.isDestroyed()) { + let raw: unknown; + try { + raw = await wc.executeJavaScript("globalThis.__aidenGrabNext?.()", true); + } catch { + if (tab.grab?.token === token) await this.stopGrab(tab, "cancelled"); + return; + } + if (tab.grab?.token !== token) return; + if (!raw || typeof raw !== "object" || (raw as { cancelled?: unknown }).cancelled === true) { + await this.stopGrab(tab, "cancelled"); + return; + } + const grabPageUrl = tab.grab.pageUrl; + + try { + const workspace = await configStore.getWorkspace(tab.state.workspaceId).catch(() => undefined); + const sanitized = await sanitizeRawGrabPayload(raw, { + pageUrl: wc.getURL(), + grabPageUrl, + pageTitle: wc.getTitle(), + workspaceRoot: workspace?.folderPath, + zoomFactor: tab.state.zoom, + }); + if (tab.grab?.token !== token) return; + + const thumbnail = await this.captureGrabThumbnail( + tab, + sanitized.element.boundingBox, + sanitized.measuredViewport, + sanitized.sensitiveRects, + ).catch(() => undefined); + if (tab.grab?.token !== token) return; + + const grabSource = tab.grab.source; + reportAnalyticsEvent("browser_element_grabbed", { + kind: sanitized.element.framework === "dom" ? "dom" : "react", + source: grabSource, + }); + + this.emit(tab.state.workspaceId, { + type: "grab", + workspaceId: tab.state.workspaceId, + tabId: tab.state.id, + capture: { + element: sanitized.element, + ...(thumbnail ? { thumbnail } : {}), + keepActive: sanitized.keepActive, + }, + }); + + if (!sanitized.keepActive) { + await this.stopGrab(tab, "picked"); + return; + } + await wc.executeJavaScript("globalThis.__aidenGrabResume?.()", true); + } catch { + if (tab.grab?.token === token) await this.stopGrab(tab, "cancelled"); + return; + } + } + } + private async pick(tab: LiveTab, signal?: AbortSignal): Promise { + if (tab.grab) await this.stopGrab(tab, "cancelled"); tab.picking = true; try { const picked = await browserDeadline( @@ -2750,10 +2978,15 @@ export class BrowserService { // While the person uses a held tab the agent can't read or drive it, // snapshots included; it may still open and use other tabs. if (context.source === "agent" && tab.hold) throw new Error(BROWSER_HELD_TAB_REFUSED); + if (context.source === "agent" && tab.grab) + throw new Error("The user is currently selecting an element in this tab."); if (context.source === "agent") this.assertHeldFieldsObserved(tab); - // Panel cleanup can cancel an already inactive picker. Hiding browser - // chrome must not interrupt automation or invalidate pending approval. + if (botWorkspace && command.action === "grab") + throw new Error("Element grab is unavailable in a Bot browser."); + // Panel cleanup can cancel an already inactive picker or grab session. Hiding + // browser chrome must not interrupt automation or invalidate pending approval. if (command.action === "annotate" && !command.enabled && !tab.picking) break; + if (command.action === "grab" && !command.enabled && !tab.grab) break; if (context.source === "user" && command.action !== "present") tab.queue.interrupt(); if (command.action === "present") { // A delayed layout report from the old tab must never cover the selected page. @@ -2772,6 +3005,11 @@ export class BrowserService { this.close(tab); break; } + if (command.action === "grab") { + if (command.enabled) await this.startGrab(tab, command.accent, command.source); + else await this.stopGrab(tab, "cancelled"); + break; + } if (command.action === "annotate" && !command.enabled) { await wc.executeJavaScript("globalThis.__aidenPickerCancel?.()"); break; diff --git a/main/services/chat-export.ts b/main/services/chat-export.ts index 6bfcbfc39b..8e52d235d4 100644 --- a/main/services/chat-export.ts +++ b/main/services/chat-export.ts @@ -38,6 +38,10 @@ function createExportBudget() { charge(attachment.mimeType); charge(attachment.kind === "image" ? attachment.data : attachment.text); } + for (const element of message.grabbedElements ?? []) { + charged += 256; + charge(JSON.stringify(element)); + } if (charged > MAX_EXPORT_BYTES) { throw new Error("This chat is too large to export as one Aiden file."); } @@ -115,6 +119,16 @@ export function projectAidenChatExport( delete message.appPanels; } if (message.attachments) message.attachments = portableAttachments(message.attachments); + if (message.grabbedElements?.length) { + const portableIds = new Set((message.attachments ?? []).map((attachment) => attachment.id)); + message.grabbedElements = message.grabbedElements.map((element) => { + if (element.thumbnailAttachmentId && !portableIds.has(element.thumbnailAttachmentId)) { + const { thumbnailAttachmentId: _missing, ...withoutThumb } = element; + return withoutThumb; + } + return element; + }); + } budget.chargeMessage(message); messages.push(message); } diff --git a/main/services/chat-first-message-commit.ts b/main/services/chat-first-message-commit.ts index ca43e4cafa..370876c41e 100644 --- a/main/services/chat-first-message-commit.ts +++ b/main/services/chat-first-message-commit.ts @@ -3,6 +3,7 @@ import { createHash, randomUUID } from "node:crypto"; import type { ParsedChatFirstMessage } from "../handlers/chat-first-message-params.js"; import { analyticsWorkspaceKind } from "./analytics/analytics-ids.js"; import { reportAnalyticsEvent } from "./analytics/analytics-report.js"; +import { countBucket } from "./analytics/analytics-sanitize.js"; import type { Chat, Workspace } from "./types.js"; import type { ChatTurnLease } from "./chat-turn-admission.js"; import type { RendererDocumentOwner } from "./renderer-document-owner.js"; @@ -148,6 +149,7 @@ export function createFirstMessageCommitter(deps: Dependencies) { content: input.content, model: input.messageModel, attachments: input.attachments, + ...(input.grabbedElements ? { grabbedElements: input.grabbedElements } : {}), skill: prepared?.provenance, ...(input.inputSource ? { inputSource: input.inputSource } : {}), }, @@ -159,6 +161,7 @@ export function createFirstMessageCommitter(deps: Dependencies) { role: "user", content: input.content, attachments: input.attachments, + grabbedElements: input.grabbedElements, workspaceId, userMessageId, }, { @@ -173,6 +176,12 @@ export function createFirstMessageCommitter(deps: Dependencies) { : await append(); committed = true; reportAnalyticsEvent("chat_created", { workspace_kind: analyticsWorkspaceKind(target) }); + if (input.grabbedElements?.length) { + reportAnalyticsEvent("browser_grab_sent", { + count_bucket: countBucket(input.grabbedElements.length), + with_screenshot: input.grabbedElements.some((element) => Boolean(element.thumbnailAttachmentId)), + }); + } return chat; } catch (error) { if (isChatCreateReconciliationRequiredError(error)) { @@ -268,7 +277,7 @@ export function createWorktreeFirstMessageCommitter(deps: WorktreeCommitDependen } let worktree: FirstMessageWorktreeInfo; try { - worktree = await deps.ensureWorktree(request, input.content || input.title || "", owner, onProgress); + worktree = await deps.ensureWorktree(request, input.content || input.title || input.grabbedElements?.[0]?.label || "", owner, onProgress); } catch (error) { return worktreeFailure(error); } diff --git a/main/services/chat-store-core.test.ts b/main/services/chat-store-core.test.ts index af74e3ab6b..20780feb96 100644 --- a/main/services/chat-store-core.test.ts +++ b/main/services/chat-store-core.test.ts @@ -10,8 +10,27 @@ import { } from "./chat-store-core.js"; import type { GenerationTimeline } from "../../renderer/shared/generation-timeline.js"; import type { SubagentMessageReferenceV1 } from "../../renderer/shared/subagent-runs.js"; -import { chatForRenderer } from "./visible-chat-projection.js"; +import { chatForRenderer, projectVisibleChatMessage } from "./visible-chat-projection.js"; import { ChatForkError } from "./chat-fork-error.js"; +import { projectAidenChatExport } from "./chat-export.js"; +import { + buildChatRenamePrompt, + buildChatTitlePrompt, + deriveChatTitleSeed, +} from "./chat-title-policy.js"; +import { + GRABBED_ELEMENT_SCHEMA_VERSION, + grabbedElementThumbnailId, + type GrabbedElementContextV1, +} from "../../renderer/shared/browser-element-grab.js"; +import { captureAnalyticsEvents } from "./analytics/test-support.js"; +import { createFirstMessageCommitter } from "./chat-first-message-commit.js"; +import { parseChatFirstMessage } from "../handlers/chat-first-message-params.js"; +import { ChatTurnAdmission } from "./chat-turn-admission.js"; +import { + WorkspaceOperationRegistry, + admitOwnedWorkspaceOperation, +} from "./workspace-operation-registry.js"; import { generationModelMeta } from "./chat-model-selection-meta.js"; async function testStore(t: test.TestContext) { @@ -2082,6 +2101,198 @@ test("getMeta answers from the index without reading the chat's transcript", asy assert.equal("designMode" in (await store.getMeta(chat.id))!, false); }); +const GRAB_TINY_PNG = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScL2aQAAAABJRU5ErkJggg=="; +const GRAB_TINY_PNG_BYTES = Buffer.byteLength(GRAB_TINY_PNG, "base64"); + +function sampleGrabbedElement(overrides: Partial = {}): GrabbedElementContextV1 { + const id = overrides.id ?? "el_card_1"; + const base: GrabbedElementContextV1 = { + version: GRABBED_ELEMENT_SCHEMA_VERSION, + id, + label: "", + framework: "react", + componentName: "PricingCard", + tagName: "article", + selector: "section.pricing > article.card", + htmlSnippet: '

Pro

', + boundingBox: { x: 24, y: 120, width: 320, height: 240 }, + pageUrl: "http://localhost:3000/pricing", + thumbnailAttachmentId: grabbedElementThumbnailId(id), + capturedAt: 1_700_000_000_000, + ...overrides, + }; + if (base.thumbnailAttachmentId === undefined) delete base.thumbnailAttachmentId; + return base; +} + +test("grabbedElements round-trip across createWithFirstMessage, append, restart, fork, export, title policy, and renderer projection", async (t) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-chat-grab-")); + t.after(() => fs.rm(directory, { recursive: true, force: true })); + const store = createChatStore(async () => directory); + + const firstElement = sampleGrabbedElement({ id: "el_first", thumbnailAttachmentId: undefined }); + const created = await store.createWithFirstMessage({ + id: "22222222-2222-4222-8222-222222222222", + workspaceId: "workspace-1", + turnId: "turn-1", + fingerprint: "fp-1", + message: { + id: "msg-1", + content: "", + grabbedElements: [firstElement], + }, + assertCurrent: () => undefined, + }); + assert.equal(created.title, "Element: "); + assert.deepEqual(created.messages[0]?.grabbedElements, [firstElement]); + + const secondElement = sampleGrabbedElement({ id: "el_second", label: "" }); + const thumbAttachment = { + id: grabbedElementThumbnailId("el_second"), + name: "HeroCta.png", + mimeType: "image/png", + kind: "image" as const, + size: GRAB_TINY_PNG_BYTES, + data: GRAB_TINY_PNG, + }; + await store.appendMessage(created.id, { + role: "assistant", + content: "Looks good.", + grabbedElements: [secondElement], + } as never); + await store.appendMessage(created.id, { + role: "user", + content: "Adjust padding", + attachments: [thumbAttachment], + grabbedElements: [secondElement], + }); + + // Cold restart preserves user grabbedElements, strips assistant grabbedElements, and keeps thumbnail hashes. + const reopened = createChatStore(async () => directory); + const loaded = await reopened.get(created.id); + assert.ok(loaded); + assert.deepEqual(loaded.messages[0]?.grabbedElements, [firstElement]); + assert.equal(loaded.messages[1]?.grabbedElements, undefined); + assert.deepEqual(loaded.messages[2]?.grabbedElements, [secondElement]); + + // Renderer projection preserves grabbedElements and turns stored thumbnail into aiden-attachment:// URL. + const withRefs = await reopened.getWithImageReferences(created.id); + const forRenderer = chatForRenderer(withRefs); + assert.deepEqual(forRenderer?.messages[2]?.grabbedElements, [secondElement]); + assert.match(forRenderer?.messages[2]?.attachments?.[0]?.url ?? "", /^aiden-attachment:\/\/image\//u); + + // Copy/fork preserves grabbedElements on user messages. + const copied = await reopened.copyVisibleHistory({ sourceChatId: created.id }); + assert.deepEqual(copied.messages[0]?.grabbedElements, [firstElement]); + assert.equal(copied.messages[1]?.grabbedElements, undefined); + assert.deepEqual(copied.messages[2]?.grabbedElements, [secondElement]); + + // Export preserves grabbedElements and strips thumbnailAttachmentId when image bytes are unavailable. + const exported = projectAidenChatExport(loaded); + assert.deepEqual(exported.chat.messages[0]?.grabbedElements, [firstElement]); + assert.deepEqual(exported.chat.messages[2]?.grabbedElements, [secondElement]); + const exportedMissingThumb = projectAidenChatExport({ + ...loaded, + messages: [ + { + ...loaded.messages[2]!, + attachments: [{ ...thumbAttachment, data: undefined, sha256: "b".repeat(64) }], + }, + ], + }); + assert.equal(exportedMissingThumb.chat.messages[0]?.grabbedElements?.[0]?.thumbnailAttachmentId, undefined); + + // Title policy seeds from grabbed element and avoids grab-thumb_* filename noise. + assert.equal( + deriveChatTitleSeed({ content: "", attachments: [thumbAttachment], grabbedElements: [secondElement] }), + "Element: ", + ); + const titlePrompt = buildChatTitlePrompt({ + content: "Tighten spacing", + attachments: [thumbAttachment], + grabbedElements: [secondElement], + }); + assert.match(titlePrompt, /- Element: /u); + assert.doesNotMatch(titlePrompt, /HeroCta\.png/u); + const renamePrompt = buildChatRenamePrompt(loaded.messages); + assert.match(renamePrompt, /Element: /u); + assert.match(renamePrompt, /Element: /u); + assert.doesNotMatch(renamePrompt, /Image: HeroCta\.png/u); + + // Corrupt entry on disk is dropped leniently on readChat without losing valid siblings. + const file = path.join(directory, `${created.id}.json`); + const raw = JSON.parse(await fs.readFile(file, "utf8")) as { messages: Array> }; + raw.messages[0]!.grabbedElements = [{ broken: true }, firstElement]; + await fs.writeFile(file, JSON.stringify(raw)); + const recovered = await createChatStore(async () => directory).get(created.id); + assert.deepEqual(recovered?.messages[0]?.grabbedElements, [firstElement]); + const projected = projectVisibleChatMessage(raw.messages[0]); + assert.deepEqual(projected?.grabbedElements, [firstElement]); +}); + +test("first-message committer reports browser_grab_sent once on commit and not on replay", async (t) => { + const sent = captureAnalyticsEvents(t); + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "aiden-first-grab-")); + t.after(() => fs.rm(directory, { recursive: true, force: true })); + const store = createChatStore(async () => directory); + const turns = new ChatTurnAdmission(); + const workspaces = new WorkspaceOperationRegistry(); + const owner = { + documentId: "doc-grab-1", + isDestroyed: () => false, + onInvalidated: () => () => undefined, + }; + const commit = createFirstMessageCommitter({ + store, + beginTurn: (chatId, turnId, ownerId) => turns.tryBegin(chatId, turnId, ownerId, false), + requiresReconciliation: (ownerId) => turns.requiresAppendReconciliation(ownerId), + markReconciliation: (ownerId) => turns.markAppendReconciliationRequired(ownerId), + clearReconciliation: (ownerId) => turns.clearAppendReconciliationRequired(ownerId), + admitWorkspace: (workspaceId, document) => admitOwnedWorkspaceOperation(workspaces, document, workspaceId), + getWorkspace: async () => ({}), + resolveSkill: async () => { + throw new Error("Skill unavailable"); + }, + }); + + const element = sampleGrabbedElement({ id: "el_analytics" }); + const parsed = parseChatFirstMessage({ + draftId: "33333333-3333-4333-8333-333333333333", + workspaceId: "workspace-1", + providerId: "openai", + model: "test-model", + turnId: "turn-grab-analytics", + message: { + role: "user", + content: "", + attachments: [ + { + id: grabbedElementThumbnailId("el_analytics"), + name: "PricingCard.png", + mimeType: "image/png", + kind: "image", + size: GRAB_TINY_PNG_BYTES, + data: GRAB_TINY_PNG, + }, + ], + grabbedElements: [element], + }, + }); + + const committed = await commit(parsed, owner); + assert.deepEqual(committed.messages[0]?.grabbedElements, [element]); + assert.deepEqual(sent, [ + { event: "chat_created", props: { workspace_kind: "folder" } }, + { event: "browser_grab_sent", props: { count_bucket: "1", with_screenshot: true } }, + ]); + + // Replay confirms delivery without double-counting analytics. + turns.releaseMatching(committed.id, parsed.turnId, owner.documentId); + await commit(parsed, owner); + assert.equal(sent.length, 2); +}); + test("an in-chat task run on another model leaves the chat's own model unchanged", async (t) => { const store = await testStore(t); const taskModel = { providerId: "task-provider", model: "task-model" }; diff --git a/main/services/chat-store-core.ts b/main/services/chat-store-core.ts index 3053adf2b2..d4c07339a2 100644 --- a/main/services/chat-store-core.ts +++ b/main/services/chat-store-core.ts @@ -47,6 +47,7 @@ import { imagePixelSize } from "../../renderer/shared/image-dimensions.js"; import { parseChatHtmlArtifacts, parseChatImagePlacements, parseHtmlArtifactPlacements } from "../../renderer/shared/chat-artifacts.js"; import { parseChatUiVisualV1, parseChatUiVisuals } from "../../renderer/shared/aiden-ui/visual.js"; import { isVisualSnapshotAttachmentId, parseVisualSnapshots } from "../../renderer/shared/visual-snapshots.js"; +import { parseGrabbedElements } from "../../renderer/shared/browser-element-grab.js"; import { MAX_ATTACHMENT_INLINE_BYTES, MAX_ATTACHMENTS_PER_MESSAGE } from "../../renderer/shared/attachment-contract.js"; import { remappedHtmlArtifactMediaId } from "./generative-ui-artifact-store.js"; import { parseStoredPiAssistantMessage } from "./pi-message-storage.js"; @@ -948,6 +949,10 @@ export function createChatStore( privacyMigrationRequired = true; } } + const grabbedElements = + message.role === "user" + ? parseGrabbedElements(message.grabbedElements, "stored") + : undefined; return { id: message.id, role: message.role, @@ -955,6 +960,7 @@ export function createChatStore( createdAt: message.createdAt, model: message.model, attachments: safeStoredAttachments(message.attachments), + ...(grabbedElements ? { grabbedElements } : {}), appPanels: assistant ? parseAppControlPanels(message.appPanels) : undefined, htmlArtifacts: assistant ? parseChatHtmlArtifacts(message.htmlArtifacts) @@ -1559,7 +1565,7 @@ export function createChatStore( model?: string; turnId: string; fingerprint: string; - message: Pick; + message: Pick; assertCurrent: () => void; }): Promise { return withImageData(await shared([input.id], true, async () => { @@ -1588,7 +1594,8 @@ export function createChatStore( if (await hasQuarantinedPayload(input.id)) { throw new Error("This draft identifier belongs to an unreadable existing chat."); } - if (!input.message.content.trim() && !input.message.attachments?.length) { + const grabbedElements = parseGrabbedElements(input.message.grabbedElements, "stored"); + if (!input.message.content.trim() && !input.message.attachments?.length && !grabbedElements?.length) { throw new Error("Add a message or attachment before sending."); } const now = Date.now(); @@ -1598,6 +1605,7 @@ export function createChatStore( content: input.message.content, model: input.message.model, attachments: safeStoredAttachments(input.message.attachments), + ...(grabbedElements ? { grabbedElements } : {}), skill: parseSkillProvenanceV1(input.message.skill), inputSource: parseChatInputSource(input.message.inputSource), createdAt: now, @@ -1833,9 +1841,17 @@ export function createChatStore( charge(artifact.mediaId); } for (const visual of message.uiVisuals ?? []) charge(JSON.stringify(visual)); + for (const element of message.grabbedElements ?? []) { + chargedBytes += 256; + charge(JSON.stringify(element)); + } if (chargedBytes > MAX_VISIBLE_COPY_BYTES) { throw new ChatForkError("too_large", "This chat is too large to copy safely."); } + const copiedGrabbedElements = + message.role === "user" + ? parseGrabbedElements(message.grabbedElements, "stored") + : undefined; sourceMessageIds.push(message.id); copiedMessages.push({ id: randomUUID(), @@ -1844,6 +1860,7 @@ export function createChatStore( createdAt: message.createdAt, model: message.model, attachments: safeStoredAttachments(message.attachments), + ...(copiedGrabbedElements ? { grabbedElements: copiedGrabbedElements } : {}), htmlArtifacts: message.role === "assistant" ? (message.htmlArtifacts ?? []).map((artifact) => { @@ -2357,6 +2374,10 @@ export function createChatStore( if (message.role === "user" && forkSummaryHoldsSend(chat.forkedFrom)) { throw new Error(FORK_SUMMARY_HOLD_MESSAGE); } + const grabbedElements = + message.role === "user" + ? parseGrabbedElements(message.grabbedElements, "stored") + : undefined; const full: ChatMessage = { id: message.id ?? newId(), role: message.role, @@ -2377,6 +2398,7 @@ export function createChatStore( ? parseProviderFailureV1(message.providerFailure) : undefined, attachments: safeStoredAttachments(message.attachments), + ...(grabbedElements ? { grabbedElements } : {}), appPanels: message.role === "assistant" ? parseAppControlPanels(message.appPanels) : undefined, htmlArtifacts: message.role === "assistant" diff --git a/main/services/chat-title-policy.ts b/main/services/chat-title-policy.ts index be5e40757a..c26d7dbfcd 100644 --- a/main/services/chat-title-policy.ts +++ b/main/services/chat-title-policy.ts @@ -4,6 +4,10 @@ import type { Attachment, ChatMessage } from "./types.js"; import { isHookBlockedPrompt } from "./hook-blocked-prompt.js"; import { chatSurface } from "../../renderer/shared/chat-visibility.js"; +import { + withoutGrabbedElementThumbnails, + type GrabbedElementContextV1, +} from "../../renderer/shared/browser-element-grab.js"; /** * Renderer-initiated renames refuse feature-owned (Design Studio) chats: the @@ -63,21 +67,31 @@ function truncateUtf8(value: string, maximumBytes: number): string { function titleMessageExcerpt(message: ChatMessage): string { const label = message.role === "assistant" ? "Assistant" : "User"; const content = compact(message.content); - const attachments = (message.attachments ?? []).map( + const grabbed = (message.grabbedElements ?? []).map( + (element) => `Element: ${compact(element.label) || "Element"}`, + ); + const attachments = withoutGrabbedElementThumbnails(message.attachments ?? []).map( (attachment) => `${attachment.kind === "image" ? "Image" : "File"}: ${compact(attachment.name)}`, ); - const body = [content, ...attachments].filter(Boolean).join(" | "); + const body = [content, ...grabbed, ...attachments].filter(Boolean).join(" | "); return body ? `${label}: ${body}` : ""; } export function deriveChatTitleSeed(input: { content: string; attachments?: Attachment[]; + grabbedElements?: GrabbedElementContextV1[]; }): string { const message = compact(input.content); if (message) return truncate(message); - const firstAttachment = input.attachments?.[0]; + const firstElement = input.grabbedElements?.[0]; + if (firstElement) { + return truncate(`Element: ${compact(firstElement.label) || "Element"}`); + } + + const firstAttachment = + withoutGrabbedElementThumbnails(input.attachments ?? [])[0] ?? input.attachments?.[0]; if (!firstAttachment) return DEFAULT_CHAT_TITLE; const prefix = firstAttachment.kind === "image" ? "Image" : "File"; return truncate(`${prefix}: ${compact(firstAttachment.name) || "Attachment"}`); @@ -124,10 +138,15 @@ export function sanitizeGeneratedChatTitle(raw: string): string | null { export function buildChatTitlePrompt(input: { content: string; attachments?: Attachment[]; + grabbedElements?: GrabbedElementContextV1[]; }): string { - const attachmentLines = (input.attachments ?? []).map( + const grabbedLines = (input.grabbedElements ?? []).map( + (element) => `- Element: ${compact(element.label) || "Element"}`, + ); + const attachmentLines = withoutGrabbedElementThumbnails(input.attachments ?? []).map( (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.size} bytes)`, ); + const metadataLines = [...grabbedLines, ...attachmentLines]; return [ "Write a concise title for this coding conversation.", "Return only the title, with no JSON, Markdown, quotes, or prefix.", @@ -139,7 +158,7 @@ export function buildChatTitlePrompt(input: { "", "User message:", input.content.slice(0, 8_000), - ...(attachmentLines.length > 0 ? ["", "Attachment metadata:", ...attachmentLines] : []), + ...(metadataLines.length > 0 ? ["", "Attachment metadata:", ...metadataLines] : []), ].join("\n"); } diff --git a/main/services/generation-messages.test.ts b/main/services/generation-messages.test.ts index 29b6581b21..eba34064bc 100644 --- a/main/services/generation-messages.test.ts +++ b/main/services/generation-messages.test.ts @@ -12,6 +12,12 @@ import { parseStoredPiAssistantMessage, storedPiAssistantMessage, } from "./pi-message-storage.js"; +import { createPiModelImageReferences } from "./pi-model-image-references.js"; +import { + GRABBED_ELEMENT_SCHEMA_VERSION, + grabbedElementThumbnailId, + type GrabbedElementContextV1, +} from "../../renderer/shared/browser-element-grab.js"; const model: Model<"openai-completions"> = { id: "test", @@ -348,3 +354,264 @@ test("skill message text is rejected before aggregate attachment concatenation e error.code === "instructions_too_large", ); }); + +function sampleGrabbedElement(overrides: Partial = {}): GrabbedElementContextV1 { + const id = overrides.id ?? "el_hero_1"; + return { + version: GRABBED_ELEMENT_SCHEMA_VERSION, + id, + label: "", + framework: "react", + componentName: "LandingHeroClient", + componentStack: [ + { + name: "LandingHeroClient", + environment: "client", + source: { filePath: "src/components/LandingHeroClient.tsx", line: 42, column: 7, symbolicated: true }, + }, + { name: "HomePage", environment: "server" }, + ], + source: { filePath: "src/components/LandingHeroClient.tsx", line: 42, column: 7, symbolicated: true }, + props: { variant: "primary", disabled: false }, + tagName: "section", + selector: "main > section.hero", + htmlSnippet: '

Hello

', + boundingBox: { x: 12, y: 80, width: 960, height: 420 }, + pageUrl: "http://localhost:3000/", + pageTitle: "Landing", + thumbnailAttachmentId: grabbedElementThumbnailId(id), + capturedAt: 1_700_000_000_000, + ...overrides, + }; +} + +test("grabbed elements serialize deterministically for vision and text-only models without noisy fallbacks", () => { + const firstElement = sampleGrabbedElement({ id: "el_one", label: "" }); + const secondElement = sampleGrabbedElement({ + id: "el_two", + label: "button.cta", + framework: "dom", + componentName: undefined, + componentStack: undefined, + source: undefined, + props: undefined, + tagName: "button", + selector: "button.cta", + }); + const attachments = [ + { + id: grabbedElementThumbnailId("el_two"), + name: "button.png", + mimeType: "image/png", + kind: "image" as const, + size: 4, + data: "THUMB_TWO", + }, + { + id: "user-photo", + name: "photo.png", + mimeType: "image/png", + kind: "image" as const, + size: 4, + data: "USER_PHOTO", + }, + { + id: grabbedElementThumbnailId("el_one"), + name: "hero.png", + mimeType: "image/png", + kind: "image" as const, + size: 4, + data: "THUMB_ONE", + }, + ]; + const message = { + id: "msg-grab", + role: "user" as const, + content: "Tighten spacing", + createdAt: 500, + attachments, + grabbedElements: [firstElement, secondElement], + }; + + // Vision model: emits with thumbnail notes + regular image then #1..#N thumbnails. + const vision = chatMessageToPiMessage(message, model, true); + assert.equal(vision.role, "user"); + assert.ok(Array.isArray(vision.content)); + const visionText = vision.content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); + assert.match(visionText, //u); + assert.match(visionText, /## Element 1: /u); + assert.match(visionText, /## Element 2: button\.cta/u); + assert.equal(visionText.match(/- Thumbnail: attached cropped screenshot/gu)?.length, 2); + assert.equal(visionText.includes("1700000000000"), false, "capturedAt must never enter prompt"); + assert.equal(visionText.includes("el_one"), false, "random element id must never enter prompt"); + const visionImages = vision.content + .filter((part) => part.type === "image") + .map((part) => part.data); + assert.deepEqual(visionImages, ["USER_PHOTO", "THUMB_ONE", "THUMB_TWO"]); + + // Cache stability: changing capturedAt and element/thumbnail ids yields identical prompt text. + const reran = chatMessageToPiMessage( + { + ...message, + grabbedElements: [ + { ...firstElement, id: "el_one_v2", thumbnailAttachmentId: grabbedElementThumbnailId("el_one_v2"), capturedAt: 9_999_999 }, + { ...secondElement, id: "el_two_v2", thumbnailAttachmentId: grabbedElementThumbnailId("el_two_v2"), capturedAt: 9_999_999 }, + ], + attachments: [ + { ...attachments[0]!, id: grabbedElementThumbnailId("el_two_v2") }, + attachments[1]!, + { ...attachments[2]!, id: grabbedElementThumbnailId("el_one_v2") }, + ], + }, + model, + true, + ); + assert.ok(Array.isArray(reran.content)); + const reranText = reran.content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); + assert.equal(reranText, visionText); + + // Text-only model: full structured metadata, NO thumbnail notes, NO image blocks, NO grab-thumb fallback lines. + const textOnly = chatMessageToPiMessage(message, model, false); + assert.equal(textOnly.role, "user"); + assert.ok(Array.isArray(textOnly.content)); + assert.equal(textOnly.content.some((part) => part.type === "image"), false); + const textOnlyBody = textOnly.content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); + assert.match(textOnlyBody, //u); + assert.match(textOnlyBody, /LandingHeroClient\.tsx:42:7/u); + assert.doesNotMatch(textOnlyBody, /- Thumbnail:/u); + assert.match(textOnlyBody, /Attached image reference: image_user-photo \(photo\.png\)/u); + assert.doesNotMatch(textOnlyBody, /grab-thumb_/u); + assert.doesNotMatch(textOnlyBody, /hero\.png|button\.png/u); +}); + +test("grabbed elements without thumbnails still serialize with empty user text and omit unavailable-image noise", () => { + const noThumbElement = sampleGrabbedElement({ id: "el_plain", thumbnailAttachmentId: undefined }); + const textOnlyGrab = chatMessageToPiMessage( + { + id: "msg-no-thumb", + role: "user", + content: "", + createdAt: 600, + grabbedElements: [noThumbElement], + }, + model, + true, + ); + assert.ok(Array.isArray(textOnlyGrab.content)); + assert.match(JSON.stringify(textOnlyGrab.content), //u); + assert.doesNotMatch(JSON.stringify(textOnlyGrab.content), /- Thumbnail:/u); + + const missingThumbElement = sampleGrabbedElement({ id: "el_missing_thumb" }); + const missingThumbMessage = chatMessageToPiMessage( + { + id: "msg-missing-thumb", + role: "user", + content: "Check this", + createdAt: 601, + grabbedElements: [missingThumbElement], + attachments: [ + { + id: grabbedElementThumbnailId("el_missing_thumb"), + name: "hero.png", + mimeType: "image/png", + kind: "image", + size: 42, + sha256: "a".repeat(64), + }, + ], + }, + model, + true, + ); + const serialized = JSON.stringify(missingThumbMessage.content); + assert.doesNotMatch(serialized, /Image unavailable/u); + assert.doesNotMatch(serialized, /- Thumbnail:/u); +}); + +test("explicit skill invocation includes grabbed elements once and keeps thumbnails for vision models", () => { + const element = sampleGrabbedElement({ id: "el_skill" }); + const thumb = { + id: grabbedElementThumbnailId("el_skill"), + name: "hero.png", + mimeType: "image/png", + kind: "image" as const, + size: 4, + data: "SKILL_THUMB", + }; + const body = chatUserTextWithAttachments("Fix alignment", [thumb], 100_000, [element]); + assert.match(body, //u); + assert.doesNotMatch(body, /- Thumbnail:/u); + assert.match(body, /Fix alignment/u); + + assert.throws( + () => chatUserTextWithAttachments("Fix", [thumb], 40, [element]), + (error: unknown) => + error instanceof SkillInvocationError && error.code === "instructions_too_large", + ); + + const wrappedPrompt = `Polish UI.\n\n${body}`; + const persisted = { + id: "msg-skill-grab", + role: "user" as const, + content: "Fix alignment", + createdAt: 700, + attachments: [thumb], + grabbedElements: [element], + }; + + const vision = chatMessageToPiMessage(persisted, model, true, wrappedPrompt); + assert.ok(Array.isArray(vision.content)); + const visionText = vision.content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); + assert.equal(visionText.match(//gu)?.length, 1); + assert.deepEqual( + vision.content.filter((part) => part.type === "image").map((part) => part.data), + ["SKILL_THUMB"], + ); + + const textOnly = chatMessageToPiMessage(persisted, model, false, wrappedPrompt); + assert.ok(Array.isArray(textOnly.content)); + assert.equal(textOnly.content.some((part) => part.type === "image"), false); + assert.doesNotMatch(JSON.stringify(textOnly.content), /Attached image reference/u); +}); + +test("model image references exclude grabbed-element thumbnails from list_image_references and resolve", async () => { + const userImage = { + id: "chat-photo", + name: "photo.png", + mimeType: "image/png", + kind: "image" as const, + size: 70, + data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScL2aQAAAABJRU5ErkJggg==", + }; + const grabThumb = { + ...userImage, + id: grabbedElementThumbnailId("el_1"), + name: "LandingHeroClient.png", + }; + const references = createPiModelImageReferences({ + snapshot: [userImage, grabThumb], + readCurrent: async () => [userImage, grabThumb], + generated: () => [], + }); + const listed = await references.listImages(); + assert.deepEqual( + listed.map((item) => item.id), + ["chat-photo"], + ); + await assert.rejects( + references.resolveImage(grabThumb.id), + /missing, changed, or does not belong/u, + ); +}); diff --git a/main/services/generation-messages.ts b/main/services/generation-messages.ts index e8f2070e8f..892c867c94 100644 --- a/main/services/generation-messages.ts +++ b/main/services/generation-messages.ts @@ -9,6 +9,11 @@ import { SkillInvocationError } from "../../renderer/shared/slash-commands.js"; import type { ChatMessage, ChatStartParams } from "./types.js"; import { visionAttachmentAlias } from "./vision-attachment-reference.js"; import { withoutVisualSnapshots } from "../../renderer/shared/visual-snapshots.js"; +import { + formatGrabbedElementsForPrompt, + withoutGrabbedElementThumbnails, + type GrabbedElementContextV1, +} from "../../renderer/shared/browser-element-grab.js"; const ZERO_USAGE = { input: 0, @@ -26,11 +31,16 @@ function userMessage( timestamp: number, contentFirst = false, includeTextAttachments = true, + grabbedElements?: readonly GrabbedElementContextV1[], + includeGrabbedElements = true, ): Message { - if (!attachments?.length) return { role: "user", content, timestamp }; + const hasGrabbedText = includeGrabbedElements && Boolean(grabbedElements?.length); + if (!attachments?.length && !hasGrabbedText) return { role: "user", content, timestamp }; + const attachmentList = attachments ?? []; + const nonGrabAttachments = withoutGrabbedElementThumbnails(attachmentList); const parts: (TextContent | ImageContent)[] = []; const textFiles = includeTextAttachments - ? attachments.filter( + ? attachmentList.filter( (attachment) => attachment.kind === "text" && attachment.text, ) : []; @@ -40,9 +50,33 @@ function userMessage( `Attached file: ${attachment.name}\n\`\`\`\n${attachment.text}\n\`\`\``, ) .join("\n\n"); + const readableImagesById = new Map( + attachmentList + .filter((attachment) => attachment.kind === "image" && Boolean(attachment.data)) + .map((attachment) => [attachment.id, attachment] as const), + ); + const grabbedForPrompt = hasGrabbedText + ? grabbedElements!.map((element) => { + if ( + supportsImages && + element.thumbnailAttachmentId && + readableImagesById.has(element.thumbnailAttachmentId) + ) { + return element; + } + if (element.thumbnailAttachmentId === undefined) return element; + const { thumbnailAttachmentId: _omitted, ...withoutThumb } = element; + return withoutThumb; + }) + : undefined; + const grabbedText = hasGrabbedText + ? formatGrabbedElementsForPrompt(grabbedForPrompt, { + includeThumbnailNote: supportsImages, + }) + : ""; const imageReferences = supportsImages ? "" - : attachments + : nonGrabAttachments .filter((attachment) => attachment.kind === "image" && attachment.data) .map((attachment) => `Attached image reference: ${visionAttachmentAlias(attachment)} (${attachment.name}).`, @@ -50,20 +84,20 @@ function userMessage( .join("\n"); // An image whose stored file is gone is named, so the model knows the // person shared one even though it can no longer be shown. - const unavailableImages = attachments + const unavailableImages = nonGrabAttachments .filter((attachment) => attachment.kind === "image" && !attachment.data) .map((attachment) => `[Image unavailable: ${attachment.name}]`) .join("\n"); const combinedText = ( contentFirst - ? [content, textPrefix, imageReferences, unavailableImages] - : [textPrefix, content, imageReferences, unavailableImages] + ? [content, textPrefix, grabbedText, imageReferences, unavailableImages] + : [textPrefix, grabbedText, content, imageReferences, unavailableImages] ) .filter(Boolean) .join("\n\n"); if (combinedText) parts.push({ type: "text", text: combinedText }); if (supportsImages) { - for (const attachment of attachments) { + for (const attachment of nonGrabAttachments) { if (attachment.kind === "image" && attachment.data) { parts.push({ type: "image", @@ -72,6 +106,20 @@ function userMessage( }); } } + const emittedThumbnails = new Set(); + for (const element of grabbedElements ?? []) { + const thumbId = element.thumbnailAttachmentId; + if (!thumbId || emittedThumbnails.has(thumbId)) continue; + const thumb = readableImagesById.get(thumbId); + if (thumb?.data) { + emittedThumbnails.add(thumbId); + parts.push({ + type: "image", + data: thumb.data, + mimeType: thumb.mimeType, + }); + } + } } return { role: "user", content: parts.length ? parts : content, timestamp }; } @@ -81,6 +129,7 @@ export function chatUserTextWithAttachments( content: string, attachments: ChatStartParams["messages"][number]["attachments"], maxBytes = Number.MAX_SAFE_INTEGER, + grabbedElements?: readonly GrabbedElementContextV1[], ): string { const textFiles: string[] = []; let totalBytes = Buffer.byteLength(content, "utf8"); @@ -98,6 +147,13 @@ export function chatUserTextWithAttachments( textFiles.push(textFile); } } + const grabbedText = formatGrabbedElementsForPrompt(grabbedElements, { + includeThumbnailNote: false, + }); + if (grabbedText) { + totalBytes += Buffer.byteLength(grabbedText, "utf8"); + if (textFiles.length > 0 || content) totalBytes += 2; + } if (totalBytes > maxBytes) { throw new SkillInvocationError( "instructions_too_large", @@ -105,7 +161,7 @@ export function chatUserTextWithAttachments( ); } const textPrefix = textFiles.join("\n\n"); - return [textPrefix, content].filter(Boolean).join("\n\n"); + return [textPrefix, grabbedText, content].filter(Boolean).join("\n\n"); } /** Shape a not-yet-sent draft exactly as the next request will carry it. */ @@ -113,8 +169,9 @@ export function draftUserPiMessage( content: string, attachments: ChatStartParams["messages"][number]["attachments"], supportsImages: boolean, + grabbedElements?: readonly GrabbedElementContextV1[], ): Message { - return userMessage(content, attachments, supportsImages, Date.now()); + return userMessage(content, attachments, supportsImages, Date.now(), false, true, grabbedElements); } /** Rehydrate Aiden chat history using the generation's exact Pi image gate. */ @@ -143,6 +200,9 @@ export function toPiMessages( message.attachments, supportsImages, now, + false, + true, + message.grabbedElements, ); }); } @@ -167,6 +227,8 @@ export function chatMessageToPiMessage( message.createdAt, true, false, + message.grabbedElements, + false, ); } if (message.role === "assistant" && message.pi) { @@ -191,6 +253,9 @@ export function chatMessageToPiMessage( role: message.role, content, attachments: message.attachments, + ...(message.role === "user" && message.grabbedElements + ? { grabbedElements: message.grabbedElements } + : {}), }, ], }; diff --git a/main/services/llm-client.ts b/main/services/llm-client.ts index 09dd1be3e7..2339e56e02 100644 --- a/main/services/llm-client.ts +++ b/main/services/llm-client.ts @@ -537,6 +537,7 @@ import { chatToolOffers, personWroteChatTurn, offersChildChats, chatTurnArgsTool import { createGenerativeUiDraftSession } from "./generative-ui-draft.js"; import { createUiDraftSession } from "./aiden-ui-draft.js"; import { withoutVisualSnapshots } from "../../renderer/shared/visual-snapshots.js"; +import { withoutGrabbedElementThumbnails } from "../../renderer/shared/browser-element-grab.js"; import { displayedAssistantUiCount } from "./aiden-ui-tool.js"; import { visualSnapshotImages } from "./visual-snapshot-core.js"; import { enqueueVisualSnapshots } from "./visual-snapshot-service.js"; @@ -1431,7 +1432,9 @@ async function prepareGeneration( const generationExtensions: PiAgentRuntimeExtension[] = []; const responseImages = () => uniqueResponseImages(sharedImages, displayedImages); const modelImageReferences = createPiModelImageReferences({ - snapshot: chat.messages.flatMap((message) => withoutVisualSnapshots(message.attachments ?? [])), + snapshot: chat.messages.flatMap((message) => + withoutGrabbedElementThumbnails(withoutVisualSnapshots(message.attachments ?? [])), + ), generated: responseImages, readCurrent: async (referenceSignal) => { signal.throwIfAborted(); @@ -1440,7 +1443,9 @@ async function prepareGeneration( signal.throwIfAborted(); referenceSignal?.throwIfAborted(); if (!current || persistedChatWorkspaceId(current.workspaceId) !== persistedChatWorkspaceId(params.workspaceId)) throw new Error("The reference image chat is no longer available in this workspace."); - return current.messages.flatMap((message) => withoutVisualSnapshots(message.attachments ?? [])); + return current.messages.flatMap((message) => + withoutGrabbedElementThumbnails(withoutVisualSnapshots(message.attachments ?? [])), + ); }, }); const shareImage = (attachment: Attachment, toolCallId: string) => { @@ -2344,7 +2349,9 @@ async function prepareGeneration( botContext && !supportsImages && botContext.admission.authority.visionProvider ? createVisionAnalysisTool( { - attachments: chat.messages.flatMap((message) => withoutVisualSnapshots(message.attachments ?? [])), + attachments: chat.messages.flatMap((message) => + withoutGrabbedElementThumbnails(withoutVisualSnapshots(message.attachments ?? [])), + ), authority: { providerId: botContext.admission.authority.visionProvider.sourceProviderId, modelId: botContext.admission.authority.visionProvider.sourceModelId, @@ -4795,6 +4802,7 @@ export const llmClient = { currentUser.content, currentUser.attachments, SLASH_LIMITS.formattedInvocationBytes, + currentUser.grabbedElements, ), workspaceId!, currentUser.id, diff --git a/main/services/pi-model-image-references.ts b/main/services/pi-model-image-references.ts index 39e4457e5c..c04e885359 100644 --- a/main/services/pi-model-image-references.ts +++ b/main/services/pi-model-image-references.ts @@ -1,4 +1,5 @@ import type { Attachment } from "./types.js"; +import { isGrabbedElementThumbnailId } from "../../renderer/shared/browser-element-grab.js"; import { resolvePiModelImageInputs, type PiModelToolsHost, @@ -49,6 +50,7 @@ export function createPiModelImageReferences(options: { typeof item.id !== "string" || !item.id || item.id.length > 128 || + Boolean(isGrabbedElementThumbnailId(item.id)) || !Number.isSafeInteger(item.size) || item.size < 1 || item.size > 8 * 1024 * 1024 diff --git a/main/services/skill-invocation-turn.ts b/main/services/skill-invocation-turn.ts index 89ad3ca2af..6eb394e4b7 100644 --- a/main/services/skill-invocation-turn.ts +++ b/main/services/skill-invocation-turn.ts @@ -8,6 +8,7 @@ import { } from "../../renderer/shared/slash-commands.js"; import type { RegisteredSkill } from "./skill-registry.js"; import type { Attachment, ChatMessage, ChatRole, ChatStartParams } from "./types.js"; +import type { GrabbedElementContextV1 } from "../../renderer/shared/browser-element-grab.js"; import { chatUserTextWithAttachments } from "./generation-messages.js"; import * as path from "node:path"; import { MAX_CHAT_MESSAGE_CONTENT_BYTES } from "../../renderer/shared/chat-message-contract.js"; @@ -26,6 +27,7 @@ export interface PrepareSkillInvocationForAppendInput { role: ChatRole; content: string; attachments: Attachment[] | undefined; + grabbedElements?: readonly GrabbedElementContextV1[]; workspaceId: string; userMessageId: string; } @@ -53,7 +55,7 @@ export async function prepareSkillInvocationForAppend( "The selected skill and message exceed Aiden’s invocation limit.", ); } - if (!input.content.trim() && !input.attachments?.length) { + if (!input.content.trim() && !input.attachments?.length && !input.grabbedElements?.length) { throw new SkillInvocationError( "invalid_reference", "Add a message or attachment before invoking a skill.", @@ -66,6 +68,7 @@ export async function prepareSkillInvocationForAppend( input.content, input.attachments, SLASH_LIMITS.formattedInvocationBytes, + input.grabbedElements, ), input.workspaceId, input.userMessageId, diff --git a/main/services/types.ts b/main/services/types.ts index 94c18766ca..e6a4d9e91f 100644 --- a/main/services/types.ts +++ b/main/services/types.ts @@ -21,6 +21,7 @@ import type { ProviderFailureV1 } from "../../renderer/shared/provider-failure.j import type { ChatHtmlArtifactV1, HtmlArtifactPlacementV1, ChatImagePlacementV1 } from "../../renderer/shared/chat-artifacts.js"; import type { ChatUiVisualV1 } from "../../renderer/shared/aiden-ui/types.js"; import type { VisualSnapshotRefV1 } from "../../renderer/shared/visual-snapshots.js"; +import type { GrabbedElementContextV1 } from "../../renderer/shared/browser-element-grab.js"; import type { ChatForkLineageV1 } from "../../renderer/shared/chat-copy-contract.js"; import type { ChatStartedByV1 } from "../../renderer/shared/chat-started-by.js"; import type { AssistantMessage } from "@earendil-works/pi-ai"; @@ -375,6 +376,8 @@ export interface ChatMessage { providerFailure?: ProviderFailureV1; /** Files presented with this user or assistant message. */ attachments?: Attachment[]; + /** Browser elements grabbed from Aiden Browser for this user message; linked thumbnails live in `attachments`. */ + grabbedElements?: GrabbedElementContextV1[]; /** Interactive HTML artifacts; bytes remain in the generative-ui store. */ appPanels?: import("../../renderer/shared/app-controls").AppControlPanel[]; htmlArtifacts?: ChatHtmlArtifactV1[]; @@ -1182,6 +1185,7 @@ export interface ChatStartParams { role: ChatRole; content: string; attachments?: Attachment[]; + grabbedElements?: GrabbedElementContextV1[]; }>; } diff --git a/main/services/visible-chat-projection.ts b/main/services/visible-chat-projection.ts index 811777beba..d804de38c1 100644 --- a/main/services/visible-chat-projection.ts +++ b/main/services/visible-chat-projection.ts @@ -9,6 +9,10 @@ import { chatImageUrl } from "./chat-attachment-request-handler.js"; import { parseChatHtmlArtifacts, parseChatImagePlacements, parseHtmlArtifactPlacements } from "../../renderer/shared/chat-artifacts.js"; import { parseChatUiVisuals } from "../../renderer/shared/aiden-ui/visual.js"; import { parseVisualSnapshots } from "../../renderer/shared/visual-snapshots.js"; +import { + parseGrabbedElements, + type GrabbedElementContextV1, +} from "../../renderer/shared/browser-element-grab.js"; import { parseSkillProvenanceV1 } from "../../renderer/shared/slash-commands.js"; import { parseAgentNoticeV1, type AgentNoticeV1 } from "../../renderer/shared/agent-notices.js"; import { hookBlockedField, type HookBlockedPromptV1 } from "./hook-blocked-prompt.js"; @@ -42,6 +46,7 @@ export interface VisibleChatMessage { createdAt: number; model?: string; attachments?: Attachment[]; + grabbedElements?: GrabbedElementContextV1[]; appPanels?: import("../../renderer/shared/app-controls.js").AppControlPanel[]; htmlArtifacts?: import("../../renderer/shared/chat-artifacts.js").ChatHtmlArtifactV1[]; htmlArtifactPlacements?: import("../../renderer/shared/chat-artifacts.js").HtmlArtifactPlacementV1[]; @@ -195,6 +200,10 @@ export function projectVisibleChatMessage(value: unknown): VisibleChatMessage | MAX_MODEL_ID_BYTES, true, ); + const grabbedElements = + message.role === "user" + ? parseGrabbedElements(message.grabbedElements, "stored") + : undefined; return { id, role: message.role, @@ -202,6 +211,7 @@ export function projectVisibleChatMessage(value: unknown): VisibleChatMessage | createdAt: message.createdAt as number, model, attachments: safeStoredAttachments(message.attachments), + ...(grabbedElements ? { grabbedElements } : {}), appPanels: message.role === "assistant" ? parseAppControlPanels(message.appPanels) : undefined, htmlArtifacts: message.role === "assistant" diff --git a/package.json b/package.json index d34675ba95..22e77a21fb 100644 --- a/package.json +++ b/package.json @@ -82,7 +82,7 @@ "test:model-insights": "tsx --test main/services/openrouter-benchmark.test.ts main/services/models.test.ts main/services/provider-model-info-core.test.ts main/handlers/ipc-contract.test.ts main/services/model-pace.test.ts main/handlers/model-pace.test.ts renderer/lib/model-pace-queries.test.ts", "test:model-pad": "tsx --test renderer/components/ui-info-hint.test.tsx renderer/components/settings/model-pad/model-pad-settings.test.tsx renderer/components/settings/model-pad/model-pad-autosave.test.tsx renderer/components/settings/model-pad/model-pad-first-visit.test.tsx renderer/components/settings/model-pad/model-pad-siblings.test.tsx renderer/components/settings/model-pad/model-pad-measured-pace.test.tsx renderer/components/settings/model-pad/model-pad-add-popover.test.tsx renderer/components/settings/model-pad/model-pad-tray.test.tsx renderer/components/settings/model-pad/model-pad-data-rows.test.tsx renderer/components/model-pad-markers.test.tsx renderer/components/model-picker-pad.test.tsx renderer/components/model-picker.test.tsx renderer/components/model-hover-details.test.tsx renderer/lib/model-details.test.ts renderer/lib/google-provider-migration.test.ts renderer/lib/model-pad-layout.test.ts renderer/lib/model-pad-pace.test.ts renderer/lib/model-picker-data.test.ts renderer/lib/pi-provider-display.test.ts renderer/shared/model-pad-preferences.test.ts renderer/lib/model-pad-preferences.test.tsx renderer/lib/reduced-motion.test.ts renderer/lib/use-presence.test.tsx", "test:command-system": "tsx --test main/services/native-menu-command-contract.test.ts main/services/renderer-readiness-core.test.ts main/services/shortcut-registration-core.test.ts main/services/shortcut-transaction-core.test.ts main/services/superseding-task-core.test.ts renderer/lib/appearance-intent.test.ts renderer/lib/command-palette-contract.test.ts renderer/lib/command-palette-results.test.ts renderer/lib/text-match.test.ts renderer/lib/reveal-in-list.test.ts renderer/components/command-palette.test.tsx renderer/lib/command-palette-recent.test.ts renderer/lib/new-chat-workspaces.test.ts renderer/lib/command-system-core.test.ts renderer/lib/shortcut-settings-contract.test.ts renderer/lib/use-model-selection.test.ts renderer/shared/keybindings.test.ts renderer/lib/composer-type-focus.test.ts renderer/lib/held-modifier-reveal.test.ts renderer/lib/input-modality.test.ts renderer/lib/focus-regions.test.tsx renderer/components/chat-find-bar.test.tsx renderer/components/composer-edit-last.test.tsx renderer/lib/shortcut-sheet.test.ts renderer/components/keyboard-shortcuts-dialog.test.tsx renderer/lib/dismiss-key.test.ts renderer/lib/layer-stack.test.tsx renderer/lib/focus-return.test.tsx renderer/lib/use-resize-handle.test.tsx renderer/lib/reorder-draft.test.tsx", - "test:slash-commands": "tsx --test main/services/generation-initialization-terminal.test.ts main/handlers/attachments.contract.test.ts main/handlers/chat.parse.test.ts main/handlers/chat-create-params.test.ts main/handlers/chat-session-params.test.ts main/handlers/worktree-create-params.test.ts main/services/chat-workspace-authority.test.ts main/handlers/chats.append.contract.test.ts main/services/attachment-contract.test.ts main/services/attachments.test.ts main/services/chat-append-commit.test.ts main/services/chat-export.test.ts main/services/chat-message-contract.test.ts main/services/chat-session-copy.test.ts main/services/chat-fork-service.test.ts main/services/chat-store-core.test.ts main/services/empty-chat-migration.test.ts main/services/chat-first-message-commit.test.ts main/services/chat-run-input-admission.test.ts main/services/chat-owed-turns.test.ts main/services/chat-owed-turn-prompts.test.ts main/services/chat-turn-admission.test.ts main/services/chat-turn-admission-lifecycle.test.ts main/services/generation-settlement.test.ts main/services/generation-messages.test.ts main/services/provider-auth-flow-core.test.ts main/services/provider-list-core.test.ts main/services/provider-artwork-core.test.ts main/services/provider-artwork.test.ts main/services/scheduled-chat-creation.test.ts main/services/skill-invocation-flow.integration.test.ts main/services/skill-invocation-turn.test.ts main/services/skill-registry-core.test.ts main/services/skill-registry.test.ts main/services/skill-tools.test.ts main/services/skills-discovery.test.ts renderer/components/assistant/assistant-ui.test.tsx renderer/components/composer.test.tsx renderer/components/composer-slash-palette.test.tsx renderer/components/composer-mentions.test.tsx renderer/lib/composer-mentions.test.ts renderer/lib/chat-message-queue.test.ts renderer/lib/chat-draft.test.ts renderer/components/message-bubble.test.tsx renderer/lib/chat-copy-view.test.ts renderer/components/fork-summary-card.test.tsx renderer/shared/chat-copy-contract.test.ts renderer/lib/codex-provider-cache.test.ts renderer/lib/composer-submission.test.ts renderer/lib/ipc-stream.test.ts renderer/lib/skill-catalog-workspace.test.ts renderer/lib/slash-command-actions.test.ts renderer/lib/slash-command-core.test.ts renderer/lib/slash-command-performance.test.ts renderer/main/chat-transition.test.tsx renderer/shared/attachment-contract.test.ts renderer/shared/chat-message-contract.test.ts renderer/shared/slash-commands.test.ts renderer/components/settings/skills-settings.test.tsx renderer/lib/composer-type-focus.test.ts renderer/lib/compaction-command-admission.test.ts main/services/on-demand-tools.test.ts", + "test:slash-commands": "tsx --test main/services/generation-initialization-terminal.test.ts main/handlers/attachments.contract.test.ts main/handlers/chat.parse.test.ts main/handlers/chat-create-params.test.ts main/handlers/chat-session-params.test.ts main/handlers/worktree-create-params.test.ts main/services/chat-workspace-authority.test.ts main/handlers/chats.append.contract.test.ts main/services/attachment-contract.test.ts main/services/attachments.test.ts main/services/chat-append-commit.test.ts main/services/chat-export.test.ts main/services/chat-message-contract.test.ts main/services/chat-session-copy.test.ts main/services/chat-fork-service.test.ts main/services/chat-store-core.test.ts main/services/empty-chat-migration.test.ts main/services/chat-first-message-commit.test.ts main/services/chat-run-input-admission.test.ts main/services/chat-owed-turns.test.ts main/services/chat-owed-turn-prompts.test.ts main/services/chat-turn-admission.test.ts main/services/chat-turn-admission-lifecycle.test.ts main/services/generation-settlement.test.ts main/services/generation-messages.test.ts main/services/provider-auth-flow-core.test.ts main/services/provider-list-core.test.ts main/services/provider-artwork-core.test.ts main/services/provider-artwork.test.ts main/services/scheduled-chat-creation.test.ts main/services/skill-invocation-flow.integration.test.ts main/services/skill-invocation-turn.test.ts main/services/skill-registry-core.test.ts main/services/skill-registry.test.ts main/services/skill-tools.test.ts main/services/skills-discovery.test.ts renderer/components/assistant/assistant-ui.test.tsx renderer/components/composer.test.tsx renderer/components/composer-slash-palette.test.tsx renderer/components/composer-mentions.test.tsx renderer/lib/composer-mentions.test.ts renderer/lib/chat-message-queue.test.ts renderer/lib/chat-draft.test.ts renderer/components/message-bubble.test.tsx renderer/lib/chat-copy-view.test.ts renderer/components/fork-summary-card.test.tsx renderer/shared/chat-copy-contract.test.ts renderer/lib/codex-provider-cache.test.ts renderer/lib/composer-submission.test.ts renderer/lib/ipc-stream.test.ts renderer/lib/skill-catalog-workspace.test.ts renderer/lib/slash-command-actions.test.ts renderer/lib/slash-command-core.test.ts renderer/lib/slash-command-performance.test.ts renderer/main/chat-transition.test.tsx renderer/shared/attachment-contract.test.ts renderer/shared/chat-message-contract.test.ts renderer/shared/slash-commands.test.ts renderer/components/settings/skills-settings.test.tsx renderer/lib/composer-type-focus.test.ts renderer/lib/compaction-command-admission.test.ts main/services/on-demand-tools.test.ts renderer/shared/browser-element-grab.test.ts renderer/components/grabbed-element-chip.test.tsx renderer/components/composer-browser-grab.test.tsx", "test:rich-links": "tsx --test renderer/lib/rich-link.test.ts renderer/lib/user-message-fold.test.ts renderer/components/message-bubble.test.tsx renderer/lib/streaming-motion-contract.test.ts renderer/components/message-list-settle.test.tsx renderer/components/streaming-markdown-reveal.test.tsx renderer/components/provider-failure-callout.test.tsx", "test:display-image": "tsx --test renderer/components/classifier-approval.test.tsx main/services/pi-model-tools.test.ts main/services/pi-local-classifier.test.ts main/services/display-image-artifact-store.test.ts main/services/display-image-extension.test.ts main/services/generation-timeline.test.ts renderer/components/message-bubble.test.tsx renderer/lib/ipc-stream.test.ts", "test:ask-user-question": "tsx --test renderer/shared/ask-user-question.test.ts main/services/ask-user-question-coordinator.test.ts main/services/ask-user-question-extension.test.ts renderer/components/ask-user-question-composer.test.ts renderer/components/ask-user-question-expiry-notice.test.tsx renderer/components/ask-user-question-recap.test.tsx renderer/components/ask-user-question-composer-keys.test.tsx", diff --git a/packages/cli/src/daemon-chats.ts b/packages/cli/src/daemon-chats.ts index 5fadeee496..d5cc81cc35 100644 --- a/packages/cli/src/daemon-chats.ts +++ b/packages/cli/src/daemon-chats.ts @@ -8,6 +8,7 @@ import { createServerVisualCollector } from "./server-visuals.ts"; import { createMcpExtension } from "./mcp.ts"; import type { InlineExtension } from "@earendil-works/pi-coding-agent"; import { visionAttachmentAlias } from "../../../main/services/vision-attachment-reference.js"; +import { formatGrabbedElementsForPrompt, withoutGrabbedElementThumbnails } from "../../../renderer/shared/browser-element-grab.js"; import { withoutMessageThreads } from "../../../main/services/pi-message-threads.js"; import { daemonSettingsManager, profileKeepsLongPromptCache, profileWarmsCaches } from "./daemon-session-settings.ts"; import { PiCacheWarmer, settleReplyCacheWarmer } from "../../../main/services/pi-cache-warming.js"; @@ -531,16 +532,40 @@ export function createDaemonChats(agentDir: string) { }); const input = params.messages.at(-1) ?? chat.messages.at(-1); if (!input) throw new Error("A user message is required."); + const stored = "id" in input && typeof input.id === "string" + ? chat.messages.find((message) => message.id === input.id && message.role === "user") + : chat.messages.findLast((message) => message.role === "user" && message.content === input.content); const attachments = parseAttachments(withReadableImages(input.attachments)) ?? []; - const text = [input.content, ...attachments.filter((item) => item.kind === "image" && !model.input.includes("image")).map((item) => `Attached image: ${visionAttachmentAlias(item)} (${item.name}). Use inspect_image to analyze it.`), ...attachments.filter((item) => item.kind === "text").map((item) => `Attachment: ${item.name}\n${item.text ?? ""}`)].join("\n\n"); + const supportsImages = model.input.includes("image"); + const grabbedElements = input.role === "user" + ? (input.grabbedElements ?? stored?.grabbedElements) + : undefined; + const readableImagesById = new Map( + attachments + .filter((item) => item.kind === "image" && Boolean(item.data)) + .map((item) => [item.id, item] as const), + ); + const grabbedForPrompt = grabbedElements?.map((element) => { + if (supportsImages && element.thumbnailAttachmentId && readableImagesById.has(element.thumbnailAttachmentId)) { + return element; + } + if (element.thumbnailAttachmentId === undefined) return element; + const { thumbnailAttachmentId: _omitted, ...withoutThumb } = element; + return withoutThumb; + }); + const grabbedText = formatGrabbedElementsForPrompt(grabbedForPrompt, { includeThumbnailNote: supportsImages }); + const nonGrabAttachments = withoutGrabbedElementThumbnails(attachments); + const text = [ + grabbedText, + input.content, + ...nonGrabAttachments.filter((item) => item.kind === "image" && !supportsImages).map((item) => `Attached image: ${visionAttachmentAlias(item)} (${item.name}). Use inspect_image to analyze it.`), + ...attachments.filter((item) => item.kind === "text").map((item) => `Attachment: ${item.name}\n${item.text ?? ""}`), + ].filter(Boolean).join("\n\n"); if (!botAdmission) { // SessionStart then UserPromptSubmit, as on the desktop. A SessionStart `continue: false` or a refused // prompt throws before the model runs; a refused prompt never reaches the journal, and its stored copy // is marked (by id) so forks and summaries never send it later. A retried prompt that goes through now // loses the mark. - const stored = "id" in input && typeof input.id === "string" - ? chat.messages.find((message) => message.id === input.id && message.role === "user") - : chat.messages.findLast((message) => message.role === "user" && message.content === input.content); turnHookContext = await runPromptIntakeHooks({ target: hookTarget, dispatch: dispatchHook, hasPriorMessages: chat.messages.some((message) => message.role === "assistant"), @@ -551,7 +576,23 @@ export function createDaemonChats(agentDir: string) { }); } await assertAuthority(); - await session.prompt(text, { expandPromptTemplates: false, preflightResult: (accepted) => { if (accepted) options.onTurnAccepted?.(); }, images: (model.input.includes("image") ? attachments : []).flatMap((item) => item.kind === "image" && item.data ? [{ type: "image" as const, data: item.data, mimeType: item.mimeType }] : []) }); + const promptImages: Array<{ type: "image"; data: string; mimeType: string }> = []; + if (supportsImages) { + for (const item of nonGrabAttachments) { + if (item.kind === "image" && item.data) promptImages.push({ type: "image", data: item.data, mimeType: item.mimeType }); + } + const emittedThumbnails = new Set(); + for (const element of grabbedElements ?? []) { + const thumbId = element.thumbnailAttachmentId; + if (!thumbId || emittedThumbnails.has(thumbId)) continue; + const thumb = readableImagesById.get(thumbId); + if (thumb?.data) { + emittedThumbnails.add(thumbId); + promptImages.push({ type: "image", data: thumb.data, mimeType: thumb.mimeType }); + } + } + } + await session.prompt(text, { expandPromptTemplates: false, preflightResult: (accepted) => { if (accepted) options.onTurnAccepted?.(); }, images: promptImages }); if (entry.stopRequested) throw new Error("Generation cancelled."); // Stop hooks may keep a workspace chat's turn going, at most MAX_STOP_HOOK_CONTINUATIONS times. for (let continuation = 0; !botAdmission && hookStop === undefined && continuation < MAX_STOP_HOOK_CONTINUATIONS; continuation += 1) { diff --git a/packages/cli/src/daemon-forks.ts b/packages/cli/src/daemon-forks.ts index 9705813543..c58fa26109 100644 --- a/packages/cli/src/daemon-forks.ts +++ b/packages/cli/src/daemon-forks.ts @@ -5,6 +5,7 @@ import { dirname } from "node:path"; import { SessionManager } from "@earendil-works/pi-coding-agent"; import type { Message } from "@earendil-works/pi-ai"; import { parseAttachments, withReadableImages } from "../../../main/services/attachment-contract.js"; +import { formatGrabbedElementsForPrompt, withoutGrabbedElementThumbnails } from "../../../renderer/shared/browser-element-grab.js"; import { createChatForkService } from "../../../main/services/chat-fork-service.js"; import { withoutHookBlockedPrompts } from "../../../main/services/hook-blocked-prompt.js"; import { workspaceFolderMissing } from "../../../main/services/workspace-folder-presence.js"; @@ -20,9 +21,42 @@ function journalMessage(message: ChatMessage): Message { usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }; } const attachments = parseAttachments(withReadableImages(message.attachments)) ?? []; - return { role: "user", timestamp: message.createdAt, content: [{ type: "text", text: message.content }, ...attachments.map((attachment) => attachment.kind === "image" && attachment.data - ? { type: "image" as const, data: attachment.data, mimeType: attachment.mimeType } - : { type: "text" as const, text: `Attachment: ${attachment.name}\n${attachment.text ?? ""}` })] }; + const readableImagesById = new Map( + attachments + .filter((attachment) => attachment.kind === "image" && Boolean(attachment.data)) + .map((attachment) => [attachment.id, attachment] as const), + ); + const grabbedForPrompt = message.grabbedElements?.map((element) => { + if (element.thumbnailAttachmentId && readableImagesById.has(element.thumbnailAttachmentId)) { + return element; + } + if (element.thumbnailAttachmentId === undefined) return element; + const { thumbnailAttachmentId: _omitted, ...withoutThumb } = element; + return withoutThumb; + }); + const grabbedText = formatGrabbedElementsForPrompt(grabbedForPrompt, { includeThumbnailNote: true }); + const textContent = [grabbedText, message.content].filter(Boolean).join("\n\n"); + const nonGrabAttachments = withoutGrabbedElementThumbnails(attachments); + const emittedThumbnails = new Set(); + const thumbnailParts = (message.grabbedElements ?? []).flatMap((element) => { + const thumbId = element.thumbnailAttachmentId; + if (!thumbId || emittedThumbnails.has(thumbId)) return []; + const thumb = readableImagesById.get(thumbId); + if (!thumb?.data) return []; + emittedThumbnails.add(thumbId); + return [{ type: "image" as const, data: thumb.data, mimeType: thumb.mimeType }]; + }); + return { + role: "user", + timestamp: message.createdAt, + content: [ + { type: "text", text: textContent }, + ...nonGrabAttachments.map((attachment) => attachment.kind === "image" && attachment.data + ? { type: "image" as const, data: attachment.data, mimeType: attachment.mimeType } + : { type: "text" as const, text: `Attachment: ${attachment.name}\n${attachment.text ?? ""}` }), + ...thumbnailParts, + ], + }; } /** diff --git a/renderer/components/browser-panel.test.tsx b/renderer/components/browser-panel.test.tsx index d36c28db2d..65a8b785a1 100644 --- a/renderer/components/browser-panel.test.tsx +++ b/renderer/components/browser-panel.test.tsx @@ -1,11 +1,30 @@ +import { emitBotTestNotification, installBotTestIpc } from "../main/bots/test-dom"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; -import test from "node:test"; +import test, { afterEach } from "node:test"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { renderToStaticMarkup } from "react-dom/server"; -import { BrowserDeviceToolbar, BrowserEmptyState } from "./browser-panel.js"; +import { BrowserDeviceToolbar, BrowserEmptyState, BrowserPanel } from "./browser-panel.js"; import { BrowserAnnotationEditor } from "./browser-annotation-editor.js"; import { storedEnvironmentPanelTab, reduceEnvironmentSurfaceState } from "../lib/environment-panel-state.js"; -import { DEFAULT_BROWSER_SETTINGS, type BrowserSnapshot, type BrowserTab } from "../shared/browser.js"; +import { + BROWSER_ELEMENT_GRAB_UNAVAILABLE, + browserElementGrabDelivery, +} from "../lib/browser-element-grab-delivery.js"; +import { + GRABBED_ELEMENT_SCHEMA_VERSION, + type GrabbedElementCapture, +} from "../shared/browser-element-grab.js"; +import { + BUILT_IN_BROWSER_PROFILES, + DEFAULT_BROWSER_SETTINGS, + type BrowserCommand, + type BrowserSnapshot, + type BrowserState, + type BrowserTab, +} from "../shared/browser.js"; + +afterEach(cleanup); const tab: BrowserTab = { id: "tab", workspaceId: "workspace", profileId: "default", url: "http://localhost:3000", title: "App", loading: false, canGoBack: false, canGoForward: false, crashed: false, audible: false, muted: false, viewport: { mode: "responsive", width: 375, height: 667 }, appearance: "system", zoom: 1, recording: false, agentControlling: false, floating: false }; @@ -113,3 +132,140 @@ test("a failed first browser state read replaces the endless spinner with Try ag assert.match(failed, /Couldn’t open the browser/u); assert.match(failed, />Try again<\/button>/u); }); + +test("Grab toolbar button toggles element grab, shows active status bar, delivers captures to composer, and cancels on Escape", async () => { + const commands: BrowserCommand[] = []; + let grabbing = false; + let revision = 1; + const currentState = (): BrowserState => ({ + workspaceId: "ws-grab", + revision, + tabs: [{ ...tab, id: "tab-grab", workspaceId: "ws-grab", grabbing }], + activeTabId: "tab-grab", + profiles: structuredClone(BUILT_IN_BROWSER_PROFILES), + defaults: structuredClone(DEFAULT_BROWSER_SETTINGS), + agentAccessOverride: "inherit", + agentAccessAllowed: true, + history: [], + servers: [], + }); + + installBotTestIpc({ + "browser:get-state": () => currentState(), + "browser:command": (_ws: unknown, cmd: unknown) => { + const command = cmd as BrowserCommand; + commands.push(command); + if (command.action === "grab") { + grabbing = command.enabled; + revision += 1; + } + return { state: currentState() }; + }, + }); + + render(); + await screen.findByRole("tab", { name: "App" }); + const grabButton = screen.getByRole("button", { name: "Grab element" }); + const annotateButton = screen.getByRole("button", { name: "Annotate" }); + const addressForm = document.querySelector(".browser-address-form"); + assert.ok(addressForm, "address form is rendered"); + // Grab sits immediately right of .browser-address-form, before Annotate. + assert.ok( + Boolean(addressForm.compareDocumentPosition(grabButton) & Node.DOCUMENT_POSITION_FOLLOWING), + "Grab button follows address form", + ); + assert.ok( + Boolean(grabButton.compareDocumentPosition(annotateButton) & Node.DOCUMENT_POSITION_FOLLOWING), + "Grab button precedes Annotate button", + ); + assert.equal(grabButton.getAttribute("aria-pressed"), "false"); + + // Click Grab -> sends grab(enabled: true) with resolved accent and shows status strip. + await act(async () => { + fireEvent.click(grabButton); + }); + await waitFor(() => { + const activeButton = screen.getByRole("button", { name: "Stop grabbing" }); + assert.equal(activeButton.getAttribute("aria-pressed"), "true"); + }); + const grabStart = commands.find((cmd) => cmd.action === "grab" && cmd.enabled); + assert.ok(grabStart && grabStart.action === "grab"); + assert.ok(grabStart.accent?.bg && grabStart.accent?.fg); + assert.equal(grabStart.source, "toolbar"); + assert.ok(screen.getByText(/Click an element to grab for chat/u)); + + // Deliver a grabbed capture through browserElementGrabDelivery when composer is registered. + const received: GrabbedElementCapture[] = []; + const unregister = browserElementGrabDelivery.register({ + workspaceId: "ws-grab", + chatId: "chat-1", + available: () => true, + receive: (capture) => { + received.push(capture); + return true; + }, + }); + const capture: GrabbedElementCapture = { + element: { + version: GRABBED_ELEMENT_SCHEMA_VERSION, + id: "el_grab_1", + label: "", + framework: "react", + componentName: "HeroCard", + tagName: "section", + selector: "main > section.hero", + htmlSnippet: "
Hello
", + boundingBox: { x: 10, y: 20, width: 300, height: 150 }, + pageUrl: "http://localhost:3000/", + capturedAt: 1_700_000_000_000, + }, + }; + await act(async () => { + emitBotTestNotification("browser:event", { + type: "grab", + workspaceId: "ws-grab", + tabId: "tab-grab", + capture, + }); + }); + assert.equal(received.length, 1); + assert.equal(received[0]?.element.label, ""); + + // When composer is unavailable, shows clear user alert instead of silently dropping. + unregister(); + await act(async () => { + emitBotTestNotification("browser:event", { + type: "grab", + workspaceId: "ws-grab", + tabId: "tab-grab", + capture, + }); + }); + assert.ok(await screen.findByText(BROWSER_ELEMENT_GRAB_UNAVAILABLE)); + + // Pressing Escape while host has focus cancels grab via useLayer("panel"). + await act(async () => { + fireEvent.keyDown(document, { key: "Escape" }); + }); + await waitFor(() => { + assert.ok(commands.some((cmd) => cmd.action === "grab" && !cmd.enabled)); + assert.equal(screen.getByRole("button", { name: "Grab element" }).getAttribute("aria-pressed"), "false"); + }); + + // Shift+Cmd+G shortcut activates grab with source="shortcut" and ignores key auto-repeat. + const countBeforeShortcut = commands.filter((cmd) => cmd.action === "grab").length; + await act(async () => { + fireEvent.keyDown(window, { key: "G", metaKey: true, shiftKey: true, repeat: true }); + }); + assert.equal(commands.filter((cmd) => cmd.action === "grab").length, countBeforeShortcut); + + await act(async () => { + fireEvent.keyDown(window, { key: "G", metaKey: true, shiftKey: true, repeat: false }); + }); + await waitFor(() => { + const enabledGrabs = commands.filter((cmd) => cmd.action === "grab" && cmd.enabled); + const shortcutGrab = enabledGrabs[enabledGrabs.length - 1]; + assert.ok(shortcutGrab && shortcutGrab.action === "grab"); + assert.equal(shortcutGrab.source, "shortcut"); + }); +}); diff --git a/renderer/components/browser-panel.tsx b/renderer/components/browser-panel.tsx index 900875e43b..109072a900 100644 --- a/renderer/components/browser-panel.tsx +++ b/renderer/components/browser-panel.tsx @@ -1,18 +1,24 @@ import * as React from "react"; import { createPortal } from "react-dom"; -import { ArrowLeft, ArrowRight, ExternalLink, Globe, History, Link2, Loader2, MessageCirclePlus, MoreVertical, PictureInPicture2, Plus, RadioTower, RotateCw, Square, Unlink2, Volume2, VolumeX, X } from "lucide-react"; -import type { BrowserAnnotation, BrowserCommand, BrowserCommandResult, BrowserImage, BrowserSnapshot, BrowserState, BrowserStylePreview, BrowserTab, BrowserViewport } from "../shared/browser"; +import { ArrowLeft, ArrowRight, ExternalLink, Globe, History, Link2, Loader2, MessageCirclePlus, MoreVertical, MousePointer2, PictureInPicture2, Plus, RadioTower, RotateCw, Square, Unlink2, Volume2, VolumeX, X } from "lucide-react"; +import type { BrowserAnnotation, BrowserCommand, BrowserCommandResult, BrowserGrabSource, BrowserImage, BrowserSnapshot, BrowserState, BrowserStylePreview, BrowserTab, BrowserViewport } from "../shared/browser"; +import { resolveGrabAccent, type GrabbedElementAccent } from "../shared/browser-element-grab"; import { browserApi } from "../lib/ipc"; import { acceptBrowserState, BROWSER_DEVICE_PRESETS, browserBoundsFromRect, enqueueBrowserPresentation, resizeBrowserViewport, savedBrowserScreenshotPath, validBrowserViewport, visibleBrowserNativeOccluders, browserNativeViewObstructed, browserOcclusionMutated, browserOcclusionScrolled } from "../lib/browser-ui-state"; -import { Button, Input, Text, toast } from "./ui"; +import { Button, Input, Text, TooltipProvider, toast } from "./ui"; +import { Kbd, Tooltip } from "./ui-primitives"; import { BrowserMenuButton, type BrowserMenuOption } from "./browser-menu-button"; import { BrowserSettings } from "./browser-settings"; import { BrowserFloatingFrame } from "./browser-floating-frame"; import { BrowserAnnotationEditor } from "./browser-annotation-editor"; import { captureBrowserAnnotation } from "../lib/browser-annotation-capture"; import { BROWSER_ANNOTATION_UNAVAILABLE, browserAnnotationDelivery } from "../lib/browser-annotation-delivery"; +import { BROWSER_ELEMENT_GRAB_UNAVAILABLE, browserElementGrabDelivery } from "../lib/browser-element-grab-delivery"; import { BrowserAnnotationPreviewQueue } from "../lib/browser-annotation-preview-queue"; import { isEscapeKey } from "../lib/dismiss-key"; +import { isMacPlatform } from "../lib/ghostty-terminal/host-platform"; +import { useLayer } from "../lib/layer-stack"; +import { cn } from "../lib/ui-utils"; /* Browser is an extension of the Environment work surface. Compact tab and * navigation rows follow the supplied reference; page content owns the area. @@ -21,6 +27,17 @@ import { isEscapeKey } from "../lib/dismiss-key"; const ZOOM_STEPS = [.25, .33, .5, .67, .75, .8, .9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5]; type RunCommand = (command: BrowserCommand) => Promise; +function readActiveThemeGrabAccent(): GrabbedElementAccent { + if (typeof document === "undefined" || typeof getComputedStyle !== "function") { + return resolveGrabAccent(); + } + const styles = getComputedStyle(document.documentElement); + return resolveGrabAccent({ + bg: styles.getPropertyValue("--fill-accent"), + fg: styles.getPropertyValue("--fill-accent-foreground"), + }); +} + /** `bot`: a Bot's own browser, shown in its panel. */ export type BrowserPanelVariant = "workspace" | "bot"; @@ -56,6 +73,7 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal const panelRef = React.useRef(null); const hostRef = React.useRef(null); const addressRef = React.useRef(null); + const grabButtonRef = React.useRef(null); const annotateButtonRef = React.useRef(null); const annotationOpen = Boolean(annotation); const annotationWasOpenRef = React.useRef(false); @@ -82,6 +100,10 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal const floatingLayout = React.useCallback(() => { presentationRef.current?.(); }, []); tabIdRef.current = tab?.id ?? null; const ready = Boolean(tab?.url && tab.url !== "about:blank" && !tab.error && !tab.crashed); + const grabActive = !bot && Boolean(tab?.grabbing); + const mac = isMacPlatform(); + const grabShortcutLabel = mac ? "⇧⌘G" : "Ctrl+Shift+G"; + const grabAriaShortcut = mac ? "Meta+Shift+G" : "Control+Shift+G"; const cancelAnnotation = React.useCallback(() => { const target = annotationTargetRef.current; annotationTargetRef.current = null; @@ -131,21 +153,49 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal React.useEffect(() => { let cancelled = false; setState(null); setError(null); cancelAnnotation(); setPickerActive(false); setAddressFocused(false); - const unsubscribe = browserApi.onEvent((event) => { if (event.type === "state") commit(event.state); }); + const unsubscribe = browserApi.onEvent((event) => { + if (event.type === "state") { + commit(event.state); + } else if (event.type === "grab" && !bot && event.workspaceId === workspaceId) { + const recipient = browserElementGrabDelivery.capture(workspaceId); + if (!recipient || !recipient.deliver(event.capture)) { + setError(BROWSER_ELEMENT_GRAB_UNAVAILABLE); + } + } + }); void browserApi.getState(workspaceId).then((next) => { if (!cancelled) commit(next); }, (cause) => { if (!cancelled) setError(cause instanceof Error ? cause.message : "Could not open the browser."); }); return () => { cancelled = true; unsubscribe(); }; - }, [workspaceId, commit, cancelAnnotation, loadAttempt]); + }, [workspaceId, bot, commit, cancelAnnotation, loadAttempt]); React.useEffect(() => { cancelAnnotation(); setAddressFocused(false); setPickerActive(false); - return () => { if (tab?.id) void browserApi.command(workspaceId, { action: "annotate", tabId: tab.id, enabled: false }).catch(() => undefined); }; - }, [workspaceId, tab?.id, cancelAnnotation]); + return () => { + if (tab?.id) { + void browserApi.command(workspaceId, { action: "annotate", tabId: tab.id, enabled: false }).catch(() => undefined); + if (!bot) void browserApi.command(workspaceId, { action: "grab", tabId: tab.id, enabled: false }).catch(() => undefined); + } + }; + }, [workspaceId, tab?.id, bot, cancelAnnotation]); React.useEffect(() => { if (surfaceActive || !tab?.id) return; setPickerActive(false); void browserApi.command(workspaceId, { action: "annotate", tabId: tab.id, enabled: false }).catch(() => undefined); - }, [surfaceActive, workspaceId, tab?.id]); + if (!bot) void browserApi.command(workspaceId, { action: "grab", tabId: tab.id, enabled: false }).catch(() => undefined); + }, [surfaceActive, workspaceId, tab?.id, bot]); + + React.useEffect(() => { + if (!settingsOpen || !grabActive || !tab?.id || bot) return; + void run({ action: "grab", tabId: tab.id, enabled: false }); + }, [settingsOpen, grabActive, tab?.id, bot, run]); + + useLayer(grabActive, "panel", { + name: "browser-grab", + onEscape: (event) => { + event.preventDefault(); + if (tab) void run({ action: "grab", tabId: tab.id, enabled: false }); + }, + }); // Main-owned page views stay alive while hidden. They must be removed from the // native stacking order whenever a renderer menu, dialog or annotation covers them. @@ -221,8 +271,26 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal } } }, [run, tab]); + const toggleGrab = React.useCallback(async (source: BrowserGrabSource = "toolbar") => { + if (bot || !tab || !ready) return; + if (grabActive) { + await run({ action: "grab", tabId: tab.id, enabled: false }); + return; + } + if (annotation) cancelAnnotation(); + if (pickerActive) setPickerActive(false); + await run({ + action: "grab", + tabId: tab.id, + enabled: true, + accent: readActiveThemeGrabAccent(), + source, + }); + }, [bot, tab, ready, grabActive, annotation, pickerActive, cancelAnnotation, run]); + const annotate = React.useCallback(async () => { if (!tab || !ready) return; + if (grabActive) await run({ action: "grab", tabId: tab.id, enabled: false }); if (annotation) { cancelAnnotation(); return; } if (pickerActive) { await run({ action: "annotate", tabId: tab.id, enabled: false }); setPickerActive(false); return; } const tabId = tab.id; @@ -269,10 +337,11 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal return browserApi.onEvent((event) => { if (event.type !== "shortcut" || event.workspaceId !== workspaceId || event.tabId !== tab?.id) return; if (event.shortcut === "annotate") { if (!bot) void annotate(); } + else if (event.shortcut === "grab") { if (!bot) void toggleGrab("shortcut"); } else if (event.shortcut === "focus_address") { addressRef.current?.focus(); addressRef.current?.select(); } else void run({ action: "reload", tabId: event.tabId, ignoreCache: event.shortcut === "hard_reload" }); }); - }, [surfaceActive, workspaceId, tab?.id, annotate, run]); + }, [surfaceActive, workspaceId, tab?.id, bot, annotate, toggleGrab, run]); React.useEffect(() => { if (!surfaceActive) return; @@ -282,12 +351,25 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal // ⌘. marks up the page only from inside the browser; elsewhere it stops a reply. // Window capture runs before the app's command keys, so focus here wins. if (key === "." && !bot && panelRef.current?.contains(document.activeElement)) { event.preventDefault(); event.stopPropagation(); void annotate(); } + else if (key === "g" && event.shiftKey && !bot && panelRef.current?.contains(document.activeElement)) { event.preventDefault(); event.stopPropagation(); if (!event.repeat) void toggleGrab("shortcut"); } else if (key === "l" && panelRef.current?.contains(document.activeElement)) { event.preventDefault(); addressRef.current?.focus(); } else if (key === "r" && panelRef.current?.contains(document.activeElement) && tab) { event.preventDefault(); void run({ action: "reload", tabId: tab.id, ignoreCache: event.shiftKey }); } }; + const bubbleKeyboard = (event: KeyboardEvent) => { + if (event.defaultPrevented || bot || !ready) return; + if (!(event.metaKey || event.ctrlKey) || !event.shiftKey || event.altKey) return; + if (event.key.toLowerCase() === "g") { + event.preventDefault(); + if (!event.repeat) void toggleGrab("shortcut"); + } + }; window.addEventListener("keydown", keyboard, true); - return () => window.removeEventListener("keydown", keyboard, true); - }, [surfaceActive, annotate, tab, run]); + window.addEventListener("keydown", bubbleKeyboard, false); + return () => { + window.removeEventListener("keydown", keyboard, true); + window.removeEventListener("keydown", bubbleKeyboard, false); + }; + }, [surfaceActive, bot, ready, annotate, toggleGrab, tab, run]); // A menu belongs to the tab and surface that opened it. const menuOwner = JSON.stringify([workspaceId, tab?.id, surfaceActive]); @@ -326,11 +408,51 @@ export function BrowserPanel({ workspaceId, active, onDock, integratedTabs = fal
{ event.preventDefault(); submitAddress(address); }}> setAddress(event.target.value)} onFocus={() => { setAddress(tab?.url === "about:blank" ? "" : tab?.url ?? ""); setAddressFocused(true); queueMicrotask(() => addressRef.current?.select()); }} onBlur={() => setAddressFocused(false)} onKeyDown={(event) => { if (isEscapeKey(event)) { event.stopPropagation(); setAddressFocused(false); event.currentTarget.blur(); } }} />
+ {bot ? null : ( + + + Stop grabbing Esc + + ) : ( + + Grab element {grabShortcutLabel} + + ) + } + > + + + + )} {bot ? null : } {integratedTabs && tab && (tab.audible || tab.muted) ? : null} setSettingsOpen(true)} onDock={onDock} /> {tab?.viewport.mode === "responsive" ? : null} + {grabActive ? ( +
+ Click an element to grab for chat · ↑↓ parent/child · ⇧Click to add multiple · Esc to cancel + +
+ ) : null} {pickerActive ?
Select an element or highlighted text. Press Esc to cancel.
: null} {tab?.agentControlling ?
{agentName ?? "Aiden"} is using this browser
: null} {bot && tab?.heldForPerson ?
{browserHoldNotice(tab.heldForPerson.reason, agentName)}
: null} diff --git a/renderer/components/composer-attachments-mounted.test.tsx b/renderer/components/composer-attachments-mounted.test.tsx index 7c52a036cc..3440abaf10 100644 --- a/renderer/components/composer-attachments-mounted.test.tsx +++ b/renderer/components/composer-attachments-mounted.test.tsx @@ -55,6 +55,7 @@ async function loadComposer() { "./chat-task-chips": "export const ChatTaskChip=()=>null;", "./started-chats-chip": "export const StartedChatsChip=()=>null;", "./busy-send-button": "export const BusySendButton=()=>null;", + "./grabbed-element-chip": "export const GrabbedElementChips=()=>null;", "./provider-icon": "export const ProviderIcon=()=>null;", "../lib/design-mode": "export const useDesignModeControls=()=>null;", // The tray a design canvas publishes; tests set it on globalThis. The diff --git a/renderer/components/composer-browser-grab.test.tsx b/renderer/components/composer-browser-grab.test.tsx new file mode 100644 index 0000000000..1e9b9025e4 --- /dev/null +++ b/renderer/components/composer-browser-grab.test.tsx @@ -0,0 +1,412 @@ +// Installs happy-dom and the fake IPC bridge; must stay the first import. +import { installBotTestIpc } from "../main/bots/test-dom"; +import assert from "node:assert/strict"; +import { afterEach, beforeEach, test } from "node:test"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import * as React from "react"; +import { Composer } from "./composer"; +import { TooltipProvider } from "./ui"; +import { CommandSystemProvider } from "../lib/command-system"; +import { browserElementGrabDelivery } from "../lib/browser-element-grab-delivery"; +import { + discardComposerDraft, + loadComposerDraftGrabbedElements, + restoreUnsentMessage, + seedComposerAttachments, + seedComposerGrabbedElements, +} from "../lib/composer-draft-store"; +import { + GRABBED_ELEMENT_SCHEMA_VERSION, + grabbedElementThumbnailId, + type GrabbedElementCapture, + type GrabbedElementContextV1, +} from "../shared/browser-element-grab"; +import type { Attachment, Chat, Workspace } from "../lib/types"; + +const ONE_PIXEL_PNG_B64 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScL2aQAAAABJRU5ErkJggg=="; + +const WORKSPACE: Workspace = { + id: "ws-grab", + name: "app", + folderPath: "/tmp/app", + permission: "full", + createdAt: 1, + updatedAt: 1, +}; + +interface SendCall { + kind: "send" | "queue" | "steer"; + text: string; + attachments: Attachment[]; + grabbedElements?: GrabbedElementContextV1[]; + btw?: boolean; +} + +let queryClient: QueryClient; +let calls: SendCall[]; +let rejectSend: Error | null; +let chatCounter = 0; + +function nextChatId(): string { + chatCounter += 1; + return `chat-grab-${chatCounter}`; +} + +function makeCapture( + overrides: Partial = {}, + options: { withThumbnail?: boolean; keepActive?: boolean } = {}, +): GrabbedElementCapture { + const id = overrides.id ?? "el-hero"; + const withThumbnail = options.withThumbnail !== false; + return { + element: { + version: GRABBED_ELEMENT_SCHEMA_VERSION, + id, + label: "", + framework: "react", + componentName: "LandingHeroClient", + tagName: "section", + selector: "main > section.hero", + htmlSnippet: '

Hero

', + boundingBox: { x: 10, y: 20, width: 640, height: 240 }, + pageUrl: "http://localhost:3000/", + capturedAt: 1700000000000, + ...overrides, + }, + ...(withThumbnail + ? { + thumbnail: { + data: ONE_PIXEL_PNG_B64, + mimeType: "image/png" as const, + width: 320, + height: 120, + }, + } + : {}), + ...(options.keepActive !== undefined ? { keepActive: options.keepActive } : {}), + }; +} + +beforeEach(() => { + localStorage.clear(); + calls = []; + rejectSend = null; + installBotTestIpc({ + "pullRequests:list": () => ({ links: [] }), + "pullRequests:current": () => null, + "pullRequests:pending": () => [], + "workspaces:repositoryIdentity": () => null, + "workspaces:files": () => ({ entries: [], truncated: false, skippedDirectories: 0 }), + "settings:get": () => null, + "shortcut:get": () => null, + "app:renderer-ready": () => null, + "skills:discover": () => [], + "providers:list": () => [], + "live:state": () => ({ offered: false, sessionActive: false, needsSetup: false }), + "followThrough:list": () => ({ checks: [], pullRequests: [] }), + "design:mode:get": () => null, + }); + queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: Infinity } }, + }); +}); + +afterEach(() => { + cleanup(); + queryClient.clear(); +}); + +async function mountComposer(props: { + chatId?: string; + visionSupported?: boolean; + isGenerating?: boolean; + firstMessageSaving?: boolean; + withQueueAndSteer?: boolean; +} = {}) { + const chatId = props.chatId ?? nextChatId(); + const chat = { + id: chatId, + title: "Grab test chat", + messages: [], + createdAt: 1, + updatedAt: 1, + } as unknown as Chat; + const inputRef = React.createRef(); + let rendered!: ReturnType; + await act(async () => { + rendered = render( + + + + undefined} + onSend={async (text, attachments, _skill, options) => { + calls.push({ + kind: "send", + text, + attachments, + grabbedElements: options?.grabbedElements, + btw: options?.btw, + }); + if (rejectSend) throw rejectSend; + }} + onQueue={ + props.withQueueAndSteer + ? async (text, attachments, _skill, options) => { + calls.push({ + kind: "queue", + text, + attachments, + grabbedElements: options?.grabbedElements, + }); + if (rejectSend) throw rejectSend; + } + : undefined + } + onSteer={ + props.withQueueAndSteer + ? async (text, attachments, _skill, options) => { + calls.push({ + kind: "steer", + text, + attachments, + grabbedElements: options?.grabbedElements, + }); + if (rejectSend) throw rejectSend; + } + : undefined + } + onStop={() => undefined} + /> + + + , + ); + }); + const textarea = rendered.container.querySelector("textarea")!; + // Happy-dom returns empty client rects; stub one so Composer's visibility fence passes. + textarea.getClientRects = () => [new DOMRect(0, 0, 200, 32)] as unknown as DOMRectList; + return { chatId, inputRef, textarea, ...rendered }; +} + +function deliverGrab(capture: GrabbedElementCapture): boolean { + return browserElementGrabDelivery.capture(WORKSPACE.id)?.deliver(capture) ?? false; +} + +test("delivers grabbed element chip, deduplicates in place, hides raw thumbnail card, and sends with empty text", async () => { + const { chatId, container } = await mountComposer(); + + let delivered = false; + await act(async () => { + delivered = deliverGrab(makeCapture({ id: "el-1" })); + }); + assert.equal(delivered, true); + + // Chip renders once; linked grab-thumb_* is NOT duplicated in the generic attachment strip. + assert.equal(container.querySelectorAll("[data-grabbed-element-chip]").length, 1); + assert.equal(screen.queryByRole("button", { name: "Remove LandingHeroClient.png" }), null); + + // Re-grabbing same element dedup key refreshes in place instead of duplicating. + await act(async () => { + delivered = deliverGrab( + makeCapture({ id: "el-2", htmlSnippet: '
' }), + ); + }); + assert.equal(delivered, true); + assert.equal(container.querySelectorAll("[data-grabbed-element-chip]").length, 1); + assert.ok(container.querySelector('[data-grabbed-element-chip="el-2"]')); + + // Empty-text send is allowed and includes both grabbedElements and linked thumbnail attachment. + const sendButton = screen.getByRole("button", { name: "Send message" }); + assert.equal((sendButton as HTMLButtonElement).disabled, false); + await act(async () => { + fireEvent.click(sendButton); + }); + + assert.equal(calls.length, 1); + assert.equal(calls[0]!.text, ""); + assert.equal(calls[0]!.grabbedElements?.length, 1); + assert.equal(calls[0]!.grabbedElements?.[0]?.id, "el-2"); + assert.equal(calls[0]!.attachments.length, 1); + assert.equal(calls[0]!.attachments[0]?.id, grabbedElementThumbnailId("el-2")); + assert.equal(loadComposerDraftGrabbedElements(chatId).length, 0, "in-memory draft clears on send"); +}); + +test("text-only models show non-blocking note and still allow sending grabbed elements", async () => { + await mountComposer({ visionSupported: false }); + + await act(async () => { + deliverGrab(makeCapture({ id: "el-text-only" })); + }); + + assert.ok(screen.getByText("Text context only for this model")); + const sendButton = screen.getByRole("button", { name: "Send message" }); + assert.equal((sendButton as HTMLButtonElement).disabled, false); + + await act(async () => { + fireEvent.click(sendButton); + }); + + assert.equal(calls.length, 1, "text-only model sends grabbed element without blocking"); + assert.equal(calls[0]!.grabbedElements?.[0]?.id, "el-text-only"); +}); + +test("delivery fence rejects grabs while firstMessageSaving is active", async () => { + await mountComposer({ firstMessageSaving: true }); + + let delivered = true; + await act(async () => { + delivered = deliverGrab(makeCapture({ id: "el-blocked" })); + }); + assert.equal(delivered, false, "delivery fence blocks grab during first-message save"); +}); + +test("Backspace at caret offset 0 removes last grabbed chip and its linked thumbnail", async () => { + const { container, textarea } = await mountComposer(); + + await act(async () => { + deliverGrab( + makeCapture({ id: "el-a", label: "", selector: ".a", componentName: "CardA" }), + ); + deliverGrab( + makeCapture({ id: "el-b", label: "", selector: ".b", componentName: "CardB" }), + ); + }); + assert.equal(container.querySelectorAll("[data-grabbed-element-chip]").length, 2); + + textarea.selectionStart = 0; + textarea.selectionEnd = 0; + await act(async () => { + fireEvent.keyDown(textarea, { key: "Backspace" }); + }); + assert.equal(container.querySelectorAll("[data-grabbed-element-chip]").length, 1); + assert.ok(container.querySelector('[data-grabbed-element-chip="el-a"]')); + + // Sending confirms el-b's thumbnail was removed along with el-b. + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Send message" })); + }); + assert.equal(calls.length, 1); + assert.deepEqual( + calls[0]!.attachments.map((a) => a.id), + [grabbedElementThumbnailId("el-a")], + ); +}); + +test("failed send restores grabbed elements and linked thumbnails; localStorage never stores them", async () => { + const { chatId, container, textarea } = await mountComposer(); + rejectSend = new Error("network down"); + + await act(async () => { + fireEvent.change(textarea, { target: { value: "Fix padding" } }); + deliverGrab(makeCapture({ id: "el-retry" })); + }); + + // Ensure localStorage has zero base64 or grabbed element metadata. + const rawStored = localStorage.getItem(`aiden:composer-draft:${chatId}`) ?? ""; + assert.equal(rawStored.includes(ONE_PIXEL_PNG_B64), false); + assert.equal(rawStored.includes("el-retry"), false); + + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Send message" })); + }); + + assert.equal(calls.length, 1); + assert.equal(textarea.value, "Fix padding", "draft text restored"); + assert.ok(container.querySelector('[data-grabbed-element-chip="el-retry"]'), "chip restored on failure"); + + // Retry succeeds and still carries the restored element + thumbnail. + rejectSend = null; + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Send message" })); + }); + assert.equal(calls.length, 2); + assert.equal(calls[1]!.grabbedElements?.[0]?.id, "el-retry"); + assert.equal(calls[1]!.attachments[0]?.id, grabbedElementThumbnailId("el-retry")); +}); + +test("grabbed elements disable Steer when generating and block /btw side questions", async () => { + const { textarea } = await mountComposer({ isGenerating: true, withQueueAndSteer: true }); + + await act(async () => { + deliverGrab(makeCapture({ id: "el-busy" })); + fireEvent.change(textarea, { target: { value: "Update header" } }); + }); + + // Submitting while generating with a grabbed element queues rather than steering. + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + assert.equal(calls.length, 1); + assert.equal(calls[0]!.kind, "queue", "busy send queues instead of steering when grabbed elements attached"); + assert.equal(calls[0]!.grabbedElements?.[0]?.id, "el-busy"); + + // /btw is blocked when grabbed elements are attached. + await act(async () => { + deliverGrab(makeCapture({ id: "el-btw" })); + fireEvent.change(textarea, { target: { value: "/btw why is this misaligned?" } }); + }); + await act(async () => { + fireEvent.keyDown(textarea, { key: "Enter" }); + }); + assert.equal(calls.length, 1, "/btw did not send while grabbed element attached"); +}); + +test("Edit-in-Fork seeds and cancelled-worktree restore repopulate grabbed chips and thumbnails", async () => { + const chatId = nextChatId(); + const element = makeCapture({ id: "el-fork" }).element; + element.thumbnailAttachmentId = grabbedElementThumbnailId("el-fork"); + const thumb: Attachment = { + id: grabbedElementThumbnailId("el-fork"), + name: "LandingHeroClient.png", + kind: "image", + mimeType: "image/png", + size: 68, + data: ONE_PIXEL_PNG_B64, + }; + seedComposerAttachments(chatId, [thumb]); + seedComposerGrabbedElements(chatId, [element], [thumb]); + + const firstMount = await mountComposer({ chatId }); + assert.ok(firstMount.container.querySelector('[data-grabbed-element-chip="el-fork"]'), "forked chip mounts"); + // Simulate switching away to another chat and returning: the seeded grabbed thumbnail persists in memory. + firstMount.unmount(); + + const { container } = await mountComposer({ chatId }); + assert.ok(container.querySelector('[data-grabbed-element-chip="el-fork"]'), "forked chip persists after chat switch"); + + // Restore unsent message (e.g. cancelled worktree send) into mounted composer. + const restoredEl = makeCapture({ id: "el-worktree", label: "