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(panel): context-menu close and stranded-rail cleanup

Shahriar2429f7b6b2d3
diff --git a/docs/guide/features/conversations.md b/docs/guide/features/conversations.md
index a9acade..cee78f8 100644
--- a/docs/guide/features/conversations.md
+++ b/docs/guide/features/conversations.md
@@ -56,7 +56,11 @@ reopen it.
The rail is drawn into the page, so it cannot appear on pages Browsentic is not allowed into —
`chrome://` pages, the Chrome Web Store and the new tab page. The toolbar icon and the right-click
-**Open Browsentic** item always work.
+**Open Browsentic** item always work; while the panel is open, that item reads **Close Browsentic**
+and closes it instead.
+
+The rail belongs to the minimized state alone. Closing the panel with the browser's own close
+button removes any rail from every page — only the header's collapse button leaves one behind.
### Knowing something is running when you are elsewhere
diff --git a/docs/internals/extension.md b/docs/internals/extension.md
index a3790e4..0ff1069 100644
--- a/docs/internals/extension.md
+++ b/docs/internals/extension.md
@@ -94,9 +94,22 @@ revived, which would strand a rail on a page with no way to clear it. The first
life always broadcasts; only a repeated *clear* is skipped. A tab that has just finished loading is
repainted on its own rather than triggering a broadcast.
+**A rail only exists while the panel is minimized on purpose.** The side panel holds a run port
+open for as long as it lives, so the background knows the moment the last panel is gone. If the
+collapsed flag is not set at that moment — the panel was closed with the browser's own button, not
+the collapse button — `clearStrandedRail()` forgets what it thinks tabs are showing and forces the
+hide onto all of them, catching any tab an earlier broadcast missed. The content script heals its
+own side of the same problem: on injection it removes any rail element left by a previous extension
+life, and on a back/forward-cache restore it drops the cached rail and asks the background for the
+current state with the rail channel's `sync` op.
+
+The same panel-presence signal drives the context menu: the item reads **Open Browsentic** or
+**Close Browsentic** to match, and a click on *Close* shuts the panel — Firefox's background closes
+the sidebar inside the gesture, Chromium panels are told over the run port to close themselves.
+
Pages that refuse content scripts — `chrome://`, the Web Store, the new-tab page — get no rail.
That is the same `TAB_UNREACHABLE` set as everywhere else, and it is why the toolbar icon and the
-**Open Browsentic** context-menu item stay the guaranteed way back in.
+**Open/Close Browsentic** context-menu item stay the guaranteed way back in.
## Tab scoping
diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.ts
index a28be55..1dc469f 100644
--- a/src/extension/entrypoints/background.ts
+++ b/src/extension/entrypoints/background.ts
@@ -10,10 +10,10 @@ import { nameStoredSession } from '@/lib/bridge/session-store';
import { analyzeStoredRecording, resumePendingAnalyses } from '@/lib/bridge/recording-store';
import { ingestSample, monitorsForTab, serveMonitor } from '@/lib/bridge/monitor';
import { appendEvents, recordingStateFor, serveRecorder } from '@/lib/bridge/recorder';
-import { serveRunPorts, serveTabSessions } from '@/lib/bridge/run-port';
-import { serveRail, setPanelCollapsed, syncRail } from '@/lib/bridge/rail';
+import { closePanels, onPanelPresence, serveRunPorts, serveTabSessions } from '@/lib/bridge/run-port';
+import { clearStrandedRail, serveRail, setPanelCollapsed, syncRail } from '@/lib/bridge/rail';
import { serveTimers } from '@/lib/bridge/timer';
-import { openSidePanel } from '@/lib/bridge/side-panel';
+import { closeSidebar, openSidePanel } from '@/lib/bridge/side-panel';
import { isAgentKind } from '@/lib/agents/catalog';
import {
RECONNECT_ALARM,
@@ -172,14 +172,30 @@ export default defineBackground(() => {
});
});
- void browser.contextMenus
+ const menuReady = browser.contextMenus
.removeAll()
.then(() =>
browser.contextMenus.create({ id: OPEN_PANEL_MENU, title: 'Open Browsentic', contexts: ['all'] }),
);
+ let panelOpen = false;
+ onPanelPresence((open) => {
+ panelOpen = open;
+ void menuReady.then(() =>
+ browser.contextMenus.update(OPEN_PANEL_MENU, {
+ title: open ? 'Close Browsentic' : 'Open Browsentic',
+ }),
+ );
+ if (!open) void clearStrandedRail();
+ });
+
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId !== OPEN_PANEL_MENU || tab?.windowId == null) return;
+ if (panelOpen) {
+ if (import.meta.env.FIREFOX) void closeSidebar();
+ else closePanels();
+ return;
+ }
void openSidePanel(tab.windowId);
});
diff --git a/src/lib/bridge/rail.ts b/src/lib/bridge/rail.ts
index ce2c56d..05e8d96 100644
--- a/src/lib/bridge/rail.ts
+++ b/src/lib/bridge/rail.ts
@@ -46,6 +46,17 @@ export function syncRail(): Promise<void> {
return inFlight;
}
+/**
+ * The panel disappeared without minimizing — closed natively, so no rail should survive it.
+ * Forgetting `showing` forces the hide onto every tab, including any that missed an earlier
+ * broadcast. A collapsed panel is different: the rail is the panel then, and it stays.
+ */
+export async function clearStrandedRail(): Promise<void> {
+ if (await readPanelCollapsed()) return;
+ showing = null;
+ await syncRail();
+}
+
async function paintRail(): Promise<void> {
const collapsed = await readPanelCollapsed();
if (!collapsed && showing === false) return;
@@ -122,8 +133,13 @@ async function readSide(): Promise<'left' | 'right'> {
export function serveRail(): void {
browser.runtime.onMessage.addListener((message, sender) => {
if (!isRailRequest(message)) return;
- const windowId = sender.tab?.windowId;
- if (windowId == null) return;
+ const { id: tabId, windowId } = sender.tab ?? {};
+ if (tabId == null || windowId == null) return;
+
+ if (message.op === 'sync') {
+ void paintTab(tabId);
+ return Promise.resolve({ ok: true });
+ }
/* The click that reached us is the only user gesture the panel will get — spend it
before any await, or `open()` rejects and the rail becomes a dead button. The rail
diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.ts
index f96e4a6..c316925 100644
--- a/src/lib/bridge/run-port.ts
+++ b/src/lib/bridge/run-port.ts
@@ -94,9 +94,12 @@ export type RunMessage =
| { op: 'mapSettled'; stagingId: string; ok: boolean; message?: string }
| { op: 'recording'; state: RecordingState | null }
| { op: 'preview'; sessionId?: string; preview: ScreenshotPreview }
- | { op: 'monitor'; state: MonitorState };
+ | { op: 'monitor'; state: MonitorState }
+ | { op: 'close' };
const ports = new Set<Browser.runtime.Port>();
+const panelPorts = new Set<Browser.runtime.Port>();
+const panelWatchers = new Set<(open: boolean) => void>();
const buffers = new Map<string, RunItem[]>();
const busy = new Set<string>();
const persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -177,6 +180,10 @@ export function serveRunPorts(): void {
browser.runtime.onConnect.addListener((port) => {
if (port.name !== RUN_PORT) return;
ports.add(port);
+ if (port.sender?.url?.includes('sidepanel.html')) {
+ panelPorts.add(port);
+ if (panelPorts.size === 1) for (const watch of panelWatchers) watch(true);
+ }
if (pendingDraft) post(port, { op: 'mapDraft', draft: pendingDraft });
void currentRecording().then((state) => post(port, { op: 'recording', state }));
void activeMonitorStates().then((states) => {
@@ -189,10 +196,23 @@ export function serveRunPorts(): void {
});
port.onMessage.addListener((message) => handle(message as RunCommand));
- port.onDisconnect.addListener(() => ports.delete(port));
+ port.onDisconnect.addListener(() => {
+ ports.delete(port);
+ if (panelPorts.delete(port) && panelPorts.size === 0) for (const watch of panelWatchers) watch(false);
+ });
});
}
+/** Fires with `true` when the first side panel connects and `false` when the last one is gone. */
+export function onPanelPresence(watch: (open: boolean) => void): void {
+ panelWatchers.add(watch);
+}
+
+/** Chromium has no menu-side close, so each panel is told to shut itself. */
+export function closePanels(): void {
+ for (const panel of panelPorts) post(panel, { op: 'close' });
+}
+
function handle(command: RunCommand): void {
switch (command.op) {
case 'instruct':
diff --git a/src/lib/bridge/side-panel.ts b/src/lib/bridge/side-panel.ts
index 2153834..6934b59 100644
--- a/src/lib/bridge/side-panel.ts
+++ b/src/lib/bridge/side-panel.ts
@@ -9,6 +9,11 @@ export function openSidePanel(windowId: number) {
return browser.sidePanel.open({ windowId });
}
+/** Firefox lets the background shut the sidebar, as long as a user gesture is still live. */
+export function closeSidebar(): Promise<void> {
+ return sidebarAction().close();
+}
+
/** Only the panel itself calls this, so `window.close()` is the fallback worth having. */
export async function closeSidePanel(windowId: number | null): Promise<void> {
try {
diff --git a/src/lib/bridge/use-run.ts b/src/lib/bridge/use-run.ts
index 8fcf20e..c1e7783 100644
--- a/src/lib/bridge/use-run.ts
+++ b/src/lib/bridge/use-run.ts
@@ -107,6 +107,8 @@ export function useRun(): Run {
write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => [...items, runMessage.item]);
} else if (runMessage.op === 'preview') {
write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => attachPreview(items, runMessage.preview));
+ } else if (runMessage.op === 'close') {
+ window.close();
} else {
write(runMessage.sessionId ?? EXTERNAL_VIEW, (items) => reduce(items, runMessage.event));
}
diff --git a/src/lib/rail/events.ts b/src/lib/rail/events.ts
index 12b411d..371bb6b 100644
--- a/src/lib/rail/events.ts
+++ b/src/lib/rail/events.ts
@@ -17,11 +17,9 @@ export type RailCommand =
| { channel: typeof RAIL_CHANNEL; op: 'show'; view: RailView }
| { channel: typeof RAIL_CHANNEL; op: 'hide' };
-export interface RailRequest {
- channel: typeof RAIL_CHANNEL;
- op: 'open';
- tab: PanelTab;
-}
+export type RailRequest =
+ | { channel: typeof RAIL_CHANNEL; op: 'open'; tab: PanelTab }
+ | { channel: typeof RAIL_CHANNEL; op: 'sync' };
export function isRailCommand(message: unknown): message is RailCommand {
if (typeof message !== 'object' || message === null) return false;
@@ -32,7 +30,7 @@ export function isRailCommand(message: unknown): message is RailCommand {
export function isRailRequest(message: unknown): message is RailRequest {
if (typeof message !== 'object' || message === null) return false;
const frame = message as { channel?: unknown; op?: unknown };
- return frame.channel === RAIL_CHANNEL && frame.op === 'open';
+ return frame.channel === RAIL_CHANNEL && (frame.op === 'open' || frame.op === 'sync');
}
/** Lucide paths, copied so the content script carries no React and no icon package. */
diff --git a/src/lib/rail/host.ts b/src/lib/rail/host.ts
index 00e121b..25c56d6 100644
--- a/src/lib/rail/host.ts
+++ b/src/lib/rail/host.ts
@@ -29,6 +29,21 @@ export function exposeRail(): void {
return Promise.resolve({ ok: true });
});
+ /* A rail drawn by a previous extension life — before a reload, or before this page went
+ into the back/forward cache — is dead markup: its click handlers reach nothing. Drop it
+ and ask the background whether a live one belongs here. */
+ document.getElementById(HOST_ID)?.remove();
+ resync();
+ window.addEventListener('pageshow', (event) => {
+ if (!event.persisted) return;
+ remove();
+ resync();
+ });
+
+ function resync(): void {
+ void browser.runtime.sendMessage({ channel: RAIL_CHANNEL, op: 'sync' }).catch(() => undefined);
+ }
+
function remove(): void {
host?.remove();
host = null;