Skip to content

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.

feat(actions): open, switch between, and close browser tabs

Shahriar5dbd73a50d87
diff --git a/README.md b/README.md
index 6aa447b..bcb2439 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@ It runs on **your own [Claude Code](https://claude.com/claude-code) login**. The
## Features
- **Voice or text.** Hands free dictation in the side panel, press to talk in the popup, plain typing anywhere.
-- **Real page control.** 19 page capabilities covering reading, clicking, typing, form submission, navigation and screenshots.
+- **Real page control.** 22 page capabilities covering reading, clicking, typing, form submission, navigation and screenshots.
- **Site maps.** Point Browsentic at a site and it explores it, then writes reusable notes so later sessions already know their way around. See [Site maps](#site-maps-teach-it-a-site-once).
- **Recordings.** Do a repetitive job once yourself and Browsentic keeps it as ordered steps, so "do it like last time" repeats it. See [Recordings](#recordings-show-it-once-repeat-it-later).
- **Instant commands.** "Go back", "scroll to the top", "open github.com" run in the browser in milliseconds instead of becoming an agent run.
@@ -192,6 +192,7 @@ bolt on the timeline. Everything else goes to the agent with the text untouched.
| --- | --- |
| back, forward, reload | "is there a login button?" |
| open github.com, open localhost:3000 | "open the settings menu" |
+| open github.com in a new tab | "close this tab", "switch to my gmail tab" |
| google something, search the web for something | "search for wireless headphones" |
| scroll up, down, top, bottom, page down | "scroll down and tell me what it says" |
| press enter, hit escape, press arrow down | "click sign in and then fill in my email" |
@@ -209,7 +210,7 @@ to the agent, as does any local command that runs and fails.
claude mcp add browsentic -- browsentic-mcp
```
-Claude Code now has 19 page tools plus `browsentic_status`, and three read only resources that
+Claude Code now has 22 page tools plus `browsentic_status`, and three read only resources that
return page context without spending a tool call. Tool definitions are generated from the same
registry the extension ships, so they cannot drift from what the browser can actually do.
@@ -219,7 +220,7 @@ registry the extension ships, so they cannot drift from what the browser can act
| --- | --- |
| Read | Structured page snapshot with a layout diagram and stable selectors, rendered text or HTML, wait for an element to appear or vanish, screenshot the tab or one element |
| Act | Click, hover, focus, type into inputs and contenteditables, choose a `<select>` option, select text, press keys with modifiers, submit a form |
-| Move | Open a URL, back, forward, reload, scroll to an element or position |
+| Move | Open a URL, back, forward, reload, scroll to an element or position, open a URL in a new tab, list and switch between open tabs, close one |
| Files | List files stored in Browsentic and attach one to a file input on the page |
| Recordings | List the browsing sessions the user recorded, and read one back as ordered, replayable steps |
@@ -240,6 +241,12 @@ Optional, at `~/.browsentic/config.json`:
}
```
+`requireApproval` lists the actions an agent run has to ask you about first. It defaults to form
+submission, which is the one effect that reaches someone other than you. Add any other action name
+to it — `"page.closeTab"` if you would rather approve each tab the agent closes, for instance. The
+cost of a longer list is a longer list: a prompt you see on every other tool call is a prompt you
+stop reading.
+
Useful commands:
```sh
diff --git a/lib/actions/page/close-tab.ts b/lib/actions/page/close-tab.ts
new file mode 100644
index 0000000..63735f7
--- /dev/null
+++ b/lib/actions/page/close-tab.ts
@@ -0,0 +1,24 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+
+export const closeTab = defineAction({
+ name: 'page.closeTab',
+ description:
+ 'Close an open tab. With no arguments it closes the tab page actions are currently targeting, and later actions follow the browser to whichever tab it brings to the front.',
+ input: z.object({
+ tabId: z
+ .number()
+ .int()
+ .optional()
+ .describe('Id of the tab to close, as reported by page.openTab or a no-argument page.switchTab.'),
+ match: z
+ .string()
+ .optional()
+ .describe(
+ 'Instead of an id, close the tab whose title or URL contains this text (case-insensitive). If several tabs match, nothing is closed and the candidates are listed.',
+ ),
+ }),
+ execute() {
+ throw new ActionError('page.closeTab is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');
+ },
+});
diff --git a/lib/actions/page/open-tab.ts b/lib/actions/page/open-tab.ts
new file mode 100644
index 0000000..7c4f11d
--- /dev/null
+++ b/lib/actions/page/open-tab.ts
@@ -0,0 +1,20 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+
+export const openTab = defineAction({
+ name: 'page.openTab',
+ description:
+ 'Open a URL in a new browser tab. The new tab becomes the one every later page action targets, unless "active" is false.',
+ input: z.object({
+ url: z.string().describe('Absolute or relative URL to open in the new tab (http/https only).'),
+ active: z
+ .boolean()
+ .default(true)
+ .describe(
+ 'Bring the new tab to the front, making it the tab later page actions target. Set false to open it in the background and leave the current tab in front.',
+ ),
+ }),
+ execute() {
+ throw new ActionError('page.openTab is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');
+ },
+});
diff --git a/lib/actions/page/switch-tab.ts b/lib/actions/page/switch-tab.ts
new file mode 100644
index 0000000..e57ebd7
--- /dev/null
+++ b/lib/actions/page/switch-tab.ts
@@ -0,0 +1,24 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+
+export const switchTab = defineAction({
+ name: 'page.switchTab',
+ description:
+ 'Bring another open tab to the front, making it the tab every later page action targets. Call it with no arguments to list the open tabs and their ids first.',
+ input: z.object({
+ tabId: z
+ .number()
+ .int()
+ .optional()
+ .describe('Id of the tab to switch to, as reported by page.openTab or a no-argument page.switchTab.'),
+ match: z
+ .string()
+ .optional()
+ .describe(
+ 'Instead of an id, switch to the tab whose title or URL contains this text (case-insensitive). If several tabs match, nothing is switched and the candidates are listed.',
+ ),
+ }),
+ execute() {
+ throw new ActionError('page.switchTab is resolved by the Browsentic extension, not in the page', 'UNSUPPORTED');
+ },
+});
diff --git a/lib/actions/registry.ts b/lib/actions/registry.ts
index df82afc..028c35d 100644
--- a/lib/actions/registry.ts
+++ b/lib/actions/registry.ts
@@ -3,6 +3,7 @@ import type { AnyAction } from './core';
import type { ToolDescriptor } from './manifest';
import { attachFile } from './page/attach-file';
import { clickElement } from './page/click-element';
+import { closeTab } from './page/close-tab';
import { extractText } from './page/extract-text';
import { fillInput } from './page/fill-input';
import { focusInput } from './page/focus-input';
@@ -12,6 +13,7 @@ import { hoverElement } from './page/hover-element';
import { listFiles } from './page/list-files';
import { listRecordings } from './page/list-recordings';
import { navigate } from './page/navigate';
+import { openTab } from './page/open-tab';
import { pressKey } from './page/press-key';
import { readRecording } from './page/read-recording';
import { screenshot } from './page/screenshot';
@@ -19,6 +21,7 @@ import { scrollTo } from './page/scroll-to';
import { selectOption } from './page/select-option';
import { selectText } from './page/select-text';
import { submitForm } from './page/submit-form';
+import { switchTab } from './page/switch-tab';
import { waitForElement } from './page/wait-for-element';
export const actions: ReadonlyMap<string, AnyAction> = new Map(
@@ -38,6 +41,9 @@ export const actions: ReadonlyMap<string, AnyAction> = new Map(
waitForElement,
highlightElement,
navigate,
+ openTab,
+ switchTab,
+ closeTab,
screenshot,
listFiles,
attachFile,
diff --git a/lib/bridge/invoke.ts b/lib/bridge/invoke.ts
index f76b073..7110e88 100644
--- a/lib/bridge/invoke.ts
+++ b/lib/bridge/invoke.ts
@@ -3,22 +3,25 @@ import { z } from 'zod';
import { invokeInTab } from '@/lib/actions/client';
import { ActionError } from '@/lib/actions/core';
import { attachFile } from '@/lib/actions/page/attach-file';
+import { closeTab } from '@/lib/actions/page/close-tab';
import { listFiles } from '@/lib/actions/page/list-files';
import { listRecordings } from '@/lib/actions/page/list-recordings';
import { navigate, resolveNavigation, type NavigateInput } from '@/lib/actions/page/navigate';
+import { openTab } from '@/lib/actions/page/open-tab';
import { readRecording } from '@/lib/actions/page/read-recording';
import { screenshot } from '@/lib/actions/page/screenshot';
+import { switchTab } from '@/lib/actions/page/switch-tab';
import { failure, success, type ActionResult } from '@/lib/actions/protocol';
import { listMeta, readBytes } from '@/lib/bridge/file-store';
import { listRecordings as listStoredMeta, readRecordingBody } from '@/lib/bridge/recording-store';
import { screenshotTab } from '@/lib/bridge/screenshot';
-
-const LOAD_TIMEOUT_MS = 10_000;
+import { closeOpenTab, openNewTab, switchToTab, watchForLoad } from '@/lib/bridge/tabs';
export async function invokeForHarness(action: string, input?: unknown, tabId?: number): Promise<ActionResult> {
if (action === listFiles.name) return listStoredFiles(input);
if (action === listRecordings.name) return listStoredRecordings(input);
if (action === readRecording.name) return readStoredRecording(input);
+ if (action === openTab.name) return openNewTab(input);
const tab = tabId == null ? (await browser.tabs.query({ active: true, currentWindow: true }))[0] : await pinnedTab(tabId);
if (tab?.id == null) {
@@ -27,6 +30,8 @@ export async function invokeForHarness(action: string, input?: unknown, tabId?:
: failure('MAPPING_TAB_CHANGED', 'The tab this run started in has been closed.');
}
if (action === navigate.name) return navigateTab(tab.id, input);
+ if (action === switchTab.name) return switchToTab({ id: tab.id, windowId: tab.windowId }, input);
+ if (action === closeTab.name) return closeOpenTab({ id: tab.id, windowId: tab.windowId }, input);
if (action === screenshot.name) return screenshotTab({ id: tab.id, windowId: tab.windowId }, input);
if (action === attachFile.name) return attachStoredFile(tab.id, input);
return invokeInTab(tab.id, action, input);
@@ -171,21 +176,3 @@ async function navigateViaTabsApi(tabId: number, input: unknown): Promise<Action
: { performed: plan.action, loaded: completed },
);
}
-
-function watchForLoad(tabId: number) {
- let settle!: (loaded: boolean) => void;
- const settled = new Promise<boolean>((resolve) => {
- settle = resolve;
- });
- const finish = (loaded: boolean) => {
- browser.tabs.onUpdated.removeListener(listener);
- clearTimeout(timer);
- settle(loaded);
- };
- const listener = (updatedTabId: number, changeInfo: { status?: string }) => {
- if (updatedTabId === tabId && changeInfo.status === 'complete') finish(true);
- };
- const timer = setTimeout(() => finish(false), LOAD_TIMEOUT_MS);
- browser.tabs.onUpdated.addListener(listener);
- return { settled, cancel: () => finish(false) };
-}
diff --git a/lib/bridge/tabs.ts b/lib/bridge/tabs.ts
new file mode 100644
index 0000000..58450ad
--- /dev/null
+++ b/lib/bridge/tabs.ts
@@ -0,0 +1,330 @@
+import { browser } from 'wxt/browser';
+import { z } from 'zod';
+import { ActionError } from '@/lib/actions/core';
+import { closeTab } from '@/lib/actions/page/close-tab';
+import { resolveNavigation } from '@/lib/actions/page/navigate';
+import { openTab } from '@/lib/actions/page/open-tab';
+import { switchTab } from '@/lib/actions/page/switch-tab';
+import { failure, success, type ActionResult } from '@/lib/actions/protocol';
+import { recordingStateFor } from '@/lib/bridge/recorder';
+
+export const LOAD_TIMEOUT_MS = 10_000;
+
+const MAX_LABEL = 120;
+const MAX_LISTED = 20;
+const SUCCESSOR_POLL_MS = 50;
+const SUCCESSOR_TRIES = 10;
+
+export interface TabRef {
+ id: number;
+ windowId?: number;
+}
+
+interface TabInfo {
+ id?: number;
+ windowId?: number;
+ index?: number;
+ url?: string;
+ title?: string;
+ active?: boolean;
+ pinned?: boolean;
+ status?: string;
+}
+
+export async function openNewTab(input: unknown): Promise<ActionResult> {
+ const parsed = openTab.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ const { url, active } = parsed.data;
+
+ if (!url.trim()) {
+ return failure(
+ 'INVALID_INPUT',
+ 'page.openTab needs a "url" — a blank new tab is a browser page that no page action can reach.',
+ );
+ }
+
+ const current = (await browser.tabs.query({ active: true, currentWindow: true }))[0] as TabInfo | undefined;
+ const base = current?.url && isPageUrl(current.url) ? current.url : undefined;
+
+ let href: string;
+ try {
+ const plan = resolveNavigation({ url }, base);
+ if (plan.kind !== 'url') return failure('INVALID_INPUT', 'page.openTab opens a URL — it has no history to walk.');
+ href = plan.href;
+ } catch (error) {
+ return error instanceof ActionError ? failure(error.code, error.message) : failure('ACTION_FAILED', String(error));
+ }
+
+ const opener =
+ current?.id != null && current.windowId != null
+ ? { windowId: current.windowId, openerTabId: current.id }
+ : {};
+
+ let created: TabInfo;
+ try {
+ created = await browser.tabs.create({ url: href, active, ...opener });
+ } catch (error) {
+ return failure('ACTION_FAILED', error instanceof Error ? error.message : String(error));
+ }
+ if (created.id == null) return failure('ACTION_FAILED', 'The browser opened a tab but reported no id for it.');
+
+ const loaded = await awaitLoad(created.id);
+ const activeTabId = active ? created.id : current?.id;
+ return success({
+ performed: `opened ${clip(href)} in a new ${active ? 'tab' : 'background tab'}`,
+ openedUrl: href,
+ tabId: created.id,
+ index: created.index,
+ loaded,
+ ...(activeTabId != null ? { activeTabId } : {}),
+ ...(active && current?.id != null ? { previousTabId: current.id } : {}),
+ });
+}
+
+export async function switchToTab(current: TabRef, input: unknown): Promise<ActionResult> {
+ const parsed = switchTab.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ const { tabId, match } = parsed.data;
+ if (tabId != null && match != null) {
+ return failure('INVALID_INPUT', 'Give either "tabId" or "match", not both.');
+ }
+
+ const tabs = await windowTabs(current);
+ if (tabId == null && match == null) return success(inventory(tabs, current));
+
+ const picked = await pickTab(tabs, { tabId, match }, 'switch to');
+ if (!picked.ok) return picked.result;
+ const target = picked.tab;
+
+ if (!isPageUrl(target.url)) {
+ return failure(
+ 'UNSUPPORTED',
+ `Tab ${target.id} is a browser page, not a web page — page actions cannot read or act on it, so there is nothing to switch to.`,
+ );
+ }
+
+ try {
+ await browser.tabs.update(target.id!, { active: true });
+ } catch (error) {
+ return failure('ACTION_FAILED', error instanceof Error ? error.message : String(error));
+ }
+ return success({
+ performed: `switched to ${label(target)}`,
+ activeTabId: target.id,
+ previousTabId: current.id,
+ tab: describeTab({ ...target, active: true }),
+ });
+}
+
+export async function closeOpenTab(current: TabRef, input: unknown): Promise<ActionResult> {
+ const parsed = closeTab.input.safeParse(input ?? {});
+ if (!parsed.success) return failure('INVALID_INPUT', z.prettifyError(parsed.error));
+ const { tabId, match } = parsed.data;
+ if (tabId != null && match != null) {
+ return failure('INVALID_INPUT', 'Give either "tabId" or "match", not both.');
+ }
+
+ const tabs = await windowTabs(current);
+ const picked =
+ tabId == null && match == null
+ ? pickCurrent(tabs, current)
+ : await pickTab(tabs, { tabId, match }, 'close');
+ if (!picked.ok) return picked.result;
+ const target = picked.tab;
+
+ if (tabs.length <= 1) {
+ return failure(
+ 'INVALID_TARGET',
+ `${label(target)} is the only tab in this window — closing it would close the window and the Browsentic panel with it. Open another tab first, or leave this one alone.`,
+ );
+ }
+ if (target.pinned) {
+ return failure(
+ 'INVALID_TARGET',
+ `${label(target)} is pinned, which means the user wants to keep it. Ask them to unpin it if it really should close.`,
+ );
+ }
+ if (!isPageUrl(target.url)) {
+ return failure(
+ 'UNSUPPORTED',
+ `Tab ${target.id} is a browser page, not a web page — Browsentic cannot see what it is, so it will not close it.`,
+ );
+ }
+ if ((await recordingStateFor(target.id)).recording) {
+ return failure(
+ 'INVALID_TARGET',
+ `A recording is in progress in ${label(target)} — closing it would cut the recording short. Stop the recording first.`,
+ );
+ }
+
+ try {
+ await browser.tabs.remove(target.id!);
+ } catch (error) {
+ return failure('ACTION_FAILED', error instanceof Error ? error.message : String(error));
+ }
+
+ const after = await settleAfterClose(current, target.id!);
+ const nowOn = after.active?.url ? clip(after.active.url) : undefined;
+ return success({
+ performed: nowOn ? `closed ${label(target)} — now on ${nowOn}` : `closed ${label(target)}`,
+ closed: describeTab(target),
+ ...(nowOn ? { nowOn } : {}),
+ ...(after.active?.id != null ? { activeTabId: after.active.id } : {}),
+ remaining: after.remaining,
+ });
+}
+
+export function watchForLoad(tabId: number) {
+ let settle!: (loaded: boolean) => void;
+ const settled = new Promise<boolean>((resolve) => {
+ settle = resolve;
+ });
+ const finish = (loaded: boolean) => {
+ browser.tabs.onUpdated.removeListener(listener);
+ clearTimeout(timer);
+ settle(loaded);
+ };
+ const listener = (updatedTabId: number, changeInfo: { status?: string }) => {
+ if (updatedTabId === tabId && changeInfo.status === 'complete') finish(true);
+ };
+ const timer = setTimeout(() => finish(false), LOAD_TIMEOUT_MS);
+ browser.tabs.onUpdated.addListener(listener);
+ return { settled, cancel: () => finish(false) };
+}
+
+async function awaitLoad(tabId: number): Promise<boolean> {
+ const watcher = watchForLoad(tabId);
+ const status = ((await browser.tabs.get(tabId).catch(() => null)) as TabInfo | null)?.status;
+ if (status == null || status === 'complete') {
+ watcher.cancel();
+ return status === 'complete';
+ }
+ return watcher.settled;
+}
+
+type Picked = { ok: true; tab: TabInfo } | { ok: false; result: ActionResult };
+
+function pickCurrent(tabs: TabInfo[], current: TabRef): Picked {
+ const tab = tabs.find((t) => t.id === current.id);
+ return tab
+ ? { ok: true, tab }
+ : { ok: false, result: failure('TARGET_NOT_FOUND', 'The tab page actions were targeting is already gone.') };
+}
+
+async function pickTab(
+ tabs: TabInfo[],
+ selector: { tabId?: number; match?: string },
+ verb: string,
+): Promise<Picked> {
+ if (selector.tabId != null) {
+ const hit = tabs.find((t) => t.id === selector.tabId);
+ if (hit) return { ok: true, tab: hit };
+ const elsewhere = await browser.tabs.get(selector.tabId).catch(() => null);
+ return {
+ ok: false,
+ result: elsewhere
+ ? failure(
+ 'INVALID_TARGET',
+ `Tab ${selector.tabId} is in a different browser window. Browsentic only acts within the window it was opened in — ${openTabsLine(tabs)}`,
+ )
+ : failure(
+ 'TARGET_NOT_FOUND',
+ `No tab with id ${selector.tabId} — it has probably been closed. ${openTabsLine(tabs)}`,
+ ),
+ };
+ }
+
+ const needle = selector.match!.trim().toLowerCase();
+ if (!needle) return { ok: false, result: failure('INVALID_INPUT', '"match" cannot be empty.') };
+ const hits = tabs
+ .filter(isPageTab)
+ .filter((t) => `${t.title ?? ''} ${t.url ?? ''}`.toLowerCase().includes(needle));
+ if (!hits.length) {
+ return {
+ ok: false,
+ result: failure('TARGET_NOT_FOUND', `No open tab matches "${clip(selector.match!)}". ${openTabsLine(tabs)}`),
+ };
+ }
+ if (hits.length > 1) {
+ return {
+ ok: false,
+ result: failure(
+ 'INVALID_TARGET',
+ `"${clip(selector.match!)}" matches ${hits.length} tabs, so nothing was touched — ${verb} one of them by id: ${tabLines(hits)}`,
+ ),
+ };
+ }
+ return { ok: true, tab: hits[0] };
+}
+
+function inventory(tabs: TabInfo[], current: TabRef) {
+ const usable = tabs.filter(isPageTab);
+ const hidden = tabs.length - usable.length;
+ const shown = usable.slice(0, MAX_LISTED);
+ return {
+ performed: `${usable.length} open tab${usable.length === 1 ? '' : 's'} in this window`,
+ activeTabId: current.id,
+ tabs: shown.map(describeTab),
+ ...(hidden ? { hidden } : {}),
+ ...(shown.length < usable.length ? { truncated: true } : {}),
+ };
+}
+
+async function settleAfterClose(
+ current: TabRef,
+ closedId: number,
+): Promise<{ active?: TabInfo; remaining: number }> {
+ let tabs: TabInfo[] = [];
+ for (let attempt = 0; attempt < SUCCESSOR_TRIES; attempt++) {
+ tabs = await windowTabs(current);
+ const active = tabs.find((t) => t.active);
+ if (active && !tabs.some((t) => t.id === closedId)) return { active, remaining: tabs.length };
+ await delay(SUCCESSOR_POLL_MS);
+ }
+ const left = tabs.filter((t) => t.id !== closedId);
+ return { active: left.find((t) => t.active), remaining: left.length };
+}
+
+async function windowTabs(current: TabRef): Promise<TabInfo[]> {
+ return (await browser.tabs.query(
+ current.windowId != null ? { windowId: current.windowId } : { currentWindow: true },
+ )) as TabInfo[];
+}
+
+function describeTab(tab: TabInfo) {
+ return {
+ tabId: tab.id,
+ title: clip(tab.title ?? ''),
+ url: clip(tab.url ?? ''),
+ ...(tab.active ? { active: true } : {}),
+ };
+}
+
+function label(tab: TabInfo): string {
+ const title = clip(tab.title ?? '');
+ const url = clip(tab.url ?? '');
+ if (title && url) return `“${title}” — ${url}`;
+ return title || url || `tab ${tab.id}`;
+}
+
+function tabLines(tabs: TabInfo[]): string {
+ const shown = tabs.slice(0, MAX_LISTED);
+ const lines = shown.map((t) => `#${t.id} ${label(t)}`).join('; ');
+ return shown.length < tabs.length ? `${lines}; …and ${tabs.length - shown.length} more` : lines;
+}
+
+function openTabsLine(tabs: TabInfo[]): string {
+ const usable = tabs.filter(isPageTab);
+ return usable.length ? `Open tabs: ${tabLines(usable)}` : 'No other web page is open in this window.';
+}
+
+const isPageTab = (tab: TabInfo) => isPageUrl(tab.url);
+
+const isPageUrl = (url: string | undefined): boolean => !!url && /^https?:/i.test(url);
+
+function clip(text: string): string {
+ const flat = text.replace(/\s+/g, ' ').trim();
+ return flat.length > MAX_LABEL ? `${flat.slice(0, MAX_LABEL - 1)}…` : flat;
+}
+
+const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
diff --git a/lib/intent/grammar.ts b/lib/intent/grammar.ts
index 9f7dfb5..49e75fb 100644
--- a/lib/intent/grammar.ts
+++ b/lib/intent/grammar.ts
@@ -1,6 +1,7 @@
import type { z } from 'zod';
import { clickElement } from '@/lib/actions/page/click-element';
import { navigate } from '@/lib/actions/page/navigate';
+import { openTab } from '@/lib/actions/page/open-tab';
import { pressKey } from '@/lib/actions/page/press-key';
import { scrollTo } from '@/lib/actions/page/scroll-to';
import { START_RECORDING_ACTION, STOP_RECORDING_ACTION } from '@/lib/recordings/events';
@@ -21,6 +22,7 @@ export interface Built {
}
type NavigateInput = z.input<typeof navigate.input>;
+type OpenTabInput = z.input<typeof openTab.input>;
type ScrollInput = z.input<typeof scrollTo.input>;
type ClickInput = z.input<typeof clickElement.input>;
type PressKeyInput = z.input<typeof pressKey.input>;
@@ -106,6 +108,21 @@ export const RULES: readonly Rule[] = [
pattern: /^(?:reload|refresh)(?:\s+(?:the|this)\s+page)?$/,
build: () => nav({ action: 'reload' }, 'Reload the page'),
},
+ {
+ id: 'tab.open',
+ action: openTab.name,
+ certainty: 0.95,
+ pattern:
+ /^(?:go\s+to|goto|open|visit|navigate\s+to|take\s+me\s+to|load|pull\s+up)\s+(?:the\s+)?(?<dest>\S+(?:\s+\S+)?)\s+in\s+(?:an?\s+)?(?:new|another|separate)\s+tab$/,
+ build: ({ dest }) => {
+ const site = SITES[dest!];
+ if (site) return openIn({ url: `https://${site}` }, `Open ${site} in a new tab`, 1);
+ const url = toUrl(dest!);
+ return url
+ ? openIn({ url }, `Open ${dest} in a new tab`, /^https?:\/\//.test(dest!) ? 1 : 0.97)
+ : null;
+ },
+ },
{
id: 'navigate.url',
action: navigate.name,
@@ -210,6 +227,8 @@ const built = (input: unknown, label: string, confidence = 1): Built => ({ input
const nav = (input: NavigateInput, label: string, confidence = 1): Built => built(input, label, confidence);
+const openIn = (input: OpenTabInput, label: string, confidence = 1): Built => built(input, label, confidence);
+
const scroll = (input: ScrollInput, label: string, confidence = 1): Built => built(input, label, confidence);
function slot(raw: string): { value: string; confidence: number } | null {
diff --git a/mcp/skills/browser-control.md b/mcp/skills/browser-control.md
index cea245b..b9783fe 100644
--- a/mcp/skills/browser-control.md
+++ b/mcp/skills/browser-control.md
@@ -28,24 +28,36 @@ After anything that changes the page, check that it landed. `page_waitForElement
Navigation has two shapes and they behave differently. `page_navigate` takes **either** a `url` **or** an `action` (`back` / `forward` / `reload`) — never both, never neither. From a tab with no content script the URL must be absolute. The result tells you which path ran: `navigatingTo` pushed a history entry so `back` works afterwards; `navigatedTo` replaced it. `loaded: true` means the load actually finished.
-## 4. Typing and forms
+## 4. Tabs — and which one you are on
+
+Every other tool here acts on the **frontmost tab of the user's current window**. Nothing you do to the page changes that; only these three tools do.
+
+`page_openTab { url: "https://…" }` opens a tab **and brings it to the front**, so every action after it lands there. Its result carries `tabId` for the new tab and `previousTabId` for the one you left — **keep `previousTabId`**, it is how you get back. Pass `active: false` to open in the background instead and stay where you are; then the new tab is reachable only by its `tabId`.
+
+`page_switchTab {}` with no arguments lists the open tabs and their ids without moving anything — do that first when you do not already hold an id. Then switch by `tabId`, or by `match`, a case-insensitive substring of a tab's title or URL. If a `match` hits more than one tab, **nothing is switched** and the candidates come back with their ids; pick one by id rather than rewording the match.
+
+`page_closeTab { tabId }` closes a tab and reports which tab the browser put in front (`activeTabId`, `nowOn`) — that is where your next action will land, so re-snapshot before acting. With no arguments it closes the tab you are on. Four refusals are final, not obstacles to route around: the only tab in the window, a pinned tab, a browser page Browsentic cannot see into, and a tab with a recording in progress. Say what happened and carry on.
+
+Two habits. **Tidy up after yourself** — if you opened a tab only to read something, close it once you have what you need, and leave the user on the tab they started on. And **only the current window exists** for these tools: a tab in another window is not something you can switch to or close.
+
+## 5. Typing and forms
`page_fillInput` writes through the native setter and fires the events frameworks listen for, so React and Vue inputs update properly. Set `submit: true` on it, or call `page_pressKey` with Enter, when the form expects a keystroke rather than a button.
`page_submitForm` runs the browser's own validation. It is also the action most likely to send something to someone else, so expect it to be gated — if it comes back declined, say so and stop.
-## 5. When something is not there
+## 6. When something is not there
`TARGET_NOT_FOUND` almost always means the page moved on without you: a menu closed, content loaded late, a modal opened over what you wanted. Re-snapshot rather than retrying the same target. If an element needs to appear first, `page_waitForElement` is cheaper and more reliable than clicking and hoping.
Content behind a hover — dropdowns, tooltips — needs `page_hoverElement` before it exists in the DOM.
-## 6. Screenshots
+## 7. Screenshots
`page_screenshot` captures the tab as an image. By default it captures the **full scroll view** and hands the picture back to you to look at — reach for it when you need to *see* layout or rendering that the text inventory can't convey. Narrow it when asked: `{ fullPage: false }` for just the current viewport, or `{ target: { text: "Pricing" } }` to capture a single element or block.
**Every capture is saved.** The image is written under `~/browsentic/screenshot/` and the result reports the exact path as `savedTo` — **always relay that path**, because the side panel renders your reply as text and turns images into links, so the path is the only way the user can actually open the picture. Pass `filename` when the user names one; otherwise it is auto-named. Pass `save: false` only when the user explicitly does not want a file, and then say nothing about a saved path. If the result carries `saveError` instead, the capture worked but the write did not — say so rather than naming a file that is not there.
-## 7. Multi-step tasks
+## 8. Multi-step tasks
Do the whole task, not the first step of it. If the user says "search for X and open the first result", that is a fill, a submit, a wait, a snapshot, and a click — finish all of it, then report once at the end. Stop early only when you are blocked on something the user must decide.
diff --git a/mcp/skills/site-mapper.md b/mcp/skills/site-mapper.md
index 08d7a2c..4781783 100644
--- a/mcp/skills/site-mapper.md
+++ b/mcp/skills/site-mapper.md
@@ -24,7 +24,7 @@ Record **what you observed**. Not advice, not rules, not instructions to anyone.
## What you cannot do here, and why
-This run is read-only. `page_clickElement`, `page_fillInput`, `page_submitForm` and the rest return `MAPPING_READ_ONLY` — the user is signed in to this site, and a mapping run must not be able to change anything while it wanders. (Clicking may be enabled in config; if it is, use it only to reveal navigation, never to commit anything.)
+This run is read-only. `page_clickElement`, `page_fillInput`, `page_submitForm` and the rest return `MAPPING_READ_ONLY` — the user is signed in to this site, and a mapping run must not be able to change anything while it wanders. (Clicking may be enabled in config; if it is, use it only to reveal navigation, never to commit anything.) `page_openTab`, `page_switchTab` and `page_closeTab` return `MAPPING_READ_ONLY` too: a mapping run is pinned to one tab on one origin, so there is nowhere else to go.
You are also locked to one host. `page_navigate` needs an **absolute** URL on the site being mapped — `https://example.com/pricing`, never `/pricing` and never `back`. If a page redirects you somewhere else, reads are blocked until you navigate back; that is not a bug, it is the lock working.
diff --git a/scripts/check-intent.mjs b/scripts/check-intent.mjs
index 2d390d4..17d07d1 100644
--- a/scripts/check-intent.mjs
+++ b/scripts/check-intent.mjs
@@ -27,6 +27,18 @@ const CASES = [
['google best noise cancelling headphones', 'act:navigate.search'],
['search the web for tide times', 'act:navigate.search'],
+ ['open github.com in a new tab', 'act:tab.open', { url: 'https://github.com' }],
+ ['open gmail in a new tab', 'act:tab.open', { url: 'https://mail.google.com' }],
+ ['take me to hacker news in another tab', 'act:tab.open', { url: 'https://news.ycombinator.com' }],
+ ['visit https://example.com/docs in a separate tab', 'act:tab.open', { url: 'https://example.com/docs' }],
+ ['open localhost:3000 in a new tab', 'act:tab.open', { url: 'http://localhost:3000' }],
+
+ ['open a new tab', 'escalate:no-match'],
+ ['open the settings menu in a new tab', 'escalate:no-match'],
+ ['close this tab', 'escalate:no-match'],
+ ['switch to my gmail tab', 'escalate:no-match'],
+ ['click the new tab button', 'act:click.text', { target: { text: 'new tab', role: 'button' } }],
+
['scroll down', 'act:scroll.direction', { direction: 'down' }],
['scroll down a bit', 'act:scroll.direction'],
['can you scroll down?', 'act:scroll.direction'],