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(panel): minimize into a rail the page carries
Shahriarea8cbbcf1ae3
diff --git a/components/brand.tsx b/components/brand.tsxindex e2de545..e5325d2 100644--- a/components/brand.tsx+++ b/components/brand.tsx@@ -33,7 +33,7 @@ export function Wordmark({ className }: { className?: string }) {return (<span className={cn('flex min-w-0 items-center gap-2', className)}><Logo className="size-6 shrink-0 text-brand" />- <span className="font-display text-[0.9375rem] leading-none font-semibold tracking-tight text-ink">+ <span className="truncate font-display text-[0.9375rem] leading-none font-semibold tracking-tight text-ink max-[19rem]:hidden">Browsentic</span></span>diff --git a/components/panel-nav.tsx b/components/panel-nav.tsxindex bd162d1..1ce7ef3 100644--- a/components/panel-nav.tsx+++ b/components/panel-nav.tsx@@ -1,10 +1,14 @@+import { useLayoutEffect, useRef, useState } from 'react';import { BookOpen, Clapperboard, History, MessagesSquare, SlidersHorizontal, type LucideIcon } from 'lucide-react';+import { type PanelTab } from '@/lib/rail/events';import { cn } from '@/lib/utils';-export type PanelTab = 'chat' | 'history' | 'skills' | 'recordings' | 'settings';+export type { PanelTab };-const TABS: { id: PanelTab; label: string; icon: LucideIcon }[] = [+export type PanelCounts = Partial<Record<PanelTab, number>>;++export const TABS: { id: PanelTab; label: string; icon: LucideIcon }[] = [{ id: 'chat', label: 'Chat', icon: MessagesSquare },{ id: 'history', label: 'History', icon: History },{ id: 'skills', label: 'Skills', icon: BookOpen },@@ -12,51 +16,105 @@ const TABS: { id: PanelTab; label: string; icon: LucideIcon }[] = [{ id: 'settings', label: 'Settings', icon: SlidersHorizontal },];+/** Every label, then only the open tab's, then none — whichever the strip has room for. */+type Fit = 'full' | 'active' | 'icons';+export function PanelNav({tab,counts,onSelect,}: {tab: PanelTab;- counts: Partial<Record<PanelTab, number>>;+ counts: PanelCounts;onSelect: (tab: PanelTab) => void;}) {+ const nav = useRef<HTMLElement>(null);+ const [fit, setFit] = useState<Fit>('full');+ const needed = useRef({ full: 0, active: 0 });+ const tally = TABS.map(({ id }) => counts[id] ?? 0).join('·');++ useLayoutEffect(() => {+ const element = nav.current;+ if (!element) return;+ let live = true;++ /* A width is only knowable while it is on screen, so each fit records its own and+ steps one rung down; stepping back up waits for the width it already learned. */+ const measure = () => {+ if (!live) return;+ const room = element.clientWidth;+ if (fit !== 'icons') needed.current[fit] = contentWidth(element);+ const { full, active } = needed.current;+ if (full > 0 && room >= full) setFit('full');+ else if (fit === 'full') setFit('active');+ else setFit(room >= active ? 'active' : 'icons');+ };++ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ void document.fonts.ready.then(measure);+ return () => {+ live = false;+ observer.disconnect();+ };+ }, [fit, tab, tally]);+return (<nav+ ref={nav}aria-label="Panel sections"- className="flex shrink-0 gap-1 overflow-x-auto border-b border-line px-2 pb-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"+ className="flex shrink-0 items-center gap-0.5 overflow-x-auto border-b border-line px-2 pb-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">{TABS.map(({ id, label, icon: Icon }) => {const active = tab === id;const count = counts[id] ?? 0;+ const labelled = fit === 'full' || (fit === 'active' && active);return (<buttonkey={id}type="button"onClick={() => onSelect(id)}+ title={labelled ? undefined : label}+ aria-label={label}aria-current={active ? 'page' : undefined}className={cn(- 'inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1.5 text-[11px] font-medium transition-colors',- active- ? 'bg-brand/12 text-brand'- : 'text-ink-faint hover:bg-surface/60 hover:text-ink-dim',+ 'relative inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1.5 text-[11px] font-medium transition-colors',+ active ? 'bg-brand/12 text-brand' : 'text-ink-faint hover:bg-surface/60 hover:text-ink-dim',)}><Icon className="size-3.5" />- {label}- {count > 0 && (- <span- className={cn(- 'rounded-full px-1 font-mono text-[9px] tabular-nums',- active ? 'bg-brand/20' : 'bg-surface text-ink-faint',- )}- >- {count}- </span>- )}+ {labelled && label}+ {count > 0 &&+ (labelled ? (+ <span+ className={cn(+ 'rounded-full px-1 font-mono text-[9px] tabular-nums',+ active ? 'bg-brand/20' : 'bg-surface text-ink-faint',+ )}+ >+ {count}+ </span>+ ) : (+ <span+ className={cn(+ 'absolute top-1 right-1 size-1.5 rounded-full',+ active ? 'bg-brand/70' : 'bg-ink-faint/60',+ )}+ />+ ))}</button>);})}</nav>);}++function contentWidth(element: HTMLElement) {+ const style = getComputedStyle(element);+ const gap = parseFloat(style.columnGap) || 0;+ const padding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);+ const children = Array.from(element.children);+ const span = children.reduce((width, child) => width + child.getBoundingClientRect().width, 0);+ return span + gap * Math.max(0, children.length - 1) + padding;+}diff --git a/docs/guide/features/conversations.md b/docs/guide/features/conversations.mdindex 000610c..5a7cc2e 100644--- a/docs/guide/features/conversations.md+++ b/docs/guide/features/conversations.md@@ -40,6 +40,20 @@ Above the chat, a row per tab that has a conversation: its live title, a pulsingworking, and how many messages it holds. Click a row to jump to that tab and its transcript; press**×** to end that session. It collapses to a single line when you want the room back.+### Minimizing to the rail++The header's collapse button closes the panel and leaves a small rail floating at the edge of the+page — the same five tabs as icons, and the link's status dot. Click any of them and the panel comes+back on that tab.++A run keeps showing itself while you are minimized: **Chat** carries a pulsing mark, the rail counts+how many runs are live, and its edge picks up the working colour. It stays minimized until you+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.+### Knowing something is running when you are elsewhereWhile a conversation is working, its tab is marked in two places — a dot on the Browsentic toolbardiff --git a/docs/internals/extension.md b/docs/internals/extension.mdindex 3d6bb0b..c8ef375 100644--- a/docs/internals/extension.md+++ b/docs/internals/extension.md@@ -43,11 +43,60 @@ it is the documented escape hatch.Adding one is a variant in `PanelTab`, an entry in `TABS`, and a branch in the side panel's body —there is no router.+**The strip labels as much as it can afford.** A `ResizeObserver` measures the width the labelled+row actually needs and steps through three fits: every label, then only the open tab's, then icons+alone with a dot where the count chip was. A width is only knowable while it is on screen, so each+fit records its own and steps one rung down; stepping back up waits for the width it already+learned, which is what keeps the strip from flapping between two fits at one panel width. In+practice five labels want ~485 px and one wants ~225 px, so a side panel at its usual size lands on+the middle fit.+**Settings** is the only tab whose state lives on the daemon rather than in extension storage. Itreads and writes `~/.browsentic/config.json` through two bridge ops, `guardrails` and`setGuardrail`, which forward to the socket frames of the same name. The extension holds no copy:every write returns the daemon's fresh view, which is what the panel then renders.+## Minimizing: the rail lives in the page++**Nothing can resize a side panel.** `chrome.sidePanel` offers `open`, `close`, `setOptions` and+`getLayout`, and `PanelLayout` carries only `side` — the width is the user's, dragged and remembered+by Chrome. So collapsing the panel *into* itself would only leave an empty column. Minimizing+instead **closes the panel and draws a 44 px rail into the page**, which is a surface the extension+can size.++| | |+| --- | --- |+| `lib/rail/events.ts` | The channel, the `RailView` the background computes, the tab list with its Lucide paths copied out, and the palette spelled in `oklch` |+| `lib/rail/host.ts` | `exposeRail()` in the content script — builds the rail in a **closed** shadow root on `documentElement` |+| `lib/bridge/rail.ts` | `serveRail()` and `syncRail()` in the background — what to paint, and when |+| `lib/bridge/panel-view.ts` | `browsentic/panelCollapsed` and `browsentic/panelTab`, read by `use-panel-view.ts` in the panel |++The content script carries no React and no icon package, which is why the paths and colours are+copied rather than imported — `components/` would drag the whole panel bundle onto every page.++**A closed shadow root on `documentElement` is load-bearing.** It keeps the rail out of+`body.innerText` (so `extractText` never returns it), out of the page's `querySelectorAll`, and out+of any page stylesheet. The host element has no layout footprint; the rail inside it is+`position: fixed`, centred on the panel's own side, inset from the edge so it never covers the+page's scrollbar.++**The click is the gesture.** `sidePanel.open()` needs user activation, and the only activation the+panel will ever get is the click on the rail, forwarded from the content script. `serveRail()`+spends it before any `await` — a single statement, no storage read in front of it. It deliberately+does *not* clear the collapsed flag: the panel clears it itself on mount with the `panelOpened`+bridge op, so an `open()` that gets refused leaves the rail on screen rather than dropping the user+into nothing.++**`syncRail()` broadcasts to every tab** instead of tracking which tabs carry a rail. That is a+service-worker decision, not laziness: a `Set` of painted tabs comes back empty when the worker is+revived, which would strand a rail on a page with no way to clear it. The first sync of a worker's+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.++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.+## Tab scopingA panel conversation is **bound to the tab it started in**.diff --git a/entrypoints/background.ts b/entrypoints/background.tsindex 3022626..624ec87 100644--- a/entrypoints/background.ts+++ b/entrypoints/background.ts@@ -10,6 +10,7 @@ import { analyzeStoredRecording, resumePendingAnalyses } from '@/lib/bridge/recoimport { 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 { openSidePanel } from '@/lib/bridge/side-panel';import { isAgentKind } from '@/lib/agents/catalog';import {@@ -127,6 +128,11 @@ export default defineBackground(() => {.catch((error) => sendResponse(failure('BRIDGE_ERROR', String(error))));return true;}+ if (message.op === 'panelOpened') {+ void setPanelCollapsed(false);+ sendResponse(success(true));+ return;+ }if (message.op === 'disconnect') {disconnectDaemon().then(() => sendResponse(success(true)))@@ -136,7 +142,7 @@ export default defineBackground(() => {sendResponse(failure('INVALID_REQUEST',- 'Expected {op:"describe"|"invoke"|"analyzeFile"|"saveSkill"|"removeSkill"|"nameSession"|"recordEvents"|"recordingState"|"analyzeRecording"|"monitorSample"|"monitorState"|"agentState"|"setAgent"|"grantAgent"|"guardrails"|"setGuardrail"|"pair"|"disconnect"}',+ 'Expected {op:"describe"|"invoke"|"analyzeFile"|"saveSkill"|"removeSkill"|"nameSession"|"recordEvents"|"recordingState"|"analyzeRecording"|"monitorSample"|"monitorState"|"agentState"|"setAgent"|"grantAgent"|"guardrails"|"setGuardrail"|"pair"|"panelOpened"|"disconnect"}',),);return;@@ -165,6 +171,8 @@ export default defineBackground(() => {serveMonitor();serveRunPorts();serveTabSessions();+ serveRail();+ void syncRail();onWelcome(() => {void resyncSkills();diff --git a/entrypoints/content.ts b/entrypoints/content.tsindex 41b87a9..04a5202 100644--- a/entrypoints/content.ts+++ b/entrypoints/content.ts@@ -1,6 +1,7 @@import { exposeActions } from '@/lib/actions/host';import { exposeIndicator } from '@/lib/indicator/host';import { exposeMonitor } from '@/lib/monitor/watch';+import { exposeRail } from '@/lib/rail/host';import { exposeRecorder } from '@/lib/recordings/host';export default defineContentScript({@@ -13,5 +14,6 @@ export default defineContentScript({exposeRecorder();exposeMonitor();exposeIndicator();+ exposeRail();},});diff --git a/entrypoints/sidepanel/App.tsx b/entrypoints/sidepanel/App.tsxindex 05d721b..b21ce2e 100644--- a/entrypoints/sidepanel/App.tsx+++ b/entrypoints/sidepanel/App.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from 'react';-import { ArrowDown, SquarePen } from 'lucide-react';+import { ArrowDown, PanelRightClose, SquarePen } from 'lucide-react';import { browser } from 'wxt/browser';import { invokeInActiveTab } from '@/lib/actions/client';@@ -27,6 +27,8 @@ import { removeRecording, type StoredRecordingMeta } from '@/lib/bridge/recordinimport { removeSession } from '@/lib/bridge/session-store';import { useActiveTabUrl } from '@/lib/bridge/use-active-tab-url';import { useDaemonState } from '@/lib/bridge/use-daemon-state';+import { closeSidePanel } from '@/lib/bridge/side-panel';+import { usePanelCollapsed, usePanelTab } from '@/lib/bridge/use-panel-view';import { useRun } from '@/lib/bridge/use-run';import { useStoredFiles } from '@/lib/bridge/use-stored-files';import { useStoredRecordings } from '@/lib/bridge/use-stored-recordings';@@ -48,9 +50,11 @@ export default function App() {const skills = useStoredSkills();const tabUrl = useActiveTabUrl();const [attachError, setAttachError] = useState<string | null>(null);- const [tab, setTab] = useState<PanelTab>('chat');+ const [tab, setTab] = usePanelTab();const [connectionOpen, setConnectionOpen] = useState(false);+ const [, setCollapsed] = usePanelCollapsed();const viewport = useRef<HTMLDivElement>(null);+ const windowId = useRef<number | null>(null);const [pinned, setPinned] = useState(true);const connected = daemon?.connected ?? false;@@ -62,6 +66,13 @@ export default function App() {const status = describeStatus(daemon, { running: run.running, listening: voice.listening });+ useEffect(() => {+ void browser.runtime.sendMessage({ channel: BRIDGE_CHANNEL, op: 'panelOpened' });+ void browser.windows.getCurrent().then((win) => {+ windowId.current = win.id ?? null;+ });+ }, []);+useEffect(() => {const element = viewport.current;if (!element) return;@@ -93,6 +104,12 @@ export default function App() {if (viewport.current) viewport.current.scrollTop = 0;}+ function minimize() {+ setConnectionOpen(false);+ setCollapsed(true);+ void closeSidePanel(windowId.current);+ }+function handleSend() {if (run.running || !connected) return;open('chat');@@ -162,6 +179,7 @@ export default function App() {const runningCount = run.sessions.filter((session) => session.runId).length;const offChatRun = runningCount > 0 && tab !== 'chat';const hasBanners = offChatRun || !!run.recording || run.monitors.length > 0 || !!run.draft;+ const counts = { history: sessions.length, skills: skills.length, recordings: recordings.length };return (<div className="flex h-screen flex-col">@@ -186,15 +204,20 @@ export default function App() {><SquarePen className="size-3.5" /></Button>+ <Button+ variant="ghost"+ size="icon-sm"+ title="Minimize to a rail on the page"+ aria-label="Minimize to a rail on the page"+ onClick={minimize}+ >+ <PanelRightClose className="size-3.5" />+ </Button></header>{connectionOpen && <ConnectionSheet onClose={() => setConnectionOpen(false)} />}- <PanelNav- tab={tab}- counts={{ history: sessions.length, skills: skills.length, recordings: recordings.length }}- onSelect={open}- />+ <PanelNav tab={tab} counts={counts} onSelect={open} /><SessionRailsessions={run.sessions}diff --git a/lib/actions/protocol.ts b/lib/actions/protocol.tsindex 057a599..552bf75 100644--- a/lib/actions/protocol.ts+++ b/lib/actions/protocol.ts@@ -27,6 +27,7 @@ export type BridgeRequest =| { channel: typeof BRIDGE_CHANNEL; op: 'invoke'; action: string; input?: unknown }| { channel: typeof BRIDGE_CHANNEL; op: 'pair'; token: string }| { channel: typeof BRIDGE_CHANNEL; op: 'disconnect' }+ | { channel: typeof BRIDGE_CHANNEL; op: 'panelOpened' }| { channel: typeof BRIDGE_CHANNEL; op: 'analyzeFile'; fileId: string }| { channel: typeof BRIDGE_CHANNEL; op: 'saveSkill'; skillId: string }| { channel: typeof BRIDGE_CHANNEL; op: 'removeSkill'; skillId: string }diff --git a/lib/bridge/panel-view.ts b/lib/bridge/panel-view.tsnew file mode 100644index 0000000..1482fe8--- /dev/null+++ b/lib/bridge/panel-view.ts@@ -0,0 +1,16 @@+import { browser } from 'wxt/browser';+import type { PanelTab } from '@/lib/rail/events';++export const PANEL_COLLAPSED_KEY = 'browsentic/panelCollapsed';+export const PANEL_TAB_KEY = 'browsentic/panelTab';++export async function readPanelCollapsed(): Promise<boolean> {+ const stored = await browser.storage.local.get(PANEL_COLLAPSED_KEY);+ return stored[PANEL_COLLAPSED_KEY] === true;+}++export async function readPanelTab(): Promise<PanelTab> {+ const stored = await browser.storage.local.get(PANEL_TAB_KEY);+ const tab = stored[PANEL_TAB_KEY];+ return typeof tab === 'string' ? (tab as PanelTab) : 'chat';+}diff --git a/lib/bridge/rail.ts b/lib/bridge/rail.tsnew file mode 100644index 0000000..ce2c56d--- /dev/null+++ b/lib/bridge/rail.ts@@ -0,0 +1,147 @@+import { browser } from 'wxt/browser';+import {+ RAIL_CHANNEL,+ isRailRequest,+ type RailTone,+ type RailView,+} from '@/lib/rail/events';+import { listRecordings } from './recording-store';+import { listSessions } from './session-store';+import { listSkillMeta } from './skill-store';+import { PANEL_COLLAPSED_KEY, PANEL_TAB_KEY, readPanelCollapsed, readPanelTab } from './panel-view';+import { openSidePanel } from './side-panel';+import { readTabSessions } from './tab-sessions';+import type { DaemonState } from './socket';++const DAEMON_KEY = 'browsentic/daemon';++export async function setPanelCollapsed(collapsed: boolean): Promise<void> {+ await browser.storage.local.set({ [PANEL_COLLAPSED_KEY]: collapsed });+ await syncRail();+}++let inFlight: Promise<void> | null = null;+let restated = false;+let showing: boolean | null = null;++/**+ * Paints the minimized panel onto every tab, or clears it from every tab. Broadcasting+ * rather than tracking which tabs carry it is what makes this survive the worker dying+ * mid-collapse — module state would come back empty and strand a rail on the page. The+ * first sync of a worker's life always broadcasts for that reason; only a repeated clear+ * is skipped.+ */+export function syncRail(): Promise<void> {+ if (inFlight) {+ restated = true;+ return inFlight;+ }+ inFlight = (async () => {+ do {+ restated = false;+ await paintRail();+ } while (restated);+ inFlight = null;+ })();+ return inFlight;+}++async function paintRail(): Promise<void> {+ const collapsed = await readPanelCollapsed();+ if (!collapsed && showing === false) return;++ const command = collapsed+ ? { channel: RAIL_CHANNEL, op: 'show' as const, view: await describeRail() }+ : { channel: RAIL_CHANNEL, op: 'hide' as const };++ const tabs = await browser.tabs.query({});+ await Promise.all(tabs.map((tab) => post(tab.id, tab.discarded, command)));+ showing = collapsed;+}++/** A tab that has just finished loading lost its rail with the old document. */+async function paintTab(tabId: number): Promise<void> {+ if (!(await readPanelCollapsed())) return;+ await post(tabId, false, { channel: RAIL_CHANNEL, op: 'show', view: await describeRail() });+}++function post(tabId: number | undefined, discarded: boolean | undefined, command: unknown) {+ if (tabId == null || discarded) return undefined;+ return browser.tabs.sendMessage(tabId, command).catch(() => undefined);+}++async function describeRail(): Promise<RailView> {+ const [daemon, sessions, skills, recordings, tabSessions, tab, side] = await Promise.all([+ readDaemon(),+ listSessions(),+ listSkillMeta(),+ listRecordings(),+ readTabSessions(),+ readPanelTab(),+ readSide(),+ ]);++ const live = Object.values(tabSessions).filter((session) => session.runId).length;+ const status = describeTone(daemon, live > 0);++ return {+ tab,+ side,+ running: live,+ tone: status.tone,+ status: status.label,+ counts: { history: sessions.length, skills: skills.length, recordings: recordings.length },+ };+}++/** The panel's own reading, minus the parts (voice, agent readiness) the rail has no room for. */+function describeTone(daemon: DaemonState | null, running: boolean): { tone: RailTone; label: string } {+ if (!daemon?.paired) return { tone: 'off', label: 'Not paired' };+ if (!daemon.connected) return { tone: 'pending', label: 'Reconnecting' };+ if (running) return { tone: 'busy', label: 'Working' };+ return { tone: 'live', label: 'Online' };+}++async function readDaemon(): Promise<DaemonState | null> {+ const stored = await browser.storage.session.get(DAEMON_KEY);+ return (stored[DAEMON_KEY] as DaemonState | undefined) ?? null;+}++async function readSide(): Promise<'left' | 'right'> {+ if (import.meta.env.FIREFOX) return 'left';+ const api = browser.sidePanel as unknown as { getLayout?: () => Promise<{ side?: string }> };+ if (!api.getLayout) return 'right';+ try {+ const layout = await api.getLayout();+ return layout.side === 'left' ? 'left' : 'right';+ } catch {+ return 'right';+ }+}++export function serveRail(): void {+ browser.runtime.onMessage.addListener((message, sender) => {+ if (!isRailRequest(message)) return;+ const windowId = sender.tab?.windowId;+ if (windowId == null) return;++ /* 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+ is not cleared here: the panel clears it itself once it is actually up, so a refused+ open leaves the rail on screen instead of dropping the user into nothing. */+ void openSidePanel(windowId).catch(() => undefined);+ void browser.storage.local.set({ [PANEL_TAB_KEY]: message.tab });++ return Promise.resolve({ ok: true });+ });++ browser.tabs.onUpdated.addListener((tabId, changed) => {+ if (changed.status === 'complete') void paintTab(tabId);+ });+ browser.storage.local.onChanged.addListener((changes) => {+ if (PANEL_COLLAPSED_KEY in changes || PANEL_TAB_KEY in changes) void syncRail();+ });+ browser.storage.session.onChanged.addListener((changes) => {+ if (DAEMON_KEY in changes) void syncRail();+ });+}diff --git a/lib/bridge/run-indicator.ts b/lib/bridge/run-indicator.tsindex ff091eb..9ef378b 100644--- a/lib/bridge/run-indicator.ts+++ b/lib/bridge/run-indicator.ts@@ -1,5 +1,6 @@import { browser } from 'wxt/browser';import { INDICATOR_CHANNEL, INDICATOR_COLOR } from '@/lib/indicator/events';+import { syncRail } from './rail';import { readTabSessions } from './tab-sessions';type BadgeAction = {@@ -24,6 +25,7 @@ export async function syncRunIndicator(): Promise<void> {}for (const tabId of busy) if (!marked.has(tabId)) await paint(tabId, true);for (const tabId of [...marked]) if (!busy.has(tabId)) await paint(tabId, false);+ await syncRail();}export function forgetTab(tabId: number): void {diff --git a/lib/bridge/side-panel.ts b/lib/bridge/side-panel.tsindex 4d0abb0..2153834 100644--- a/lib/bridge/side-panel.ts+++ b/lib/bridge/side-panel.ts@@ -1,8 +1,30 @@-type SidebarAction = { open: () => Promise<void> };+type SidebarAction = { open: () => Promise<void>; close: () => Promise<void> };++function sidebarAction(): SidebarAction {+ return (browser as unknown as { sidebarAction: SidebarAction }).sidebarAction;+}export function openSidePanel(windowId: number) {- if (import.meta.env.FIREFOX) {- return (browser as unknown as { sidebarAction: SidebarAction }).sidebarAction.open();- }+ if (import.meta.env.FIREFOX) return sidebarAction().open();return browser.sidePanel.open({ windowId });}++/** Only the panel itself calls this, so `window.close()` is the fallback worth having. */+export async function closeSidePanel(windowId: number | null): Promise<void> {+ try {+ if (import.meta.env.FIREFOX) {+ await sidebarAction().close();+ return;+ }+ const api = browser.sidePanel as unknown as {+ close?: (options: { windowId: number }) => Promise<void>;+ };+ if (api.close && windowId != null) {+ await api.close({ windowId });+ return;+ }+ } catch {+ /* falls through to closing the page */+ }+ if (typeof window !== 'undefined') window.close();+}diff --git a/lib/bridge/use-panel-view.ts b/lib/bridge/use-panel-view.tsnew file mode 100644index 0000000..838f880--- /dev/null+++ b/lib/bridge/use-panel-view.ts@@ -0,0 +1,46 @@+import { useCallback, useEffect, useState } from 'react';+import { browser } from 'wxt/browser';+import type { PanelTab } from '@/lib/rail/events';+import { PANEL_COLLAPSED_KEY, PANEL_TAB_KEY } from './panel-view';++export function usePanelCollapsed(): [boolean, (collapsed: boolean) => void] {+ return useStoredLocal(PANEL_COLLAPSED_KEY, false, (value): value is boolean => typeof value === 'boolean');+}++export function usePanelTab(): [PanelTab, (tab: PanelTab) => void] {+ return useStoredLocal(PANEL_TAB_KEY, 'chat' as PanelTab, (value): value is PanelTab => typeof value === 'string');+}++function useStoredLocal<T>(+ key: string,+ fallback: T,+ accepts: (value: unknown) => value is T,+): [T, (next: T) => void] {+ const [value, setValue] = useState(fallback);++ useEffect(() => {+ let live = true;+ void browser.storage.local.get(key).then((stored) => {+ if (live && accepts(stored[key])) setValue(stored[key] as T);+ });+ const listener = (changes: Record<string, { newValue?: unknown }>) => {+ const change = changes[key];+ if (change && accepts(change.newValue)) setValue(change.newValue);+ };+ browser.storage.local.onChanged.addListener(listener);+ return () => {+ live = false;+ browser.storage.local.onChanged.removeListener(listener);+ };+ }, [key]);++ const set = useCallback(+ (next: T) => {+ setValue(next);+ void browser.storage.local.set({ [key]: next });+ },+ [key],+ );++ return [value, set];+}diff --git a/lib/rail/events.ts b/lib/rail/events.tsnew file mode 100644index 0000000..12b411d--- /dev/null+++ b/lib/rail/events.ts@@ -0,0 +1,107 @@+export const RAIL_CHANNEL = 'browsentic/rail';++export type PanelTab = 'chat' | 'history' | 'skills' | 'recordings' | 'settings';++export type RailTone = 'off' | 'pending' | 'live' | 'busy' | 'listening' | 'warn';++export interface RailView {+ tab: PanelTab;+ side: 'left' | 'right';+ running: number;+ tone: RailTone;+ status: string;+ counts: Partial<Record<PanelTab, number>>;+}++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 function isRailCommand(message: unknown): message is RailCommand {+ if (typeof message !== 'object' || message === null) return false;+ const frame = message as { channel?: unknown; op?: unknown };+ return frame.channel === RAIL_CHANNEL && (frame.op === 'show' || frame.op === 'hide');+}++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';+}++/** Lucide paths, copied so the content script carries no React and no icon package. */+export const RAIL_TABS: { id: PanelTab; label: string; paths: string[] }[] = [+ {+ id: 'chat',+ label: 'Chat',+ paths: [+ 'M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z',+ 'M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1',+ ],+ },+ {+ id: 'history',+ label: 'History',+ paths: ['M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8', 'M3 3v5h5', 'M12 7v5l4 2'],+ },+ {+ id: 'skills',+ label: 'Skills',+ paths: [+ 'M12 5v16',+ 'M20.001 19A2 2 0 0 0 22 17V5a2 2 0 0 0-1.999-2L16 3.002A5 5 0 0 0 12 5a5 5 0 0 0-4-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 1.999 2H8a5 5 0 0 1 4 2 5 5 0 0 1 4-2z',+ ],+ },+ {+ id: 'recordings',+ label: 'Recordings',+ paths: [+ 'm12.296 3.464 3.02 3.956',+ 'M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z',+ 'M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z',+ 'm6.18 5.276 3.1 3.899',+ ],+ },+ {+ id: 'settings',+ label: 'Settings',+ paths: [+ 'M10 5H3',+ 'M12 19H3',+ 'M14 3v4',+ 'M16 17v4',+ 'M21 12h-9',+ 'M21 19h-5',+ 'M21 5h-7',+ 'M8 10v4',+ 'M8 12H3',+ ],+ },+];++/** The panel's tokens, spelled out — a content script has no stylesheet to read them from. */+export const RAIL_PALETTE = {+ ground: 'oklch(0.152 0.016 52)',+ ground2: 'oklch(0.183 0.018 50)',+ surface: 'oklch(0.213 0.019 48)',+ ink: 'oklch(0.958 0.012 70)',+ inkDim: 'oklch(0.735 0.018 60)',+ inkFaint: 'oklch(0.575 0.02 55)',+ line: 'oklch(0.98 0.01 60 / 12%)',+ brand: 'oklch(0.83 0.13 195)',+} as const;++export const RAIL_TONES: Record<RailTone, string> = {+ off: 'oklch(0.575 0.02 55 / 50%)',+ pending: 'oklch(0.84 0.15 85)',+ live: 'oklch(0.84 0.18 150)',+ busy: 'oklch(0.83 0.13 195)',+ listening: 'oklch(0.7 0.21 335)',+ warn: 'oklch(0.735 0.168 42)',+};diff --git a/lib/rail/host.ts b/lib/rail/host.tsnew file mode 100644index 0000000..00e121b--- /dev/null+++ b/lib/rail/host.ts@@ -0,0 +1,192 @@+import { browser } from 'wxt/browser';+import {+ RAIL_CHANNEL,+ RAIL_PALETTE,+ RAIL_TABS,+ RAIL_TONES,+ isRailCommand,+ type PanelTab,+ type RailView,+} from './events';++export { RAIL_CHANNEL } from './events';++const HOST_ID = 'browsentic-rail';++/**+ * The minimized panel, drawn into the page. It lives in a closed shadow root so the+ * page cannot style or read it and `extractText` cannot pick it up, and it is only ever+ * as wide as its icons — the side panel is closed while this is up.+ */+export function exposeRail(): void {+ let host: HTMLElement | null = null;+ let root: ShadowRoot | null = null;++ browser.runtime.onMessage.addListener((message: unknown) => {+ if (!isRailCommand(message)) return;+ if (message.op === 'show') render(message.view);+ else remove();+ return Promise.resolve({ ok: true });+ });++ function remove(): void {+ host?.remove();+ host = null;+ root = null;+ }++ function render(view: RailView): void {+ if (!document.documentElement) return;+ if (!host || !host.isConnected) {+ remove();+ host = document.createElement('div');+ host.id = HOST_ID;+ host.setAttribute('aria-hidden', 'false');+ host.style.cssText = 'all: initial; position: static;';+ root = host.attachShadow({ mode: 'closed' });+ document.documentElement.append(host);+ }+ if (!root) return;++ root.innerHTML = `<style>${styles(view)}</style>${markup(view)}`;++ for (const button of root.querySelectorAll<HTMLButtonElement>('button[data-tab]')) {+ button.addEventListener('click', (event) => {+ event.preventDefault();+ event.stopPropagation();+ void browser.runtime.sendMessage({+ channel: RAIL_CHANNEL,+ op: 'open',+ tab: button.dataset.tab as PanelTab,+ });+ });+ }+ }+}++function markup(view: RailView): string {+ const tabs = RAIL_TABS.map(({ id, label, paths }) => {+ const active = id === view.tab;+ const busy = id === 'chat' && view.running > 0;+ const count = view.counts[id] ?? 0;+ const mark = busy+ ? '<span class="mark busy"></span>'+ : count > 0+ ? '<span class="mark"></span>'+ : '';+ const title = busy ? `${label} — ${runLabel(view.running)}` : label;+ return `<button type="button" data-tab="${id}" class="tab${active ? ' active' : ''}" title="${escape(title)}" aria-label="${escape(label)}">${icon(paths)}${mark}</button>`;+ }).join('');++ const runs =+ view.running > 0+ ? `<span class="runs" title="${escape(runLabel(view.running))}"><i></i><i></i><i></i><b>${view.running}</b></span>`+ : '';++ return `<div class="rail" role="toolbar" aria-label="Browsentic">${tabs}<span class="sep"></span>${runs}<span class="status" title="${escape(view.status)}"></span></div>`;+}++function icon(paths: string[]): string {+ const body = paths.map((d) => `<path d="${d}"/>`).join('');+ return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;+}++function runLabel(running: number): string {+ return running === 1 ? 'A run is in progress' : `${running} runs are in progress`;+}++function escape(text: string): string {+ return text.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');+}++function styles(view: RailView): string {+ const edge = view.side === 'left' ? 'left: 12px' : 'right: 12px';+ return `+ :host { all: initial; }+ * { box-sizing: border-box; margin: 0; padding: 0; }+ .rail {+ position: fixed;+ ${edge};+ top: 50%;+ transform: translateY(-50%);+ z-index: 2147483647;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 4px;+ width: 44px;+ padding: 6px 0;+ border: 1px solid ${RAIL_PALETTE.line};+ border-radius: 16px;+ background: ${RAIL_PALETTE.ground2};+ box-shadow: 0 10px 34px -12px rgb(0 0 0 / 70%), 0 0 0 1px rgb(0 0 0 / 25%);+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;+ ${view.running > 0 ? `outline: 1px solid color-mix(in oklch, ${RAIL_PALETTE.brand} 45%, transparent); outline-offset: -1px;` : ''}+ }+ .tab {+ position: relative;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ border: 0;+ border-radius: 11px;+ background: transparent;+ color: ${RAIL_PALETTE.inkFaint};+ cursor: pointer;+ transition: background-color 150ms, color 150ms;+ }+ .tab:hover { background: ${RAIL_PALETTE.surface}; color: ${RAIL_PALETTE.ink}; }+ .tab.active { background: color-mix(in oklch, ${RAIL_PALETTE.brand} 14%, transparent); color: ${RAIL_PALETTE.brand}; }+ .tab svg { width: 17px; height: 17px; display: block; }+ .mark {+ position: absolute;+ top: 4px;+ right: 4px;+ width: 6px;+ height: 6px;+ border-radius: 999px;+ background: ${RAIL_PALETTE.inkFaint};+ }+ .mark.busy {+ background: ${RAIL_PALETTE.brand};+ box-shadow: 0 0 8px 1px color-mix(in oklch, ${RAIL_PALETTE.brand} 75%, transparent);+ animation: browsentic-rail-pulse 1.4s ease-in-out infinite;+ }+ .sep { width: 20px; height: 1px; background: ${RAIL_PALETTE.line}; margin: 3px 0; }+ .runs { display: flex; align-items: center; gap: 2px; flex-wrap: wrap; justify-content: center; width: 32px; }+ .runs i {+ width: 4px;+ height: 4px;+ border-radius: 999px;+ background: ${RAIL_PALETTE.brand};+ animation: browsentic-rail-think 1.2s ease-in-out infinite;+ }+ .runs i:nth-child(2) { animation-delay: 0.16s; }+ .runs i:nth-child(3) { animation-delay: 0.32s; }+ .runs b {+ width: 100%;+ text-align: center;+ font: 600 9px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;+ color: ${RAIL_PALETTE.brand};+ font-variant-numeric: tabular-nums;+ }+ .status {+ width: 7px;+ height: 7px;+ margin: 2px 0 1px;+ border-radius: 999px;+ background: ${RAIL_TONES[view.tone]};+ box-shadow: 0 0 8px 1px color-mix(in oklch, ${RAIL_TONES[view.tone]} 70%, transparent);+ }+ @keyframes browsentic-rail-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }+ @keyframes browsentic-rail-think {+ 0%, 70%, 100% { opacity: 0.25; transform: translateY(0); }+ 35% { opacity: 1; transform: translateY(-2px); }+ }+ @media (prefers-reduced-motion: reduce) {+ .mark.busy, .runs i { animation: none; }+ }+ `;+}