An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(tools): a saved tool can run by itself on every visit to its page — a Chrome user script mirrored from the saved list, once Chrome allows user scripts
Shahriard0bcada29e32
diff --git a/src/daemon/skills/page-scripting.md b/src/daemon/skills/page-scripting.mdindex e21d8cc..ab83173 100644--- a/src/daemon/skills/page-scripting.md+++ b/src/daemon/skills/page-scripting.md@@ -68,3 +68,7 @@ Two things follow for you.no `page_*` tool reaches it. If the user asks for the same effect again on that site, tell themto run `/<name>` rather than writing the same code a second time. You will see a skill note foreach one they kept, which is how you know it exists.+- **Some kept tools run on every visit.** The user can switch that on when they keep one, or later+ from `/remove-tools`, and its skill note then says so. Its effect is usually already on the page,+ so look before you add it again. If it did not take, suggest running `/<name>` or switching+ **Allow User Scripts** on for Browsentic in `chrome://extensions`.diff --git a/src/extension/components/saved-tools.tsx b/src/extension/components/saved-tools.tsxindex 47b8e8c..19116e1 100644--- a/src/extension/components/saved-tools.tsx+++ b/src/extension/components/saved-tools.tsx@@ -3,6 +3,8 @@ import { createPortal } from 'react-dom';import { Check, Trash2, X, Zap } from 'lucide-react';import { Button } from '@/extension/components/ui/button';+import { Switch } from '@/extension/components/ui/switch';+import { openUserScriptSettings } from '@/lib/bridge/auto-run';import type { ToolOffer } from '@/lib/bridge/code-toolkit';import type { SavedToolMeta } from '@/lib/bridge/saved-tools';import { displayName, slugify } from '@/lib/skills/saved-tool';@@ -11,18 +13,26 @@ import { displayName, slugify } from '@/lib/skills/saved-tool';* The offer, a second after an approved toolkit lands. It shows the name it would take* rather than asking for one, because the answer is usually yes and the name is usually* right — but the last segment stays editable, since that is the part the user will type.+ * Running on every visit starts off: it is a second decision, about code that will then+ * run without being asked for.*/export function KeepToolPrompt({offer,+ autoRunReady,onKeep,onDismiss,}: {offer: ToolOffer;- onKeep: (slug: string) => void;+ autoRunReady: boolean;+ onKeep: (slug: string, autoRun: boolean) => void;onDismiss: () => void;}) {const [slug, setSlug] = useState(offer.suggestedSlug);- useEffect(() => setSlug(offer.suggestedSlug), [offer.suggestedSlug]);+ const [autoRun, setAutoRun] = useState(false);+ useEffect(() => {+ setSlug(offer.suggestedSlug);+ setAutoRun(false);+ }, [offer.toolkitId, offer.suggestedSlug]);const clean = slugify(slug) || offer.suggestedSlug;const where = offer.segment === 'root' ? offer.host : `${offer.host}/${offer.segment}`;@@ -54,11 +64,17 @@ export function KeepToolPrompt({runs with /{displayName({ host: offer.host, segment: offer.segment }, clean)}</p>+ <label className="mt-2.5 flex items-center gap-2 text-[11px] text-ink-dim">+ <Switch checked={autoRun} onChange={setAutoRun} label={`Also run it on every visit to ${where}`} />+ Also run it on every visit to {where}+ </label>+ {autoRun && !autoRunReady && <AllowUserScripts />}+<div className="mt-2.5 flex gap-1.5"><Button variant="ghost" size="sm" className="flex-1" onClick={onDismiss}><X className="size-3" /> No</Button>- <Button size="sm" className="flex-1" onClick={() => onKeep(clean)}>+ <Button size="sm" className="flex-1" onClick={() => onKeep(clean, autoRun)}><Check className="size-3" /> Yes, keep it</Button></div>@@ -66,13 +82,30 @@ export function KeepToolPrompt({);}-/** `/remove-tools`: everything saved, with a cross on each. */+/** Chrome keeps user scripts behind a per-extension switch that no API can flip, so point at it. */+function AllowUserScripts() {+ return (+ <p className="mt-1.5 text-[10px] leading-relaxed text-amber">+ Chrome runs a tool on every visit only once <span className="font-medium">Allow User Scripts</span> is on for+ Browsentic.{' '}+ <button type="button" onClick={openUserScriptSettings} className="underline underline-offset-2 hover:text-ink">+ Open settings+ </button>+ </p>+ );+}++/** `/remove-tools`: everything saved, with a cross on each and whether it runs on every visit. */export function SavedToolList({tools,+ autoRunReady,+ onAutoRun,onForget,onClose,}: {tools: SavedToolMeta[];+ autoRunReady: boolean;+ onAutoRun: (id: string, on: boolean) => void;onForget: (id: string) => void;onClose: () => void;}) {@@ -93,6 +126,7 @@ export function SavedToolList({<p className="mt-0.5 text-[11px] leading-relaxed text-ink-dim">Removing one deletes its code from the browser and its note from the daemon.</p>+ {!autoRunReady && tools.some((tool) => tool.autoRun) && <AllowUserScripts />}</div><buttontype="button"@@ -117,6 +151,14 @@ export function SavedToolList({<div className="min-w-0 flex-1"><p className="truncate font-mono text-[11px] text-ink">{tool.name}</p><p className="mt-0.5 text-[11px] leading-relaxed text-ink-dim">{tool.description}</p>+ <label className="mt-1.5 flex items-center gap-2 text-[10px] text-ink-faint">+ <Switch+ checked={tool.autoRun === true}+ onChange={(on) => onAutoRun(tool.id, on)}+ label={`Run ${tool.name} on every visit`}+ />+ Every visit+ </label></div><buttontype="button"diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.tsindex ced5c38..12bc853 100644--- a/src/extension/entrypoints/background.ts+++ b/src/extension/entrypoints/background.ts@@ -3,6 +3,7 @@ import { injectContentScript } from '@/lib/actions/client';import { describeOwnActions } from '@/lib/bridge/own-actions';import { invokeForHarness } from '@/lib/bridge/invoke';import { serveDebuggerEvents } from '@/lib/bridge/cdp';+import { serveAutoRuns } from '@/lib/bridge/auto-run';import { serveCodeToolkits } from '@/lib/bridge/code-toolkit';import { serveDiagnostics } from '@/lib/bridge/diagnostics';import { serveFrameFocus } from '@/lib/bridge/frame-focus';@@ -226,6 +227,7 @@ export default defineBackground(() => {serveDiagnostics();serveFrameFocus();serveCodeToolkits();+ serveAutoRuns();serveRecorder();serveMonitor();serveTimers();diff --git a/src/extension/entrypoints/sidepanel/App.tsx b/src/extension/entrypoints/sidepanel/App.tsxindex a3a85ae..d76925f 100644--- a/src/extension/entrypoints/sidepanel/App.tsx+++ b/src/extension/entrypoints/sidepanel/App.tsx@@ -438,13 +438,24 @@ export default function App() {</div>{showTools && (- <SavedToolList tools={run.tools} onForget={run.forgetTool} onClose={() => setShowTools(false)} />+ <SavedToolList+ tools={run.tools}+ autoRunReady={run.autoRunReady}+ onAutoRun={run.setAutoRun}+ onForget={run.forgetTool}+ onClose={() => setShowTools(false)}+ />)}{tab === 'chat' && (<footer className="shrink-0 border-t border-line p-3">{run.toolOffer && (- <KeepToolPrompt offer={run.toolOffer} onKeep={run.keepTool} onDismiss={run.dismissTool} />+ <KeepToolPrompt+ offer={run.toolOffer}+ autoRunReady={run.autoRunReady}+ onKeep={run.keepTool}+ onDismiss={run.dismissTool}+ />)}<Composervoice={voice}diff --git a/src/lib/bridge/auto-run.test.ts b/src/lib/bridge/auto-run.test.tsnew file mode 100644index 0000000..ff9ceaf--- /dev/null+++ b/src/lib/bridge/auto-run.test.ts@@ -0,0 +1,261 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import type { Browser } from 'wxt/browser';+import { fakeBrowser } from 'wxt/testing';+import { autoRunSource, QUIET_MS, SETTLE_CAP_MS, syncAutoRuns } from './auto-run';+import { saveTool, scopeMatches, type SavedTool } from './saved-tools';++type UserScript = Browser.userScripts.RegisteredUserScript;++const MARK = 'tools.mark = () => { window.marks.push(location.href); };';++function tool(overrides: Partial<SavedTool> = {}): SavedTool {+ return {+ id: 't1',+ name: 'youtube.com:watch:mark-visit',+ skillName: 'tool-youtube-com-watch-mark-visit',+ description: 'Mark the visit',+ scope: { host: 'youtube.com', segment: 'watch' },+ origin: 'https://www.youtube.com',+ code: MARK,+ fn: 'mark',+ autoRun: true,+ createdAt: 0,+ ...overrides,+ };+}++interface FakePage {+ marks: string[];+ warnings: unknown[][];+ go: (url: string) => void;+ mutate: () => void;+ load: () => void;+}++/** Just enough of a page for the injected source: a location, the Navigation API, a DOM that can change and load. */+function openPage(url: string, saved: SavedTool = tool(), readyState = 'complete'): FakePage {+ const location = new URL(url);+ const document = { readyState, documentElement: {} };+ const marks: string[] = [];+ const warnings: unknown[][] = [];+ const entryListeners: Array<() => void> = [];+ const loadListeners: Array<() => void> = [];+ const observers = new Set<() => void>();++ const window = {+ marks,+ navigation: { addEventListener: (_type: string, listener: () => void) => entryListeners.push(listener) },+ addEventListener: (_type: string, listener: () => void) => loadListeners.push(listener),+ };+ class Observer {+ constructor(private readonly callback: () => void) {}+ observe() {+ observers.add(this.callback);+ }+ disconnect() {+ observers.delete(this.callback);+ }+ }+ const console = { warn: (...args: unknown[]) => warnings.push(args) };++ new Function('location', 'document', 'window', 'MutationObserver', 'console', autoRunSource(saved))(+ location,+ document,+ window,+ Observer,+ console,+ );++ return {+ marks,+ warnings,+ go: (next) => {+ location.href = next;+ for (const listener of entryListeners) listener();+ },+ mutate: () => {+ for (const observer of [...observers]) observer();+ },+ load: () => {+ document.readyState = 'complete';+ for (const listener of loadListeners) listener();+ },+ };+}++describe('the script Chrome injects', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ test('runs the entry point once the page goes quiet', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a');+ await vi.advanceTimersByTimeAsync(QUIET_MS - 1);+ expect(page.marks).toEqual([]);+ await vi.advanceTimersByTimeAsync(1);+ expect(page.marks).toEqual(['https://www.youtube.com/watch?v=a']);+ });++ test('a page that never stops changing still gets it, at the cap', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a');+ for (let elapsed = 0; elapsed < SETTLE_CAP_MS - 100; elapsed += 100) {+ await vi.advanceTimersByTimeAsync(100);+ page.mutate();+ }+ expect(page.marks).toEqual([]);+ await vi.advanceTimersByTimeAsync(100);+ expect(page.marks).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS);+ expect(page.marks).toHaveLength(1);+ });++ test('waits for the load event', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a', tool(), 'interactive');+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS * 2);+ expect(page.marks).toEqual([]);+ page.load();+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks).toHaveLength(1);+ });++ test('stays out of another part of the same site', async () => {+ const page = openPage('https://www.youtube.com/results?q=cats');+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS);+ expect(page.marks).toEqual([]);+ });++ test('a single-page site runs it on each arrival, not on every move within', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ page.go('https://www.youtube.com/watch?v=b');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks).toEqual(['https://www.youtube.com/watch?v=a']);++ page.go('https://www.youtube.com/results?q=cats');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ page.go('https://www.youtube.com/watch?v=c');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks).toEqual(['https://www.youtube.com/watch?v=a', 'https://www.youtube.com/watch?v=c']);+ });++ test('leaving before the page settles cancels that run', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a');+ page.go('https://www.youtube.com/results?q=cats');+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS);+ expect(page.marks).toEqual([]);+ });++ test('a tool that throws is reported, not raised into the page', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a', tool({ code: 'tools.mark = () => { throw new Error("gone"); };' }));+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.warnings).toHaveLength(1);+ expect(String(page.warnings[0][1])).toContain('gone');+ });++ test('code that fails while defining its tools is reported the same way', async () => {+ const page = openPage('https://www.youtube.com/watch?v=a', tool({ code: 'missing.thing = 1;' }));+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.warnings).toHaveLength(1);+ });++ const watch = tool();+ const root = tool({ scope: { host: 'example.com', segment: 'root' }, origin: 'https://example.com' });+ test.each([+ [watch, 'https://www.youtube.com/watch?v=a'],+ [watch, 'https://www.youtube.com/Watch'],+ [watch, 'https://www.youtube.com/watch/live'],+ [watch, 'https://www.youtube.com/watchlater'],+ [watch, 'https://www.youtube.com/'],+ [watch, 'https://youtube.com/watch?v=a'],+ [watch, 'http://www.youtube.com/watch?v=a'],+ [watch, 'https://www.youtube.com:8443/watch?v=a'],+ [watch, 'https://music.youtube.com/watch?v=a'],+ [root, 'https://example.com/'],+ [root, 'https://example.com/?q=1'],+ [root, 'https://example.com/about'],+ ])('decides %# the way `/` does', async (saved, url) => {+ const page = openPage(url, saved);+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks.length > 0).toBe(scopeMatches(saved, url));+ });+});++function stubUserScripts(registered: UserScript[] = []) {+ const scripts = new Map(registered.map((script) => [script.id, script]));+ const api = {+ getScripts: vi.fn(async () => [...scripts.values()]),+ register: vi.fn(async (list: UserScript[]) => {+ for (const script of list) scripts.set(script.id, script);+ }),+ unregister: vi.fn(async ({ ids }: { ids: string[] }) => {+ for (const id of ids) scripts.delete(id);+ }),+ };+ Object.assign(fakeBrowser, { userScripts: api });+ return { api, scripts };+}++describe('keeping Chrome in step with the saved list', () => {+ beforeEach(() => {+ fakeBrowser.reset();+ // WXT's test plugin passes build flags as strings, and "false" is truthy.+ vi.stubEnv('FIREFOX', '');+ });+ afterEach(() => vi.unstubAllEnvs());++ test('registers each tool set to run on every visit, in the page’s world, on its host', async () => {+ const { scripts } = stubUserScripts();+ await saveTool(tool());+ await saveTool(tool({ id: 't2', name: 'youtube.com:watch:other', autoRun: false }));+ await syncAutoRuns();++ expect([...scripts.keys()]).toEqual(['browsentic-tool-t1']);+ expect(scripts.get('browsentic-tool-t1')).toMatchObject({+ matches: ['https://www.youtube.com/*'],+ world: 'MAIN',+ runAt: 'document_idle',+ });+ });++ test('takes a script back out once its tool stops asking for it', async () => {+ const { scripts } = stubUserScripts();+ await saveTool(tool());+ await syncAutoRuns();+ await saveTool(tool({ autoRun: false }));+ await syncAutoRuns();+ expect(scripts.size).toBe(0);+ });++ test('replaces a script whose code changed, and leaves an unchanged one alone', async () => {+ const { api, scripts } = stubUserScripts();+ await saveTool(tool());+ await syncAutoRuns();+ await syncAutoRuns();+ expect(api.register).toHaveBeenCalledTimes(1);++ await saveTool(tool({ code: 'tools.mark = () => 2;' }));+ await syncAutoRuns();+ expect(api.register).toHaveBeenCalledTimes(2);+ expect(scripts.get('browsentic-tool-t1')?.js?.[0]?.code).toContain('tools.mark = () => 2;');+ });++ test('leaves scripts it did not register alone', async () => {+ const { scripts } = stubUserScripts([{ id: 'someone-else', matches: ['https://a.test/*'], js: [{ code: '' }] }]);+ await syncAutoRuns();+ expect([...scripts.keys()]).toEqual(['someone-else']);+ });++ test('waits quietly while Chrome does not allow user scripts', async () => {+ const register = vi.fn();+ Object.assign(fakeBrowser, {+ userScripts: {+ getScripts: () => {+ throw new Error('The userScripts API is only available once Allow User Scripts is on.');+ },+ register,+ },+ });+ await saveTool(tool());+ await expect(syncAutoRuns()).resolves.toBeUndefined();+ expect(register).not.toHaveBeenCalled();+ });+});diff --git a/src/lib/bridge/auto-run.ts b/src/lib/bridge/auto-run.tsnew file mode 100644index 0000000..7501450--- /dev/null+++ b/src/lib/bridge/auto-run.ts@@ -0,0 +1,190 @@+/**+ * Saved tools that run by themselves on every visit.+ *+ * Chrome's `userScripts` API is the mechanism, not the debugger the `/` path uses: a user+ * script is injected by the browser on each matching load, needs no debugging bar, works+ * with DevTools open, is exempt from the page's CSP and outlives a restart. It only runs+ * once the user has turned on **Allow User Scripts** for the extension, which is why the+ * flag on the saved tool is the truth and the registration is a mirror of it, brought back+ * into line whenever the list changes, the worker starts, the alarm fires, or the panel asks.+ *+ * The match pattern is the whole host on purpose. Scope is decided in the page by the same+ * rule `/` applies — exact origin, then the first path segment's slug — so it holds for+ * single-page sites too, where arriving at `/watch` is a history entry, not a load.+ */++import { browser, type Browser } from 'wxt/browser';+import { MAX_SLUG, ROOT_SEGMENT } from '@/lib/skills/saved-tool';+import { listSavedTools, onSavedToolsChange, type SavedTool } from './saved-tools';++const SCRIPT_PREFIX = 'browsentic-tool-';++const SYNC_ALARM = 'browsentic/autoRun';++/** How long the page must go without a DOM change before the tool runs. */+export const QUIET_MS = 400;++/** The longest a tool waits for quiet, since some pages never stop changing. */+export const SETTLE_CAP_MS = 3_000;++type UserScript = Browser.userScripts.RegisteredUserScript;++type AutoRunTool = Pick<SavedTool, 'name' | 'origin' | 'scope' | 'fn' | 'code'>;++/** Whether Chrome will accept a registration right now: false on Firefox and until Allow User Scripts is on. */+export function autoRunReady(): boolean {+ if (import.meta.env.FIREFOX) return false;+ try {+ browser.userScripts.getScripts().catch(() => undefined);+ return true;+ } catch {+ return false;+ }+}++/** The extension's own details page, where Chrome keeps the Allow User Scripts switch. */+export function openUserScriptSettings(): void {+ void browser.tabs.create({ url: `chrome://extensions/?id=${browser.runtime.id}` });+}++/**+ * Chrome raises no event when Allow User Scripts is switched on, and the API simply appears+ * in the running worker, so a tool waiting on it is picked up by the panel asking while it+ * shows the wait, or by this alarm once the panel is gone.+ */+export function serveAutoRuns(): void {+ if (import.meta.env.FIREFOX) return;+ onSavedToolsChange(() => void syncAutoRuns());+ browser.alarms.create(SYNC_ALARM, { periodInMinutes: 1 });+ browser.alarms.onAlarm.addListener((alarm) => {+ if (alarm.name === SYNC_ALARM) void syncAutoRuns();+ });+ void syncAutoRuns();+}++let syncing: Promise<void> = Promise.resolve();++export function syncAutoRuns(): Promise<void> {+ syncing = syncing.then(reconcile, reconcile);+ return syncing;+}++async function reconcile(): Promise<void> {+ if (import.meta.env.FIREFOX || !autoRunReady()) return;+ const wanted = new Map(+ (await listSavedTools()).filter((tool) => tool.autoRun).map((tool) => [scriptIdOf(tool), scriptFor(tool)]),+ );+ const ours = (await browser.userScripts.getScripts()).filter((script) => script.id.startsWith(SCRIPT_PREFIX));+ const current = new Set(ours.filter((script) => sameScript(script, wanted.get(script.id))).map((script) => script.id));+ const stale = ours.filter((script) => !current.has(script.id)).map((script) => script.id);++ if (stale.length) await browser.userScripts.unregister({ ids: stale });+ for (const [id, script] of wanted) {+ if (!current.has(id)) await browser.userScripts.register([script]).catch(() => undefined);+ }+}++function scriptIdOf(tool: SavedTool): string {+ return `${SCRIPT_PREFIX}${tool.id}`;+}++function scriptFor(tool: SavedTool): UserScript {+ return {+ id: scriptIdOf(tool),+ matches: [hostPattern(tool.origin)],+ js: [{ code: autoRunSource(tool) }],+ runAt: 'document_idle',+ world: 'MAIN',+ };+}++/** Every path on the tool's host, any port; the page narrows it to the exact origin and segment. */+function hostPattern(origin: string): string {+ const { protocol, hostname } = new URL(origin);+ return `${protocol}//${hostname}/*`;+}++function sameScript(registered: UserScript, wanted: UserScript | undefined): boolean {+ return (+ !!wanted &&+ registered.js?.[0]?.code === wanted.js?.[0]?.code &&+ registered.world === wanted.world &&+ JSON.stringify(registered.matches) === JSON.stringify(wanted.matches)+ );+}++/**+ * What Chrome injects. The approved code is wrapped exactly as the installer wraps it, so+ * it parses the same way it did when the user read it, and it is evaluated once per+ * document. The entry point runs each time the document arrives in scope — on the load,+ * and again after a single-page site navigates away and back — once the page has loaded+ * and its DOM has gone quiet, which is the state the user watched the tool work in.+ */+export function autoRunSource(tool: AutoRunTool): string {+ return `(() => {+ const origin = ${JSON.stringify(tool.origin)};+ const segment = ${JSON.stringify(tool.scope.segment)};+ const entry = ${JSON.stringify(tool.fn)};+ const label = ${JSON.stringify(tool.name)};++ const slug = (text) =>+ text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, ${MAX_SLUG}).replace(/-+$/, '');+ const inScope = () => {+ if (location.origin !== origin) return false;+ const [first = ''] = location.pathname.split('/').filter(Boolean);+ return (slug(first) || ${JSON.stringify(ROOT_SEGMENT)}) === segment;+ };+ const report = (error) => console.warn('Browsentic: “' + label + '” did not run on this visit.', error);++ let tools = null;+ const run = () => {+ if (!inScope()) return;+ try {+ if (!tools) {+ tools = {};+ (function (tools) {+${tool.code}+ })(tools);+ }+ const fn = tools[entry];+ Promise.resolve().then(() => fn()).catch(report);+ } catch (error) {+ report(error);+ }+ };++ const whenSettled = (then) => {+ let over = false;+ let quiet;+ const finish = () => {+ if (over) return;+ over = true;+ observer.disconnect();+ clearTimeout(quiet);+ clearTimeout(cap);+ then();+ };+ const arm = () => {+ clearTimeout(quiet);+ quiet = setTimeout(finish, ${QUIET_MS});+ };+ const observer = new MutationObserver(arm);+ const cap = setTimeout(finish, ${SETTLE_CAP_MS});+ observer.observe(document.documentElement, { childList: true, subtree: true });+ arm();+ };+ const whenLoaded = (then) => {+ if (document.readyState === 'complete') then();+ else window.addEventListener('load', () => then(), { once: true });+ };++ let inside = false;+ const visit = () => {+ const now = inScope();+ if (now && !inside) whenLoaded(() => whenSettled(run));+ inside = now;+ };+ visit();+ window.navigation?.addEventListener('currententrychange', visit);+})();`;+}diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.tsindex 3b907f0..5f0e4a2 100644--- a/src/lib/bridge/run-port.ts+++ b/src/lib/bridge/run-port.ts@@ -16,10 +16,11 @@ import { planReplay, type ReplayCall } from '@/lib/recordings/replay';import type { TaskContext, TaskJob, TaskOrder, TaskResult } from '@/lib/schedules/task';import type { SiteMapDraft } from '@/lib/skills/site-map';import { navigate } from '@/lib/actions/page/navigate';+import { autoRunReady, syncAutoRuns } from './auto-run';import { onToolOffer, runSavedTool, toolkitCode, type ToolOffer } from './code-toolkit';import { CONTEXT_COMMAND, isContextCommand, type ContextBreakdown } from './commands';import { listSavedTools, withoutCode, type SavedToolMeta } from './saved-tools';-import { dropTool, keepTool } from './tool-registry';+import { dropTool, keepTool, switchAutoRun } from './tool-registry';import { tryFastPath } from './fast-path';import { dropDiagnosticsForSession } from './diagnostics';import {@@ -114,9 +115,10 @@ export type RunCommand =| { op: 'startRecording'; captureValues: boolean }| { op: 'stopRecording' }| { op: 'stopMonitor'; monitorId: string }- | { op: 'keepTool'; toolkitId: string; tabId: number; slug?: string }+ | { op: 'keepTool'; toolkitId: string; tabId: number; slug?: string; autoRun?: boolean }| { op: 'dismissTool'; toolkitId: string }| { op: 'forgetTool'; id: string }+ | { op: 'autoRunTool'; id: string; on: boolean }| { op: 'runTool'; id: string; tab: TabAnchor }| { op: 'listTools' }| { op: 'attach'; file: NewFile; tab: TabAnchor }@@ -134,7 +136,7 @@ export type RunMessage =| { op: 'monitor'; state: MonitorState }| { op: 'toolOffer'; offer: ToolOffer }| { op: 'toolOfferSettled'; toolkitId: string }- | { op: 'tools'; tools: SavedToolMeta[] }+ | { op: 'tools'; tools: SavedToolMeta[]; autoRunReady: boolean }| { op: 'close' };const ports = new Set<Browser.runtime.Port>();@@ -251,7 +253,7 @@ export function serveRunPorts(): void {post(port, { op: 'mapDraft', sessionId: held.sessionId, draft: held.draft });}void currentRecording().then((state) => post(port, { op: 'recording', state }));- void listSavedTools().then((tools) => post(port, { op: 'tools', tools: tools.map(withoutCode) }));+ void toolsMessage().then((message) => post(port, message));void activeMonitorStates().then((states) => {for (const state of states) post(port, { op: 'monitor', state });});@@ -365,7 +367,9 @@ function handle(command: RunCommand): void {void serialized(async () => {const offer = pendingOffers.get(command.toolkitId);const code = offer ? await toolkitCode(command.tabId, command.toolkitId) : null;- if (offer && code) await keepTool({ offer, code, slug: command.slug }).catch(() => undefined);+ if (offer && code) {+ await keepTool({ offer, code, slug: command.slug, autoRun: command.autoRun }).catch(() => undefined);+ }pendingOffers.delete(command.toolkitId);broadcast({ op: 'toolOfferSettled', toolkitId: command.toolkitId });await publishTools();@@ -381,6 +385,12 @@ function handle(command: RunCommand): void {await publishTools();});return;+ case 'autoRunTool':+ void serialized(async () => {+ await switchAutoRun(command.id, command.on);+ await publishTools();+ });+ return;case 'runTool':void serialized(async () => {const result = await runSavedTool(command.tab.tabId, command.tab.url, command.id);@@ -388,7 +398,7 @@ function handle(command: RunCommand): void {});return;case 'listTools':- void publishTools();+ void syncAutoRuns().then(publishTools);return;case 'attach':void serialized(() => attach(command.file, command.tab));@@ -442,8 +452,12 @@ function toolRunItem(id: string, result: { ok: boolean; error?: { code: string;: notice('error', `${result.error?.code}: ${result.error?.message}`);}+async function toolsMessage(): Promise<RunMessage> {+ return { op: 'tools', tools: (await listSavedTools()).map(withoutCode), autoRunReady: autoRunReady() };+}+async function publishTools(): Promise<void> {- broadcast({ op: 'tools', tools: (await listSavedTools()).map(withoutCode) });+ broadcast(await toolsMessage());}async function absorb(runId: string, event: RunEvent): Promise<void> {diff --git a/src/lib/bridge/saved-tools.ts b/src/lib/bridge/saved-tools.tsindex 6ef0fda..dddd7de 100644--- a/src/lib/bridge/saved-tools.ts+++ b/src/lib/bridge/saved-tools.ts@@ -35,6 +35,8 @@ export interface SavedTool {code: string;/** The zero-argument entry point `/` invokes. */fn: string;+ /** Also run it by itself on every visit to its scope, as a user script Chrome injects. */+ autoRun?: boolean;createdAt: number;}@@ -66,6 +68,23 @@ export async function saveTool(tool: SavedTool): Promise<void> {await browser.storage.local.set({ [TOOLS_KEY]: [tool, ...kept].slice(0, MAX_SAVED_TOOLS) });}+export async function setAutoRun(id: string, autoRun: boolean): Promise<SavedTool | null> {+ const tools = await listSavedTools();+ const changed = tools.find((tool) => tool.id === id);+ if (!changed) return null;+ changed.autoRun = autoRun;+ await browser.storage.local.set({ [TOOLS_KEY]: tools });+ return changed;+}++/** Fires with the whole list whenever it changes, from any context. */+export function onSavedToolsChange(listener: (tools: SavedTool[]) => void): void {+ browser.storage.local.onChanged.addListener((changes) => {+ const change = changes[TOOLS_KEY];+ if (change) listener(Array.isArray(change.newValue) ? (change.newValue as SavedTool[]) : []);+ });+}+export async function forgetSavedTool(id: string): Promise<SavedToolMeta | null> {const tools = await listSavedTools();const going = tools.find((tool) => tool.id === id);diff --git a/src/lib/bridge/tool-registry.ts b/src/lib/bridge/tool-registry.tsindex 44b2d13..d87f7e8 100644--- a/src/lib/bridge/tool-registry.ts+++ b/src/lib/bridge/tool-registry.ts@@ -19,6 +19,7 @@ import { deleteSkill, saveSkill } from './socket';import {forgetSavedTool,saveTool,+ setAutoRun,uniqueName,withoutCode,type SavedTool,@@ -32,6 +33,8 @@ export interface KeepRequest {code: string;/** User-editable last name segment; falls back to the suggestion on the offer. */slug?: string;+ /** Run it by itself on every visit to its scope as well. */+ autoRun?: boolean;}export async function keepTool(request: KeepRequest): Promise<SavedToolMeta> {@@ -49,6 +52,7 @@ export async function keepTool(request: KeepRequest): Promise<SavedToolMeta> {origin: offer.origin,code,fn: offer.fn,+ autoRun: request.autoRun === true,createdAt: Date.now(),};@@ -58,6 +62,12 @@ export async function keepTool(request: KeepRequest): Promise<SavedToolMeta> {return withoutCode(tool);}+/** The flag is the truth; the user script follows it from the store's change listener. */+export async function switchAutoRun(id: string, autoRun: boolean): Promise<void> {+ const tool = await setAutoRun(id, autoRun);+ if (tool) await saveSkill(skillFor(tool)).catch(() => undefined);+}+export async function dropTool(id: string): Promise<SavedToolMeta | null> {const gone = await forgetSavedTool(id);if (gone) await deleteSkill(gone.skillName).catch(() => undefined);@@ -88,6 +98,9 @@ function skillFor(tool: SavedTool): SkillDraft {'',`It runs from the side panel, by typing \`/${tool.name}\`. It is already approved, so it`,'needs no further permission and costs no round trip.',+ ...(tool.autoRun+ ? ['', `It also runs by itself on every visit to ${where}, so its effect is usually already on the page.`]+ : []),'','## What you should do','',diff --git a/src/lib/bridge/use-run.ts b/src/lib/bridge/use-run.tsindex f3e596b..e7189e8 100644--- a/src/lib/bridge/use-run.ts+++ b/src/lib/bridge/use-run.ts@@ -15,6 +15,9 @@ import type { TabSession } from './tab-sessions';const RECONNECT_MS = 1_000;+/** How often the panel asks again while a tool waits on Chrome's Allow User Scripts switch. */+const USER_SCRIPTS_RECHECK_MS = 2_000;+const EXTERNAL_VIEW = 'external';export type { RunItem };@@ -50,9 +53,12 @@ export interface Run {tools: SavedToolMeta[];/** Raised a second after an approved toolkit lands, asking whether to keep it. */toolOffer: ToolOffer | null;- keepTool: (slug?: string) => void;+ /** Whether Chrome will run a tool on every visit yet — false until Allow User Scripts is on. */+ autoRunReady: boolean;+ keepTool: (slug?: string, autoRun?: boolean) => void;dismissTool: () => void;forgetTool: (id: string) => void;+ setAutoRun: (id: string, on: boolean) => void;runTool: (id: string) => void;/** Gives a file the panel has stored to the conversation of the tab in front, which reads it. */attachFile: (file: NewFile) => void;@@ -66,6 +72,7 @@ export function useRun(): Run {const [monitors, setMonitors] = useState<MonitorState[]>([]);const [offer, setOffer] = useState<ToolOffer | null>(null);const [tools, setTools] = useState<SavedToolMeta[]>([]);+ const [autoRunReady, setAutoRunReady] = useState(false);const [bySession, setBySession] = useState<Record<string, RunItem[]>>({});const port = useRef<Browser.runtime.Port | null>(null);@@ -134,6 +141,7 @@ export function useRun(): Run {setOffer((held) => (held?.toolkitId === runMessage.toolkitId ? null : held));} else if (runMessage.op === 'tools') {setTools(runMessage.tools);+ setAutoRunReady(runMessage.autoRunReady);} else if (runMessage.op === 'close') {window.close();} else {@@ -173,6 +181,13 @@ export function useRun(): Run {if (sessionId) post({ op: 'replay', sessionId });}, [sessionId, post]);+ const awaitingUserScripts = !autoRunReady && (!!offer || tools.some((tool) => tool.autoRun));+ useEffect(() => {+ if (!awaitingUserScripts) return;+ const recheck = setInterval(() => post({ op: 'listTools' }), USER_SCRIPTS_RECHECK_MS);+ return () => clearInterval(recheck);+ }, [awaitingUserScripts, post]);+const items = useMemo(() => {const own = sessionId ? (bySession[sessionId] ?? []) : [];const external = bySession[EXTERNAL_VIEW] ?? [];@@ -249,9 +264,12 @@ export function useRun(): Run {}, [post]),tools,toolOffer: offer,+ autoRunReady,keepTool: useCallback(- (slug?: string) => {- if (offer && tab.tabId != null) post({ op: 'keepTool', toolkitId: offer.toolkitId, tabId: tab.tabId, slug });+ (slug?: string, autoRun?: boolean) => {+ if (offer && tab.tabId != null) {+ post({ op: 'keepTool', toolkitId: offer.toolkitId, tabId: tab.tabId, slug, autoRun });+ }},[offer, post, tab.tabId],),@@ -264,6 +282,12 @@ export function useRun(): Run {},[post],),+ setAutoRun: useCallback(+ (id: string, on: boolean) => {+ post({ op: 'autoRunTool', id, on });+ },+ [post],+ ),runTool: useCallback((id: string) => {if (tab.tabId != null) {diff --git a/src/lib/skills/saved-tool.ts b/src/lib/skills/saved-tool.tsindex bc9ce3f..a1baa34 100644--- a/src/lib/skills/saved-tool.ts+++ b/src/lib/skills/saved-tool.ts@@ -17,7 +17,7 @@ import { SKILL_NAME_RE } from './format';export const ROOT_SEGMENT = 'root';/** Long enough for three readable parts, short enough to sit in a menu row. */-const MAX_SLUG = 48;+export const MAX_SLUG = 48;export interface ToolScope {/** Hostname, lowercased, without a leading `www.`. */diff --git a/wxt.config.ts b/wxt.config.tsindex e078f34..ed51f19 100644--- a/wxt.config.ts+++ b/wxt.config.ts@@ -28,7 +28,8 @@ export default defineConfig({'notifications', 'downloads', 'nativeMessaging',// Firefox has no sidePanel, debugger or offscreen permission, and addons.mozilla.org flags each name it does not know.// offscreen is the hidden page hands-free mode listens through once the side panel is closed.- ...(browser === 'firefox' ? [] : ['sidePanel', 'debugger', 'offscreen']),+ // userScripts runs a saved tool on every visit, once the user turns on Allow User Scripts.+ ...(browser === 'firefox' ? [] : ['sidePanel', 'debugger', 'offscreen', 'userScripts']),],host_permissions: ['<all_urls>'],// Release Firefox installs only what addons.mozilla.org has signed, and signing needs a