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(extension): Browsentic Home replaces the new tab page: the panel’s composer with an agent chip, suggestions from the sites you visit most, frequent sites, recent conversations and runs in other tabs, and the latest request’s progress with its approvals; sending opens the side panel with the conversation before the agent takes the tab to a site, and Settings → Extension → New tab switches it off, handing Chrome back its own page and other browsers a plain page of frequent sites
Shahriar3e47a26deb69
diff --git a/src/extension/assets/globals.css b/src/extension/assets/globals.cssindex 17a3bf6..8252d90 100644--- a/src/extension/assets/globals.css+++ b/src/extension/assets/globals.css@@ -337,6 +337,15 @@);}+/* The light Browsentic Home's composer sits in, as strong as the theme's glow dial allows. */+@utility home-halo {+ background: radial-gradient(+ ellipse 65% 60% at 50% 42%,+ color-mix(in oklch, var(--brand) calc(var(--glow) * 0.13), transparent),+ transparent 72%+ );+}+@utility text-gradient {background: linear-gradient(100deg,@@ -417,6 +426,27 @@}}+/* The mark tracing itself once on Browsentic Home: the path, then its three stops. */+@keyframes browsentic-trace {+ from {+ stroke-dashoffset: 1;+ }+ to {+ stroke-dashoffset: 0;+ }+}++@keyframes browsentic-stop {+ from {+ opacity: 0;+ transform: scale(0.4);+ }+ to {+ opacity: 1;+ transform: none;+ }+}+/* The panel folding down into the hands-free mic before it closes. */@keyframes browsentic-fold {to {@@ -461,6 +491,25 @@animation: browsentic-detach-orb 0.56s var(--ease-out-expo) both;}+ .logo-drawn path:last-of-type {+ stroke-dasharray: 1;+ animation: browsentic-trace 0.7s var(--ease-out-expo) 0.1s both;+ }+ .logo-drawn circle:nth-last-of-type(-n + 3) {+ transform-box: fill-box;+ transform-origin: center;+ animation: browsentic-stop 0.4s var(--ease-out-expo) both;+ }+ .logo-drawn circle:nth-last-of-type(3) {+ animation-delay: 0.1s;+ }+ .logo-drawn circle:nth-last-of-type(2) {+ animation-delay: 0.38s;+ }+ .logo-drawn circle:nth-last-of-type(1) {+ animation-delay: 0.62s;+ }+[data-stream] .tok {animation: browsentic-token 0.42s var(--ease-out-expo) both;}diff --git a/src/extension/components/agent-chip.tsx b/src/extension/components/agent-chip.tsxnew file mode 100644index 0000000..01d6587--- /dev/null+++ b/src/extension/components/agent-chip.tsx@@ -0,0 +1,40 @@+import { ChevronDown } from 'lucide-react';++import { AgentMark } from '@/extension/components/agent-marks';+import { AGENTS, activeRunner, type AgentState } from '@/lib/agents/catalog';+import { cn } from '@/lib/utils';++/** Which agent a message goes to, and on which model; pressing it opens the picker. */+export function AgentChip({+ state,+ expanded,+ onClick,+}: {+ state: AgentState | undefined;+ expanded: boolean;+ onClick: () => void;+}) {+ const runner = activeRunner(state);+ if (!state || !runner) return null;+ const { label } = AGENTS[state.active];+ return (+ <button+ type="button"+ onClick={onClick}+ aria-expanded={expanded}+ aria-label={`Agent: ${label}${runner.model ? `, ${runner.model}` : ''}. Choose another`}+ className={cn(+ 'inline-flex h-7 min-w-0 items-center gap-1.5 rounded-full px-2.5 text-xs transition-colors',+ expanded ? 'bg-surface text-ink' : 'text-ink-dim hover:bg-surface/70 hover:text-ink',+ !runner.ready && 'text-ember',+ )}+ >+ <AgentMark kind={state.active} className="size-3" />+ <span className="truncate">+ {label}+ {runner.model && <span className="text-ink-faint"> · {runner.model}</span>}+ </span>+ <ChevronDown className={cn('size-3 shrink-0 text-ink-faint transition-transform', expanded && 'rotate-180')} />+ </button>+ );+}diff --git a/src/extension/components/brand.tsx b/src/extension/components/brand.tsxindex e5325d2..e52f9f4 100644--- a/src/extension/components/brand.tsx+++ b/src/extension/components/brand.tsx@@ -1,8 +1,9 @@import { cn } from '@/lib/utils';-export function Logo({ className }: { className?: string }) {+/** `drawn` traces the path and drops its three stops in, once, as the mark first appears. */+export function Logo({ className, drawn = false }: { className?: string; drawn?: boolean }) {return (- <svg viewBox="0 0 32 32" fill="none" className={cn('size-7', className)} aria-hidden>+ <svg viewBox="0 0 32 32" fill="none" className={cn('size-7', drawn && 'logo-drawn', className)} aria-hidden><rectx="2.25"y="4.25"@@ -18,6 +19,7 @@ export function Logo({ className }: { className?: string }) {<circle cx="9.8" cy="7.4" r="1" fill="currentColor" fillOpacity="0.35" /><pathd="M9 22.2c2.4 0 2.4-6.4 6.9-6.4s4.6 6.4 7 6.4"+ pathLength={1}stroke="currentColor"strokeWidth="1.75"strokeLinecap="round"diff --git a/src/extension/components/composer.tsx b/src/extension/components/composer.tsxindex 732ed7a..864cdd5 100644--- a/src/extension/components/composer.tsx+++ b/src/extension/components/composer.tsx@@ -1,4 +1,4 @@-import { useEffect, useId, useMemo, useRef, useState, type MouseEvent } from 'react';+import { useEffect, useId, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react';import {CalendarClock,Code2,@@ -32,6 +32,11 @@ export interface AttachedSkill {name: string;}+const SIZES = {+ panel: { card: 'rounded-2xl', field: 'max-h-48 min-h-14 px-3 pt-2.5', bar: 'px-1.5 pb-1.5', rows: 2 },+ hero: { card: 'rounded-3xl', field: 'max-h-72 min-h-20 px-4 pt-3.5 text-[0.9375rem]', bar: 'px-2.5 pb-2.5', rows: 3 },+} as const;+export function Composer({voice,voiceEnabled,@@ -49,8 +54,11 @@ export function Composer({android,onToggleLiveTools,onPhone = false,- scheduling,+ scheduling = false,onToggleScheduling,+ placeholder = 'Tell me what to do on this page…',+ size = 'panel',+ accessory,actionCues,onToggleActionCues,onAttachSkill,@@ -85,8 +93,13 @@ export function Composer({/** The panel is showing the phone conversation: what only works in a desktop tab is not offered. */onPhone?: boolean;onToggleLiveTools: () => void;- scheduling: boolean;- onToggleScheduling: () => void;+ scheduling?: boolean;+ /** Absent where a message cannot be scheduled from, which takes the button away. */+ onToggleScheduling?: () => void;+ placeholder?: string;+ size?: keyof typeof SIZES;+ /** Sits beside the send button. */+ accessory?: ReactNode;actionCues: boolean;onToggleActionCues: () => void;onAttachSkill: (skill: AttachedSkill | null) => void;@@ -96,7 +109,8 @@ export function Composer({onSend: () => void;onStop: () => void;onToggleVoice: () => void;- onPick: () => void;+ /** Absent where there is no page to point at, which takes A-Eye away. */+ onPick?: () => void;onClearFocus: () => void;onAttachFile: (file: File) => void;onRemoveFile: (fileId: string) => void;@@ -143,6 +157,8 @@ export function Composer({composerRef.current?.focus();}+ const sized = SIZES[size];+return (<>{attachError && (@@ -194,7 +210,8 @@ export function Composer({<divonClick={focusComposer}className={cn(- 'panel-card relative flex flex-col rounded-2xl transition-colors has-[textarea:focus]:border-brand/50',+ 'panel-card relative flex flex-col transition-colors has-[textarea:focus]:border-brand/50',+ sized.card,connected && 'cursor-text',)}>@@ -245,29 +262,28 @@ export function Composer({}}}placeholder={- !connected- ? 'Pair the browser to get started'- : scheduling- ? 'Say what to do, then pick when…'- : 'Tell me what to do on this page…'+ !connected ? 'Pair the browser to get started' : scheduling ? 'Say what to do, then pick when…' : placeholder}+ aria-label="Instruction for Browsentic"disabled={!connected}- rows={2}- className="max-h-48 min-h-14 resize-none rounded-none border-0 bg-transparent px-3 pt-2.5 pb-0 focus-visible:border-0"+ rows={sized.rows}+ className={cn('resize-none rounded-none border-0 bg-transparent pb-0 focus-visible:border-0', sized.field)}/>- <div className="flex items-center gap-0.5 px-1.5 pb-1.5">- <Button- variant={focus || picking ? 'subtle' : 'ghost'}- size="icon-sm"- title="A-Eye — point at an element on the page and send it with your next message"- aria-label="Point at an element with A-Eye"- onClick={onPick}- disabled={!connected || picking}- className={cn(focus || picking ? 'text-ember' : undefined)}- >- <ScanEye className={cn('size-3.5', picking && 'animate-pulse')} />- </Button>+ <div className={cn('flex items-center gap-0.5', sized.bar)}>+ {onPick && (+ <Button+ variant={focus || picking ? 'subtle' : 'ghost'}+ size="icon-sm"+ title="A-Eye — point at an element on the page and send it with your next message"+ aria-label="Point at an element with A-Eye"+ onClick={onPick}+ disabled={!connected || picking}+ className={cn(focus || picking ? 'text-ember' : undefined)}+ >+ <ScanEye className={cn('size-3.5', picking && 'animate-pulse')} />+ </Button>+ )}<Buttonvariant="ghost"size="icon-sm"@@ -295,7 +311,7 @@ export function Composer({><Code2 className="size-3.5" /></Button>- {!onPhone && (+ {!onPhone && onToggleScheduling && (<Buttonvariant={scheduling ? 'subtle' : 'ghost'}size="icon-sm"@@ -345,22 +361,24 @@ export function Composer({{voiceEnabled && !voice.error ? <Mic className="size-3.5" /> : <MicOff className="size-3.5" />}</Button>- {running && !scheduling ? (- <Button size="icon-sm" variant="destructive" className="ml-auto" aria-label="Stop the agent" onClick={onStop}>- <Square className="size-3 fill-current" />- </Button>- ) : (- <Button- size="icon-sm"- className="ml-auto"- aria-label={scheduling ? 'Schedule this…' : 'Send message'}- title={scheduling ? 'Schedule this…' : undefined}- onClick={onSend}- disabled={!voice.input.trim() || !connected}- >- {scheduling ? <CalendarClock className="size-3.5" /> : <Send className="size-3.5" />}- </Button>- )}+ <div className="ml-auto flex min-w-0 items-center gap-1.5">+ {accessory}+ {running && !scheduling ? (+ <Button size="icon-sm" variant="destructive" aria-label="Stop the agent" onClick={onStop}>+ <Square className="size-3 fill-current" />+ </Button>+ ) : (+ <Button+ size="icon-sm"+ aria-label={scheduling ? 'Schedule this…' : 'Send message'}+ title={scheduling ? 'Schedule this…' : undefined}+ onClick={onSend}+ disabled={!voice.input.trim() || !connected}+ >+ {scheduling ? <CalendarClock className="size-3.5" /> : <Send className="size-3.5" />}+ </Button>+ )}+ </div></div></div>diff --git a/src/extension/components/extension-settings.tsx b/src/extension/components/extension-settings.tsxindex fe83514..d270ecb 100644--- a/src/extension/components/extension-settings.tsx+++ b/src/extension/components/extension-settings.tsx@@ -8,6 +8,7 @@ import {openShortcutSettings,useActionCues,useContextMenuChoice,+ useNewTabChoice,usePushToTalk,useShortcuts,} from '@/lib/bridge/use-extension-settings';@@ -18,6 +19,7 @@ export function ExtensionSettings() {const handsFree = useHandsFreeSupported();return (<>+ <NewTab /><ActionCues /><ContextMenuItems handsFree={handsFree} /><KeyboardShortcuts handsFree={handsFree} />@@ -26,6 +28,37 @@ export function ExtensionSettings() {);}+function NewTab() {+ const [choice, setChoice] = useNewTabChoice();+ const hidden = choice.hidden.length;+ return (+ <SettingsGroup+ title="New tab"+ note="With Home off, a new tab shows Chrome’s own new tab page. Edge, Brave and Firefox keep theirs out of an extension’s reach, so they get a plain page of your frequent sites instead."+ >+ <Row+ title="Open Browsentic Home on new tabs"+ note="A composer, your frequent sites and your recent conversations. Sending from it opens the side panel, which keeps the conversation when the agent takes the tab to a site."+ >+ <Switch checked={choice.home} label="Open Browsentic Home on new tabs" onChange={(home) => setChoice({ ...choice, home })} />+ </Row>+ <Row+ title="Show frequent sites"+ note={`The sites you visit most, as the browser ranks them. Hover one to hide it.${hidden ? ` ${hidden} hidden now.` : ''}`}+ >+ <div className="flex items-center gap-3">+ {hidden > 0 && (+ <Button variant="ghost" size="sm" onClick={() => setChoice({ ...choice, hidden: [] })}>+ Show hidden+ </Button>+ )}+ <Switch checked={choice.sites} label="Show frequent sites" onChange={(sites) => setChoice({ ...choice, sites })} />+ </div>+ </Row>+ </SettingsGroup>+ );+}+function ActionCues() {const [on, setOn] = useActionCues();return (diff --git a/src/extension/components/frequent-sites.tsx b/src/extension/components/frequent-sites.tsxnew file mode 100644index 0000000..124854d--- /dev/null+++ b/src/extension/components/frequent-sites.tsx@@ -0,0 +1,66 @@+import { useState } from 'react';+import { X } from 'lucide-react';++import type { FrequentSite } from '@/lib/home/frequent-sites';+import type { FrequentSites as Frequent } from '@/lib/bridge/use-frequent-sites';++export function FrequentSites({ frequent, onHide }: { frequent: Frequent; onHide: (host: string) => void }) {+ if (frequent.needsGrant) {+ return (+ <div className="flex flex-wrap items-center justify-center gap-3 rounded-2xl border border-dashed border-line px-4 py-4 text-center">+ <p className="text-xs text-ink-faint">The sites you visit most can sit here, one click away.</p>+ <button+ type="button"+ onClick={frequent.grant}+ className="rounded-full border border-line-strong px-3 py-1 text-xs text-ink-dim transition-colors hover:border-brand/45 hover:text-ink"+ >+ Show frequent sites+ </button>+ </div>+ );+ }++ if (!frequent.loaded || frequent.sites.length === 0) return null;+ return (+ <nav aria-label="Frequent sites">+ <ul className="flex flex-wrap justify-center gap-1">+ {frequent.sites.map((site) => (+ <li key={site.host} className="group relative w-[5.25rem]">+ <Tile site={site} />+ <button+ type="button"+ onClick={() => onHide(site.host)}+ aria-label={`Hide ${site.host} from frequent sites`}+ title="Hide from frequent sites"+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-surface-2 text-ink-faint opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 hover:text-ink focus-visible:opacity-100"+ >+ <X className="size-3" />+ </button>+ </li>+ ))}+ </ul>+ </nav>+ );+}++function Tile({ site }: { site: FrequentSite }) {+ const [broken, setBroken] = useState(false);+ return (+ <a+ href={site.url}+ title={site.url}+ className="flex flex-col items-center gap-2 rounded-2xl px-1 pt-3 pb-2 outline-none transition-colors hover:bg-surface/60 focus-visible:bg-surface/60 focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <span className="grid size-12 place-items-center rounded-2xl border border-line bg-ground-2 transition-colors group-hover:border-line-strong">+ {site.icon && !broken ? (+ <img src={site.icon} alt="" className="size-6 rounded-sm" onError={() => setBroken(true)} />+ ) : (+ <span className="font-display text-base font-semibold text-ink-dim uppercase">{site.host.charAt(0)}</span>+ )}+ </span>+ <span className="w-full truncate text-center text-xs text-ink-dim transition-colors group-hover:text-ink">+ {site.label}+ </span>+ </a>+ );+}diff --git a/src/extension/components/home-customize.tsx b/src/extension/components/home-customize.tsxnew file mode 100644index 0000000..aa49ef1--- /dev/null+++ b/src/extension/components/home-customize.tsx@@ -0,0 +1,102 @@+import type { ReactNode } from 'react';+import { Check, SlidersHorizontal } from 'lucide-react';+import { browser } from 'wxt/browser';++import { Switch } from '@/extension/components/ui/switch';+import { useTheme } from '@/lib/bridge/use-theme';+import type { NewTabChoice } from '@/lib/settings/new-tab';+import { THEMES } from '@/lib/settings/theme';+import { cn } from '@/lib/utils';++export function HomeCustomize({+ choice,+ onChange,+ onTurnOff,+}: {+ choice: NewTabChoice;+ onChange: (next: NewTabChoice) => void;+ /** Switching Home off hands this tab on as well, so the change shows at once. */+ onTurnOff: () => void;+}) {+ const [theme, setTheme] = useTheme();+ const hidden = choice.hidden.length;++ return (+ <div className="space-y-4">+ <div className="space-y-2">+ <h2 className="text-xs font-medium text-ink-dim">Theme</h2>+ <div className="grid grid-cols-4 gap-2">+ {THEMES.map(({ id, name }) => {+ const active = id === theme;+ return (+ <button+ key={id}+ type="button"+ data-theme={id}+ aria-pressed={active}+ onClick={() => setTheme(id)}+ className={cn(+ 'flex flex-col items-center gap-1.5 rounded-xl border bg-ground px-1 pt-2.5 pb-2 transition-colors',+ active ? 'glow-brand border-brand/60' : 'border-line hover:border-line-strong',+ )}+ >+ <span className="relative grid size-6 place-items-center rounded-full bg-surface-2">+ <span className="size-3 rounded-full bg-brand" />+ {active && (+ <span className="absolute -right-1 -bottom-1 grid size-3.5 place-items-center rounded-full bg-brand text-ground">+ <Check className="size-2.5" strokeWidth={3} />+ </span>+ )}+ </span>+ <span className="text-[11px] text-ink">{name}</span>+ </button>+ );+ })}+ </div>+ </div>++ <div className="divide-y divide-line rounded-xl border border-line">+ <Toggle+ title="Frequent sites"+ note={+ hidden ? (+ <>+ {hidden} hidden.{' '}+ <button type="button" onClick={() => onChange({ ...choice, hidden: [] })} className="text-brand hover:underline">+ Show them again+ </button>+ </>+ ) : (+ 'The sites you visit most, as the browser ranks them.'+ )+ }+ >+ <Switch checked={choice.sites} label="Show frequent sites" onChange={(sites) => onChange({ ...choice, sites })} />+ </Toggle>+ <Toggle title="Browsentic Home" note="Off, new tabs open the browser’s own page again.">+ <Switch checked label="Open Browsentic Home on new tabs" onChange={onTurnOff} />+ </Toggle>+ </div>++ <button+ type="button"+ onClick={() => void browser.runtime.openOptionsPage()}+ className="inline-flex items-center gap-1.5 text-xs text-ink-faint transition-colors hover:text-brand"+ >+ <SlidersHorizontal className="size-3" /> All settings+ </button>+ </div>+ );+}++function Toggle({ title, note, children }: { title: string; note: ReactNode; children: ReactNode }) {+ return (+ <div className="flex items-start gap-4 px-3 py-2.5">+ <div className="min-w-0 flex-1">+ <p className="text-sm text-ink">{title}</p>+ <p className="mt-0.5 text-[11px] leading-relaxed text-ink-faint">{note}</p>+ </div>+ <div className="pt-1">{children}</div>+ </div>+ );+}diff --git a/src/extension/components/plain-new-tab.tsx b/src/extension/components/plain-new-tab.tsxnew file mode 100644index 0000000..9603e42--- /dev/null+++ b/src/extension/components/plain-new-tab.tsx@@ -0,0 +1,28 @@+import { FrequentSites } from '@/extension/components/frequent-sites';+import { useNewTabChoice } from '@/lib/bridge/use-extension-settings';+import { useFrequentSites } from '@/lib/bridge/use-frequent-sites';+import { hideSite } from '@/lib/settings/new-tab';++/** A new tab with Browsentic Home switched off, in a browser whose own new tab page an extension cannot open. */+export function PlainNewTab({ onTurnOn }: { onTurnOn: () => void }) {+ const [choice, setChoice] = useNewTabChoice();+ const frequent = useFrequentSites(choice.sites, choice.hidden);++ return (+ <main className="flex min-h-screen flex-col items-center justify-center px-5 pb-[14vh]">+ <div className="w-full max-w-[44rem]">+ {choice.sites && <FrequentSites frequent={frequent} onHide={(host) => setChoice(hideSite(choice, host))} />}+ </div>+ <button+ type="button"+ onClick={() => {+ setChoice({ ...choice, home: true });+ onTurnOn();+ }}+ className="fixed right-4 bottom-4 text-[11px] text-ink-faint transition-colors hover:text-ink-dim"+ >+ Turn Browsentic Home on+ </button>+ </main>+ );+}diff --git a/src/extension/components/popover.tsx b/src/extension/components/popover.tsxnew file mode 100644index 0000000..80f5eba--- /dev/null+++ b/src/extension/components/popover.tsx@@ -0,0 +1,59 @@+import { useEffect, useRef, type ReactNode } from 'react';++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. */+export function Popover({+ open,+ label,+ onClose,+ align = 'end',+ className,+ children,+}: {+ open: boolean;+ label: string;+ onClose: () => void;+ align?: 'start' | 'end';+ className?: string;+ children: ReactNode;+}) {+ const card = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!open) return;+ const anchor = card.current?.parentElement;+ const pressed = (event: PointerEvent) => {+ const target = event.target as Element;+ if (!anchor?.contains(target) && !target.closest(OPEN_LAYER)) onClose();+ };+ const keyed = (event: KeyboardEvent) => {+ if (event.key === 'Escape' && !document.querySelector(OPEN_LAYER)) onClose();+ };+ document.addEventListener('pointerdown', pressed);+ document.addEventListener('keydown', keyed);+ return () => {+ document.removeEventListener('pointerdown', pressed);+ document.removeEventListener('keydown', keyed);+ };+ }, [open, onClose]);++ if (!open) return null;+ return (+ <div+ ref={card}+ 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',+ align === 'end' ? 'right-0' : 'left-0',+ className,+ )}+ >+ {children}+ </div>+ );+}diff --git a/src/extension/components/recent-conversations.tsx b/src/extension/components/recent-conversations.tsxnew file mode 100644index 0000000..f9770bb--- /dev/null+++ b/src/extension/components/recent-conversations.tsx@@ -0,0 +1,96 @@+import { useState, type ReactNode } from 'react';+import { MessagesSquare } from 'lucide-react';++import type { StoredSessionMeta } from '@/lib/bridge/session-store';+import type { TabSession } from '@/lib/bridge/tab-sessions';+import { faviconOf } from '@/lib/bridge/top-sites';+import { formatWhen } from '@/lib/format-when';++export function RecentConversations({+ running,+ recent,+ onWatch,+ onOpen,+ onShowAll,+}: {+ /** Runs going on in other tabs right now. */+ running: TabSession[];+ recent: StoredSessionMeta[];+ onWatch: (sessionId: string) => void;+ onOpen: (sessionId: string) => void;+ /** Absent in a browser with no side panel to list them in. */+ onShowAll?: () => void;+}) {+ if (!running.length && !recent.length) return null;+ return (+ <section aria-labelledby="recent-conversations" className="space-y-2">+ <div className="flex items-baseline justify-between gap-3 px-1">+ <h2 id="recent-conversations" className="text-sm font-medium text-ink-dim">+ Recent conversations+ </h2>+ {onShowAll && (+ <button type="button" onClick={onShowAll} className="text-xs text-ink-faint transition-colors hover:text-brand">+ All conversations+ </button>+ )}+ </div>+ <ul className="divide-y divide-line overflow-hidden rounded-2xl border border-line bg-ground/40">+ {running.map((session) => (+ <Row+ key={session.sessionId}+ onClick={() => onWatch(session.sessionId)}+ icon={<span className="glow-dot size-2 animate-pulse rounded-full bg-brand text-brand" />}+ title={session.title}+ detail={session.host ? `Running on ${session.host}` : 'Running'}+ action="Watch"+ />+ ))}+ {recent.map((session) => (+ <Row+ key={session.id}+ onClick={() => onOpen(session.id)}+ icon={<SiteIcon url={session.url} />}+ title={session.title ?? (session.host ? `Conversation on ${session.host}` : 'Untitled conversation')}+ detail={[session.host, formatWhen(session.updatedAt)].filter(Boolean).join(' · ')}+ />+ ))}+ </ul>+ </section>+ );+}++function Row({+ onClick,+ icon,+ title,+ detail,+ action,+}: {+ onClick: () => void;+ icon: ReactNode;+ title: string;+ detail: string;+ action?: string;+}) {+ return (+ <li>+ <button+ type="button"+ onClick={onClick}+ className="flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors outline-none hover:bg-surface/50 focus-visible:bg-surface/60"+ >+ <span className="grid size-6 shrink-0 place-items-center">{icon}</span>+ <span className="min-w-0 flex-1 truncate text-sm text-ink">{title}</span>+ <span className="shrink-0 text-xs text-ink-faint">{detail}</span>+ {action && <span className="shrink-0 text-xs font-medium text-brand">{action}</span>}+ </button>+ </li>+ );+}++function SiteIcon({ url }: { url?: string }) {+ const [broken, setBroken] = useState(false);+ const icon = faviconOf(url);+ if (!icon || broken) return <MessagesSquare className="size-4 text-ink-faint" />;+ return <img src={icon} alt="" className="size-4 rounded-sm" onError={() => setBroken(true)} />;+}diff --git a/src/extension/components/run-card.tsx b/src/extension/components/run-card.tsxnew file mode 100644index 0000000..6def2c8--- /dev/null+++ b/src/extension/components/run-card.tsx@@ -0,0 +1,145 @@+import { Check, PanelRight, TriangleAlert, X } from 'lucide-react';++import { Markdown } from '@/extension/components/markdown';+import { Button } from '@/extension/components/ui/button';+import { injectCode } from '@/lib/actions/page/inject-code';+import { toolName, type RunSummary } from '@/lib/home/run-summary';+import { cn } from '@/lib/utils';++/** Home's view of its own conversation: the latest request and where it stands. The side panel holds the rest. */+export function RunCard({+ summary,+ onOpenPanel,+ onDecide,+ onDismiss,+}: {+ summary: Exclude<RunSummary, { phase: 'idle' }>;+ /** Absent in a browser with no side panel. */+ onOpenPanel?: () => void;+ onDecide: (toolId: string, allow: boolean) => void;+ onDismiss: () => void;+}) {+ const live = summary.phase === 'working' || summary.phase === 'approval' || (summary.phase === 'reply' && summary.live);+ return (+ <section+ aria-live="polite"+ aria-label="This tab’s conversation"+ className={cn('panel-card enters relative overflow-hidden rounded-2xl', live && 'sweep')}+ >+ <header className="flex items-start gap-3 px-4 pt-3.5">+ <p className="line-clamp-2 min-w-0 flex-1 text-sm font-medium text-ink">{summary.asked}</p>+ {!live && (+ <button+ type="button"+ onClick={onDismiss}+ aria-label="End this conversation"+ title="End this conversation"+ className="-mt-0.5 shrink-0 rounded-full p-1 text-ink-faint transition-colors hover:bg-surface hover:text-ink"+ >+ <X className="size-3.5" />+ </button>+ )}+ </header>++ <div className="px-4 pt-2 pb-3.5">+ <Body summary={summary} onOpenPanel={onOpenPanel} onDecide={onDecide} />+ </div>++ {onOpenPanel && summary.phase !== 'approval' && (+ <footer className="flex items-center justify-between gap-3 border-t border-line px-4 py-2">+ <span className="text-[11px] text-ink-faint">Every step is in the side panel.</span>+ <button+ type="button"+ onClick={onOpenPanel}+ className="inline-flex items-center gap-1.5 text-xs text-ink-dim transition-colors hover:text-brand"+ >+ <PanelRight className="size-3.5" /> Open the side panel+ </button>+ </footer>+ )}+ </section>+ );+}++function Body({+ summary,+ onOpenPanel,+ onDecide,+}: {+ summary: Exclude<RunSummary, { phase: 'idle' }>;+ onOpenPanel?: () => void;+ onDecide: (toolId: string, allow: boolean) => void;+}) {+ switch (summary.phase) {+ case 'working':+ return (+ <p className="flex min-w-0 items-center gap-2 text-xs text-ink-dim">+ <span className="flex shrink-0 items-center gap-1">+ {[0, 1, 2].map((dot) => (+ <span key={dot} className="think-dot size-1.5 rounded-full bg-brand" />+ ))}+ </span>+ {summary.step ? (+ <span className="min-w-0 truncate">+ <span className="font-mono text-[11px] text-ink">{toolName(summary.step)}</span>+ {summary.step.summary && <span className="text-ink-faint"> · {summary.step.summary}</span>}+ </span>+ ) : (+ 'Thinking'+ )}+ </p>+ );+ case 'approval': {+ const code = summary.step.action === injectCode.name;+ return (+ <div className="flex flex-wrap items-center gap-2 rounded-xl border border-ember/45 bg-ember/10 px-3 py-2">+ <p className="min-w-0 flex-1 text-xs text-ink">+ {code ? 'The agent wrote code it wants to run.' : 'Allow this action?'}{' '}+ <span className="font-mono text-[11px] text-ink-dim">+ {toolName(summary.step)}+ {summary.step.site && ` on ${summary.step.site}`}+ </span>+ </p>+ {code ? (+ onOpenPanel && (+ <Button size="sm" variant="outline" onClick={onOpenPanel}>+ Review it in the side panel+ </Button>+ )+ ) : (+ <>+ <Button size="sm" variant="ghost" onClick={() => onDecide(summary.step.id, false)}>+ Deny+ </Button>+ <Button size="sm" onClick={() => onDecide(summary.step.id, true)}>+ Allow+ </Button>+ </>+ )}+ </div>+ );+ }+ case 'reply':+ return (+ <div className="max-h-[22rem] overflow-y-auto pr-1">+ <Markdown text={summary.reply} streaming={summary.live} className="text-sm leading-relaxed text-ink-dim" />+ </div>+ );+ case 'failed':+ return (+ <p className="flex items-start gap-2 text-xs leading-relaxed text-destructive">+ <TriangleAlert className="mt-px size-3.5 shrink-0" />+ <span className="min-w-0 break-words">{summary.message}</span>+ </p>+ );+ case 'done':+ return (+ <p className="flex min-w-0 items-center gap-2 text-xs text-ink-dim">+ <Check className="size-3.5 shrink-0 text-lime" />+ <span className="min-w-0 truncate">+ Done{summary.step && <span className="font-mono text-[11px]"> · {toolName(summary.step)}</span>}+ </span>+ </p>+ );+ }+}diff --git a/src/extension/entrypoints/newtab/App.tsx b/src/extension/entrypoints/newtab/App.tsxnew file mode 100644index 0000000..2286f76--- /dev/null+++ b/src/extension/entrypoints/newtab/App.tsx@@ -0,0 +1,326 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import { PanelRight, SlidersHorizontal } from 'lucide-react';+import { browser } from 'wxt/browser';++import { AgentChip } from '@/extension/components/agent-chip';+import { AgentPicker } from '@/extension/components/agent-picker';+import { Logo, Wordmark } from '@/extension/components/brand';+import { Composer, type AttachedSkill } from '@/extension/components/composer';+import { DaemonLink } from '@/extension/components/daemon-link';+import { DropMask } from '@/extension/components/drop-mask';+import { FrequentSites } from '@/extension/components/frequent-sites';+import { HomeCustomize } from '@/extension/components/home-customize';+import { Popover } from '@/extension/components/popover';+import { RecentConversations } from '@/extension/components/recent-conversations';+import { RunCard } from '@/extension/components/run-card';+import { SavedToolList } from '@/extension/components/saved-tools';+import { StatusPill, describeStatus, type StatusBlocker } from '@/extension/components/status-pill';+import { Button } from '@/extension/components/ui/button';+import { BRIDGE_CHANNEL } from '@/lib/actions/protocol';+import { isRemoveToolsCommand } from '@/lib/bridge/commands';+import { showPanelTab } from '@/lib/bridge/panel-view';+import { hasSidePanel, openSidePanel } from '@/lib/bridge/side-panel';+import { useOwnTab } from '@/lib/bridge/use-active-tab';+import { useAttachFiles } from '@/lib/bridge/use-attach-files';+import { useDaemonState } from '@/lib/bridge/use-daemon-state';+import { useActionCues, useNewTabChoice } from '@/lib/bridge/use-extension-settings';+import { useFileDrop } from '@/lib/bridge/use-file-drop';+import { useFrequentSites } from '@/lib/bridge/use-frequent-sites';+import { useRun } from '@/lib/bridge/use-run';+import { useStoredFiles } from '@/lib/bridge/use-stored-files';+import { useStoredSessions } from '@/lib/bridge/use-stored-sessions';+import { useVoiceComposer } from '@/lib/bridge/use-voice-composer';+import { MAX_STORED_FILE_BYTES } from '@/lib/files/report';+import { greeting } from '@/lib/home/greeting';+import { summarize } from '@/lib/home/run-summary';+import { suggestionsFor } from '@/lib/home/suggestions';+import { hideSite } from '@/lib/settings/new-tab';++type Sheet = 'connection' | 'agent' | 'customize';++const RECENT = 4;++const SETUP: Record<StatusBlocker, { text: string; action: string; sheet: Sheet }> = {+ unpaired: { text: 'This browser isn’t connected to Browsentic Bridge yet.', action: 'Set up the link', sheet: 'connection' },+ offline: { text: 'Browsentic Bridge isn’t answering. Start it and this reconnects on its own.', action: 'Check the link', sheet: 'connection' },+ agent: { text: 'The chosen agent can’t run on this computer.', action: 'Choose another agent', sheet: 'agent' },+};++const composerField = () => document.querySelector<HTMLTextAreaElement>('textarea[data-slot="textarea"]');++const TYPING_TARGETS = 'input, textarea, select, button, a, [contenteditable="true"]';++export default function App({ onTurnOff }: { onTurnOff: () => void }) {+ const daemon = useDaemonState();+ const own = useOwnTab();+ const run = useRun(own);+ const [choice, setChoice] = useNewTabChoice();+ const frequent = useFrequentSites(choice.sites, choice.hidden);+ const stored = useStoredSessions();+ const storedFiles = useStoredFiles();+ const [micOn, setMicOn] = useState(false);+ const [actionCues, setActionCues] = useActionCues();+ const [liveTools, setLiveTools] = useState(false);+ const [attachedSkill, setAttachedSkill] = useState<AttachedSkill | null>(null);+ const [attachError, setAttachError] = useState<string | null>(null);+ const attachFiles = useAttachFiles(run.attachFile, setAttachError);+ const [showTools, setShowTools] = useState(false);+ const [sheet, setSheet] = useState<Sheet | null>(null);+ const closeSheet = useCallback(() => setSheet(null), []);+ const toggle = (next: Sheet) => setSheet((open) => (open === next ? null : next));++ const panel = hasSidePanel();+ const connected = daemon?.connected ?? false;++ /** Must run first in a click or key press: the browser opens a side panel only while the gesture is fresh. */+ function reveal() {+ if (panel && own.windowId != null) void openSidePanel(own.windowId).catch(() => undefined);+ }++ /* Per page, not the panel's stored switch: new tabs open all day, and none may start listening on its own. */+ const voice = useVoiceComposer({+ active: micOn && connected && !run.running,+ onSubmit: (text) => {+ reveal();+ run.send(text, { agentSkillId: attachedSkill?.id, liveTools });+ setAttachedSkill(null);+ },+ });++ const dragging = useFileDrop({ active: connected, onDrop: (dropped) => void attachFiles(dropped) });++ useEffect(() => {+ if (!connected || daemon?.skillCatalog) return;+ void browser.runtime.sendMessage({ channel: BRIDGE_CHANNEL, op: 'listSkills' });+ }, [connected, daemon?.skillCatalog]);++ useEffect(() => {+ const typed = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || event.key.length !== 1) return;+ if ((event.target as HTMLElement).closest(TYPING_TARGETS)) return;+ composerField()?.focus();+ };+ document.addEventListener('keydown', typed);+ return () => document.removeEventListener('keydown', typed);+ }, []);++ const status = describeStatus(daemon, { running: run.running, listening: voice.listening });+ const files = useMemo(+ () => storedFiles.filter((file) => file.sessionId !== undefined && file.sessionId === run.sessionId),+ [storedFiles, run.sessionId],+ );+ const summary = useMemo(+ () => summarize(run.items.filter((item) => !(item.kind === 'tool' && item.source === 'external')), run.running),+ [run.items, run.running],+ );+ const ideas = useMemo(() => suggestionsFor(frequent.sites.map((site) => site.host)), [frequent.sites]);+ const running = run.sessions.filter((session) => session.runId && session.sessionId !== run.sessionId);+ const recent = stored+ .filter((session) => session.id !== run.sessionId && !running.some((live) => live.sessionId === session.id))+ .slice(0, RECENT);+ const hello = greeting(new Date().getHours(), daemon?.preferences?.profile.fields.givenName);+ const setup = status.blocker && SETUP[status.blocker];++ function send() {+ if (!connected || run.running) return;+ voice.submitNow();+ }++ function command(text: string) {+ if (isRemoveToolsCommand(text)) {+ setShowTools(true);+ return;+ }+ reveal();+ run.send(text);+ }++ function use(text: string) {+ voice.setInput(text);+ composerField()?.focus();+ }++ function toggleVoice() {+ if (micOn && voice.error) voice.retry();+ else setMicOn(!micOn);+ }++ function openConversation(sessionId: string) {+ reveal();+ void run.restore(sessionId);+ }++ function watch(sessionId: string) {+ reveal();+ run.focusSession(sessionId);+ }++ function showAll() {+ reveal();+ void showPanelTab('history');+ }++ function turnOff() {+ setChoice({ ...choice, home: false });+ onTurnOff();+ }++ return (+ <div className="relative flex min-h-screen flex-col overflow-x-clip">+ <div aria-hidden className="dot-grid fade-radial pointer-events-none fixed inset-0" />++ <header className="relative z-20 flex items-center gap-2 px-5 py-4">+ <Wordmark />+ <div className="ml-auto flex items-center gap-1">+ <div className="relative">+ <StatusPill tone={status.tone} expanded={sheet === 'connection'} onClick={() => toggle('connection')}>+ {status.label}+ </StatusPill>+ <Popover open={sheet === 'connection'} label="Connection" onClose={closeSheet}>+ <div className="space-y-4">+ <DaemonLink />+ <AgentPicker />+ </div>+ </Popover>+ </div>+ {panel && (+ <Button variant="ghost" size="icon-sm" title="Open the side panel" aria-label="Open the side panel" onClick={reveal}>+ <PanelRight className="size-3.5" />+ </Button>+ )}+ <div className="relative">+ <Button+ variant="ghost"+ size="icon-sm"+ title="Customize"+ aria-label="Customize this page"+ aria-expanded={sheet === 'customize'}+ onClick={() => toggle('customize')}+ >+ <SlidersHorizontal className="size-3.5" />+ </Button>+ <Popover open={sheet === 'customize'} label="Customize" onClose={closeSheet}>+ <HomeCustomize choice={choice} onChange={setChoice} onTurnOff={turnOff} />+ </Popover>+ </div>+ </div>+ </header>++ <main className="relative z-10 mx-auto flex w-full max-w-[44rem] flex-1 flex-col px-5 pt-[9vh] pb-16">+ <div className="flex flex-col items-center text-center">+ <Logo drawn className="size-11 text-brand" />+ <h1 className="mt-4 font-display text-[2rem] leading-tight font-semibold tracking-tight text-ink sm:text-[2.5rem]">+ {hello}+ </h1>+ </div>++ <div className="relative mt-8">+ <div aria-hidden className="home-halo pointer-events-none absolute -inset-x-24 -inset-y-16" />+ <div className="relative">+ <Composer+ size="hero"+ voice={voice}+ voiceEnabled={micOn}+ connected={connected}+ running={run.running}+ files={files}+ attachError={attachError}+ catalog={daemon?.skillCatalog}+ tabUrl=""+ attachedSkill={attachedSkill}+ focus={null}+ picking={false}+ liveTools={liveTools}+ onToggleLiveTools={() => setLiveTools((on) => !on)}+ actionCues={actionCues}+ onToggleActionCues={() => setActionCues(!actionCues)}+ onAttachSkill={setAttachedSkill}+ handsFree={false}+ placeholder="Tell me what to do, or where to go…"+ accessory={+ <div className="relative min-w-0">+ <AgentChip state={daemon?.agent} expanded={sheet === 'agent'} onClick={() => toggle('agent')} />+ <Popover open={sheet === 'agent'} label="Agent" onClose={closeSheet}>+ <AgentPicker />+ </Popover>+ </div>+ }+ onCommand={command}+ tools={run.tools}+ onRunTool={(id) => {+ reveal();+ run.runTool(id);+ }}+ onSend={send}+ onStop={run.cancel}+ onToggleVoice={toggleVoice}+ onClearFocus={() => undefined}+ onAttachFile={(file) => void attachFiles([file])}+ onRemoveFile={run.detachFile}+ onRetryFile={run.reanalyzeFile}+ />+ </div>+ </div>++ <div className="mt-5">+ {setup ? (+ <div className="enters flex flex-wrap items-center justify-center gap-x-3 gap-y-2 rounded-2xl border border-amber/30 bg-amber/8 px-4 py-3 text-center">+ <p className="text-sm text-ink">{setup.text}</p>+ <Button size="sm" variant="outline" onClick={() => setSheet(setup.sheet)}>+ {setup.action}+ </Button>+ </div>+ ) : summary.phase !== 'idle' ? (+ <RunCard+ summary={summary}+ onOpenPanel={panel ? reveal : undefined}+ onDecide={(toolId, allow) => run.decide(toolId, allow)}+ onDismiss={run.clear}+ />+ ) : (+ <ul aria-label="Suggestions" className="flex flex-wrap justify-center gap-2">+ {ideas.map((text) => (+ <li key={text}>+ <button+ type="button"+ onClick={() => use(text)}+ className="rounded-full border border-line bg-ground-2/60 px-3 py-1.5 text-xs text-ink-dim transition-colors hover:border-brand/40 hover:text-ink"+ >+ {text}+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>++ {choice.sites && (+ <div className="mt-12">+ <FrequentSites frequent={frequent} onHide={(host) => setChoice(hideSite(choice, host))} />+ </div>+ )}++ <div className="mt-10">+ <RecentConversations+ running={running}+ recent={recent}+ onWatch={watch}+ onOpen={openConversation}+ onShowAll={panel ? showAll : undefined}+ />+ </div>+ </main>++ {showTools && (+ <SavedToolList+ tools={run.tools}+ autoRunReady={run.autoRunReady}+ onAutoRun={run.setAutoRun}+ onForget={run.forgetTool}+ onClose={() => setShowTools(false)}+ />+ )}+ {dragging && <DropMask connected={connected} maxBytes={MAX_STORED_FILE_BYTES} />}+ </div>+ );+}diff --git a/src/extension/entrypoints/newtab/index.html b/src/extension/entrypoints/newtab/index.htmlnew file mode 100644index 0000000..e94bce1--- /dev/null+++ b/src/extension/entrypoints/newtab/index.html@@ -0,0 +1,14 @@+<!doctype html>+<html lang="en" data-theme="ember" style="background-color: #1a1512">+ <head>+ <meta charset="UTF-8" />+ <meta name="color-scheme" content="dark" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>New Tab</title>+ <link rel="icon" type="image/png" href="/icon/32.png" />+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./main.tsx"></script>+ </body>+</html>diff --git a/src/extension/entrypoints/newtab/main.tsx b/src/extension/entrypoints/newtab/main.tsxnew file mode 100644index 0000000..5495a1b--- /dev/null+++ b/src/extension/entrypoints/newtab/main.tsx@@ -0,0 +1,47 @@+import React from 'react';+import ReactDOM from 'react-dom/client';+import App from './App';+import { PlainNewTab } from '@/extension/components/plain-new-tab';+import { browserOwnNewTab, handTabTo, homeLooksOff, readNewTabChoice, rememberHome } from '@/lib/bridge/new-tab';+import { mountTheme } from '@/lib/bridge/theme';+import '@/extension/assets/globals.css';++mountTheme();++const root = ReactDOM.createRoot(document.getElementById('root')!);++function showHome() {+ root.render(+ <React.StrictMode>+ <App onTurnOff={() => void handOn()} />+ </React.StrictMode>,+ );+}++/** Home is off: the browser's own page where it can be opened, a quiet page of frequent sites where it cannot. */+async function handOn() {+ const own = browserOwnNewTab();+ if (own && (await handTabTo(own).catch(() => false))) return;+ root.render(+ <React.StrictMode>+ <PlainNewTab onTurnOn={showHome} />+ </React.StrictMode>,+ );+}++const lookedOff = homeLooksOff();+if (!lookedOff) showHome();++void readNewTabChoice()+ .then(({ home }) => {+ rememberHome(home);+ if (!home) void handOn();+ else if (lookedOff) showHome();+ })+ .catch(() => {+ if (lookedOff) void handOn();+ });++window.addEventListener('pageshow', (event) => {+ if (event.persisted && homeLooksOff()) void handOn();+});diff --git a/src/extension/entrypoints/sidepanel/App.tsx b/src/extension/entrypoints/sidepanel/App.tsxindex 840325e..1b5d1b6 100644--- a/src/extension/entrypoints/sidepanel/App.tsx+++ b/src/extension/entrypoints/sidepanel/App.tsx@@ -33,11 +33,11 @@ import { StatusPill, describeStatus } from '@/extension/components/status-pill';import { Button } from '@/extension/components/ui/button';import { ScrollArea } from '@/extension/components/ui/scroll-area';import { pickFocus } from '@/lib/bridge/aeye';-import { putBytes } from '@/lib/bridge/file-store';import { removeRecording, type StoredRecordingMeta } from '@/lib/bridge/recording-store';import { removeSession } from '@/lib/bridge/session-store';import { useActiveTabUrl } from '@/lib/bridge/use-active-tab-url';import { useActionCues, useBlockedPattern } from '@/lib/bridge/use-extension-settings';+import { useAttachFiles } from '@/lib/bridge/use-attach-files';import { useDaemonState } from '@/lib/bridge/use-daemon-state';import { useFileDrop } from '@/lib/bridge/use-file-drop';import { closeSidePanel } from '@/lib/bridge/side-panel';@@ -92,6 +92,7 @@ export default function App() {const pageUrl = phone ? (currentTarget(phone)?.url ?? '') : tabUrl;const blockedHere = useBlockedPattern(pageUrl);const [attachError, setAttachError] = useState<string | null>(null);+ const attachFiles = useAttachFiles(run.attachFile, setAttachError);const [attachedSkill, setAttachedSkill] = useState<AttachedSkill | null>(null);const [focus, setFocus] = useState<FocusedElement | null>(null);const [showTools, setShowTools] = useState(false);@@ -272,25 +273,6 @@ export default function App() {else if ('error' in outcome) setAttachError(`A-Eye couldn’t read that element: ${outcome.error}`);}- async function attachFiles(incoming: File[]) {- setAttachError(null);- for (const file of incoming) await storeFile(file);- }-- /** A file over the cap is handed over by name and size only, so the analyst can say why it was not read. */- async function storeFile(file: File) {- const stored = { id: crypto.randomUUID(), name: file.name, mime: file.type || 'application/octet-stream', size: file.size };- if (file.size <= MAX_STORED_FILE_BYTES) {- try {- await putBytes({ id: stored.id, name: stored.name, mime: stored.mime, content: await readAsBase64(file) });- } catch (error) {- setAttachError(`Couldn’t store “${file.name}”: ${error instanceof Error ? error.message : String(error)}`);- return;- }- }- run.attachFile(stored);- }-function toggleVoice() {if (!voiceEnabled) {setVoiceEnabled(true);@@ -555,15 +537,3 @@ export default function App() {</div>);}--function readAsBase64(file: File): Promise<string> {- return new Promise((resolve, reject) => {- const reader = new FileReader();- reader.onload = () => {- const result = reader.result;- resolve(typeof result === 'string' ? result.slice(result.indexOf(',') + 1) : '');- };- reader.onerror = () => reject(reader.error ?? new Error('Could not read the file'));- reader.readAsDataURL(file);- });-}diff --git a/src/lib/bridge/new-tab.ts b/src/lib/bridge/new-tab.tsnew file mode 100644index 0000000..7de37b3--- /dev/null+++ b/src/lib/bridge/new-tab.ts@@ -0,0 +1,33 @@+import { browser } from 'wxt/browser';+import { NEW_TAB_KEY, asNewTabChoice, browserNewTabPage, type NewTabChoice } from '@/lib/settings/new-tab';+import { brandFrom } from './identity';++/* storage.local answers after the first frame, so a tab with Home switched off would flash it+ before handing itself on. The switch is mirrored here, where a page can read it at once. */+const PAINT_HINT = 'browsentic/newTab.paint';++export async function readNewTabChoice(): Promise<NewTabChoice> {+ return asNewTabChoice((await browser.storage.local.get(NEW_TAB_KEY))[NEW_TAB_KEY]);+}++export function rememberHome(home: boolean): void {+ localStorage.setItem(PAINT_HINT, home ? 'on' : 'off');+}++export const homeLooksOff = (): boolean => localStorage.getItem(PAINT_HINT) === 'off';++type Brand = { brand: string };++export function browserOwnNewTab(): string | null {+ if (import.meta.env.FIREFOX) return null;+ const brands = (navigator as Navigator & { userAgentData?: { brands?: Brand[] } }).userAgentData?.brands ?? [];+ return browserNewTabPage(brandFrom(brands));+}++/** Only the tabs API may open a browser page; the page itself is refused a `chrome://` address. */+export async function handTabTo(url: string): Promise<boolean> {+ const tab = await browser.tabs.getCurrent();+ if (tab?.id == null) return false;+ await browser.tabs.update(tab.id, { url });+ return true;+}diff --git a/src/lib/bridge/panel-view.ts b/src/lib/bridge/panel-view.tsindex 61e0a2f..93d6401 100644--- a/src/lib/bridge/panel-view.ts+++ b/src/lib/bridge/panel-view.ts@@ -39,6 +39,9 @@ export const startHandsFree = (): Promise<void> => writeHandsFree({ muted: falseexport const endHandsFree = (): Promise<void> => writeHandsFree(null);+/** Picks the side panel's tab, whether the panel is open already or about to be. */+export const showPanelTab = (tab: PanelTab): Promise<void> => browser.storage.local.set({ [PANEL_TAB_KEY]: tab });+export async function readPanelTab(): Promise<PanelTab> {const stored = await browser.storage.local.get(PANEL_TAB_KEY);const tab = stored[PANEL_TAB_KEY];diff --git a/src/lib/bridge/side-panel.ts b/src/lib/bridge/side-panel.tsindex c8cd142..93626d5 100644--- a/src/lib/bridge/side-panel.ts+++ b/src/lib/bridge/side-panel.ts@@ -6,6 +6,9 @@ function sidebarAction(): SidebarAction {return (browser as unknown as { sidebarAction: SidebarAction }).sidebarAction;}+/** Some Chromium browsers have no side panel, and their toolbar button opens the launcher instead. */+export const hasSidePanel = (): boolean => import.meta.env.FIREFOX || typeof browser.sidePanel?.open === 'function';+export function openSidePanel(windowId: number) {if (import.meta.env.FIREFOX) return sidebarAction().open();return browser.sidePanel.open({ windowId });diff --git a/src/lib/bridge/top-sites.ts b/src/lib/bridge/top-sites.tsnew file mode 100644index 0000000..9d17458--- /dev/null+++ b/src/lib/bridge/top-sites.ts@@ -0,0 +1,24 @@+import { browser } from 'wxt/browser';+import type { VisitedSite } from '@/lib/home/frequent-sites';++const TOP_SITES = { permissions: ['topSites' as const] };++const FIREFOX_TOP_SITES = { includeFavicon: true, onePerDomain: true, newtab: true, limit: 24 };++type GeckoTopSites = { get: (options: typeof FIREFOX_TOP_SITES) => Promise<VisitedSite[]> };++/** Chrome grants this with the extension. Firefox asks for it from a click, so an update never waits on a new permission. */+export const canReadTopSites = (): Promise<boolean> => browser.permissions.contains(TOP_SITES);++export const askForTopSites = (): Promise<boolean> => browser.permissions.request(TOP_SITES);++/** The icon the browser keeps for a page, read through Chromium's favicon service; Firefox has none to ask. */+export function faviconOf(pageUrl: string | undefined, size = 32): string | undefined {+ if (import.meta.env.FIREFOX || !pageUrl) return undefined;+ return `${browser.runtime.getURL('/')}_favicon/?pageUrl=${encodeURIComponent(pageUrl)}&size=${size}`;+}++export async function readTopSites(): Promise<VisitedSite[]> {+ if (import.meta.env.FIREFOX) return (browser.topSites as unknown as GeckoTopSites).get(FIREFOX_TOP_SITES);+ return (await browser.topSites.get()).map(({ url, title }) => ({ url, title, favicon: faviconOf(url, 64) }));+}diff --git a/src/lib/bridge/use-active-tab.ts b/src/lib/bridge/use-active-tab.tsindex 61d7087..ae4b83a 100644--- a/src/lib/bridge/use-active-tab.ts+++ b/src/lib/bridge/use-active-tab.ts@@ -47,3 +47,24 @@ export function useActiveTab(): ActiveTab {return tab;}++/** The tab a page is itself open in, for a page whose conversation is its own whichever tab is in front. */+export function useOwnTab(): ActiveTab {+ const [tab, setTab] = useState<ActiveTab>(NO_TAB);++ useEffect(() => {+ let live = true;+ void browser.tabs+ .getCurrent()+ .then((found) => {+ if (!live || found?.id == null) return;+ setTab({ url: found.url ?? '', tabId: found.id, windowId: found.windowId, title: found.title ?? document.title });+ })+ .catch(() => undefined);+ return () => {+ live = false;+ };+ }, []);++ return tab;+}diff --git a/src/lib/bridge/use-attach-files.ts b/src/lib/bridge/use-attach-files.tsnew file mode 100644index 0000000..ba319e5--- /dev/null+++ b/src/lib/bridge/use-attach-files.ts@@ -0,0 +1,43 @@+import { useCallback } from 'react';+import { MAX_STORED_FILE_BYTES } from '@/lib/files/report';+import { putBytes, type NewFile } from './file-store';++/**+ * Stores each file's bytes, then gives it to the conversation. A file over the cap is handed+ * over by name and size only, so the analyst can say why it was not read.+ */+export function useAttachFiles(+ attach: (file: NewFile) => void,+ onError: (message: string | null) => void,+): (files: File[]) => Promise<void> {+ return useCallback(+ async (files: File[]) => {+ onError(null);+ for (const file of files) {+ const stored = { id: crypto.randomUUID(), name: file.name, mime: file.type || 'application/octet-stream', size: file.size };+ if (file.size <= MAX_STORED_FILE_BYTES) {+ try {+ await putBytes({ id: stored.id, name: stored.name, mime: stored.mime, content: await readAsBase64(file) });+ } catch (error) {+ onError(`Couldn’t store “${file.name}”: ${error instanceof Error ? error.message : String(error)}`);+ continue;+ }+ }+ attach(stored);+ }+ },+ [attach, onError],+ );+}++function readAsBase64(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ const result = reader.result;+ resolve(typeof result === 'string' ? result.slice(result.indexOf(',') + 1) : '');+ };+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the file'));+ reader.readAsDataURL(file);+ });+}diff --git a/src/lib/bridge/use-extension-settings.ts b/src/lib/bridge/use-extension-settings.tsindex be567a2..9f33c78 100644--- a/src/lib/bridge/use-extension-settings.ts+++ b/src/lib/bridge/use-extension-settings.ts@@ -1,10 +1,12 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { browser } from 'wxt/browser';import { BLOCKED_SITES_KEY, blockedBy, compileBlockedSites } from '@/lib/settings/blocked-sites';+import { NEW_TAB_KEY, asNewTabChoice, type NewTabChoice } from '@/lib/settings/new-tab';import { shortcutsOf, shortcutsPageFor, type Shortcut } from '@/lib/settings/shortcuts';import { ACTION_CUES_KEY, actionCuesOn } from './action-cues';import { CONTEXT_MENU_KEY, asContextMenuChoice, type ContextMenuChoice } from './context-menu';import { brandFrom } from './identity';+import { rememberHome } from './new-tab';import { PUSH_TO_TALK_KEY } from './panel-view';export function useLocalSetting<T>(key: string, parse: (value: unknown) => T): [T, (next: T) => void] {@@ -45,6 +47,18 @@ export const usePushToTalk = (): [boolean, (on: boolean) => void] => useLocalSetexport const useActionCues = (): [boolean, (on: boolean) => void] => useLocalSetting(ACTION_CUES_KEY, actionCuesOn);+export function useNewTabChoice(): [NewTabChoice, (next: NewTabChoice) => void] {+ const [choice, write] = useLocalSetting(NEW_TAB_KEY, asNewTabChoice);+ const change = useCallback(+ (next: NewTabChoice) => {+ rememberHome(next.home);+ write(next);+ },+ [write],+ );+ return [choice, change];+}+const asPatterns = (value: unknown): string[] =>Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];diff --git a/src/lib/bridge/use-frequent-sites.ts b/src/lib/bridge/use-frequent-sites.tsnew file mode 100644index 0000000..24a8a63--- /dev/null+++ b/src/lib/bridge/use-frequent-sites.ts@@ -0,0 +1,36 @@+import { useCallback, useEffect, useMemo, useState } from 'react';+import { frequentSites, type FrequentSite, type VisitedSite } from '@/lib/home/frequent-sites';+import { askForTopSites, canReadTopSites, readTopSites } from './top-sites';++export interface FrequentSites {+ sites: FrequentSite[];+ /** False until the browser has answered, so the row never jumps in under the composer. */+ loaded: boolean;+ needsGrant: boolean;+ /** Spends the click it is called from on the browser's permission prompt. */+ grant: () => void;+}++export function useFrequentSites(shown: boolean, hidden: readonly string[]): FrequentSites {+ const [visited, setVisited] = useState<VisitedSite[] | null>(null);+ const [granted, setGranted] = useState<boolean | null>(null);++ const load = useCallback(async () => {+ const allowed = await canReadTopSites().catch(() => false);+ setGranted(allowed);+ setVisited(allowed ? await readTopSites().catch(() => []) : []);+ }, []);++ useEffect(() => {+ if (shown) void load();+ }, [shown, load]);++ const grant = useCallback(() => {+ void askForTopSites().then((allowed) => {+ if (allowed) void load();+ });+ }, [load]);++ const sites = useMemo(() => frequentSites(visited ?? [], hidden), [visited, hidden]);+ return { sites, loaded: visited !== null, needsGrant: granted === false, grant };+}diff --git a/src/lib/bridge/use-run.ts b/src/lib/bridge/use-run.tsindex d1cd796..e1ac219 100644--- a/src/lib/bridge/use-run.ts+++ b/src/lib/bridge/use-run.ts@@ -9,7 +9,7 @@ import type { NewFile } from './file-store';import type { SavedToolMeta } from './saved-tools';import { attachPreview, notice, reduce, type RunItem } from './run-items';import { RUN_PORT, type RunCommand, type RunMessage } from './run-port';-import { useActiveTab } from './use-active-tab';+import { useActiveTab, type ActiveTab } from './use-active-tab';import { useTabSessions } from './use-tab-sessions';import type { TabSession } from './tab-sessions';@@ -73,7 +73,8 @@ export interface Run {reanalyzeFile: (fileId: string) => void;}-export function useRun(): Run {+/** Follows the tab in front, unless given a tab of its own to stay on. */+export function useRun(pinned?: ActiveTab): Run {const [drafts, setDrafts] = useState<Record<string, SiteMapDraft>>({});const [recording, setRecording] = useState<RecordingState | null>(null);const [monitors, setMonitors] = useState<MonitorState[]>([]);@@ -84,7 +85,8 @@ export function useRun(): Run {const [completed, setCompleted] = useState<CompletedTurn | null>(null);const port = useRef<Browser.runtime.Port | null>(null);- const tab = useActiveTab();+ const front = useActiveTab();+ const tab = pinned ?? front;const sessions = useTabSessions();const displayed = useMemo(() => (tab.tabId == null ? null : (sessions.find((s) => s.tabIds.includes(tab.tabId!)) ?? null)),diff --git a/src/lib/home/frequent-sites.test.ts b/src/lib/home/frequent-sites.test.tsnew file mode 100644index 0000000..76fba3b--- /dev/null+++ b/src/lib/home/frequent-sites.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest';+import { frequentSites, siteHost, siteLabel } from './frequent-sites';++describe('siteHost', () => {+ it('names a web page by its host, without www', () => {+ expect(siteHost('https://www.github.com/notifications')).toBe('github.com');+ expect(siteHost('http://news.ycombinator.com/')).toBe('news.ycombinator.com');+ });++ it('has no host for anything but a web page', () => {+ for (const url of ['chrome://settings', 'file:///Users/me/a.pdf', 'chrome-extension://abc/options.html', 'not a url']) {+ expect(siteHost(url)).toBeNull();+ }+ });+});++describe('siteLabel', () => {+ it('takes the part of the title that names the domain', () => {+ expect(siteLabel('Reddit - Dive into anything', 'reddit.com')).toBe('Reddit');+ expect(siteLabel('Feed | LinkedIn', 'linkedin.com')).toBe('LinkedIn');+ expect(siteLabel('Home / X', 'x.com')).toBe('X');+ expect(siteLabel('GitHub: Let’s build from here', 'github.com')).toBe('GitHub');+ expect(siteLabel('Stack Overflow - Where Developers Learn, Share, & Build Careers', 'stackoverflow.com')).toBe(+ 'Stack Overflow',+ );+ });++ it('falls back to the last part, where most sites put their name', () => {+ expect(siteLabel('Inbox (3) - [email protected] - Gmail', 'mail.google.com')).toBe('Gmail');+ });++ it('drops an unread count in front of the title', () => {+ expect(siteLabel('(12) YouTube', 'youtube.com')).toBe('YouTube');+ });++ it('does not match a short domain inside an unrelated word', () => {+ expect(siteLabel('Explore / X', 'x.com')).toBe('X');+ });++ it('uses the host when the title is missing or too long to read', () => {+ expect(siteLabel(undefined, 'example.com')).toBe('example.com');+ expect(siteLabel('A very long page title that says nothing about the site', 'example.com')).toBe('example.com');+ });+});++describe('frequentSites', () => {+ const visited = [+ { url: 'https://github.com/notifications', title: 'Notifications · GitHub' },+ { url: 'https://github.com/pulls', title: 'Pull requests · GitHub' },+ { url: 'chrome://settings', title: 'Settings' },+ { url: 'https://www.youtube.com/', title: 'YouTube', favicon: 'data:image/png;base64,AAAA' },+ { url: 'https://example.com/', title: 'Example Domain' },+ ];++ it('keeps one tile per host, in the order the browser ranked them', () => {+ expect(frequentSites(visited, []).map((site) => site.host)).toEqual(['github.com', 'youtube.com', 'example.com']);+ });++ it('labels each tile and carries the icon the browser gave', () => {+ expect(frequentSites(visited, [])[1]).toEqual({+ url: 'https://www.youtube.com/',+ host: 'youtube.com',+ label: 'YouTube',+ icon: 'data:image/png;base64,AAAA',+ });+ expect(frequentSites(visited, [])[0]).not.toHaveProperty('icon');+ });++ it('leaves out the hosts the user hid', () => {+ expect(frequentSites(visited, ['youtube.com']).map((site) => site.host)).toEqual(['github.com', 'example.com']);+ });++ it('stops at the limit', () => {+ expect(frequentSites(visited, [], 2)).toHaveLength(2);+ });+});diff --git a/src/lib/home/frequent-sites.ts b/src/lib/home/frequent-sites.tsnew file mode 100644index 0000000..0f51c9c--- /dev/null+++ b/src/lib/home/frequent-sites.ts@@ -0,0 +1,69 @@+export interface VisitedSite {+ url: string;+ title?: string;+ favicon?: string;+}++export interface FrequentSite {+ url: string;+ host: string;+ label: string;+ icon?: string;+}++export const FREQUENT_SITES = 8;++const MAX_LABEL = 20;++const TITLE_PARTS = /\s+[-–—|·•/]\s+|:\s+/;++const UNREAD_COUNT = /^\(\d+\+?\)\s*/;++export function siteHost(url: string): string | null {+ try {+ const { protocol, hostname } = new URL(url);+ return /^https?:$/.test(protocol) && hostname ? hostname.replace(/^www\./, '') : null;+ } catch {+ return null;+ }+}++const squashed = (text: string) => text.toLowerCase().replace(/[^a-z0-9]/g, '');++/** The name a site calls itself: the title part that matches its domain, else the last part, where most sites put their name. */+export function siteLabel(title: string | undefined, host: string): string {+ const parts = (title ?? '')+ .replace(UNREAD_COUNT, '')+ .split(TITLE_PARTS)+ .map((part) => part.trim())+ .filter(Boolean);+ const domain = host.split('.').at(-2) ?? host;+ const named = parts.find((part) => {+ const name = squashed(part);+ return name === domain || (domain.length >= 4 && name.includes(domain));+ });+ const label = named ?? parts.at(-1);+ return label && label.length <= MAX_LABEL ? label : host;+}++export function frequentSites(+ visited: readonly VisitedSite[],+ hidden: readonly string[],+ limit = FREQUENT_SITES,+): FrequentSite[] {+ const hosted = visited.map((site) => ({ site, host: siteHost(site.url) }));+ return hosted+ .filter(+ (entry, index): entry is { site: VisitedSite; host: string } =>+ entry.host !== null &&+ !hidden.includes(entry.host) &&+ hosted.findIndex((other) => other.host === entry.host) === index,+ )+ .slice(0, limit)+ .map(({ site, host }) => ({+ url: site.url,+ host,+ label: siteLabel(site.title, host),+ ...(site.favicon ? { icon: site.favicon } : {}),+ }));+}diff --git a/src/lib/home/greeting.test.ts b/src/lib/home/greeting.test.tsnew file mode 100644index 0000000..6329d22--- /dev/null+++ b/src/lib/home/greeting.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';+import { greeting } from './greeting';++describe('greeting', () => {+ it('follows the time of day', () => {+ expect(greeting(3)).toBe('Hello');+ expect(greeting(5)).toBe('Good morning');+ expect(greeting(11)).toBe('Good morning');+ expect(greeting(12)).toBe('Good afternoon');+ expect(greeting(18)).toBe('Good evening');+ expect(greeting(23)).toBe('Good evening');+ });++ it('uses the first name from the profile when there is one', () => {+ expect(greeting(9, 'Ada')).toBe('Good morning, Ada');+ expect(greeting(9, ' ')).toBe('Good morning');+ });+});diff --git a/src/lib/home/greeting.ts b/src/lib/home/greeting.tsnew file mode 100644index 0000000..804de5c--- /dev/null+++ b/src/lib/home/greeting.ts@@ -0,0 +1,12 @@+const PARTS_OF_DAY = [+ { from: 0, words: 'Hello' },+ { from: 5, words: 'Good morning' },+ { from: 12, words: 'Good afternoon' },+ { from: 18, words: 'Good evening' },+] as const;++export function greeting(hour: number, name?: string): string {+ const { words } = PARTS_OF_DAY.findLast(({ from }) => hour >= from) ?? PARTS_OF_DAY[0];+ const called = name?.trim();+ return called ? `${words}, ${called}` : words;+}diff --git a/src/lib/home/run-summary.test.ts b/src/lib/home/run-summary.test.tsnew file mode 100644index 0000000..eb395cb--- /dev/null+++ b/src/lib/home/run-summary.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';+import type { RunItem } from '@/lib/bridge/run-items';+import { summarize, toolName } from './run-summary';++const user = (text: string): RunItem => ({ kind: 'user', id: `u-${text}`, text });+const reply = (text: string): RunItem => ({ kind: 'assistant', id: `a-${text}`, text });+const tool = (action: string, extra: Partial<Extract<RunItem, { kind: 'tool' }>> = {}): RunItem => ({+ kind: 'tool',+ id: `t-${action}`,+ action,+ input: {},+ ...extra,+});+const failure = (text: string): RunItem => ({ kind: 'notice', id: `n-${text}`, tone: 'error', text });++describe('summarize', () => {+ it('has nothing to tell before the first message', () => {+ expect(summarize([], false)).toEqual({ phase: 'idle' });+ expect(summarize([{ kind: 'notice', id: 'n', tone: 'info', text: 'Loaded skill' }], false)).toEqual({ phase: 'idle' });+ });++ it('tells only the latest turn', () => {+ const items = [user('first'), reply('old answer'), user('second')];+ expect(summarize(items, true)).toEqual({ phase: 'working', asked: 'second', step: undefined });+ });++ it('names the step the agent is on while it works', () => {+ const items = [user('find flights'), tool('page.navigate', { summary: 'google.com/travel' })];+ expect(summarize(items, true)).toMatchObject({ phase: 'working', step: { action: 'page.navigate' } });+ });++ it('puts an approval first, even with a reply streaming beside it', () => {+ const items = [user('pay the bill'), tool('page.clickElement', { awaiting: true, site: 'bank.example' }), reply('One moment')];+ expect(summarize(items, true)).toMatchObject({ phase: 'approval', step: { action: 'page.clickElement' } });+ });++ it('streams the reply while it arrives, and keeps it once the run ends', () => {+ expect(summarize([user('q'), reply('Half an ans')], true)).toEqual({ phase: 'reply', asked: 'q', reply: 'Half an ans', live: true });+ expect(summarize([user('q'), reply('The answer'), tool('page.screenshot')], false)).toEqual({+ phase: 'reply',+ asked: 'q',+ reply: 'The answer',+ live: false,+ });+ });++ it('reports a turn that ended on an error', () => {+ expect(summarize([user('q'), failure('AGENT_MISSING: Claude Code cannot run.')], false)).toEqual({+ phase: 'failed',+ asked: 'q',+ message: 'AGENT_MISSING: Claude Code cannot run.',+ });+ });++ it('settles a turn that only acted', () => {+ expect(summarize([user('go to example.com'), tool('page.navigate', { ok: true })], false)).toMatchObject({+ phase: 'done',+ step: { action: 'page.navigate' },+ });+ });+});++describe('toolName', () => {+ it('drops the page prefix the panel drops too', () => {+ expect(toolName(tool('page.navigate') as Extract<RunItem, { kind: 'tool' }>)).toBe('navigate');+ expect(toolName(tool('browsentic.readFile') as Extract<RunItem, { kind: 'tool' }>)).toBe('browsentic.readFile');+ });+});diff --git a/src/lib/home/run-summary.ts b/src/lib/home/run-summary.tsnew file mode 100644index 0000000..d29c834--- /dev/null+++ b/src/lib/home/run-summary.ts@@ -0,0 +1,37 @@+import type { RunItem } from '@/lib/bridge/run-items';++type Tool = Extract<RunItem, { kind: 'tool' }>;++type User = Extract<RunItem, { kind: 'user' }>;++/** The latest turn of a conversation, told in one card: what was asked and where it stands. */+export type RunSummary =+ | { phase: 'idle' }+ | { phase: 'working'; asked: string; step?: Tool }+ | { phase: 'approval'; asked: string; step: Tool }+ | { phase: 'reply'; asked: string; reply: string; live: boolean }+ | { phase: 'failed'; asked: string; message: string }+ | { phase: 'done'; asked: string; step?: Tool };++const isTool = (item: RunItem): item is Tool => item.kind === 'tool';++export function summarize(items: readonly RunItem[], running: boolean): RunSummary {+ const start = items.findLastIndex((item) => item.kind === 'user');+ if (start < 0) return { phase: 'idle' };++ const asked = (items[start] as User).text;+ const turn = items.slice(start + 1);+ const step = turn.findLast(isTool);+ const awaiting = turn.find((item): item is Tool => isTool(item) && item.awaiting === true);+ if (running && awaiting) return { phase: 'approval', asked, step: awaiting };++ const last = turn.at(-1);+ if (last?.kind === 'assistant') return { phase: 'reply', asked, reply: last.text, live: running };+ if (last?.kind === 'notice' && last.tone === 'error') return { phase: 'failed', asked, message: last.text };+ if (running) return { phase: 'working', asked, step };++ const reply = turn.findLast((item) => item.kind === 'assistant');+ return reply ? { phase: 'reply', asked, reply: reply.text, live: false } : { phase: 'done', asked, step };+}++export const toolName = (step: Tool): string => step.action.replace(/^page\./, '');diff --git a/src/lib/home/suggestions.test.ts b/src/lib/home/suggestions.test.tsnew file mode 100644index 0000000..ea0085b--- /dev/null+++ b/src/lib/home/suggestions.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { suggestionsFor } from './suggestions';++describe('suggestionsFor', () => {+ it('offers general tasks to someone with no frequent sites yet', () => {+ expect(suggestionsFor([])).toEqual([+ 'Find a flight to Lisbon next Friday and compare prices',+ 'Compare the three best-reviewed noise-cancelling headphones',+ 'Summarise the top stories on Hacker News',+ ]);+ });++ it('puts tasks on the sites visited most first, in visit order', () => {+ expect(suggestionsFor(['mail.google.com', 'example.com', 'github.com'])).toEqual([+ 'Summarise my unread email',+ 'List the pull requests waiting on my review',+ 'Find a flight to Lisbon next Friday and compare prices',+ ]);+ });++ it('matches a site on its subdomains and country domains', () => {+ expect(suggestionsFor(['acme.atlassian.net'], 1)).toEqual(['List the Jira issues assigned to me']);+ expect(suggestionsFor(['amazon.co.uk'], 1)).toEqual(['Where is my latest Amazon order?']);+ expect(suggestionsFor(['app.slack.com'], 1)).toEqual(['Summarise my unread Slack messages']);+ });++ it('does not repeat a task a site and the general list share', () => {+ const offered = suggestionsFor(['news.ycombinator.com'], 4);+ expect(offered).toHaveLength(new Set(offered).size);+ expect(offered[0]).toBe('Summarise the top stories on Hacker News');+ });++ it('does not take a lookalike domain for the real one', () => {+ expect(suggestionsFor(['notgithub.com', 'amazon.example.com'], 1)).toEqual([+ 'Find a flight to Lisbon next Friday and compare prices',+ ]);+ });+});diff --git a/src/lib/home/suggestions.ts b/src/lib/home/suggestions.tsnew file mode 100644index 0000000..47c2748--- /dev/null+++ b/src/lib/home/suggestions.ts@@ -0,0 +1,31 @@+interface SiteTask {+ site: RegExp;+ text: string;+}++const SITE_TASKS: readonly SiteTask[] = [+ { site: /(^|\.)github\.com$/, text: 'List the pull requests waiting on my review' },+ { site: /^(mail\.google\.com|outlook\.(live|office|office365)\.com)$/, text: 'Summarise my unread email' },+ { site: /^calendar\.google\.com$/, text: 'What is on my calendar tomorrow?' },+ { site: /^news\.ycombinator\.com$/, text: 'Summarise the top stories on Hacker News' },+ { site: /(^|\.)linkedin\.com$/, text: 'Show my unread LinkedIn messages' },+ { site: /(^|\.)youtube\.com$/, text: 'List the new videos from my YouTube subscriptions' },+ { site: /(^|\.)reddit\.com$/, text: 'Summarise the top posts on my Reddit front page' },+ { site: /^(x|twitter)\.com$/, text: 'Summarise my notifications on X' },+ { site: /\.atlassian\.net$/, text: 'List the Jira issues assigned to me' },+ { site: /(^|\.)slack\.com$/, text: 'Summarise my unread Slack messages' },+ { site: /(^|\.)amazon\.(com|ca|de|fr|in|it|es|nl|se|pl|com\.au|com\.br|com\.mx|co\.uk|co\.jp)$/, text: 'Where is my latest Amazon order?' },+ { site: /^docs\.google\.com$/, text: 'Open the Google Doc I edited last' },+];++const ANYWHERE = [+ 'Find a flight to Lisbon next Friday and compare prices',+ 'Compare the three best-reviewed noise-cancelling headphones',+ 'Summarise the top stories on Hacker News',+];++/** Tasks on the sites the user visits most come first, in the order they visit them; general ones fill the rest. */+export function suggestionsFor(hosts: readonly string[], count = 3): string[] {+ const personal = hosts.flatMap((host) => SITE_TASKS.filter(({ site }) => site.test(host)).map(({ text }) => text));+ return [...new Set([...personal, ...ANYWHERE])].slice(0, count);+}diff --git a/src/lib/settings/new-tab.test.ts b/src/lib/settings/new-tab.test.tsnew file mode 100644index 0000000..454287d--- /dev/null+++ b/src/lib/settings/new-tab.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';+import { MAX_HIDDEN_SITES, asNewTabChoice, browserNewTabPage, hideSite } from './new-tab';++describe('asNewTabChoice', () => {+ it('opens Home with frequent sites until the user says otherwise', () => {+ expect(asNewTabChoice(undefined)).toEqual({ home: true, sites: true, hidden: [] });+ expect(asNewTabChoice('on')).toEqual({ home: true, sites: true, hidden: [] });+ });++ it('keeps what the user switched off', () => {+ expect(asNewTabChoice({ home: false, sites: false, hidden: ['example.com'] })).toEqual({+ home: false,+ sites: false,+ hidden: ['example.com'],+ });+ });++ it('drops anything in the hidden list that is not a host', () => {+ expect(asNewTabChoice({ hidden: ['a.com', 7, null, 'b.com'] }).hidden).toEqual(['a.com', 'b.com']);+ expect(asNewTabChoice({ hidden: 'a.com' }).hidden).toEqual([]);+ });++ it('keeps only the newest hidden hosts', () => {+ const hidden = Array.from({ length: MAX_HIDDEN_SITES + 5 }, (_, index) => `site${index}.com`);+ const kept = asNewTabChoice({ hidden }).hidden;+ expect(kept).toHaveLength(MAX_HIDDEN_SITES);+ expect(kept.at(-1)).toBe(`site${MAX_HIDDEN_SITES + 4}.com`);+ });+});++describe('hideSite', () => {+ it('adds a host once, as the newest', () => {+ const choice = asNewTabChoice({ hidden: ['a.com', 'b.com'] });+ expect(hideSite(choice, 'a.com').hidden).toEqual(['b.com', 'a.com']);+ expect(hideSite(choice, 'c.com').hidden).toEqual(['a.com', 'b.com', 'c.com']);+ });++ it('leaves the other switches as they were', () => {+ expect(hideSite(asNewTabChoice({ sites: false }), 'a.com')).toMatchObject({ home: true, sites: false });+ });+});++describe('browserNewTabPage', () => {+ it('hands Google Chrome back its own page', () => {+ expect(browserNewTabPage('Google Chrome')).toBe('chrome://new-tab-page/');+ });++ it('has no page to hand back anywhere else', () => {+ for (const brand of ['Microsoft Edge', 'Brave', 'Opera', 'Chromium', undefined]) expect(browserNewTabPage(brand)).toBeNull();+ });+});diff --git a/src/lib/settings/new-tab.ts b/src/lib/settings/new-tab.tsnew file mode 100644index 0000000..14e99c5--- /dev/null+++ b/src/lib/settings/new-tab.ts@@ -0,0 +1,32 @@+/**+ * Browsentic Home, the page a new tab opens on. A browser takes a new tab page from the manifest+ * alone, so switching Home off cannot give the slot back: the page hands each tab on instead, to+ * the browser's own page where an extension can open it, or to a quiet page of frequent sites.+ */++export const NEW_TAB_KEY = 'browsentic/newTab';++export const MAX_HIDDEN_SITES = 100;++export interface NewTabChoice {+ home: boolean;+ sites: boolean;+ /** Hosts the user took off the frequent sites row. */+ hidden: string[];+}++export function asNewTabChoice(value: unknown): NewTabChoice {+ const stored = (value !== null && typeof value === 'object' ? value : {}) as Partial<Record<keyof NewTabChoice, unknown>>;+ const hidden = Array.isArray(stored.hidden) ? stored.hidden.filter((host): host is string => typeof host === 'string') : [];+ return { home: stored.home !== false, sites: stored.sites !== false, hidden: hidden.slice(-MAX_HIDDEN_SITES) };+}++export const hideSite = (choice: NewTabChoice, host: string): NewTabChoice => ({+ ...choice,+ hidden: [...choice.hidden.filter((kept) => kept !== host), host].slice(-MAX_HIDDEN_SITES),+});++/** Google Chrome keeps its own new tab page at an address an extension may open; Edge, Brave and Firefox do not. */+export function browserNewTabPage(brand: string | undefined): string | null {+ return brand === 'Google Chrome' ? 'chrome://new-tab-page/' : null;+}diff --git a/wxt.config.ts b/wxt.config.tsindex e747bac..8630eb2 100644--- a/wxt.config.ts+++ b/wxt.config.ts@@ -30,8 +30,11 @@ export default defineConfig({// Firefox has no sidePanel, debugger or offscreen permission, and addons.mozilla.org flags each name it does not know.// offscreen is the hidden page hands-free mode listens through once the side panel is closed.// userScripts runs a saved tool on every visit, once the user turns on Allow User Scripts.- ...(browser === 'firefox' ? [] : ['sidePanel', 'debugger', 'offscreen', 'userScripts']),+ // topSites and favicon fill the new tab page's frequent sites; <all_urls> already covers both warnings in Chrome.+ ...(browser === 'firefox' ? [] : ['sidePanel', 'debugger', 'offscreen', 'userScripts', 'topSites', 'favicon']),],+ // Firefox shows topSites as a new warning, which would hold every update until accepted, so the new tab page asks for it.+ ...(browser === 'firefox' && { optional_permissions: ['topSites'] }),host_permissions: ['<all_urls>'],// WXT writes the toolbar key only for a popup entrypoint, and the toolbar button opens the side panel instead.action: { default_title: 'Browsentic' },