// src/background/actions.js // DOM action executors — each action type runs inside the target tab. // Native browser tools (bookmarks, saves, monitors, skills) run in the SW. // Imported and called by the agent loop in sw.js. import { sleep } from '../lib/utils.js'; import { getAllSkills } from '../lib/skills.js'; import { searchPageParts, highlightPart } from '../lib/page-rag.js'; import { findInHistory } from '../lib/vector-history.js'; // TAB-GROUP SANDBOX: shared boundary logic (same module the SW uses). import { ensureTaskGroup, filterToSandbox } from '../lib/tab-sandbox.js'; /** * Execute a single agent action in the given tab. * Returns a metadata object { ok, …outcome fields }. */ export async function executeAction(tabId, action, agentState) { switch (action.type) { // Navigate case 'navigate': { // URL allow-list — the VLM must not steer the browser onto // browser-internal or non-web schemes (chrome://, file://, javascript:, // data:). Only http(s) passes. const navUrl = String(action.url || '').trim(); if (!/^https?:\/\//i.test(navUrl)) { throw new Error(`navigate: only http(s) URLs are allowed — blocked: "${navUrl.slice(0, 80)}"`); } const tab = await chrome.tabs.update(tabId, { url: navUrl }); await sleep(800); return { ok: true, url: tab.url, tabId: tab.id }; } // Click case 'click': { const clickContext = { ...(getInteractiveContext(action, agentState) || {}), x: Number.isFinite(Number(action.x)) ? Number(action.x) : null, y: Number.isFinite(Number(action.y)) ? Number(action.y) : null, }; // Action verification // Synthetic clicks on modern SPA players (YouTube etc.) are sometimes // silently ignored — the old code reported "success" because the DOM // call didn't throw, and the VLM declared the task done while nothing // had happened. We now fingerprint the page BEFORE and AFTER and feed // the honest diff back to the model + console. const before = await inject(tabId, domPageFingerprint); // collapsed field-group aware click resolution (Gmail opens the // compose dialog with the recipients row collapsed — the "To" input is // only created after the visible "Recipients" chip is clicked). const result = await executeClickWithExpansion(tabId, action.selector || action.text || '', clickContext); if (!result?.ok) throw new Error(clickFailMessage(result)); await sleep(750); // let SPA state settle (playback toggles, navigations) let after = await inject(tabId, domPageFingerprint); // ignore media TIME drift for non-media actions — 750ms of video // playback always drifted >0.35s and faked "PAGE CHANGED" for dead clicks. let verification = diffFingerprints(before, after, { ignoreMediaTime: true }); // NAVIGATION LENS: when the click NAVIGATED, the post-action // injection legitimately fails (the document is mid-teardown) and // diffFingerprints reports "fingerprint unavailable → no change" — // a verdict that must not be read as "nothing happened". The tab // itself is the honest signal source: if the tab's URL/title moved // vs the pre-click fingerprint, the click DID navigate. Strictly // scoped to `!after` — it can never inflate a readable-page verdict. if (!after && before) { const nav = await tabNavigationSignal(tabId, before); if (nav) verification = nav; } // trusted-input fallback: a synthetic (isTrusted=false) click that // verifies as ineffective is re-dispatched as REAL browser input via the // DevTools protocol (chrome.debugger). Hardened widgets (Gmail Send, // player controls) ignore synthetic events but must honor real ones. // Attaching fails harmlessly when DevTools already owns the tab — we // keep the synthetic verdict instead of guessing. if (!verification.changed && result.rect) { const trusted = await trustedClick(tabId, result.rect); if (trusted?.ok) { await sleep(750); const after2 = await inject(tabId, domPageFingerprint); const v2 = diffFingerprints(before, after2, { ignoreMediaTime: true }); if (v2.changed) { verification = v2; after = after2; result.trustedRetry = true; console.log('[Open Comet] Click re-dispatched as TRUSTED input (CDP) → PAGE CHANGED'); } } else if (trusted?.reason) { console.log(`[Open Comet] Trusted-click fallback unavailable: ${trusted.reason}`); } } // mail/compose success signals — clicking Send closes the compose // window and raises a "Message sent" toast, which the structural // fingerprint can miss while the dialog is mid-teardown. Probe the // explicit success markers before declaring "no visible change". // HOST GATE: the probe only makes sense on mail hosts. On other pages // composeClosed=true fires with no compose dialog ever present and // the history would claim a mail send that never happened. if (!verification.changed && await isMailHostTab(tabId)) { try { const mail = await inject(tabId, verifyMailSendOutcome); if (mail?.sent || mail?.composeClosed) { verification = { changed: true, summary: mail.composeClosed ? 'compose window closed after the click (mail send flow advanced)' : `mail success toast detected ("${String(mail.toast || '').slice(0, 40)}")`, }; result.mailSendVerified = true; console.log('[Open Comet] Click verify · mail send signals detected → PAGE CHANGED'); } } catch { /* additive verification only */ } } result.changed = verification.changed; result.verification = verification; console.log(`[Open Comet] Click verify · target="${String(action.selector || action.text || '').substring(0, 60)}" · matched="${String(result.matchedText || '').substring(0, 60)}"${result.resolution ? ` via ${result.resolution}` : ''}${result.expandedToggle ? ` (expanded "${result.expandedToggle}")` : ''} → ` + `${verification.changed ? 'PAGE CHANGED' : 'NO VISIBLE CHANGE'} · ${verification.summary}`); if (!verification.changed) { console.warn('[Open Comet] Click had no visible effect. Page fingerprint before/after:', before, after); } return result; } // Media control (direct