Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Bot browser panel: browsed chip, pane header and trail, auto-open/close (#589)

Oleksandr Ivanchenkoa20bd0ad24dd
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 524ddd96..4c57adec 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -40,7 +40,8 @@ import {
openStepsByKwant,
turnsAwaitingStep,
} from './humanSteps';
-import { notifyBrowserPages, pageTeam, stepPage } from './browserPages';
+import { noteTitle, notifyBrowserPages, pageTeam, stepPage } from './browserPages';
+import { AUTO_CLOSE_DELAY_MS, PANE_EXIT_MS, PHONE_PANE_QUERY, type PaneOpener, shouldAutoClose, shouldAutoOpen } from './browserPanel';
import { McpSuggestionCard, type SuggestionSignInResult } from './components/McpSuggestionCard';
import { isSignInDeadEndCode } from './mcpSignInDeadEnd';
import { ConnectionSuggestionCard } from './components/ConnectionSuggestionCard';
@@ -1016,6 +1017,41 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// running turns are in and the chat's browser is active. Otherwise (an unknown, malformed or idle
// link) it shows the plain "this bot isn't browsing now" page (W-L4).
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
+ // 0.9.8 browser panel (design browser-panel/design.md D): who opened it, and whether the person used it.
+ // Only a panel a bot opened closes itself, after that bot's turn, and never while the person uses it.
+ const [paneOpenedBy, setPaneOpenedBy] = useState<PaneOpener | null>(null);
+ const [paneTouched, setPaneTouched] = useState(false);
+ const [paneUsage, setPaneUsage] = useState({ control: false, pointPending: false });
+ const [paneClosing, setPaneClosing] = useState(false);
+ const markPaneTouched = useCallback(() => setPaneTouched(true), []);
+ // Set by autoOpenPane just before it opens the panel; the open effect below reads it to mark `bot`
+ const autoOpeningRef = useRef<string | null>(null);
+ const isVmPaneOpenRef = useRef(false);
+ isVmPaneOpenRef.current = isVmPaneOpen;
+ /** A browser event opens the panel: on desktop, when it's closed. Never on a phone (the live chip is the way in). */
+ const autoOpenPane = (owner: string) => {
+ const narrow = typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_PANE_QUERY).matches;
+ if (!shouldAutoOpen({ open: isVmPaneOpenRef.current, narrow })) return;
+ autoOpeningRef.current = owner;
+ isVmPaneOpenRef.current = true;
+ setIsVmPaneOpen(true);
+ };
+ const wasPaneOpen = useRef(false);
+ useEffect(() => {
+ if (isVmPaneOpen && !wasPaneOpen.current) {
+ // Every open but a browser event's is the person's: the chip, the Bot browser button, a step, a link
+ const bot = autoOpeningRef.current;
+ setPaneOpenedBy(bot ? { by: 'bot', owner: bot } : { by: 'person', owner: activeSandboxIdRef.current || 'default' });
+ setPaneTouched(false);
+ setPaneUsage({ control: false, pointPending: false });
+ }
+ if (!isVmPaneOpen) {
+ setPaneOpenedBy(null);
+ setPaneClosing(false);
+ }
+ autoOpeningRef.current = null;
+ wasPaneOpen.current = isVmPaneOpen;
+ }, [isVmPaneOpen]);
const [liveGate, setLiveGate] = useState<null | 'pending' | 'miss'>(() => (initialTarget?.live ? 'pending' : null));
// W1: chats whose browser is active right now, from the browser events every stream gets
const [browsing, setBrowsing] = useState<BrowsingMap>({});
@@ -1678,6 +1714,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'BrowserNavigated': {
const teamId = event.data?.team_id;
notifyBrowserPages(teamId);
+ noteTitle(event.data?.url, event.data?.title);
setBrowsing((m) => noteBrowser(m, teamId, event.data?.url, Date.now()));
const currentTid = activeSandboxIdRef.current;
const k = currentKwantRef.current;
@@ -1694,7 +1731,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (isMatch) {
if (event.data?.url) setActiveUrl(event.data.url);
if (event.data?.title) setPageTitle(event.data.title);
- setIsVmPaneOpen(true);
+ autoOpenPane(activeSandboxIdRef.current || teamId || 'default');
playSfx('blip');
}
break;
@@ -1720,7 +1757,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setIsVmRunning(true);
if (event.data?.image_base64) setScreenshotBase64(event.data.image_base64);
if (event.data?.url) setActiveUrl(event.data.url);
- setIsVmPaneOpen(true);
+ autoOpenPane(activeSandboxIdRef.current || teamId || 'default');
playSfx('blip');
}
break;
@@ -3578,6 +3615,52 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}, [browsingKey]);
const globes = globeRows(liveBrowsing, runningTurns, channels, teamOfCh);
const browserNeedsYou = new Set(Object.values(humanSteps).filter((st) => st.status === 'open' && st.sandbox_target).map((st) => st.sandbox_target!));
+
+ // 0.9.8 D: close a panel the bot opened once that bot's turn ends (not the one-minute browsing expiry,
+ // which fires mid-turn while a bot reads), 600 ms later so the final step lands, unless the person uses it.
+ const openerRunning = !!paneOpenedBy && ownerStillRunning(paneOpenedBy.owner, runningTurns, channels, teamOfCh);
+ // Only a turn the app saw running ends: a panel opened before the turns are in must not close at once
+ const [openerSeenRunning, setOpenerSeenRunning] = useState(false);
+ useEffect(() => {
+ if (!paneOpenedBy) setOpenerSeenRunning(false);
+ else if (openerRunning) setOpenerSeenRunning(true);
+ }, [paneOpenedBy, openerRunning]);
+ const openerHumanStep =
+ !!paneOpenedBy && [...browserNeedsYou].some((target) => target === paneOpenedBy.owner || pageTeam(target) === paneOpenedBy.owner);
+ const paneAutoCloses =
+ isVmPaneOpen &&
+ openerSeenRunning &&
+ shouldAutoClose({
+ by: paneOpenedBy?.by ?? null,
+ touched: paneTouched,
+ control: paneUsage.control,
+ humanStep: openerHumanStep,
+ pointPending: paneUsage.pointPending,
+ running: openerRunning,
+ });
+ useEffect(() => {
+ if (!paneAutoCloses) return;
+ const still = !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ let exit: number | undefined;
+ const wait = window.setTimeout(() => {
+ if (still) {
+ setIsVmPaneOpen(false);
+ return;
+ }
+ setPaneClosing(true);
+ exit = window.setTimeout(() => setIsVmPaneOpen(false), PANE_EXIT_MS);
+ }, AUTO_CLOSE_DELAY_MS);
+ return () => {
+ window.clearTimeout(wait);
+ if (exit !== undefined) window.clearTimeout(exit);
+ setPaneClosing(false);
+ };
+ }, [paneAutoCloses]);
+ /** The person opens the panel (a reply's chip): open it, or make a panel the bot opened theirs. */
+ const openPaneByPerson = () => {
+ if (isVmPaneOpen) setPaneOpenedBy({ by: 'person', owner: activeSandboxId });
+ else setIsVmPaneOpen(true);
+ };
const describeOwner = (owner: string) => {
const t = teams.find((x) => x.id === owner);
if (t) return { kind: 'team' as const, label: t.name };
@@ -4179,6 +4262,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
vmSolveRequest={solveRequest}
vmPagePick={pagePick}
vmBotNames={kwantNames}
+ vmRunning={ownerStillRunning(activeSandboxId, runningTurns, channels, teamOfCh)}
+ onVmOpenByPerson={openPaneByPerson}
+ onVmTouch={markPaneTouched}
+ onVmUsage={setPaneUsage}
+ vmClosing={paneClosing}
vmShowOnceBot={currentKwant && !currentTeam ? { id: currentKwant.id, name: currentKwant.name } : undefined}
pinned={pinned}
onEditInstructions={
diff --git a/frontend/src/activity.ts b/frontend/src/activity.ts
index 1229e624..ae20c781 100644
--- a/frontend/src/activity.ts
+++ b/frontend/src/activity.ts
@@ -16,6 +16,8 @@ export interface ActivityStep {
/** The thinking step's whole text (set once it ends; live text is in `LiveActivity.thinking`). */
text?: string;
ref_id?: string;
+ /** A browser open/navigate step: the title the page reported once it loaded (server 0.9.8+, optional). */
+ page_title?: string;
started_at: string;
ended_at?: string;
duration_ms?: number;
@@ -54,6 +56,7 @@ export function parseStep(raw: unknown): ActivityStep | null {
detail: str(s.detail),
text: str(s.text),
ref_id: str(s.ref_id),
+ page_title: str(s.page_title),
started_at: typeof s.started_at === 'string' ? s.started_at : '',
ended_at: str(s.ended_at),
duration_ms: typeof s.duration_ms === 'number' ? s.duration_ms : undefined,
diff --git a/frontend/src/browserPages.ts b/frontend/src/browserPages.ts
index a11b293d..ffd9abae 100644
--- a/frontend/src/browserPages.ts
+++ b/frontend/src/browserPages.ts
@@ -154,3 +154,128 @@ export function parsePageList(raw: unknown): BrowserPageList | null {
pages,
};
}
+
+// ---------- Browser panel (0.9.8, design browser-panel/design.md A, B) ----------
+
+/** The bot browser's own open/navigate tools. WebFetch and fetch never touch it, so they don't count. */
+export const BROWSER_PAGE_TOOLS: readonly string[] = ['browser_open', 'browser_navigate', 'navigate', 'open_url'];
+
+/** A tool's own name: `mcp__kwnt__browser_open` → `browser_open`. */
+export function ownToolName(tool: string | null | undefined): string {
+ if (!tool) return '';
+ const i = tool.lastIndexOf('__');
+ return (i >= 0 ? tool.slice(i + 2) : tool).toLowerCase();
+}
+
+/** The fields of an activity step the trail reads (a saved reply's or a running turn's). */
+export interface PageStep {
+ kind: string;
+ status?: string;
+ tool?: string;
+ detail?: string;
+ /** The title the browser reported once the page loaded (server 0.9.8+, optional). */
+ page_title?: string;
+ started_at: string;
+}
+
+/** One row of the trail: a page the bot opened in its browser. */
+export interface ReplyPage {
+ /** When the bot opened it (the newest visit), ISO time from the step. */
+ at: string;
+ url: string;
+ host: string;
+ /** The title the step reported (page_title), if any. Resolve the shown title at render with pageTitleOf,
+ * so a title the app sees later (live stream, browser_navigated) still shows on a memoized trail. */
+ stepTitle: string | null;
+}
+
+/** An http(s) address without its #hash, or null when it isn't one. */
+function pageAddress(raw: string | null | undefined): URL | null {
+ if (!raw) return null;
+ try {
+ const u = new URL(raw.trim());
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
+ u.hash = '';
+ return u;
+ } catch {
+ return null;
+ }
+}
+
+// Titles the app saw live (`browser_navigated` carries one), per address, for a session.
+const TITLE_MAX = 200;
+const titles = new Map<string, string>();
+
+/** Remembers a page's title (the newest 200 addresses). */
+export function noteTitle(url: string | null | undefined, title: string | null | undefined): void {
+ const u = pageAddress(url);
+ const t = title?.trim();
+ if (!u || !t || t.startsWith('about:')) return;
+ const key = u.href;
+ titles.delete(key);
+ titles.set(key, t);
+ while (titles.size > TITLE_MAX) titles.delete(titles.keys().next().value as string);
+}
+
+/** A title the app saw for this address, if any. */
+export function titleFor(url: string | null | undefined): string | null {
+ const u = pageAddress(url);
+ return (u && titles.get(u.href)) || null;
+}
+
+/** For tests: forget every title. */
+export function clearTitles(): void {
+ titles.clear();
+}
+
+/** The trail's line 1: the step's page title, else one seen live, else the path ("/" reads as the host). */
+export function pageTitleOf(url: string, stepTitle?: string | null): string {
+ const t = stepTitle?.trim();
+ if (t) return t;
+ const seen = titleFor(url);
+ if (seen) return seen;
+ const u = pageAddress(url);
+ if (!u) return url;
+ const path = decodeURI(u.pathname).replace(/\/+$/, '');
+ return path ? path + u.search : pageHost(u.href) ?? u.host;
+}
+
+/** Whether a step opened a page in the bot's browser: an own open/navigate tool with an address that didn't fail. */
+export function isPageStep(s: PageStep): boolean {
+ return s.kind === 'tool' && s.status !== 'failed' && BROWSER_PAGE_TOOLS.includes(ownToolName(s.tool)) && !!pageAddress(s.detail);
+}
+
+/** The pages a reply opened in the bot's browser: distinct addresses (hash stripped), newest first. */
+export function pagesOfReply(steps: readonly PageStep[] | null | undefined): ReplyPage[] {
+ const out = new Map<string, { at: string; url: string; host: string; stepTitle: string | null }>();
+ for (const s of steps ?? []) {
+ if (!isPageStep(s)) continue;
+ const u = pageAddress(s.detail)!;
+ const key = u.href;
+ // A later visit moves the page up; the newest reported title wins
+ const prev = out.get(key);
+ out.delete(key);
+ out.set(key, { at: s.started_at, url: key, host: pageHost(key) ?? u.host, stepTitle: s.page_title?.trim() || prev?.stepTitle || null });
+ }
+ return [...out.values()].reverse();
+}
+
+/** The chip's words: "Ben opened 2 pages", or while browsing the host and the count from 2 up. */
+export function browsedChipText(botName: string, pages: readonly ReplyPage[], live: boolean): { lead: string; host: string | null; count: string | null; label: string } {
+ const n = pages.length;
+ if (live) {
+ const host = pages[0]?.host ?? null;
+ return { lead: `${botName} is on`, host, count: n >= 2 ? `${n} pages` : null, label: `Watch ${botName}'s browser` };
+ }
+ return { lead: `${botName} opened ${n} ${n === 1 ? 'page' : 'pages'}`, host: null, count: null, label: `Show the ${n === 1 ? 'page' : `${n} pages`} ${botName} opened` };
+}
+
+/** "10:45" in the person's locale, without AM/PM (the panel header has the full time). */
+export function trailTime(iso: string, locale?: string): string {
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '';
+ return d
+ .toLocaleTimeString(locale ?? [], { hour: 'numeric', minute: '2-digit' })
+ .replace(/\s?[AaPp]\.?\s?[Mm]\.?$/, '')
+ .trim();
+}
diff --git a/frontend/src/browserPanel.ts b/frontend/src/browserPanel.ts
new file mode 100644
index 00000000..26652e4c
--- /dev/null
+++ b/frontend/src/browserPanel.ts
@@ -0,0 +1,41 @@
+// 0.9.8 browser panel (design browser-panel/design.md D): when the panel closes itself.
+
+export interface PaneOpener {
+ /** `bot`: a browser event opened it; `person`: a chip, the Bot browser button, a step, a link. */
+ by: 'bot' | 'person';
+ /** The browser's owner (a bot, team or channel id) whose turn opened it. */
+ owner: string;
+}
+
+/** After the owner's turn ends, this long for the final step to land before the panel closes. */
+export const AUTO_CLOSE_DELAY_MS = 600;
+/** The close animation (opacity and a short slide), instant under reduced motion. */
+export const PANE_EXIT_MS = 160;
+
+/**
+ * Whether the panel closes itself now. Only a panel a bot opened closes, once that bot's turn has
+ * ended, and never while the person is using it: touched, in control, a step waiting on them, or
+ * Point picks still pending. A panel the person opened never closes itself; it shows Finished.
+ */
+export function shouldAutoClose(s: { by: PaneOpener['by'] | null; touched: boolean; control: boolean; humanStep: boolean; pointPending: boolean; running: boolean }): boolean {
+ return s.by === 'bot' && !s.running && !s.touched && !s.control && !s.humanStep && !s.pointPending;
+}
+
+/** Phone width: the panel is a bottom sheet there and never opens by itself. */
+export const PHONE_PANE_QUERY = '(max-width: 639px)';
+
+/** Whether a browser event may open the panel: never on a phone (the live chip is the way in), and not when it's open. */
+export function shouldAutoOpen(s: { open: boolean; narrow: boolean }): boolean {
+ return !s.open && !s.narrow;
+}
+
+/** The panel header's status line: "Browsing now", "Finished 10:46 PM", or "Idle". */
+export function paneStatus(s: { running: boolean; finishedAt: string | null; locale?: string }): { kind: 'browsing' | 'finished' | 'idle'; text: string } {
+ if (s.running) return { kind: 'browsing', text: 'Browsing now' };
+ if (s.finishedAt) {
+ const d = new Date(s.finishedAt);
+ if (!Number.isNaN(d.getTime())) return { kind: 'finished', text: `Finished ${d.toLocaleTimeString(s.locale ?? [], { hour: 'numeric', minute: '2-digit' })}` };
+ return { kind: 'finished', text: 'Finished' };
+ }
+ return { kind: 'idle', text: 'Idle' };
+}
diff --git a/frontend/src/components/ActivityList.tsx b/frontend/src/components/ActivityList.tsx
index 86a1123a..0433f5d8 100644
--- a/frontend/src/components/ActivityList.tsx
+++ b/frontend/src/components/ActivityList.tsx
@@ -196,7 +196,7 @@ const Steps: React.FC<{ steps: ActivityStep[]; live?: LiveActivity; dropped?: nu
* one 44 px row, "Steps · 2 ▸", that opens to the same list; the engine's note (what it can't show of
* its thinking) moves behind an ⓘ in that row, since the working strip already says the bot works.
*/
-export const LiveActivityList: React.FC<{ live: LiveActivity; idBase: string; compact?: boolean }> = ({ live, idBase, compact = false }) => {
+export const LiveActivityList: React.FC<{ live: LiveActivity; idBase: string; compact?: boolean; lead?: React.ReactNode }> = ({ live, idBase, compact = false, lead }) => {
const { steps } = live;
const [open, setOpen] = useState(false);
const [noteOpen, setNoteOpen] = useState(false);
@@ -216,6 +216,7 @@ export const LiveActivityList: React.FC<{ live: LiveActivity; idBase: string; co
const noteId = `${idBase}-note`;
return (
<section aria-label="What the bot is doing" data-steps-compact="" className="mb-2 w-full max-w-2xl rounded-xl border border-zinc-700/60 bg-zinc-900/60 overflow-hidden">
+ {lead && <div className="flex items-center min-h-[44px] px-2.5 border-b border-zinc-700/40">{lead}</div>}
<div className="flex items-center">
<button
type="button"
@@ -270,6 +271,7 @@ export const LiveActivityList: React.FC<{ live: LiveActivity; idBase: string; co
· {work} {work === 1 ? 'step' : 'steps'}
</span>
</p>
+ {lead && <div className="px-3 pt-1 pb-2">{lead}</div>}
{announce}
<div className="max-h-[22rem] overflow-y-auto">
<Steps steps={steps} live={live} id={`${idBase}-live`} />
diff --git a/frontend/src/components/BrowsedChip.tsx b/frontend/src/components/BrowsedChip.tsx
new file mode 100644
index 00000000..586096ac
--- /dev/null
+++ b/frontend/src/components/BrowsedChip.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import { ChevronRight, Globe } from 'lucide-react';
+import { browsedChipText, pagesOfReply, type PageStep } from '../browserPages';
+
+/**
+ * 0.9.8 (design browser-panel/design.md A): the pages a reply opened in the bot's browser, as a chip.
+ * Live: "● Ben is on roastco.example.com · 2 pages ›" (first row of the Working block).
+ * After: "🌐 Ben opened 2 pages ›" (first item of the action row). No chip when the reply opened none.
+ */
+export const BrowsedChip = React.forwardRef<
+ HTMLButtonElement,
+ { botName: string; steps: readonly PageStep[] | null | undefined; live: boolean; phone?: boolean; onOpen: () => void }
+>(({ botName, steps, live, phone = false, onOpen }, ref) => {
+ const pages = pagesOfReply(steps);
+ if (pages.length === 0) return null;
+ const t = browsedChipText(botName, pages, live);
+ const tone = live ? 'bg-emerald-400/[0.08] border-emerald-400/40' : 'bg-sky-400/10 border-sky-400/35';
+ return (
+ <button
+ ref={ref}
+ type="button"
+ onClick={onOpen}
+ aria-label={t.label}
+ data-browsed-chip={live ? 'live' : 'finished'}
+ className={`inline-flex max-w-full min-w-0 items-center gap-1.5 ${phone ? 'h-8' : 'h-7'} pl-2 pr-2.5 rounded-full border ${tone} text-[13px] font-medium text-zinc-100 transition-colors hover:brightness-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 focus-visible:ring-offset-2 focus-visible:ring-offset-[#120e26]`}
+ >
+ {live ? (
+ <span aria-hidden="true" className="shrink-0 w-2 h-2 rounded-full bg-emerald-400 ring-[3px] ring-emerald-400/20 animate-[pulse_1.2s_ease-in-out_infinite] motion-reduce:animate-none" />
+ ) : (
+ <Globe size={14} aria-hidden="true" className="shrink-0 text-sky-300" />
+ )}
+ <span className="shrink-0">{t.lead}</span>
+ {t.host && <span className={`min-w-0 truncate font-normal text-zinc-300 ${phone ? 'max-w-[96px]' : 'max-w-[160px]'}`}>{t.host}</span>}
+ {t.count && <span className="shrink-0 font-normal text-zinc-300">· {t.count}</span>}
+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 text-zinc-400" />
+ </button>
+ );
+});
+BrowsedChip.displayName = 'BrowsedChip';
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 6f4d1f52..ad58602f 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -38,6 +38,8 @@ import { AllowedFromTelegram, ViaTelegram } from './TelegramMarks';
import { HumanStep, HumanStepMeta, parseHumanStepMeta } from '../humanSteps';
import { LiveActivity, hasThinkingText, parseActivityMeta } from '../activity';
import { LiveActivityList, SavedActivityList } from './ActivityList';
+import { BrowsedChip } from './BrowsedChip';
+import { pagesOfReply, type ReplyPage } from '../browserPages';
import { FailoverNote, ReplyMeta } from './ReplyMeta';
import { assignSwitchNotes, liveSwitchNote, type SwitchNote } from '../failoverNotes';
import { savedFailoverHandoff, savedFailoverNotice } from '../failover';
@@ -273,6 +275,16 @@ export interface ChatViewProps {
vmBotNames?: Record<string, string>;
/** Show it once: the single bot this chat's browser belongs to (absent in teams and channels). */
vmShowOnceBot?: { id: string; name: string };
+ /** 0.9.8 browser panel: this chat's browser owner has a turn running (Live / Browsing now). */
+ vmRunning?: boolean;
+ /** 0.9.8: the person opened the panel (a chip): opens it, or marks a panel the bot opened as theirs. */
+ onVmOpenByPerson?: () => void;
+ /** 0.9.8: the person used the panel, so it won't close itself. */
+ onVmTouch?: () => void;
+ /** 0.9.8: control and pending Point picks, which also keep it open. */
+ onVmUsage?: (u: { control: boolean; pointPending: boolean }) => void;
+ /** 0.9.8: the panel is playing its close animation. */
+ vmClosing?: boolean;
/** Pinned team/channel instructions, shown collapsed above the messages. */
pinned?: PinnedItem[];
/** Opens the channel's instructions editor; only for channels. */
@@ -524,6 +536,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
vmPagePick,
vmBotNames,
vmShowOnceBot,
+ vmRunning = false,
+ onVmOpenByPerson,
+ onVmTouch,
+ onVmUsage,
+ vmClosing = false,
pinned = [],
onEditInstructions,
highlightMessageId,
@@ -578,6 +595,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
// rows while in use. Desktop never changes.
const phone = useMedia(PHONE_QUERY);
const touch = useMedia(TOUCH_QUERY);
+
const [composerFocused, setComposerFocused] = useState(false);
const kbd = keyboardMode({ phone, touch, focused: composerFocused });
const [fieldWidth, setFieldWidth] = useState(0);
@@ -661,6 +679,52 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (home?.kind === 'bot' && home.bot) all.push({ id: home.bot.id, name: home.bot.name });
return all;
}, [activeKwants, teamMembers, home]);
+
+ // ---------- 0.9.8 browser panel (design browser-panel/design.md A, B) ----------
+ // The trail the panel shows: the reply whose chip was tapped; else the running turn's; else the newest reply that browsed.
+ const [trailFrom, setTrailFrom] = useState<string | null>(null);
+ const liveTurnId = liveActivity?.turnId ?? null;
+ useEffect(() => {
+ // A new turn browses: the panel follows it, not an older chip's reply
+ if (liveTurnId) setTrailFrom(null);
+ }, [liveTurnId]);
+ const liveSpeaker = streamingSpeakerName || title;
+ const livePages = useMemo(() => pagesOfReply(liveActivity?.steps), [liveActivity?.steps]);
+ const savedTrail = useMemo((): { id: string; bot: string; pages: ReplyPage[] } | null => {
+ const from = (m: ChatMessage) => {
+ if (m.sender_role !== 'kwant' || !m.meta) return null;
+ const pages = pagesOfReply(parseActivityMeta(m.meta)?.steps);
+ return pages.length ? { id: m.id, bot: botDisplayName(m.sender_id, knownBots), pages } : null;
+ };
+ if (trailFrom) {
+ const m = messages.find((x) => x.id === trailFrom);
+ const t = m && from(m);
+ if (t) return t;
+ }
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const t = from(messages[i]);
+ if (t) return t;
+ }
+ return null;
+ }, [messages, trailFrom, knownBots]);
+ const showLiveTrail = !trailFrom && livePages.length > 0;
+ const paneTrail = showLiveTrail ? livePages : savedTrail?.pages ?? [];
+ const paneBot = showLiveTrail ? liveSpeaker : savedTrail?.bot ?? (home?.kind === 'bot' ? home.bot?.name ?? null : null);
+ // "Finished 10:46 PM": when this chat's turn ended here, else the newest page of the shown trail
+ const [endedAt, setEndedAt] = useState<string | null>(null);
+ const wasRunning = useRef(vmRunning);
+ useEffect(() => {
+ if (wasRunning.current && !vmRunning) setEndedAt(new Date().toISOString());
+ wasRunning.current = vmRunning;
+ }, [vmRunning]);
+ useEffect(() => setEndedAt(null), [teamId]);
+ const paneFinishedAt = trailFrom ? paneTrail[0]?.at ?? null : endedAt ?? paneTrail[0]?.at ?? null;
+ const openBrowserFor = (msgId: string | null) => {
+ playSfx('click');
+ setTrailFrom(msgId);
+ if (onVmOpenByPerson) onVmOpenByPerson();
+ else if (!vmOpen) toggleVm();
+ };
// Each routed reply's question: the person's latest saved message before it ("Wrong bot?").
const questionOf = useMemo(() => questionsOfReplies(messages), [messages]);
const activeTeams = teamsProp || internalTeams;
@@ -1677,9 +1741,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
{!isUser && msg.tool_calls && !savedActivity && <ToolCallsList raw={msg.tool_calls} />}
+ {/* 0.9.8: on a phone the browsed chip gets its own 44 px row above the action row (it would wrap) */}
+ {!isUser && !filesOnly && phone && savedActivity && (
+ <div className="mt-1 flex items-center min-h-[44px] max-w-full min-w-0">
+ <BrowsedChip botName={displayName} steps={savedActivity.steps} live={false} phone onOpen={() => openBrowserFor(msg.id)} />
+ </div>
+ )}
{/* Action row: icon chips; the smart-result actions portal in after Copy */}
{!isUser && !filesOnly && (
<div className="mt-2 flex flex-wrap items-center gap-2 text-zinc-400 text-xs max-w-full min-w-0">
+ {!phone && savedActivity && (
+ <BrowsedChip botName={displayName} steps={savedActivity.steps} live={false} onOpen={() => openBrowserFor(msg.id)} />
+ )}
<button
type="button"
onClick={() => handleCopy(text, msg.id)}
@@ -2245,7 +2318,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
{liveNote && <FailoverNote text={liveNote} />}
- {liveActivity && <LiveActivityList live={liveActivity} idBase={`live-${liveActivity.turnId}`} compact={phone} />}
+ {liveActivity && (
+ <LiveActivityList
+ live={liveActivity}
+ idBase={`live-${liveActivity.turnId}`}
+ compact={phone}
+ lead={
+ livePages.length > 0 ? (
+ <BrowsedChip botName={liveSpeaker} steps={liveActivity.steps} live phone={phone} onOpen={() => openBrowserFor(null)} />
+ ) : undefined
+ }
+ />
+ )}
{streamingThinking && (
<div className="mb-2 p-2.5 rounded-xl bg-violet-950/20 border border-violet-500/20 text-xs text-violet-300/90 flex items-center gap-2 animate-pulse motion-reduce:animate-none max-w-full">
@@ -2744,6 +2828,13 @@ export const ChatView: React.FC<ChatViewProps> = ({
botNames={vmBotNames}
showOnceBot={vmShowOnceBot}
point={pointSink}
+ running={vmRunning}
+ finishedAt={paneFinishedAt}
+ browsingBot={paneBot}
+ trail={paneTrail}
+ onTouch={onVmTouch}
+ onUsage={onVmUsage}
+ closing={vmClosing}
/>
</div>
{layerPhase && (
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index f40d5d69..2924d307 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -12,14 +12,16 @@ import {
Laptop,
Puzzle,
CheckCircle2,
- Eye,
Hand,
Crosshair,
+ Maximize2,
} from 'lucide-react';
import { playSfx } from '../audio/chiptune';
import { BOT_BUSY_TEXT, HELD_BY_PERSON_TEXT, useBrowserStream } from '../useBrowserStream';
import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, SignInLine, useComputerMode } from './ComputerModeSwitch';
-import { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMode';
+import { browserFooterLabel, browserOwnerWord, isBlankPage, showsLocalWindow } from '../computerMode';
+import { paneStatus } from '../browserPanel';
+import { ModernAvatar } from './ModernAvatar';
import { loginMatchesPage } from '../savedPasswords';
import { PendingLoginPrompt, SavedPasswordsPanel, useSavedPasswords } from './SavedPasswordsPanel';
import { usePasswordStore } from './PasswordStorePanel';
@@ -32,7 +34,7 @@ import { showOnce, showOnceStore, useShowOnce } from '../showOnce';
import { RecordStepsButton, RecordingStrip } from './ShowOnce';
import { PointLayer, PointSink } from './PointLayer';
import { POINT_COPY, footerText } from '../point';
-import { choosePage, pageTeam, shownPage, stepPage } from '../browserPages';
+import { choosePage, noteTitle, pageTeam, pageTitleOf, shownPage, stepPage, trailTime, type ReplyPage } from '../browserPages';
import { useBrowserPages } from '../useBrowserPages';
import { BrowserPageStrip } from './BrowserPageStrip';
@@ -111,6 +113,20 @@ export interface VirtualMachinePaneProps {
pagePick?: { page: string; n: number } | null;
/** Bot names by id, for the page strip. */
botNames?: Record<string, string>;
+ /** 0.9.8: the browser's owner has a turn running now (header "Browsing now", pill "Live"). */
+ running?: boolean;
+ /** 0.9.8: when that turn ended, for "Finished 10:46 PM"; null with no run since the app opened (Idle). */
+ finishedAt?: string | null;
+ /** 0.9.8: the bot browsing ("Ben's browser") when the page on screen isn't a bot's job page. */
+ browsingBot?: string | null;
+ /** 0.9.8: the pages the reply opened (the tapped chip's, else the running turn's), newest first. */
+ trail?: ReplyPage[];
+ /** 0.9.8: the person used the panel (a tab, Point, Take over, the trail, Enlarge, the address bar). */
+ onTouch?: () => void;
+ /** 0.9.8: what keeps a bot-opened panel open after the turn: control, Point picks waiting to be sent. */
+ onUsage?: (u: { control: boolean; pointPending: boolean }) => void;
+ /** 0.9.8: playing the close animation (the panel closes itself in a moment). */
+ closing?: boolean;
}
type PaneTab = 'browser' | 'terminal' | 'vault';
@@ -160,6 +176,13 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
showOnceBot,
pagePick = null,
botNames,
+ running = false,
+ finishedAt = null,
+ browsingBot = null,
+ trail = [],
+ onTouch,
+ onUsage,
+ closing = false,
}) => {
const [activeTab, setActiveTab] = useState<PaneTab>(() => chosenPaneTab(teamId));
useEffect(() => rememberPaneTab(teamId, activeTab), [teamId, activeTab]);
@@ -217,6 +240,11 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
const botName = useCallback((id: string) => botNames?.[id], [botNames]);
// Who the page on screen belongs to: its bot on a job page, else the team ("Architect needs you to sign in")
const pageBot = (pageInfo?.job && pageInfo.kwant_id && botNames?.[pageInfo.kwant_id]) || teamName;
+ // 0.9.8 header and footer: "Ben's browser", or "The team's browser" when no bot owns the page on screen
+ const whoBrowses = (pageInfo?.job && pageInfo.kwant_id && botNames?.[pageInfo.kwant_id]) || browsingBot || null;
+ const whose = browserOwnerWord(whoBrowses);
+ const paneTitle = `${whose.charAt(0).toUpperCase()}${whose.slice(1)} browser`;
+ const touch = useCallback(() => onTouch?.(), [onTouch]);
// Interactive Remote Control State
const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending, chosenPage);
@@ -250,6 +278,10 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
useEffect(() => {
if (stream.location?.url) setInputUrl(stream.location.url);
}, [stream.location]);
+ // The pane's own stream knows each page's title too, so the trail can name pages the bot opened
+ useEffect(() => {
+ noteTitle(stream.location?.url, stream.location?.title);
+ }, [stream.location?.url, stream.location?.title]);
useEffect(() => {
setInputUrl(activeUrl);
@@ -423,33 +455,149 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
pointButton.current?.focus();
}, []);
+ // 0.9.8 D: a panel the bot opened stays open while the person controls it or has picks to send
+ const pointPending = (point?.picks ?? 0) > 0;
+ useEffect(() => onUsage?.({ control: isControlMode, pointPending }), [onUsage, isControlMode, pointPending]);
+
+ // 0.9.8 C: Enlarge shows the same frame big, view only
+ const [enlarged, setEnlarged] = useState(false);
+ const enlargeClose = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ if (!enlarged) return;
+ enlargeClose.current?.focus();
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ setEnlarged(false);
+ }
+ };
+ window.addEventListener('keydown', onKey, true);
+ return () => window.removeEventListener('keydown', onKey, true);
+ }, [enlarged]);
+ useEffect(() => {
+ if (enlarged && !frameSrc) setEnlarged(false);
+ }, [enlarged, frameSrc]);
+
+ // 0.9.8 E: the phone sheet takes focus to its ✕ and gives it back (to the chip) when it closes
+ const closeButton = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ if (!isOpen || !narrow) return;
+ const before = document.activeElement as HTMLElement | null;
+ closeButton.current?.focus();
+ return () => {
+ if (before && before.isConnected && before !== document.body) before.focus();
+ };
+ }, [isOpen, narrow]);
+ // Dragging the grabber down more than 96 px closes the sheet; a tap does nothing
+ const [drag, setDrag] = useState<{ y0: number; dy: number } | null>(null);
+ const dragging = drag && drag.dy > 0 ? drag.dy : 0;
+
if (!isOpen) return null;
const switching = !!switcher && switcher.entries.length >= 2;
+ const status = paneStatus({ running, finishedAt });
+ const live = status.kind === 'browsing';
+ const finished = status.kind === 'finished';
+ const close = () => {
+ playSfx('click');
+ onClose();
+ };
+ const statusLine = (
+ <p className="text-[11px] text-zinc-400 truncate flex items-center gap-1" aria-live="polite" data-pane-status={status.kind}>
+ {live && <span aria-hidden="true" className="shrink-0 w-[7px] h-[7px] rounded-full bg-emerald-400" />}
+ <span className="truncate">
+ {status.text} · @{teamName}
+ </span>
+ </p>
+ );
+ const pointButtonEl =
+ pointShown || (point && takeover && !isWindow) ? (
+ <button
+ ref={pointButton}
+ type="button"
+ data-point-button=""
+ aria-pressed={pointOn}
+ aria-label={POINT_COPY.buttonName}
+ title={takeover ? POINT_COPY.handBack : POINT_COPY.buttonName}
+ disabled={takeover}
+ onClick={() => {
+ playSfx('click');
+ touch();
+ setPointing((p) => !p);
+ }}
+ className={`${narrow ? 'h-11 flex-1 justify-center' : 'h-8'} px-3 rounded-[10px] inline-flex items-center gap-1.5 text-[13px] font-semibold whitespace-nowrap cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 border ${
+ pointOn ? 'bg-violet-600 border-violet-400 text-white ring-[3px] ring-violet-500/25' : 'border-[#3f3868] text-zinc-200 hover:bg-white/5'
+ }`}
+ >
+ <Crosshair size={14} aria-hidden="true" />
+ {POINT_COPY.button}
+ </button>
+ ) : null;
return (
- // On a phone the panel is the whole screen (0.7.7 nice-to-have 5): a 384 px column beside the chat left the chat a sliver.
+ // 0.9.8 E: on a phone the panel is a 70 % bottom sheet over a scrim; the chat stays readable above it.
+ <>
+ {narrow && (
+ <div
+ aria-hidden="true"
+ data-vm-scrim=""
+ onClick={close}
+ className={`fixed inset-0 z-[59] bg-[rgb(5_3_14/0.42)] transition-opacity duration-150 motion-reduce:transition-none ${closing ? 'opacity-0' : 'opacity-100'}`}
+ />
+ )}
<div
data-vm-pane=""
- className={`${narrow ? 'fixed inset-0 z-[60] w-full h-[100dvh] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]' : 'w-96 border-l border-zinc-800 h-full z-30'} bg-zinc-950 flex flex-col shadow-2xl select-none animate-in slide-in-from-right duration-200`}
+ data-pane-closing={closing || undefined}
+ role={narrow ? 'dialog' : undefined}
+ aria-modal={narrow ? true : undefined}
+ aria-label={narrow ? paneTitle : undefined}
+ style={dragging ? { transform: `translateY(${dragging}px)`, transition: 'none' } : undefined}
+ className={`${
+ narrow
+ ? `fixed inset-x-0 bottom-0 z-[60] h-[70dvh] rounded-t-[20px] border-t border-[#3a3266] bg-[#0d0a1d] shadow-[0_-12px_40px_rgba(0,0,0,.5)] pb-[env(safe-area-inset-bottom)] overflow-hidden animate-in slide-in-from-bottom duration-200 ${closing ? 'translate-y-full opacity-0' : ''}`
+ : `w-96 border-l border-zinc-800 h-full z-30 bg-zinc-950 shadow-2xl animate-in slide-in-from-right duration-200 ${closing ? 'translate-x-4 opacity-0' : ''}`
+ } flex flex-col select-none transition-[transform,opacity] ease-out duration-150 motion-reduce:transition-none motion-reduce:animate-none`}
>
- {/* Top Header */}
- <div className="h-14 border-b border-zinc-800 px-4 flex items-center justify-between gap-2 bg-zinc-900/60">
+ {narrow && (
+ <div
+ data-vm-grabber=""
+ aria-hidden="true"
+ className="shrink-0 pt-2 pb-1 touch-none cursor-grab"
+ onPointerDown={(e) => {
+ (e.target as HTMLElement).setPointerCapture?.(e.pointerId);
+ setDrag({ y0: e.clientY, dy: 0 });
+ }}
+ onPointerMove={(e) => drag && setDrag({ y0: drag.y0, dy: e.clientY - drag.y0 })}
+ onPointerUp={() => {
+ const far = !!drag && drag.dy > 96;
+ setDrag(null);
+ if (far) close();
+ }}
+ onPointerCancel={() => setDrag(null)}
+ >
+ <div className="mx-auto w-9 h-1 rounded-full bg-[#4b4478]" />
+ </div>
+ )}
+ {/* Header: whose browser it is and whether it's browsing now (0.9.8 C) */}
+ <div className={`${narrow ? 'h-[52px]' : 'h-14 bg-zinc-900/60'} border-b border-zinc-800 px-4 flex items-center justify-between gap-2`}>
<div className="flex items-center gap-2 min-w-0">
- <div className={`shrink-0 w-2.5 h-2.5 rounded-full ${browserReady ? 'bg-emerald-400 animate-pulse' : 'bg-zinc-500'}`} />
+ <ModernAvatar role={whoBrowses ?? teamName} name={whoBrowses ?? teamName} size={24} modelBadge={false} />
<div className="min-w-0">
{switching && !narrow ? (
<BrowserSwitcherMenu
entries={switcher!.entries}
current={switcher!.current}
- onPick={switcher!.onPick}
+ onPick={(owner) => {
+ touch();
+ switcher!.onPick(owner);
+ }}
disabled={isControlMode}
- title={`@${teamName}`}
- sub={<p className="text-[10px] text-zinc-400 truncate">{isLocal ? 'Your Chrome' : 'Live Chromium'}</p>}
+ title={paneTitle}
+ sub={statusLine}
/>
) : (
<>
- <div className="text-xs font-semibold text-zinc-100 truncate" title={`@${teamName}`}>@{teamName}</div>
- <p className="text-[10px] text-zinc-400 truncate">{isLocal ? 'Your Chrome' : 'Live Chromium'}</p>
+ <div className="text-[13px] font-semibold text-zinc-100 truncate" data-pane-title="">{paneTitle}</div>
+ {statusLine}
</>
)}
</div>
@@ -458,98 +606,19 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<div className="flex items-center gap-1 shrink-0">
<ComputerModeChip api={computer} />
<OpenWindowButton api={computer} />
-
- {pointShown || (point && takeover && !isWindow) ? (
- <button
- ref={pointButton}
- type="button"
- data-point-button=""
- aria-pressed={pointOn}
- aria-label={POINT_COPY.buttonName}
- title={takeover ? POINT_COPY.handBack : POINT_COPY.buttonName}
- disabled={takeover}
- onClick={() => {
- playSfx('click');
- setPointing((p) => !p);
- }}
- className={`${narrow ? 'h-11' : 'h-[30px]'} px-2.5 rounded-[10px] inline-flex items-center gap-1.5 text-[13px] font-semibold whitespace-nowrap cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 border ${
- pointOn ? 'bg-violet-600 border-violet-400 text-white ring-[3px] ring-violet-500/25' : 'border-[#3f3868] text-zinc-200 hover:bg-[#2c2552]'
- }`}
- >
- <Crosshair size={14} aria-hidden="true" />
- {POINT_COPY.button}
- </button>
- ) : null}
-
- {/* Take over: always there while a browser exists, so keyboard users have a way in.
- On a phone with Point showing, the view's own Take over is the way in (no room for both). */}
- {!isWindow && !(narrow && pointShown && !isControlMode) && (
- <button
- type="button"
- onClick={() => (isControlMode ? handBack() : takeOver())}
- disabled={!stream.connected || waitingForBot}
- title={isControlMode ? 'Hand the browser back to the bot' : `Take over @${teamName}'s browser`}
- data-takeover-button
- className={`h-[30px] px-2.5 rounded-[10px] inline-flex items-center gap-1.5 text-[13px] font-semibold whitespace-nowrap cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 ${
- isControlMode ? 'border border-[#3f3868] bg-[rgb(44_37_82/0.8)] text-zinc-100' : 'bg-control text-control-ink hover:brightness-110'
- }`}
- >
- {isControlMode ? <Hand size={14} aria-hidden="true" /> : <MousePointerClick size={14} aria-hidden="true" />}
- {isControlMode ? 'Hand back' : 'Take over'}
- </button>
- )}
-
<button
+ ref={closeButton}
type="button"
- onClick={() => {
- playSfx('click');
- setActiveTab((curr) => (curr === 'vault' ? 'browser' : 'vault'));
- }}
- title={`Saved logins (${savedCount})`}
- aria-label={`Saved logins (${savedCount})`}
- className={`p-1.5 rounded-md transition-colors cursor-pointer relative ${
- activeTab === 'vault'
- ? 'text-sky-400 bg-sky-500/10'
- : 'text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800'
- }`}
+ onClick={close}
+ aria-label="Close"
+ title="Close"
+ className={`${narrow ? 'w-11 h-11' : 'w-[30px] h-[30px]'} inline-flex items-center justify-center rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300`}
>
- <Key size={13} />
- {savedCount > 0 && (
- <span className="absolute -top-1 -right-1 min-w-3.5 h-3.5 px-0.5 bg-sky-500 text-[9px] font-bold text-zinc-950 rounded-full flex items-center justify-center">
- {savedCount}
- </span>
- )}
- </button>
-
- {onRefresh && (
- <button
- type="button"
- onClick={() => {
- playSfx('click');
- onRefresh();
- passwords.reload();
- }}
- title="Refresh Screenshot & Passwords"
- className="p-1.5 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors cursor-pointer"
- >
- <RefreshCw size={13} />
- </button>
- )}
-
- <button
- type="button"
- onClick={() => {
- playSfx('click');
- onClose();
- }}
- title="Close VM Pane"
- className="p-1.5 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors cursor-pointer"
- >
- <X size={15} />
+ <X size={narrow ? 18 : 15} aria-hidden="true" />
</button>
</div>
</div>
- {switching && narrow && <BrowserSwitcherRow entries={switcher!.entries} current={switcher!.current} onPick={switcher!.onPick} disabled={isControlMode} />}
+ {switching && narrow && <BrowserSwitcherRow entries={switcher!.entries} current={switcher!.current} onPick={(owner) => { touch(); switcher!.onPick(owner); }} disabled={isControlMode} />}
{computer.state.error && (
<div className="px-3 pt-2">
@@ -558,11 +627,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
{/* Tabs */}
- <div className="flex border-b border-zinc-800 bg-zinc-900/30 text-xs font-medium">
+ <div className={`flex border-b border-zinc-800 bg-zinc-900/30 text-xs font-medium ${narrow ? 'h-10 shrink-0' : ''}`}>
<button
type="button"
onClick={() => {
playSfx('click');
+ touch();
setActiveTab('browser');
}}
aria-pressed={activeTab === 'browser'}
@@ -579,6 +649,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
type="button"
onClick={() => {
playSfx('click');
+ touch();
setActiveTab('terminal');
}}
aria-pressed={activeTab === 'terminal'}
@@ -595,6 +666,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
type="button"
onClick={() => {
playSfx('click');
+ touch();
setActiveTab('vault');
}}
aria-pressed={activeTab === 'vault'}
@@ -623,7 +695,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
<LocalBrowserNote api={computer} />
</div>
) : activeTab === 'browser' ? (
- <div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden">
+ <div className="flex-1 min-h-0 flex flex-col p-3 gap-2 overflow-y-auto" onScroll={touch} data-pane-body="">
{pages.list && (
<BrowserPageStrip
pages={pages.list.pages}
@@ -633,18 +705,23 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
narrow={narrow}
onPick={(page) => {
playSfx('click');
+ touch();
setPicked(page);
}}
/>
)}
- {/* Browser Address Bar */}
+ {/* Browser Address Bar (not on a phone: the trail's host says where it is, typing a URL is a Take over job) */}
+ {!narrow && (
<div className="flex items-center gap-1.5 p-1.5 bg-zinc-900 border border-zinc-800 rounded-lg text-xs">
<Globe size={13} className="text-zinc-400 flex-shrink-0" />
<input
type="text"
readOnly={!onNavigate}
value={inputUrl}
- onChange={(e) => setInputUrl(e.target.value)}
+ onChange={(e) => {
+ touch();
+ setInputUrl(e.target.value);
+ }}
onKeyDown={(e) => {
if (e.key === 'Enter' && onNavigate && inputUrl.trim()) {
let target = inputUrl.trim();
@@ -686,8 +763,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
</a>
)}
</div>
+ )}
- {shownTitle && (
+ {shownTitle && !narrow && (
<div className="text-[11px] text-zinc-400 truncate px-1 font-medium">
{shownTitle}
</div>
@@ -803,7 +881,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
onLoad={() => { if (paneFrameId.current !== null) stream.acknowledgeFrame(paneFrameId.current); }}
onError={() => { if (paneFrameId.current !== null) stream.acknowledgeFrame(paneFrameId.current); }}
draggable={false}
- className="w-full h-full object-contain"
+ data-frame-finished={finished || undefined}
+ className={`w-full h-full object-contain ${finished ? 'saturate-[.6] brightness-[.82]' : ''}`}
/>
{pointOn && point && (
<PointLayer
@@ -820,9 +899,10 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
}}
/>
)}
- {!pointOn && !needsYou && !waitingForBot && !waitBot?.gaveUp && (
- <span className="absolute top-2 left-2 h-[22px] px-2 inline-flex items-center gap-1 rounded-full bg-[rgb(14_10_33/0.88)] text-[11px] text-zinc-200 pointer-events-none group-hover:opacity-0 group-focus-within:opacity-0 kw-veil-in">
- <Eye size={12} aria-hidden="true" /> Watching
+ {!pointOn && !needsYou && !waitingForBot && !waitBot?.gaveUp && (live || finished) && (
+ <span data-pane-pill={live ? 'live' : 'finished'} className="absolute top-2 left-2 h-[22px] px-2 inline-flex items-center gap-1.5 rounded-full bg-[rgb(14_10_33/0.88)] text-[11px] text-zinc-200 pointer-events-none group-hover:opacity-0 group-focus-within:opacity-0 kw-veil-in">
+ {live && <span aria-hidden="true" className="w-1.5 h-1.5 rounded-full bg-emerald-400" />}
+ {live ? 'Live' : 'Finished'}
</span>
)}
{!pointOn && !isWindow && stream.connected && (
@@ -861,15 +941,96 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{!needsYou && !waitingForBot && !waitBot?.gaveUp && <span className="text-xs text-zinc-200">Click anywhere to take over. @{pageBot} pauses.</span>}
</button>
)}
+ {!pointOn && !isInteracting && (
+ <button
+ type="button"
+ aria-label="Enlarge"
+ title="Enlarge"
+ data-pane-enlarge=""
+ onClick={() => {
+ playSfx('click');
+ touch();
+ setEnlarged(true);
+ }}
+ className="absolute top-2 right-2 z-10 w-7 h-7 inline-flex items-center justify-center rounded-lg bg-[rgb(14_10_33/0.88)] text-zinc-200 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300"
+ >
+ <Maximize2 size={14} aria-hidden="true" />
+ </button>
+ )}
</>
) : (
<div className="text-center p-6 text-zinc-500 text-xs">
<Globe size={32} className="mx-auto mb-2 opacity-40 text-zinc-500" />
<p>{browserReady ? 'Browser idle' : 'Browser unavailable'}</p>
- <p className="text-[10px] text-zinc-500 mt-1">{browserReady ? 'Enter a URL above to open a page' : isLocal ? 'Check that Chrome is installed, then use Restart Browser below' : 'Start Docker, then use Restart Browser below'}</p>
+ <p className="text-[10px] text-zinc-500 mt-1">{browserReady ? 'Enter a URL above to open a page' : isLocal ? 'Check that Chrome is installed, then use Restart browser below' : 'Start Docker, then use Restart browser below'}</p>
</div>
)}
</div>
+
+ {/* 0.9.8 C: Point at it and Take over under the preview, both secondary; Hand back as today */}
+ {!isWindow && (pointButtonEl || stream.connected || isControlMode) && (
+ <div className="flex gap-2 shrink-0" data-pane-actions="">
+ {pointButtonEl}
+ <button
+ type="button"
+ onClick={() => {
+ if (isControlMode) handBack();
+ else {
+ touch();
+ takeOver();
+ }
+ }}
+ disabled={!stream.connected || waitingForBot}
+ title={isControlMode ? 'Hand the browser back to the bot' : `Take over ${whose} browser`}
+ data-takeover-button
+ className={`${narrow ? 'h-11 flex-1 justify-center' : 'h-8'} px-3 rounded-[10px] inline-flex items-center gap-1.5 text-[13px] font-semibold whitespace-nowrap cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 border border-[#3f3868] ${
+ isControlMode ? 'bg-[rgb(44_37_82/0.8)] text-zinc-100' : 'text-zinc-200 hover:bg-white/5'
+ }`}
+ >
+ {isControlMode ? <Hand size={14} aria-hidden="true" /> : <MousePointerClick size={14} aria-hidden="true" />}
+ {isControlMode ? 'Hand back' : 'Take over'}
+ </button>
+ </div>
+ )}
+
+ {/* 0.9.8 B: the pages this reply opened, newest first; a row opens the page in a new tab */}
+ {trail.length > 0 && (
+ <section aria-labelledby="pane-trail-head" data-pane-trail="" className="shrink-0">
+ <h3 id="pane-trail-head" className="mt-1 mb-1.5 text-[11px] font-medium uppercase tracking-[0.08em] text-zinc-400">
+ Pages this reply · {trail.length}
+ </h3>
+ <ol className="rounded-xl border border-[#2c2552] overflow-hidden">
+ {trail.map((p, i) => {
+ const now = live && i === 0;
+ return (
+ <li key={p.url} className={i > 0 ? 'border-t border-[#2c2552]' : ''}>
+ <a
+ href={p.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={touch}
+ title={p.url}
+ className={`grid grid-cols-[44px_1fr_auto] items-center gap-2.5 px-2.5 py-2 ${narrow ? 'min-h-11' : 'min-h-12'} hover:bg-white/[0.04] focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-sky-300 ${now ? 'bg-emerald-400/5' : ''}`}
+ >
+ <span className="text-xs text-zinc-400 tabular-nums">{trailTime(p.at)}</span>
+ <span className="min-w-0">
+ <span className="block text-[13px] text-zinc-100 truncate">{pageTitleOf(p.url, p.stepTitle)}</span>
+ <span className="block text-xs text-zinc-400 truncate">{p.host}</span>
+ </span>
+ {now ? (
+ <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-emerald-400">
+ <span aria-hidden="true" className="w-1.5 h-1.5 rounded-full bg-emerald-400" /> Now
+ </span>
+ ) : (
+ <ExternalLink size={14} aria-hidden="true" className="text-zinc-500" />
+ )}
+ </a>
+ </li>
+ );
+ })}
+ </ol>
+ </section>
+ )}
</div>
) : activeTab === 'terminal' ? (
/* Terminal Tab */
@@ -920,6 +1081,30 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
</div>
+ {enlarged && frameSrc && (
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-label={`${paneTitle}, enlarged`}
+ data-pane-enlarged=""
+ className="fixed inset-0 z-[80] flex items-center justify-center bg-[rgb(5_3_14/0.78)]"
+ onClick={() => setEnlarged(false)}
+ >
+ <div className="relative max-w-[1024px] w-[calc(100vw-48px)]" onClick={(e) => e.stopPropagation()}>
+ <img src={frameSrc} alt={`${paneTitle}, enlarged`} draggable={false} className={`w-full h-auto rounded-xl border border-white/10 ${finished ? 'saturate-[.6] brightness-[.82]' : ''}`} />
+ <button
+ ref={enlargeClose}
+ type="button"
+ aria-label="Close"
+ onClick={() => setEnlarged(false)}
+ className="absolute top-2 right-2 w-9 h-9 inline-flex items-center justify-center rounded-lg bg-[rgb(14_10_33/0.88)] text-zinc-200 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300"
+ >
+ <X size={16} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ )}
+
{showFullScreen && (
<BrowserControlOverlay
botName={pageBot}
@@ -977,14 +1162,14 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
{/* Footer Status */}
- <div className="p-2.5 border-t border-zinc-800 bg-zinc-900/60 flex items-center justify-between text-[11px] text-zinc-400">
- <div className="flex items-center gap-1.5 shrink-0" data-browser-footer>
+ <div className="h-10 shrink-0 px-2.5 border-t border-zinc-800 bg-zinc-900/60 flex items-center justify-between gap-2 text-xs text-zinc-400">
+ <div className="flex items-center gap-1.5 min-w-0" data-browser-footer>
{isLocal ? (
<Laptop size={12} className={browserReady || isWindow ? 'text-amber-300/80' : 'text-zinc-500'} />
) : (
<Cpu size={12} className={browserReady ? 'text-emerald-400' : 'text-zinc-500'} />
)}
- <span>{browserFooterLabel(computer.state.settings, browserReady)}</span>
+ <span className="truncate">{browserFooterLabel(computer.state.settings, browserReady, { botName: whoBrowses, browsing: live })}</span>
</div>
{pointOn && point ? (
<span data-point-footer="" className="min-w-0 flex-1 px-2 text-center leading-snug text-zinc-300 [overflow-wrap:anywhere]">
@@ -1002,20 +1187,37 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
) : point && takeover && !isWindow ? (
<span data-point-footer="" className="min-w-0 flex-1 px-2 text-center leading-snug text-zinc-400">{POINT_COPY.handBack}</span>
) : null}
- {onRestartVm && !isWindow && (
- <button
- type="button"
- onClick={() => {
- playSfx('click');
- onRestartVm();
- }}
- className="hover:text-zinc-200 text-zinc-400 flex items-center gap-1 transition-colors cursor-pointer"
- >
- <RefreshCw size={11} />
- <span>Restart Browser</span>
- </button>
- )}
+ <div className="flex items-center gap-3 shrink-0">
+ {onRefresh && !narrow && (
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onRefresh();
+ passwords.reload();
+ }}
+ title="Refresh the picture and saved logins"
+ className="hover:text-zinc-200 text-zinc-400 transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 rounded"
+ >
+ Refresh
+ </button>
+ )}
+ {onRestartVm && !isWindow && (
+ <button
+ type="button"
+ onClick={() => {
+ playSfx('click');
+ onRestartVm();
+ }}
+ className={`hover:text-zinc-200 text-zinc-400 flex items-center gap-1 transition-colors cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 rounded ${narrow ? 'min-h-11' : ''}`}
+ >
+ <RefreshCw size={11} aria-hidden="true" />
+ <span>Restart browser</span>
+ </button>
+ )}
+ </div>
</div>
</div>
+ </>
);
};
diff --git a/frontend/src/computerMode.ts b/frontend/src/computerMode.ts
index 65cf77b7..c93473ae 100644
--- a/frontend/src/computerMode.ts
+++ b/frontend/src/computerMode.ts
@@ -98,11 +98,24 @@ export const isBlankPage = (url: string | null | undefined) => {
return u === '' || u === 'about:blank';
};
-/** The browser panel's footer: where Chrome runs and where you see it. */
-export function browserFooterLabel(s: ComputerSettings | null | undefined, ready: boolean): string {
- if (s?.mode !== 'local') return ready ? 'Browser Ready' : 'Browser Offline';
- if (s.window.visible) return 'Chrome window on your computer';
- return ready ? 'Chrome shown here (no window)' : 'Chrome offline';
+/** "Ben's" for a bot's browser, "the team's" for the team page. */
+export const browserOwnerWord = (botName: string | null | undefined) => (botName?.trim() ? `${botName.trim()}'s` : "the team's");
+
+const capitalise = (t: string) => t.charAt(0).toUpperCase() + t.slice(1);
+
+/**
+ * The browser panel's footer, in sentence case: whose browser it is and what it's doing
+ * ("Live view of Ben's browser", "Ben's browser is idle", "Ben's browser is off").
+ */
+export function browserFooterLabel(
+ s: ComputerSettings | null | undefined,
+ ready: boolean,
+ who: { botName?: string | null; browsing?: boolean } = {},
+): string {
+ const whose = browserOwnerWord(who.botName);
+ if (s?.mode === 'local' && s.window.visible) return capitalise(`${whose} browser is open in a Chrome window`);
+ if (!ready) return capitalise(`${whose} browser is off`);
+ return who.browsing ? `Live view of ${whose} browser` : capitalise(`${whose} browser is idle`);
}
/** Fired on window after a successful switch so every open control shows the new mode. */
diff --git a/frontend/tests/browsedChip.test.mjs b/frontend/tests/browsedChip.test.mjs
new file mode 100644
index 00000000..42673e32
--- /dev/null
+++ b/frontend/tests/browsedChip.test.mjs
@@ -0,0 +1,39 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ export { BrowsedChip } from './src/components/BrowsedChip';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+
+const step = (tool, detail, at = '2026-11-13T10:45:00Z') => ({ id: at + detail, kind: 'tool', status: 'ok', title: 'Opening', tool, detail, started_at: at });
+const chip = (props) => m.renderToStaticMarkup(m.createElement(m.BrowsedChip, { botName: 'Ben', live: false, onOpen: () => {}, ...props }));
+
+test('no chip when the reply opened no pages in the bot browser', () => {
+ assert.equal(chip({ steps: [] }), '');
+ assert.equal(chip({ steps: undefined }), '');
+ assert.equal(chip({ steps: [step('WebFetch', 'https://a.example.com/')] }), '');
+});
+
+test('after the reply: "Ben opened 1 page" / "2 pages", a button that says what it shows', () => {
+ const one = chip({ steps: [step('mcp__kwnt__browser_open', 'https://roastco.example.com/')] });
+ assert.match(one, /^<button[^>]*type="button"/);
+ assert.match(one, /Ben opened 1 page</);
+ assert.match(one, /aria-label="Show the page Ben opened"/);
+ assert.match(one, /data-browsed-chip="finished"/);
+ const two = chip({ steps: [step('browser_open', 'https://roastco.example.com/'), step('browser_navigate', 'https://roastco.example.com/cart')] });
+ assert.match(two, /Ben opened 2 pages</);
+ assert.match(two, /aria-label="Show the 2 pages Ben opened"/);
+});
+
+test('while browsing: the host now, and the count only from 2 pages', () => {
+ const one = chip({ live: true, steps: [step('browser_open', 'https://www.roastco.example.com/shop')] });
+ assert.match(one, /Ben is on<\/span><span[^>]*>roastco\.example\.com</);
+ assert.doesNotMatch(one, /pages/);
+ assert.match(one, /aria-label="Watch Ben&#x27;s browser"/);
+ assert.match(one, /motion-reduce:animate-none/);
+ const two = chip({ live: true, steps: [step('browser_open', 'https://roastco.example.com/'), step('browser_open', 'https://beans.example.org/', '2026-11-13T10:46:00Z')] });
+ assert.match(two, /beans\.example\.org<\/span><span[^>]*>· 2 pages</);
+});
diff --git a/frontend/tests/browserPages.test.mjs b/frontend/tests/browserPages.test.mjs
index a233feb4..1c463928 100644
--- a/frontend/tests/browserPages.test.mjs
+++ b/frontend/tests/browserPages.test.mjs
@@ -120,3 +120,92 @@ test('the pane picks the page by choosePage and streams it; the card\'s Sign in
const hook = await readFile(new URL('../src/useBrowserStream.ts', import.meta.url), 'utf8');
assert.match(hook, /\}, \[id, visible, page\]\);/, 'a new page reconnects the stream');
});
+
+// ---------- 0.9.8 browser panel: the chip and the page trail ----------
+const bp = await load('../src/browserPages.ts');
+const step = (tool, detail, at, extra = {}) => ({ kind: 'tool', status: 'done', tool, detail, started_at: at, ...extra });
+
+test('pagesOfReply: counts the bot browser\'s own open/navigate tools, MCP-prefixed too', () => {
+ bp.clearTitles();
+ const pages = bp.pagesOfReply([
+ step('mcp__kwnt__browser_open', 'https://www.roastco.example.com/shop/coffee/1kg', '2026-11-13T10:44:00Z'),
+ step('browser_navigate', 'https://roastco.example.com/cart', '2026-11-13T10:45:00Z'),
+ step('mcp__kwnt__open_url', 'https://beans.example.org/', '2026-11-13T10:46:00Z'),
+ ]);
+ assert.deepEqual(pages.map((p) => p.url), ['https://beans.example.org/', 'https://roastco.example.com/cart', 'https://www.roastco.example.com/shop/coffee/1kg']);
+ assert.deepEqual(pages.map((p) => p.host), ['beans.example.org', 'roastco.example.com', 'roastco.example.com']);
+});
+
+test('pagesOfReply: WebFetch, fetch, failed steps, non-tool steps and non-http details don\'t count', () => {
+ assert.deepEqual(
+ bp.pagesOfReply([
+ step('WebFetch', 'https://a.example.com/', 't1'),
+ step('mcp__kwnt__webfetch', 'https://a.example.com/', 't1'),
+ step('fetch', 'https://a.example.com/', 't1'),
+ step('browser_open', 'https://a.example.com/', 't1', { status: 'failed' }),
+ step('browser_open', 'Timed out loading the page', 't1'),
+ step('browser_open', 'file:///etc/hosts', 't1'),
+ { kind: 'thinking', detail: 'https://a.example.com/', started_at: 't1' },
+ step('browser_click', 'https://a.example.com/', 't1'),
+ ]),
+ [],
+ );
+ assert.deepEqual(bp.pagesOfReply(null), []);
+});
+
+test('pagesOfReply: distinct addresses with the hash stripped; a later visit moves the page up', () => {
+ const pages = bp.pagesOfReply([
+ step('browser_open', 'https://a.example.com/x#top', '2026-11-13T10:00:00Z'),
+ step('browser_open', 'https://a.example.com/y', '2026-11-13T10:01:00Z'),
+ step('browser_open', 'https://a.example.com/x#reviews', '2026-11-13T10:02:00Z'),
+ ]);
+ assert.deepEqual(pages.map((p) => [p.url, p.at]), [
+ ['https://a.example.com/x', '2026-11-13T10:02:00Z'],
+ ['https://a.example.com/y', '2026-11-13T10:01:00Z'],
+ ]);
+});
+
+test('page titles: the step\'s page_title, then one seen live, then the path; "/" reads as the host', () => {
+ bp.clearTitles();
+ bp.noteTitle('https://roastco.example.com/cart#x', 'Your cart · RoastCo');
+ const pages = bp.pagesOfReply([
+ step('browser_open', 'https://roastco.example.com/', 't1'),
+ step('browser_open', 'https://roastco.example.com/shop/coffee/1kg', 't2'),
+ step('browser_open', 'https://roastco.example.com/cart', 't3'),
+ step('browser_open', 'https://roastco.example.com/about', 't4', { page_title: 'About RoastCo' }),
+ ]);
+ assert.deepEqual(pages.map((p) => bp.pageTitleOf(p.url, p.stepTitle)), ['About RoastCo', 'Your cart · RoastCo', '/shop/coffee/1kg', 'roastco.example.com']);
+});
+
+test('a title noted after pagesOfReply ran still shows through pageTitleOf (memoized trails)', () => {
+ bp.clearTitles();
+ const pages = bp.pagesOfReply([step('browser_open', 'https://roastco.example.com/cart', 't1')]);
+ assert.equal(pages[0].stepTitle, null);
+ assert.equal(bp.pageTitleOf(pages[0].url, pages[0].stepTitle), '/cart');
+ bp.noteTitle('https://roastco.example.com/cart', 'Your cart · RoastCo');
+ assert.equal(bp.pageTitleOf(pages[0].url, pages[0].stepTitle), 'Your cart · RoastCo');
+ // A step's own page_title still wins over a live one
+ const own = bp.pagesOfReply([step('browser_open', 'https://roastco.example.com/cart', 't2', { page_title: 'Cart' })]);
+ assert.equal(bp.pageTitleOf(own[0].url, own[0].stepTitle), 'Cart');
+});
+
+test('noteTitle keeps the newest 200 addresses and ignores blank titles', () => {
+ bp.clearTitles();
+ for (let i = 0; i < 205; i++) bp.noteTitle(`https://a.example.com/${i}`, `Page ${i}`);
+ assert.equal(bp.titleFor('https://a.example.com/0'), null);
+ assert.equal(bp.titleFor('https://a.example.com/204'), 'Page 204');
+ bp.noteTitle('https://b.example.com/', ' ');
+ bp.noteTitle('about:blank', 'Blank');
+ assert.equal(bp.titleFor('https://b.example.com/'), null);
+});
+
+test('the chip\'s words: "1 page" / "2 pages" after, the host and a count from 2 while browsing', () => {
+ const one = bp.pagesOfReply([step('browser_open', 'https://roastco.example.com/', 't1')]);
+ const two = bp.pagesOfReply([step('browser_open', 'https://roastco.example.com/', 't1'), step('browser_open', 'https://www.beans.example.org/a', 't2')]);
+ assert.equal(bp.browsedChipText('Ben', one, false).lead, 'Ben opened 1 page');
+ assert.equal(bp.browsedChipText('Ben', one, false).label, 'Show the page Ben opened');
+ assert.equal(bp.browsedChipText('Ben', two, false).lead, 'Ben opened 2 pages');
+ assert.equal(bp.browsedChipText('Ben', two, false).label, 'Show the 2 pages Ben opened');
+ assert.deepEqual(bp.browsedChipText('Ben', one, true), { lead: 'Ben is on', host: 'roastco.example.com', count: null, label: "Watch Ben's browser" });
+ assert.deepEqual(bp.browsedChipText('Ben', two, true), { lead: 'Ben is on', host: 'beans.example.org', count: '2 pages', label: "Watch Ben's browser" });
+});
diff --git a/frontend/tests/browserPanel.test.mjs b/frontend/tests/browserPanel.test.mjs
index 42c0922e..e7b24048 100644
--- a/frontend/tests/browserPanel.test.mjs
+++ b/frontend/tests/browserPanel.test.mjs
@@ -42,14 +42,19 @@ test('once the bot has opened a page the live frame shows', () => {
assert.doesNotMatch(html, /Browser idle/);
});
-test('the footer says where Chrome runs and where you see it', () => {
- assert.equal(m.browserFooterLabel(settings('local'), true), 'Chrome shown here (no window)');
- assert.equal(m.browserFooterLabel(settings('local', true), true), 'Chrome window on your computer');
- assert.equal(m.browserFooterLabel(settings('local'), false), 'Chrome offline');
- assert.equal(m.browserFooterLabel(settings('vm'), true), 'Browser Ready');
- assert.equal(m.browserFooterLabel(settings('vm'), false), 'Browser Offline');
+test('the footer says whose browser it is and what it is doing, in sentence case', () => {
+ const ben = { botName: 'Ben', browsing: true };
+ assert.equal(m.browserFooterLabel(settings('local'), true, ben), "Live view of Ben's browser");
+ assert.equal(m.browserFooterLabel(settings('vm'), true, ben), "Live view of Ben's browser");
+ assert.equal(m.browserFooterLabel(settings('local', true), true, ben), "Ben's browser is open in a Chrome window");
+ assert.equal(m.browserFooterLabel(settings('vm'), true, { botName: 'Ben', browsing: false }), "Ben's browser is idle");
+ assert.equal(m.browserFooterLabel(settings('local'), false, ben), "Ben's browser is off");
+ assert.equal(m.browserFooterLabel(settings('vm'), false, ben), "Ben's browser is off");
+ // The team page has no bot owner.
+ assert.equal(m.browserFooterLabel(settings('vm'), false), "The team's browser is off");
+ assert.equal(m.browserFooterLabel(settings('vm'), true, { browsing: true }), "Live view of the team's browser");
// Settings not loaded yet: no claim about the user's computer.
- assert.equal(m.browserFooterLabel(null, true), 'Browser Ready');
+ assert.equal(m.browserFooterLabel(null, true, { botName: 'Ben' }), "Ben's browser is idle");
});
// On a phone, Back to the list unmounts the chat while the pane stays open; it must come back on
@@ -70,3 +75,48 @@ test('a remounted pane comes back on the tab chosen for that bot', () => {
// Another bot keeps its own tab
assert.deepEqual(pressedTab(pane({ teamId: 'bot-b' })), ['Browser']);
});
+
+// ---------- 0.9.8 browser panel (design browser-panel/design.md C) ----------
+const trail = [
+ { at: '2026-11-13T10:46:00Z', url: 'https://roastco.example.com/cart', host: 'roastco.example.com', stepTitle: 'Your cart · RoastCo' },
+ { at: '2026-11-13T10:45:00Z', url: 'https://roastco.example.com/shop/coffee/1kg', host: 'roastco.example.com', stepTitle: null },
+];
+
+test('the header says whose browser it is and whether it browses now; no Take over, Point, Key or Refresh up there', () => {
+ const html = pane({ teamName: 'Spring launch', browsingBot: 'Ben', running: true, activeUrl: 'https://roastco.example.com/cart' });
+ assert.match(html, /data-pane-title="">Ben&#x27;s browser</);
+ assert.match(html, /data-pane-status="browsing"[\s\S]*?Browsing now · @Spring launch/);
+ const header = html.slice(0, html.indexOf('aria-pressed'));
+ assert.doesNotMatch(header, /data-takeover-button|data-point-button|Saved logins|Refresh/);
+ assert.match(html, /data-pane-pill="live"[^>]*>[\s\S]*?Live</);
+});
+
+test('after the turn: Finished with the time, a muted frame and no Live pill; with no run, Idle and no pill', () => {
+ const html = pane({ browsingBot: 'Ben', running: false, finishedAt: '2026-11-13T22:46:00Z', activeUrl: 'https://roastco.example.com/' });
+ assert.match(html, /data-pane-status="finished"[\s\S]*?Finished \d{1,2}:46/);
+ assert.match(html, /data-pane-pill="finished"/);
+ assert.match(html, /data-frame-finished="true"[^>]*saturate-\[\.6\] brightness-\[\.82\]/);
+ const idle = pane({ activeUrl: 'https://roastco.example.com/' });
+ assert.match(idle, /data-pane-status="idle"[\s\S]*?Idle · @Team/);
+ assert.match(idle, /data-pane-title="">The team&#x27;s browser</);
+ assert.doesNotMatch(idle, /data-pane-pill/);
+});
+
+test('the trail lists the reply\'s pages, newest first, each opening in a new tab; the current one says Now while live', () => {
+ const html = pane({ browsingBot: 'Ben', running: true, trail, activeUrl: 'https://roastco.example.com/cart' });
+ assert.match(html, /Pages this reply · 2/);
+ const rows = [...html.matchAll(/<a href="([^"]+)" target="_blank" rel="noopener noreferrer"/g)].map((x) => x[1]);
+ assert.deepEqual(rows, ['https://roastco.example.com/cart', 'https://roastco.example.com/shop/coffee/1kg']);
+ assert.match(html, /Your cart · RoastCo/);
+ assert.equal((html.match(/> Now</g) ?? []).length, 1);
+ assert.doesNotMatch(pane({ browsingBot: 'Ben', running: false, trail, activeUrl: 'https://roastco.example.com/' }), /> Now</);
+ assert.doesNotMatch(pane({ activeUrl: 'https://roastco.example.com/' }), /Pages this reply/);
+});
+
+test('the frame has an Enlarge button; the footer offers Refresh and "Restart browser"', () => {
+ const html = pane({ activeUrl: 'https://roastco.example.com/', onRefresh: () => {}, onRestartVm: () => {} });
+ assert.match(html, /aria-label="Enlarge"/);
+ assert.match(html, />Refresh</);
+ assert.match(html, /Restart browser/);
+ assert.doesNotMatch(html, /Restart Browser/);
+});
diff --git a/frontend/tests/browserPanelClose.test.mjs b/frontend/tests/browserPanelClose.test.mjs
new file mode 100644
index 00000000..48d96cff
--- /dev/null
+++ b/frontend/tests/browserPanelClose.test.mjs
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+// 0.9.8 browser panel (design browser-panel/design.md D): the panel closes itself only when a bot opened it.
+const load = async (path) => {
+ const source = await readFile(new URL(path, import.meta.url), 'utf8');
+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } });
+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
+};
+const { shouldAutoClose, shouldAutoOpen, paneStatus, AUTO_CLOSE_DELAY_MS } = await load('../src/browserPanel.ts');
+
+const ended = { by: 'bot', touched: false, control: false, humanStep: false, pointPending: false, running: false };
+
+test('a panel the bot opened closes once its turn ends and nobody used it', () => {
+ assert.equal(shouldAutoClose(ended), true);
+ assert.equal(AUTO_CLOSE_DELAY_MS, 600);
+});
+
+test('it stays open while the turn runs', () => {
+ assert.equal(shouldAutoClose({ ...ended, running: true }), false);
+});
+
+test('a panel the person opened never closes itself', () => {
+ assert.equal(shouldAutoClose({ ...ended, by: 'person' }), false);
+ assert.equal(shouldAutoClose({ ...ended, by: null }), false);
+});
+
+test('it stays open while the person uses it: touched, in control, a step waiting on them, Point picks pending', () => {
+ for (const k of ['touched', 'control', 'humanStep', 'pointPending']) assert.equal(shouldAutoClose({ ...ended, [k]: true }), false, k);
+});
+
+test('a browser event never opens the panel on a phone, nor reopens an open one', () => {
+ assert.equal(shouldAutoOpen({ open: false, narrow: false }), true);
+ assert.equal(shouldAutoOpen({ open: false, narrow: true }), false);
+ assert.equal(shouldAutoOpen({ open: true, narrow: false }), false);
+});
+
+test('the header status: Browsing now, Finished with the time, Idle', () => {
+ assert.deepEqual(paneStatus({ running: true, finishedAt: '2026-11-13T22:46:00Z' }), { kind: 'browsing', text: 'Browsing now' });
+ const f = paneStatus({ running: false, finishedAt: '2026-11-13T22:46:00Z', locale: 'en-US' });
+ assert.equal(f.kind, 'finished');
+ assert.match(f.text, /^Finished \d{1,2}:46/);
+ assert.deepEqual(paneStatus({ running: false, finishedAt: null }), { kind: 'idle', text: 'Idle' });
+});