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(extension): the composer's tabs button lists a conversation's tabs and adds open ones with the tab strip's selection ticked, and the right-click menu adds a tab to any open conversation

Shahriar74b5e22ff2e1
diff --git a/src/extension/components/composer.tsx b/src/extension/components/composer.tsx
index 864cdd5..8b45a6d 100644
--- a/src/extension/components/composer.tsx
+++ b/src/extension/components/composer.tsx
@@ -59,6 +59,7 @@ export function Composer({
placeholder = 'Tell me what to do on this page…',
size = 'panel',
accessory,
+ tabs,
actionCues,
onToggleActionCues,
onAttachSkill,
@@ -100,6 +101,8 @@ export function Composer({
size?: keyof typeof SIZES;
/** Sits beside the send button. */
accessory?: ReactNode;
+ /** The conversation's tabs, after the paperclip; it also puts `/tabs` in the menu. */
+ tabs?: ReactNode;
actionCues: boolean;
onToggleActionCues: () => void;
onAttachSkill: (skill: AttachedSkill | null) => void;
@@ -124,8 +127,8 @@ export function Composer({
const [highlight, setHighlight] = useState(0);
const menuId = useId();
const menuItems = useMemo(
- () => (menuOpen ? skillMenuItems(catalog, tabUrl, slash ?? '', tools, { handsFree, android }) : []),
- [menuOpen, catalog, tabUrl, slash, tools, handsFree, android],
+ () => (menuOpen ? skillMenuItems(catalog, tabUrl, slash ?? '', tools, { handsFree, android, tabs: !!tabs }) : []),
+ [menuOpen, catalog, tabUrl, slash, tools, handsFree, android, tabs],
);
useEffect(() => setHighlight(0), [slash]);
@@ -294,6 +297,7 @@ export function Composer({
>
<Paperclip className="size-3.5" />
</Button>
+ {tabs}
<Button
variant={liveTools ? 'subtle' : 'ghost'}
size="icon-sm"
diff --git a/src/extension/components/conversation-tabs.tsx b/src/extension/components/conversation-tabs.tsx
new file mode 100644
index 0000000..c026771
--- /dev/null
+++ b/src/extension/components/conversation-tabs.tsx
@@ -0,0 +1,364 @@
+import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
+import { browser, type Browser } from 'wxt/browser';
+import { Check, ChevronLeft, Globe, PanelsTopLeft, Plus, X } from 'lucide-react';
+
+import { Popover } from '@/extension/components/popover';
+import { Button } from '@/extension/components/ui/button';
+import { Input } from '@/extension/components/ui/input';
+import { hostOf, type TabSession } from '@/lib/bridge/tab-sessions';
+import { faviconOf } from '@/lib/bridge/top-sites';
+import { useBlockedCheck } from '@/lib/bridge/use-extension-settings';
+import { useWindowTabs } from '@/lib/bridge/use-window-tabs';
+import { cn } from '@/lib/utils';
+
+type Tab = Browser.tabs.Tab & { id: number };
+
+const MAX_FACES = 3;
+
+/**
+ * The conversation's tabs, behind one composer button: an icon while it has one tab, its tabs'
+ * faces once it has more. The card lists them and adds more, with the tabs selected in the tab
+ * strip already ticked.
+ */
+export function ConversationTabs({
+ session,
+ sessions,
+ open,
+ onOpenChange,
+ onAdd,
+ onRemove,
+}: {
+ session: TabSession | null;
+ sessions: TabSession[];
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onAdd: (tabIds: number[]) => void;
+ onRemove: (tabId: number) => void;
+}) {
+ const windowTabs = useWindowTabs().filter((tab): tab is Tab => tab.id != null);
+ const frontTabId = windowTabs.find((tab) => tab.active)?.id;
+ const members = windowTabs.filter((tab) => session?.tabIds.includes(tab.id));
+ const elsewhere = (session?.tabIds.length ?? 0) - members.length;
+ const spread = members.length > 1;
+ const [picking, setPicking] = useState(false);
+ const showPicker = picking || !spread;
+
+ const close = () => {
+ setPicking(false);
+ onOpenChange(false);
+ };
+
+ const names = members.map((tab) => tab.title || hostOf(tab.url) || 'Untitled').join(', ');
+
+ return (
+ <span>
+ <Button
+ variant={open ? 'subtle' : 'ghost'}
+ size={spread ? 'sm' : 'icon-sm'}
+ aria-expanded={open}
+ aria-label={spread ? `This conversation’s ${members.length} tabs` : 'Add other open tabs to this conversation'}
+ title={spread ? `Tabs in this conversation: ${names}` : 'Tabs: add other open tabs to this conversation'}
+ onClick={() => (open ? close() : onOpenChange(true))}
+ className={cn(spread && 'h-7 gap-1 px-1.5 has-[>svg]:px-1.5')}
+ >
+ {spread ? (
+ <>
+ <span className="flex -space-x-1.5">
+ {members.slice(0, MAX_FACES).map((tab) => (
+ <TabFace key={tab.id} tab={tab} className="rounded-full ring-2 ring-ground-2" />
+ ))}
+ </span>
+ <span className="font-mono text-[10px] tabular-nums">{session!.tabIds.length}</span>
+ </>
+ ) : (
+ <PanelsTopLeft className="size-3.5" />
+ )}
+ </Button>
+
+ <Popover
+ open={open}
+ label="Tabs in this conversation"
+ onClose={close}
+ side="top"
+ align="start"
+ className="inset-x-0 w-auto max-w-none p-0"
+ >
+ {showPicker ? (
+ <TabPicker
+ candidates={windowTabs.filter((tab) => tab.id !== frontTabId && !session?.tabIds.includes(tab.id) && hostOf(tab.url))}
+ sessions={sessions}
+ onBack={spread ? () => setPicking(false) : undefined}
+ onAdd={(tabIds) => {
+ onAdd(tabIds);
+ if (spread) setPicking(false);
+ else close();
+ }}
+ />
+ ) : (
+ <TabList
+ session={session!}
+ members={members}
+ elsewhere={elsewhere}
+ frontTabId={frontTabId}
+ onRemove={onRemove}
+ onPick={() => setPicking(true)}
+ />
+ )}
+ </Popover>
+ </span>
+ );
+}
+
+function TabList({
+ session,
+ members,
+ elsewhere,
+ frontTabId,
+ onRemove,
+ onPick,
+}: {
+ session: TabSession;
+ members: Tab[];
+ elsewhere: number;
+ frontTabId?: number;
+ onRemove: (tabId: number) => void;
+ onPick: () => void;
+}) {
+ const running = session.runId !== null;
+ const removable = session.tabIds.length > 1;
+
+ return (
+ <div>
+ <CardHeading>Tabs in this conversation</CardHeading>
+ <ul className="max-h-64 overflow-y-auto px-1.5 pb-1" onKeyDown={moveFocus}>
+ {members.map((tab) => {
+ const here = tab.id === frontTabId;
+ const agentHere = running && tab.id === session.currentTabId && !here;
+ const opened = session.openedTabIds.includes(tab.id);
+ return (
+ <li key={tab.id} className="group flex items-center gap-1 rounded-lg hover:bg-surface/60 focus-within:bg-surface/60">
+ <button
+ type="button"
+ data-row
+ onClick={() => void browser.tabs.update(tab.id, { active: true })}
+ onKeyDown={(event) => {
+ if ((event.key === 'Delete' || event.key === 'Backspace') && removable && !running) onRemove(tab.id);
+ }}
+ title={tab.url}
+ className="flex min-w-0 flex-1 items-center gap-2.5 px-2 py-1.5 text-left outline-none"
+ >
+ <TabFace tab={tab} />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-1.5">
+ {here && <span className="glow-dot size-1.5 shrink-0 rounded-full bg-brand text-brand" aria-label="You’re on this tab" />}
+ <span className="truncate text-xs text-ink">{tab.title || hostOf(tab.url) || 'Untitled'}</span>
+ </span>
+ <span className="block truncate font-mono text-[10px] text-ink-faint">
+ {hostOf(tab.url) ?? 'no site'}
+ {opened && ' · opened by the agent'}
+ </span>
+ </span>
+ {agentHere && (
+ <span className="shrink-0 rounded-full border border-brand/35 px-1.5 font-mono text-[9px] tracking-[0.1em] text-brand uppercase">
+ Agent
+ </span>
+ )}
+ </button>
+ {removable && (
+ <button
+ type="button"
+ onClick={() => onRemove(tab.id)}
+ disabled={running}
+ aria-label={`Take ${tab.title || 'this tab'} out of the conversation`}
+ title={running ? 'Stop the run before taking a tab out' : 'Take it out of the conversation. The tab stays open.'}
+ className="mr-1 shrink-0 rounded-full p-1 text-ink-faint opacity-0 transition group-hover:opacity-100 group-focus-within:opacity-100 hover:bg-surface hover:text-ink focus-visible:opacity-100 disabled:opacity-30"
+ >
+ <X className="size-3" />
+ </button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ {elsewhere > 0 && (
+ <p className="px-4 pb-1 text-[11px] text-ink-faint">
+ {elsewhere === 1 ? 'One more is in another window.' : `${elsewhere} more are in other windows.`}
+ </p>
+ )}
+ <div className="border-t border-line p-1.5">
+ <Button variant="ghost" size="sm" className="w-full justify-start" onClick={onPick}>
+ <Plus className="size-3.5" /> Add tabs
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function TabPicker({
+ candidates,
+ sessions,
+ onBack,
+ onAdd,
+}: {
+ candidates: Tab[];
+ sessions: TabSession[];
+ onBack?: () => void;
+ onAdd: (tabIds: number[]) => void;
+}) {
+ const blocked = useBlockedCheck();
+ const [filter, setFilter] = useState('');
+ const [chosen, setChosen] = useState<Set<number>>(() => new Set());
+ const seeded = useRef(false);
+
+ const rows = useMemo(
+ () =>
+ candidates.map((tab) => {
+ const holder = sessions.find((session) => session.tabIds.includes(tab.id));
+ const why = blocked(tab.url)
+ ? 'Blocked site'
+ : holder?.runId
+ ? `“${holder.title}” is working here`
+ : holder?.phone || holder?.task
+ ? `In “${holder.title}”`
+ : null;
+ return { tab, holder, why };
+ }),
+ [candidates, sessions, blocked],
+ );
+ const selectable = rows.filter((row) => !row.why);
+ const selected = selectable.filter((row) => row.tab.highlighted);
+
+ useEffect(() => {
+ if (seeded.current || !candidates.length) return;
+ seeded.current = true;
+ setChosen(new Set(selected.map((row) => row.tab.id)));
+ }, [candidates.length, selected]);
+
+ const needle = filter.trim().toLowerCase();
+ const shown = needle
+ ? rows.filter(({ tab }) => `${tab.title ?? ''} ${tab.url ?? ''}`.toLowerCase().includes(needle))
+ : rows;
+ const picked = selectable.filter((row) => chosen.has(row.tab.id)).map((row) => row.tab.id);
+
+ const toggle = (tabId: number) =>
+ setChosen((previous) => {
+ const next = new Set(previous);
+ if (!next.delete(tabId)) next.add(tabId);
+ return next;
+ });
+
+ return (
+ <div>
+ <CardHeading>
+ {onBack && (
+ <button
+ type="button"
+ onClick={onBack}
+ aria-label="Back to this conversation’s tabs"
+ className="-ml-1 rounded-full p-0.5 text-ink-faint transition-colors hover:bg-surface hover:text-ink"
+ >
+ <ChevronLeft className="size-3.5" />
+ </button>
+ )}
+ Add tabs to this conversation
+ </CardHeading>
+ {rows.length ? (
+ <>
+ <div className="px-3 pb-2">
+ <Input
+ autoFocus
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ placeholder="Filter open tabs"
+ aria-label="Filter open tabs"
+ className="h-8 text-xs"
+ />
+ {selected.length > 0 && (
+ <p className="mt-1.5 text-[11px] text-ink-faint">
+ {selected.length === 1 ? 'One tab is' : `${selected.length} tabs are`} selected in the tab strip.
+ </p>
+ )}
+ </div>
+ <ul className="max-h-64 overflow-y-auto px-1.5 pb-1" onKeyDown={moveFocus}>
+ {shown.map(({ tab, holder, why }) => {
+ const on = !why && chosen.has(tab.id);
+ return (
+ <li key={tab.id}>
+ <button
+ type="button"
+ data-row
+ role="checkbox"
+ aria-checked={on}
+ disabled={!!why}
+ onClick={() => toggle(tab.id)}
+ title={why ?? (holder ? `Moves here from “${holder.title}”` : tab.url)}
+ className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none hover:bg-surface/60 focus-visible:bg-surface/60 disabled:cursor-not-allowed disabled:opacity-45"
+ >
+ <span
+ className={cn(
+ 'grid size-3.5 shrink-0 place-items-center rounded border transition-colors',
+ on ? 'border-brand bg-brand text-ground' : 'border-line-strong',
+ )}
+ >
+ {on && <Check className="size-2.5" strokeWidth={3} />}
+ </span>
+ <TabFace tab={tab} />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs text-ink">{tab.title || hostOf(tab.url)}</span>
+ <span className="block truncate font-mono text-[10px] text-ink-faint">
+ {why ?? (holder ? `in “${holder.title}” · moves here` : hostOf(tab.url))}
+ </span>
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ {!shown.length && <li className="px-2 py-3 text-center text-[11px] text-ink-faint">No open tab matches.</li>}
+ </ul>
+ <div className="flex justify-end border-t border-line p-2">
+ <Button size="sm" disabled={!picked.length} onClick={() => onAdd(picked)}>
+ {picked.length > 1 ? `Add ${picked.length} tabs` : 'Add tab'}
+ </Button>
+ </div>
+ </>
+ ) : (
+ <p className="px-4 pb-4 text-[11px] leading-relaxed text-ink-dim">
+ No other web pages are open in this window. Open the pages this work needs, then add them here, or select them in
+ the tab strip first.
+ </p>
+ )}
+ </div>
+ );
+}
+
+function CardHeading({ children }: { children: ReactNode }) {
+ return (
+ <p className="flex items-center gap-1.5 px-4 pt-3 pb-2 font-mono text-[10px] tracking-[0.12em] text-ink-faint uppercase">
+ {children}
+ </p>
+ );
+}
+
+function TabFace({ tab, className }: { tab: Browser.tabs.Tab; className?: string }) {
+ const [broken, setBroken] = useState(false);
+ const icon = faviconOf(tab.url, 32) ?? tab.favIconUrl;
+ if (!icon || broken) {
+ return (
+ <span className={cn('grid size-3.5 shrink-0 place-items-center bg-surface text-ink-faint', className)}>
+ <Globe className="size-2.5" />
+ </span>
+ );
+ }
+ return <img src={icon} alt="" className={cn('size-3.5 shrink-0 rounded-sm', className)} onError={() => setBroken(true)} />;
+}
+
+/** Up and down move between rows, the way a menu reads. */
+function moveFocus(event: KeyboardEvent<HTMLUListElement>) {
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
+ const rows = [...event.currentTarget.querySelectorAll<HTMLButtonElement>('[data-row]:not(:disabled)')];
+ const at = rows.indexOf(document.activeElement as HTMLButtonElement);
+ const next = rows[(at + (event.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length];
+ if (!next) return;
+ event.preventDefault();
+ next.focus();
+}
diff --git a/src/extension/components/extension-settings.tsx b/src/extension/components/extension-settings.tsx
index d270ecb..c3944f9 100644
--- a/src/extension/components/extension-settings.tsx
+++ b/src/extension/components/extension-settings.tsx
@@ -102,6 +102,16 @@ function ContextMenuItems({ handsFree }: { handsFree: boolean }) {
/>
</Row>
)}
+ <Row
+ title="Add this tab to"
+ note="Lists the conversations open on other tabs, to bring this tab, or every tab selected with it, into one."
+ >
+ <Switch
+ checked={choice.addTab}
+ label="Show Add this tab to in the right-click menu"
+ onChange={(addTab) => setChoice({ ...choice, addTab })}
+ />
+ </Row>
</SettingsGroup>
);
}
diff --git a/src/extension/components/popover.tsx b/src/extension/components/popover.tsx
index 80f5eba..2f18edc 100644
--- a/src/extension/components/popover.tsx
+++ b/src/extension/components/popover.tsx
@@ -5,12 +5,16 @@ import { cn } from '@/lib/utils';
/** A select inside the card drops its list into a portal at the end of the body, so presses and Escape there belong to the card. */
const OPEN_LAYER = '[data-radix-popper-content-wrapper]';
-/** A card that drops from whatever it sits beside. Put both in a `relative` box: a press anywhere outside that box, or Escape, closes it. */
+/**
+ * A card that drops from whatever it sits beside, or rises above it with `side="top"`. Put both in one
+ * box, positioned to anchor the card: a press anywhere outside that box, or Escape, closes it.
+ */
export function Popover({
open,
label,
onClose,
align = 'end',
+ side = 'bottom',
className,
children,
}: {
@@ -18,6 +22,7 @@ export function Popover({
label: string;
onClose: () => void;
align?: 'start' | 'end';
+ side?: 'top' | 'bottom';
className?: string;
children: ReactNode;
}) {
@@ -48,7 +53,8 @@ export function Popover({
role="dialog"
aria-label={label}
className={cn(
- 'enters absolute top-full z-40 mt-2 w-[22rem] max-w-[calc(100vw-2rem)] rounded-2xl border border-line-strong bg-ground-2/95 p-4 shadow-2xl shadow-black/40 backdrop-blur',
+ 'enters absolute z-40 w-[22rem] max-w-[calc(100vw-2rem)] rounded-2xl border border-line-strong bg-ground-2/95 p-4 shadow-2xl shadow-black/40 backdrop-blur',
+ side === 'top' ? 'bottom-full mb-2' : 'top-full mt-2',
align === 'end' ? 'right-0' : 'left-0',
className,
)}
diff --git a/src/extension/components/session-rail.tsx b/src/extension/components/session-rail.tsx
index f9a8d97..b4123b3 100644
--- a/src/extension/components/session-rail.tsx
+++ b/src/extension/components/session-rail.tsx
@@ -63,7 +63,7 @@ function SessionRailRow({
onFocus: (sessionId: string) => void;
onEnd: (sessionId: string) => void;
}) {
- const subtabs = session.tabIds.length - 1;
+ const tabs = session.tabIds.length;
return (
<div
className={cn(
@@ -87,7 +87,7 @@ function SessionRailRow({
<span className="block truncate text-ink">{session.title}</span>
<span className="block font-mono text-[10px] text-ink-faint">
{session.turns} {session.turns === 1 ? 'message' : 'messages'}
- {subtabs > 0 && ` · +${subtabs} tab${subtabs === 1 ? '' : 's'}`}
+ {tabs > 1 && ` · ${tabs} tabs`}
{session.host && ` · ${session.host}`}
</span>
</span>
diff --git a/src/extension/components/skill-menu.tsx b/src/extension/components/skill-menu.tsx
index 1beddbb..467c230 100644
--- a/src/extension/components/skill-menu.tsx
+++ b/src/extension/components/skill-menu.tsx
@@ -15,6 +15,8 @@ import {
HANDS_FREE_DESCRIPTION,
REMOVE_TOOLS_COMMAND,
REMOVE_TOOLS_DESCRIPTION,
+ TABS_COMMAND,
+ TABS_DESCRIPTION,
} from '@/lib/bridge/commands';
import type { SavedToolMeta } from '@/lib/bridge/saved-tools';
import { hostMatchesDomains, hostnameOf } from '@/lib/skills/format';
@@ -63,7 +65,7 @@ export function skillMenuItems(
tabUrl: string,
query: string,
tools: readonly SavedToolMeta[] = [],
- { handsFree = false, android }: { handsFree?: boolean; android?: AndroidOption } = {},
+ { handsFree = false, android, tabs = false }: { handsFree?: boolean; android?: AndroidOption; tabs?: boolean } = {},
): SkillMenuItem[] {
const host = hostnameOf(tabUrl);
const items: SkillMenuItem[] = [
@@ -75,6 +77,9 @@ export function skillMenuItems(
command: CONTEXT_COMMAND,
},
];
+ if (tabs) {
+ items.push({ key: 'command:tabs', group: 'command', name: 'tabs', description: TABS_DESCRIPTION, command: TABS_COMMAND });
+ }
if (handsFree) {
items.push({
key: 'command:hands-free',
diff --git a/src/extension/entrypoints/sidepanel/App.tsx b/src/extension/entrypoints/sidepanel/App.tsx
index 5228ec3..4302d5a 100644
--- a/src/extension/entrypoints/sidepanel/App.tsx
+++ b/src/extension/entrypoints/sidepanel/App.tsx
@@ -2,13 +2,14 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ArrowDown, PanelRightClose, PictureInPicture2, SlidersHorizontal, SquarePen } from 'lucide-react';
import { browser } from 'wxt/browser';
-import { isAndroidCommand, isHandsFreeCommand, isRemoveToolsCommand } from '@/lib/bridge/commands';
+import { isAndroidCommand, isHandsFreeCommand, isRemoveToolsCommand, isTabsCommand } from '@/lib/bridge/commands';
import { BRIDGE_CHANNEL, type FocusedElement } from '@/lib/actions/protocol';
import { MAX_STORED_FILE_BYTES } from '@/lib/files/report';
import { Wordmark } from '@/extension/components/brand';
import { BLOCKED_HERE, BlockedSiteNote } from '@/extension/components/blocked-site-note';
import { Composer, type AttachedSkill } from '@/extension/components/composer';
import { ConnectionSheet } from '@/extension/components/connection-sheet';
+import { ConversationTabs } from '@/extension/components/conversation-tabs';
import { DetachVeil } from '@/extension/components/detach-veil';
import { DropMask } from '@/extension/components/drop-mask';
import { Greeting } from '@/extension/components/greeting';
@@ -81,6 +82,7 @@ export default function App() {
const tasks = useStoredTasks();
const [taskSeed, setTaskSeed] = useState<TaskSeed | null>(null);
const [scheduling, setScheduling] = useState(false);
+ const [tabsOpen, setTabsOpen] = useState(false);
const takeSeed = useCallback(() => setTaskSeed(null), []);
const tabUrl = useActiveTabUrl();
const phone = useMirroredPhone();
@@ -214,6 +216,12 @@ export default function App() {
detach();
return true;
}
+ if (isTabsCommand(text) && !onPhone) {
+ voice.setInput('');
+ open('chat');
+ setTabsOpen(true);
+ return true;
+ }
if (isAndroidCommand(text)) {
voice.setInput('');
void phoneSwitch.toggle().then((result) => setAttachError(result.ok ? null : result.error.message));
@@ -508,6 +516,18 @@ export default function App() {
handsFree={handsFree}
android={androidOption}
onPhone={onPhone}
+ tabs={
+ !onPhone && (
+ <ConversationTabs
+ session={run.session}
+ sessions={run.sessions}
+ open={tabsOpen}
+ onOpenChange={setTabsOpen}
+ onAdd={run.addTabs}
+ onRemove={run.removeTab}
+ />
+ )
+ }
onCommand={(command) => {
if (takeCommand(command)) return;
if (isRemoveToolsCommand(command)) {
diff --git a/src/lib/bridge/commands.ts b/src/lib/bridge/commands.ts
index aa9ca22..a05fd39 100644
--- a/src/lib/bridge/commands.ts
+++ b/src/lib/bridge/commands.ts
@@ -22,6 +22,12 @@ export const isHandsFreeCommand = (text: string): boolean => {
return typed === HANDS_FREE_COMMAND || HANDS_FREE_ALIASES.some((alias) => typed === `/${alias}`);
};
+export const TABS_COMMAND = '/tabs';
+
+export const TABS_DESCRIPTION = 'Add other open tabs to this conversation, or see the ones it has.';
+
+export const isTabsCommand = (text: string): boolean => text.trim().toLowerCase() === TABS_COMMAND;
+
export const ANDROID_COMMAND = '/android';
export const ANDROID_ALIASES = ['phone'];
diff --git a/src/lib/bridge/context-menu.test.ts b/src/lib/bridge/context-menu.test.ts
index 647aa6c..e78937a 100644
--- a/src/lib/bridge/context-menu.test.ts
+++ b/src/lib/bridge/context-menu.test.ts
@@ -1,8 +1,19 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
-import { CONTEXT_MENU_KEY, HANDS_FREE_ITEM, PANEL_ITEM, asContextMenuChoice, describeMenu, readContextMenuChoice } from './context-menu';
+import {
+ ADD_TAB_ITEM,
+ CONTEXT_MENU_KEY,
+ HANDS_FREE_ITEM,
+ PANEL_ITEM,
+ addTabItem,
+ asContextMenuChoice,
+ describeMenu,
+ readContextMenuChoice,
+ sessionOfItem,
+} from './context-menu';
+import type { TabSession } from './tab-sessions';
-const both = { panel: true, handsFree: true };
+const both = { panel: true, handsFree: true, addTab: true };
const idle = { choice: both, speech: true, panelOpen: false, handsFree: false };
beforeEach(() => {
@@ -27,8 +38,8 @@ describe('describeMenu', () => {
});
it('leaves out what was switched off, down to an empty menu', () => {
- expect(describeMenu({ ...idle, choice: { panel: false, handsFree: true } }).map(({ id }) => id)).toEqual([HANDS_FREE_ITEM]);
- expect(describeMenu({ ...idle, choice: { panel: false, handsFree: false } })).toEqual([]);
+ expect(describeMenu({ ...idle, choice: { ...both, panel: false } }).map(({ id }) => id)).toEqual([HANDS_FREE_ITEM]);
+ expect(describeMenu({ ...idle, choice: { panel: false, handsFree: false, addTab: true } })).toEqual([]);
});
});
@@ -36,7 +47,7 @@ describe('the stored choice', () => {
it('has both items on until one is switched off', async () => {
expect(await readContextMenuChoice()).toEqual(both);
await fakeBrowser.storage.local.set({ [CONTEXT_MENU_KEY]: { panel: false } });
- expect(await readContextMenuChoice()).toEqual({ panel: false, handsFree: true });
+ expect(await readContextMenuChoice()).toEqual({ panel: false, handsFree: true, addTab: true });
});
it('reads anything malformed as the default', () => {
@@ -45,3 +56,44 @@ describe('the stored choice', () => {
expect(asContextMenuChoice({ panel: 0, handsFree: 'no' })).toEqual(both);
});
});
+
+describe('Add this tab to', () => {
+ const conversation = (sessionId: string, patch: Partial<TabSession> = {}): TabSession => ({
+ sessionId,
+ mainTabId: 1,
+ tabIds: [1],
+ userTabIds: [1],
+ openedTabIds: [],
+ currentTabId: 1,
+ windowId: 1,
+ title: `Conversation ${sessionId}`,
+ host: `${sessionId}.example`,
+ runId: null,
+ turns: 1,
+ createdAt: 0,
+ lastActivityAt: 0,
+ ...patch,
+ });
+ const quiet = { ...idle, choice: { panel: false, handsFree: false, addTab: true } };
+
+ it('lists the conversations on other tabs, under one item', () => {
+ const sessions = [conversation('jira', { tabIds: [1, 2] }), conversation('docs', { mainTabId: 5, tabIds: [5] })];
+ expect(describeMenu({ ...quiet, sessions, frontTabId: 2 })).toEqual([
+ { id: ADD_TAB_ITEM, title: 'Add this tab to' },
+ { id: addTabItem('docs'), parentId: ADD_TAB_ITEM, title: '“Conversation docs” · docs.example' },
+ ]);
+ });
+
+ it('is not there with nowhere to add the tab, nor when switched off', () => {
+ const phone = conversation('phone', { phone: { serial: 's' }, tabIds: [9] });
+ expect(describeMenu({ ...quiet, sessions: [phone, conversation('own')], frontTabId: 1 })).toEqual([]);
+ expect(describeMenu({ ...idle, choice: { ...both, addTab: false }, sessions: [conversation('other')], frontTabId: 7 }).map(({ id }) => id)).toEqual([
+ PANEL_ITEM,
+ HANDS_FREE_ITEM,
+ ]);
+ });
+
+ it('names the conversation in its item id', () => {
+ expect([sessionOfItem(addTabItem('abc')), sessionOfItem(PANEL_ITEM), sessionOfItem(3)]).toEqual(['abc', null, null]);
+ });
+});
diff --git a/src/lib/bridge/context-menu.ts b/src/lib/bridge/context-menu.ts
index f66fe6d..10ab01e 100644
--- a/src/lib/bridge/context-menu.ts
+++ b/src/lib/bridge/context-menu.ts
@@ -1,17 +1,22 @@
import { browser } from 'wxt/browser';
+import type { TabSession } from './tab-sessions';
export const CONTEXT_MENU_KEY = 'browsentic/contextMenu';
export const PANEL_ITEM = 'open-side-panel';
export const HANDS_FREE_ITEM = 'open-hands-free';
+export const ADD_TAB_ITEM = 'add-tab-to';
+
+const MAX_MENU_TITLE = 48;
export interface ContextMenuChoice {
panel: boolean;
handsFree: boolean;
+ addTab: boolean;
}
export function asContextMenuChoice(value: unknown): ContextMenuChoice {
const stored = (value !== null && typeof value === 'object' ? value : {}) as Partial<Record<keyof ContextMenuChoice, unknown>>;
- return { panel: stored.panel !== false, handsFree: stored.handsFree !== false };
+ return { panel: stored.panel !== false, handsFree: stored.handsFree !== false, addTab: stored.addTab !== false };
}
export async function readContextMenuChoice(): Promise<ContextMenuChoice> {
@@ -23,15 +28,45 @@ export interface MenuState {
speech: boolean;
panelOpen: boolean;
handsFree: boolean;
+ /** The live conversations, and the tab in front, for “Add this tab to”. */
+ sessions?: readonly TabSession[];
+ frontTabId?: number;
}
export interface MenuItem {
id: string;
title: string;
+ parentId?: string;
}
-export function describeMenu({ choice, speech, panelOpen, handsFree }: MenuState): MenuItem[] {
+export function describeMenu({ choice, speech, panelOpen, handsFree, sessions = [], frontTabId }: MenuState): MenuItem[] {
const panel = { id: PANEL_ITEM, title: panelOpen ? 'Close Browsentic' : 'Open Browsentic' };
const mic = { id: HANDS_FREE_ITEM, title: handsFree ? 'Close Browsentic (Hands Free)' : 'Open Browsentic (Hands Free)' };
- return [...(choice.panel ? [panel] : []), ...(choice.handsFree && speech ? [mic] : [])];
+ const into = choice.addTab ? sessions.filter((session) => addable(session, frontTabId)) : [];
+ return [
+ ...(choice.panel ? [panel] : []),
+ ...(choice.handsFree && speech ? [mic] : []),
+ ...(into.length
+ ? [
+ { id: ADD_TAB_ITEM, title: 'Add this tab to' },
+ ...into.map((session) => ({ id: addTabItem(session.sessionId), parentId: ADD_TAB_ITEM, title: menuTitleOf(session) })),
+ ]
+ : []),
+ ];
+}
+
+/** A conversation the tab in front could join: on this computer's browser, not a schedule's, and not already holding it. */
+const addable = (session: TabSession, frontTabId: number | undefined) =>
+ !session.phone && !session.task && (frontTabId === undefined || !session.tabIds.includes(frontTabId));
+
+export const addTabItem = (sessionId: string) => `${ADD_TAB_ITEM}:${sessionId}`;
+
+export function sessionOfItem(itemId: string | number): string | null {
+ const prefix = `${ADD_TAB_ITEM}:`;
+ return typeof itemId === 'string' && itemId.startsWith(prefix) ? itemId.slice(prefix.length) : null;
+}
+
+function menuTitleOf(session: TabSession): string {
+ const title = session.title.length > MAX_MENU_TITLE ? `${session.title.slice(0, MAX_MENU_TITLE - 1)}…` : session.title;
+ return session.host && session.host !== session.title ? `“${title}” · ${session.host}` : `“${title}”`;
}
diff --git a/src/lib/bridge/launchers.ts b/src/lib/bridge/launchers.ts
index ff6bfbe..88acfd9 100644
--- a/src/lib/bridge/launchers.ts
+++ b/src/lib/bridge/launchers.ts
@@ -1,13 +1,15 @@
-import { browser } from 'wxt/browser';
+import { browser, type Browser } from 'wxt/browser';
import { HANDS_FREE_SHORTCUT, PANEL_SHORTCUT } from '@/lib/settings/shortcuts';
-import { CONTEXT_MENU_KEY, HANDS_FREE_ITEM, PANEL_ITEM, describeMenu, readContextMenuChoice } from './context-menu';
+import { CONTEXT_MENU_KEY, HANDS_FREE_ITEM, PANEL_ITEM, describeMenu, readContextMenuChoice, sessionOfItem } from './context-menu';
import { HANDS_FREE_KEY, endHandsFree, readHandsFree, startHandsFree } from './panel-view';
-import { closePanels, onPanelPresence } from './run-port';
+import { addTabsTo, closePanels, onPanelPresence } from './run-port';
+import { TAB_SESSIONS_KEY, readTabSessions } from './tab-sessions';
import { closeSidebar, openPanelFromToolbar, openSidePanel, toggleSidebar } from './side-panel';
import { SPEECH_SERVICE_KEY, handsFreeSupported } from './speech-support';
let panelOpen = false;
let painting: Promise<void> = Promise.resolve();
+let painted = '';
/** One paint at a time, so a second change never lands its items between another's removeAll and creates. */
function repaintMenu(): void {
@@ -16,14 +18,43 @@ function repaintMenu(): void {
.catch((error) => console.warn('[browsentic] context menu paint failed:', error));
}
+/** Firefox also lists it on the tab strip's own menu, where a right-click names the tab it is about. */
+const ADD_CONTEXTS: NonNullable<Browser.contextMenus.CreateProperties['contexts']> = import.meta.env.FIREFOX
+ ? ['all', 'tab']
+ : ['all'];
+
async function paintMenu(): Promise<void> {
- const [choice, speech, handsFree] = await Promise.all([readContextMenuChoice(), handsFreeSupported(), readHandsFree()]);
+ const [choice, speech, handsFree, sessions, [front]] = await Promise.all([
+ readContextMenuChoice(),
+ handsFreeSupported(),
+ readHandsFree(),
+ readTabSessions(),
+ browser.tabs.query({ active: true, lastFocusedWindow: true }).catch(() => []),
+ ]);
+ const items = describeMenu({
+ choice,
+ speech,
+ panelOpen,
+ handsFree: handsFree !== null,
+ sessions: Object.values(sessions).sort((a, b) => b.lastActivityAt - a.lastActivityAt),
+ frontTabId: front?.id,
+ });
+ const drawn = JSON.stringify(items);
+ if (drawn === painted) return;
+ painted = drawn;
await browser.contextMenus.removeAll();
- describeMenu({ choice, speech, panelOpen, handsFree: handsFree !== null }).forEach((item) =>
- browser.contextMenus.create({ ...item, contexts: ['all'] }),
+ items.forEach((item) =>
+ browser.contextMenus.create({ ...item, contexts: item.id === PANEL_ITEM || item.id === HANDS_FREE_ITEM ? ['all'] : ADD_CONTEXTS }),
);
}
+/** The tab right-clicked, or every tab selected with it in the tab strip. */
+async function tabsToAdd(tab: Browser.tabs.Tab): Promise<number[]> {
+ if (!tab.highlighted || tab.windowId == null) return tab.id != null ? [tab.id] : [];
+ const selected = await browser.tabs.query({ windowId: tab.windowId, highlighted: true }).catch(() => [tab]);
+ return selected.flatMap((each) => (each.id != null ? [each.id] : []));
+}
+
/** Called with a user gesture that the first await would spend, so the panel opens before anything is awaited. */
function togglePanel(windowId: number): void {
if (!panelOpen) void openSidePanel(windowId);
@@ -48,8 +79,12 @@ export function serveLaunchers(): void {
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === PANEL_ITEM && tab?.windowId != null) togglePanel(tab.windowId);
if (info.menuItemId === HANDS_FREE_ITEM) void toggleHandsFree();
+ const into = sessionOfItem(info.menuItemId);
+ if (into && tab) void tabsToAdd(tab).then((tabIds) => addTabsTo(into, tabIds));
});
+ browser.tabs.onActivated.addListener(() => repaintMenu());
+
browser.commands.onCommand.addListener((command, tab) => {
if (command === PANEL_SHORTCUT && tab?.windowId != null) togglePanel(tab.windowId);
if (command === HANDS_FREE_SHORTCUT) void toggleHandsFree();
@@ -57,7 +92,7 @@ export function serveLaunchers(): void {
browser.storage.session.onChanged.addListener((changes) => {
const handsFree = changes[HANDS_FREE_KEY];
- if (handsFree && !handsFree.oldValue !== !handsFree.newValue) repaintMenu();
+ if ((handsFree && !handsFree.oldValue !== !handsFree.newValue) || TAB_SESSIONS_KEY in changes) repaintMenu();
});
browser.storage.local.onChanged.addListener((changes) => {
if (CONTEXT_MENU_KEY in changes || SPEECH_SERVICE_KEY in changes) repaintMenu();
diff --git a/src/lib/bridge/use-extension-settings.ts b/src/lib/bridge/use-extension-settings.ts
index 9f33c78..5d47fd0 100644
--- a/src/lib/bridge/use-extension-settings.ts
+++ b/src/lib/bridge/use-extension-settings.ts
@@ -70,6 +70,15 @@ export function useBlockedPattern(url: string | undefined): string | null {
return useMemo(() => blockedBy(url, compileBlockedSites(patterns) ?? []), [url, patterns]);
}
+/** One compiled list for checking many pages, such as every tab in a window. */
+export function useBlockedCheck(): (url: string | undefined) => boolean {
+ const [patterns] = useBlockedSites();
+ return useMemo(() => {
+ const list = compileBlockedSites(patterns) ?? [];
+ return (url) => blockedBy(url, list) !== null;
+ }, [patterns]);
+}
+
export function openBlockedSites(): void {
void browser.tabs.create({ url: `${browser.runtime.getURL('/options.html')}#blocked` });
}
diff --git a/src/lib/bridge/use-run.ts b/src/lib/bridge/use-run.ts
index e1ac219..081c43b 100644
--- a/src/lib/bridge/use-run.ts
+++ b/src/lib/bridge/use-run.ts
@@ -38,6 +38,8 @@ export interface Run {
items: RunItem[];
running: boolean;
sessionId: string | null;
+ /** The conversation of the tab in front, when it has one. */
+ session: TabSession | null;
sessions: TabSession[];
/** The latest turn an agent saw through to the end, in any conversation, as it happened — never from a replay. */
completed: CompletedTurn | null;
@@ -69,6 +71,9 @@ export interface Run {
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;
+ /** Puts open tabs in the conversation of the tab in front, starting one there if need be. */
+ addTabs: (tabIds: number[]) => void;
+ removeTab: (tabId: number) => void;
detachFile: (fileId: string) => void;
reanalyzeFile: (fileId: string) => void;
}
@@ -251,6 +256,7 @@ export function useRun(pinned?: ActiveTab): Run {
items,
running: displayed?.runId != null,
sessionId,
+ session: displayed,
sessions,
completed,
send,
@@ -317,6 +323,20 @@ export function useRun(pinned?: ActiveTab): Run {
},
[post, tab],
),
+ addTabs: useCallback(
+ (tabIds: number[]) => {
+ if (tab.tabId != null) {
+ post({ op: 'addTabs', tabIds, tab: { tabId: tab.tabId, url: tab.url, windowId: tab.windowId, title: tab.title } });
+ }
+ },
+ [post, tab],
+ ),
+ removeTab: useCallback(
+ (tabId: number) => {
+ if (sessionId) post({ op: 'removeTab', sessionId, tabId });
+ },
+ [post, sessionId],
+ ),
detachFile: useCallback((fileId: string) => post({ op: 'detach', fileId }), [post]),
reanalyzeFile: useCallback((fileId: string) => post({ op: 'reanalyze', fileId }), [post]),
monitors,
diff --git a/src/lib/bridge/use-window-tabs.ts b/src/lib/bridge/use-window-tabs.ts
new file mode 100644
index 0000000..dbfb4f9
--- /dev/null
+++ b/src/lib/bridge/use-window-tabs.ts
@@ -0,0 +1,44 @@
+import { useEffect, useState } from 'react';
+import { browser, type Browser } from 'wxt/browser';
+
+/** The tabs of the window the page is in, in tab-strip order, kept live: titles, icons, order and the tab strip's selection. */
+export function useWindowTabs(): Browser.tabs.Tab[] {
+ const [tabs, setTabs] = useState<Browser.tabs.Tab[]>([]);
+
+ useEffect(() => {
+ let live = true;
+ const refresh = () => {
+ void browser.tabs
+ .query({ currentWindow: true })
+ .then((found) => live && setTabs([...found].sort((a, b) => a.index - b.index)))
+ .catch(() => undefined);
+ };
+ refresh();
+
+ const onUpdated = (_id: number, change: { title?: string; url?: string; favIconUrl?: string }) => {
+ if (change.title !== undefined || change.url !== undefined || change.favIconUrl !== undefined) refresh();
+ };
+ const { onCreated, onRemoved, onMoved, onActivated, onHighlighted, onAttached, onDetached } = browser.tabs;
+ onCreated.addListener(refresh);
+ onRemoved.addListener(refresh);
+ onMoved.addListener(refresh);
+ onActivated.addListener(refresh);
+ onHighlighted.addListener(refresh);
+ onAttached.addListener(refresh);
+ onDetached.addListener(refresh);
+ browser.tabs.onUpdated.addListener(onUpdated);
+ return () => {
+ live = false;
+ onCreated.removeListener(refresh);
+ onRemoved.removeListener(refresh);
+ onMoved.removeListener(refresh);
+ onActivated.removeListener(refresh);
+ onHighlighted.removeListener(refresh);
+ onAttached.removeListener(refresh);
+ onDetached.removeListener(refresh);
+ browser.tabs.onUpdated.removeListener(onUpdated);
+ };
+ }, []);
+
+ return tabs;
+}