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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.9.3: browser page strip, live view follows the job's page (#532)
Oleksandr Ivanchenko5f2a4ee15a11
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 430d54be..30277539 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -36,6 +36,7 @@ import {openStepsByKwant,turnsAwaitingStep,} from './humanSteps';+import { notifyBrowserPages, pageTeam, stepPage } from './browserPages';import { McpSuggestionCard } from './components/McpSuggestionCard';import { ConnectionSuggestionCard } from './components/ConnectionSuggestionCard';import type { ConnectionSuggestionMeta } from './connectionSuggestions';@@ -683,8 +684,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({else if (n.kind === 'fact_disputed') openBoardForTier();else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) {setIsVmPaneOpen(true);+ const step = latestOpenStep(humanStepsRef.current, n.kwant_id);+ // The step's own page, not whichever page the pane showed last+ pickPage(stepPage(step));// A CAPTCHA lands straight in the solve view- if (latestOpenStep(humanStepsRef.current, n.kwant_id)?.kind === 'captcha') setSolveRequest((v) => v + 1);+ if (step?.kind === 'captcha') setSolveRequest((v) => v + 1);}else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openPlaceRef.current(n);};@@ -969,6 +973,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const [turnsHydrated, setTurnsHydrated] = useState(0);const [browsingSeeded, setBrowsingSeeded] = useState(0);const [solveRequest, setSolveRequest] = useState(0);+ // 0.9.3: a card's Sign in / Solve (or a step notification) asks the pane to show that step's own page+ const [pagePick, setPagePick] = useState<{ page: string; n: number } | null>(null);+ const pickPage = (page: string | null | undefined) => {+ if (page) setPagePick((p) => ({ page, n: (p?.n ?? 0) + 1 }));+ };const [activeUrl, setActiveUrl] = useState('');const [pageTitle, setPageTitle] = useState('');const [screenshotBase64, setScreenshotBase64] = useState<string | null>(null);@@ -1459,6 +1468,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const st: HumanStep | undefined = event.data?.step;if (!st?.id) break;setHumanSteps((prev) => applyHumanStep(prev, st));+ notifyBrowserPages(stepPage(st));if (st.status === 'open') playSfx('alert');break;}@@ -1612,6 +1622,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({case 'browser_navigated':case 'BrowserNavigated': {const teamId = event.data?.team_id;+ notifyBrowserPages(teamId);setBrowsing((m) => noteBrowser(m, teamId, event.data?.url, Date.now()));const currentTid = activeSandboxIdRef.current;const k = currentKwantRef.current;@@ -1662,6 +1673,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({case 'sandbox_status':case 'SandboxStatusChanged': {const teamId = event.data?.team_id;+ notifyBrowserPages(teamId);const currentTid = activeSandboxIdRef.current;const k = currentKwantRef.current;const t = currentTeamRef.current;@@ -2413,7 +2425,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({kwantId={st?.kwant_id}live={st}waiting={!!turnId && !!turns[turnId]}- onOpenBrowser={(_target, solve) => {+ onOpenBrowser={(_target, solve, page) => {+ pickPage(page);setIsVmPaneOpen(true);if (solve) {setSolveRequest((v) => v + 1);@@ -3328,13 +3341,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}};- const handleNavigateVm = async (url: string) => {+ // `page`: the page the pane shows (0.9.3), so the address bar drives that page and not the team page+ const handleNavigateVm = async (url: string, page?: string | null) => {const sid = activeSandboxId;if (!sid || sid === 'default') return;+ const target = page && pageTeam(page) === sid ? page : sid;setBrowserError(null);setIsVmPaneOpen(true);try {- const res = await fetch(`/api/sandbox/${sid}/navigate`, {+ const res = await fetch(`/api/sandbox/${encodeURIComponent(target)}/navigate`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ url }),@@ -4094,6 +4109,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({vmSwitcher={vmSwitcher}onVmStepDone={(id) => answerHumanStep(id, 'done')}vmSolveRequest={solveRequest}+ vmPagePick={pagePick}+ vmBotNames={kwantNames}vmShowOnceBot={currentKwant && !currentTeam ? { id: currentKwant.id, name: currentKwant.name } : undefined}pinned={pinned}onEditInstructions={diff --git a/frontend/src/browserPages.ts b/frontend/src/browserPages.tsnew file mode 100644index 00000000..a11b293d--- /dev/null+++ b/frontend/src/browserPages.ts@@ -0,0 +1,156 @@+// 0.9.3: every job (a bot in a chat) has its own page in its team's browser, and a sign-in or+// CAPTCHA step holds only its own page. The browser pane shows one page at a time and offers the+// team's other pages in a small strip (impl.md "For Pixel: a tab strip").++/** Separates the parts of a job page key: `team#bot#chat`. The team page's key is the team id. */+export const PAGE_SEP = '#';++/** One page of a team's browser, as `GET /api/sandbox/:team/pages` lists it. */+export interface BrowserPage {+ page: string;+ team_id: string;+ /** The bot of a job page; null for the team page. */+ kwant_id: string | null;+ chat_id: string | null;+ /** False for the team page (the person's own and the bots' with no chat). */+ job: boolean;+ url: string | null;+ title: string | null;+ /** An open step (sign-in, code, CAPTCHA) is waiting on this page. */+ held: boolean;+ idle_seconds: number | null;+}++export interface BrowserPageList {+ team_id: string;+ /** The page the live view shows when no `?page=` is given. */+ live: string;+ max_job_pages: number;+ /** Newest first; the team page is always there. */+ pages: BrowserPage[];+}++/** The team a page belongs to: the key itself for the team page. */+export const pageTeam = (key: string) => key.split(PAGE_SEP)[0];++/** A step's page: its own `page_key`, else (a step from before job pages) the team page. */+export function stepPage(step: { page_key?: string | null; sandbox_target: string | null } | null | undefined): string | null {+ if (!step) return null;+ return step.page_key || step.sandbox_target || null;+}++/**+ * Which page the pane shows, in order:+ * 1. the page the person picked (a tab, or a card's Sign in / Solve), while it still exists;+ * 2. else the page of the newest open step for this team;+ * 3. else nothing: the server's default (`live`).+ * `pages` is the latest list, or null before the first one loads (then a pick or step page is+ * trusted as is). A new step never moves the view off a picked page: the pick comes first.+ */+export function choosePage(input: { picked: string | null; stepPage: string | null; pages: readonly string[] | null }): string | null {+ const { picked, stepPage: step, pages } = input;+ const exists = (key: string | null): key is string => !!key && (!pages || pages.includes(key));+ if (exists(picked)) return picked;+ if (exists(step)) return step;+ return null;+}++/** The page the pane is showing: the chosen one, else the server's default, else the team page. */+export function shownPage(chosen: string | null, list: BrowserPageList | null, team: string | undefined): string | null {+ return chosen ?? list?.live ?? team ?? null;+}++/** Only the host of an address ("tiktok.com"), as the step card shows it. */+export function pageHost(url: string | null | undefined): string | null {+ if (!url) return null;+ try {+ const u = new URL(url);+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;+ return u.hostname.replace(/^www\./, '') || null;+ } catch {+ return null;+ }+}++/** The tab's name: the bot's name for a job page, "Shared" for the team page. */+export function pageOwner(p: Pick<BrowserPage, 'job' | 'kwant_id'>, botName: (id: string) => string | undefined): string {+ if (!p.job || !p.kwant_id) return PAGE_COPY.shared;+ return botName(p.kwant_id) || PAGE_COPY.someBot;+}++/** Where the tab is: the site's host, else the title (not an "about:" one), else "nothing open". */+export function pageWhere(p: Pick<BrowserPage, 'url' | 'title'>): string {+ const title = p.title?.trim();+ return pageHost(p.url) || (title && !title.startsWith('about:') ? title : null) || PAGE_COPY.blank;+}++/** The tab's tooltip and accessible name: "Architect's page: tiktok.com (needs you)". */+export function pageLabel(p: BrowserPage, botName: (id: string) => string | undefined): string {+ const owner = pageOwner(p, botName);+ const whose = p.job ? `${owner}'s page` : PAGE_COPY.sharedLong;+ return `${whose}: ${pageWhere(p)}${p.held ? ` (${PAGE_COPY.waiting})` : ''}`;+}++export const PAGE_COPY = {+ stripName: 'Pages in this browser',+ shared: 'Shared',+ sharedLong: 'Shared page',+ someBot: 'A bot',+ blank: 'nothing open',+ waiting: 'needs you',+ handBackFirst: 'Hand back to switch pages',+};++// Live list refreshes: App hears BrowserNavigated, SandboxStatusChanged and human_step_updated+// for a team and pokes the pane's strip here.+type Listener = (team: string) => void;+const listeners = new Set<Listener>();++export function notifyBrowserPages(teamOrPage: string | null | undefined): void {+ if (!teamOrPage) return;+ const team = pageTeam(teamOrPage);+ for (const l of listeners) l(team);+}++export function onBrowserPagesChanged(l: Listener): () => void {+ listeners.add(l);+ return () => {+ listeners.delete(l);+ };+}++/** The team's pages, or null when the server has none to list (an older server, or no browser yet). */+export async function fetchBrowserPages(team: string, signal?: AbortSignal): Promise<BrowserPageList | null> {+ const res = await fetch(`/api/sandbox/${encodeURIComponent(team)}/pages`, { signal });+ if (!res.ok) return null;+ return parsePageList(await res.json().catch(() => null));+}++/** Keeps a parsed list only when it is the shape we expect (an older server has no such route). */+export function parsePageList(raw: unknown): BrowserPageList | null {+ if (!raw || typeof raw !== 'object') return null;+ const r = raw as Record<string, unknown>;+ if (!Array.isArray(r.pages) || typeof r.team_id !== 'string') return null;+ const pages: BrowserPage[] = [];+ for (const p of r.pages) {+ if (!p || typeof p !== 'object' || typeof (p as BrowserPage).page !== 'string') continue;+ const q = p as Record<string, unknown>;+ pages.push({+ page: q.page as string,+ team_id: typeof q.team_id === 'string' ? q.team_id : (r.team_id as string),+ kwant_id: typeof q.kwant_id === 'string' && q.kwant_id ? q.kwant_id : null,+ chat_id: typeof q.chat_id === 'string' && q.chat_id ? q.chat_id : null,+ job: q.job === true,+ url: typeof q.url === 'string' ? q.url : null,+ title: typeof q.title === 'string' ? q.title : null,+ held: q.held === true,+ idle_seconds: typeof q.idle_seconds === 'number' ? q.idle_seconds : null,+ });+ }+ return {+ team_id: r.team_id as string,+ live: typeof r.live === 'string' && r.live ? r.live : (r.team_id as string),+ max_job_pages: typeof r.max_job_pages === 'number' ? r.max_job_pages : 0,+ pages,+ };+}diff --git a/frontend/src/browserViewport.ts b/frontend/src/browserViewport.tsindex 4e0da5c4..308cf327 100644--- a/frontend/src/browserViewport.ts+++ b/frontend/src/browserViewport.ts@@ -1,6 +1,9 @@/** Always tunnel through Kwnt's public origin, including HTTPS reverse proxies. */-export function browserStreamUrl(location: { protocol: string; host: string }, id: string) {- return (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/api/sandbox/' + encodeURIComponent(id) + '/stream';+/** The live view of a team's browser; `page` (0.9.3) picks one of its pages, else the server's default. */+export function browserStreamUrl(location: { protocol: string; host: string }, id: string, page?: string | null) {+ const base = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/api/sandbox/' + encodeURIComponent(id) + '/stream';+ // A job page's key holds '#' (team#bot#chat), so it must be encoded or it would read as a fragment+ return page ? `${base}?page=${encodeURIComponent(page)}` : base;}/** Map a pointer through the centered letterboxing applied by object-fit: contain. */diff --git a/frontend/src/components/BrowserPageStrip.tsx b/frontend/src/components/BrowserPageStrip.tsxnew file mode 100644index 00000000..89319577--- /dev/null+++ b/frontend/src/components/BrowserPageStrip.tsx@@ -0,0 +1,67 @@+import React, { useId } from 'react';++import { BrowserPage, PAGE_COPY, pageLabel, pageOwner, pageWhere } from '../browserPages';+import { ScrollRow } from './ScrollRow';++const FOCUS = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#b8adff]';++interface Props {+ pages: BrowserPage[];+ /** The page on screen. */+ current: string | null;+ botName: (id: string) => string | undefined;+ onPick: (page: string) => void;+ /** The person holds the browser: switching would drop their control, so it waits for Hand back. */+ disabled?: boolean;+ narrow?: boolean;+}++/**+ * 0.9.3: the team's pages in one row above the address bar, shown when there are 2 or more. Each+ * tab names its bot and site; a page waiting for the person has the amber "needs you" dot the+ * browser switcher uses.+ */+export const BrowserPageStrip: React.FC<Props> = ({ pages, current, botName, onPick, disabled, narrow }) => {+ const hintId = useId();+ if (pages.length < 2) return null;+ return (+ <div role="group" aria-label={PAGE_COPY.stripName} data-page-strip="" className={`flex items-center gap-2 -my-1 -ml-1 ${narrow ? 'flex-wrap' : ''}`}>+ <ScrollRow className="kw-scroll-row min-w-0 flex items-center gap-1 overflow-x-auto p-1">+ {pages.map((p) => {+ const here = p.page === current;+ const label = pageLabel(p, botName);+ return (+ <button+ key={p.page}+ type="button"+ data-page-tab={p.page}+ data-page-held={p.held ? '' : undefined}+ title={label}+ aria-label={label}+ aria-current={here || undefined}+ aria-disabled={(disabled && !here) || undefined}+ aria-describedby={disabled && !here ? hintId : undefined}+ onClick={() => !disabled && !here && onPick(p.page)}+ className={`shrink-0 inline-flex items-center gap-1.5 max-w-[11rem] ${narrow ? 'h-11' : 'h-7'} px-2.5 rounded-[10px] border text-[12px] transition-colors ${FOCUS} ${+ here+ ? 'border-[#b8adff] bg-[rgb(44_37_82/0.8)] text-zinc-100'+ : `border-zinc-800 bg-zinc-900 text-zinc-300 ${disabled ? 'opacity-60 cursor-not-allowed' : 'hover:bg-zinc-800 hover:text-zinc-100 cursor-pointer'}`+ }`}+ >+ {p.held && <span data-page-needs-you="" aria-hidden="true" className="shrink-0 h-2 w-2 rounded-full bg-[#fcd34d]" />}+ <span className="font-semibold truncate">{pageOwner(p, botName)}</span>+ <span className="text-zinc-400 truncate">{pageWhere(p)}</span>+ </button>+ );+ })}+ </ScrollRow>+ {disabled && (+ <span id={hintId} data-page-strip-hint=""+ className={`text-[11px] text-zinc-400 ${narrow ? 'basis-full' : 'shrink-0 whitespace-nowrap'}`}+ >+ {PAGE_COPY.handBackFirst}+ </span>+ )}+ </div>+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex d37b3919..7066018d 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -242,7 +242,7 @@ export interface ChatViewProps {terminalLogs?: TerminalLogEntry[];onRefreshVm?: () => void;onRestartVm?: () => void;- onNavigateVm?: (url: string) => void;+ onNavigateVm?: (url: string, page?: string | null) => void;/** Some bot in the space runs without asking (the saved-passwords note). */vmApprovalsOff?: boolean;/** The CAPTCHA the open bot's browser waits on, and a counter that opens it to solve. */@@ -256,6 +256,10 @@ export interface ChatViewProps {/** Answers that step as done from the browser; resolves to an error message on failure. */onVmStepDone?: (id: string) => Promise<string | void> | void;vmSolveRequest?: number;+ /** 0.9.3: show this page of the team's browser (a card's Sign in / Solve); `n` goes up per ask. */+ vmPagePick?: { page: string; n: number } | null;+ /** Bot names by id, for the pane's page strip. */+ 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 };/** Pinned team/channel instructions, shown collapsed above the messages. */@@ -498,6 +502,8 @@ export const ChatView: React.FC<ChatViewProps> = ({vmSwitcher,onVmStepDone,vmSolveRequest,+ vmPagePick,+ vmBotNames,vmShowOnceBot,pinned = [],onEditInstructions,@@ -2596,6 +2602,8 @@ export const ChatView: React.FC<ChatViewProps> = ({switcher={vmSwitcher}onStepDone={onVmStepDone}solveRequest={vmSolveRequest}+ pagePick={vmPagePick}+ botNames={vmBotNames}showOnceBot={vmShowOnceBot}point={pointSink}/>diff --git a/frontend/src/components/HumanStepCard.tsx b/frontend/src/components/HumanStepCard.tsxindex fd4d5050..ff7d7f9a 100644--- a/frontend/src/components/HumanStepCard.tsx+++ b/frontend/src/components/HumanStepCard.tsx@@ -13,7 +13,8 @@ export interface HumanStepCardProps {/** A turn is paused on this step right now (else Done starts a new reply). */waiting: boolean;/** Shows the bot's browser panel; `solve` takes control and, on a phone, opens it full screen. */- onOpenBrowser?: (sandboxTarget: string | null, solve?: boolean) => void;+ /** `page`: the step's own browser page (0.9.3), else its team page. */+ onOpenBrowser?: (sandboxTarget: string | null, solve?: boolean, page?: string | null) => void;/** Resolve to an error message on failure. */onDone: (id: string) => Promise<string | void>;onSkip: (id: string) => Promise<string | void>;@@ -119,7 +120,7 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k{onOpenBrowser && captcha && (<buttontype="button"- onClick={() => onOpenBrowser(view.sandbox_target, true)}+ onClick={() => onOpenBrowser(view.sandbox_target, true, view.page_key ?? view.sandbox_target)}className={`inline-flex items-center justify-center gap-2 min-h-[48px] sm:min-h-[38px] px-4 py-2 rounded-xl text-base sm:text-sm font-semibold bg-amber-400 text-zinc-950 hover:bg-amber-300 ${focusRing}`}><Puzzle size={16} className="shrink-0" aria-hidden="true" /> Solve it@@ -128,7 +129,7 @@ export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, k{onOpenBrowser && !captcha && (<buttontype="button"- onClick={() => onOpenBrowser(view.sandbox_target, true)}+ onClick={() => onOpenBrowser(view.sandbox_target, true, view.page_key ?? view.sandbox_target)}className={`inline-flex items-center justify-center gap-2 min-h-[48px] sm:min-h-[38px] px-4 py-2 rounded-xl text-base sm:text-sm font-semibold bg-amber-400 text-zinc-950 hover:bg-amber-300 ${focusRing}`}><MonitorPlay size={16} className="shrink-0" aria-hidden="true" /> Open browserdiff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex f0a80547..447c392d 100644--- a/frontend/src/components/VirtualMachinePane.tsx+++ b/frontend/src/components/VirtualMachinePane.tsx@@ -32,6 +32,9 @@ 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 { useBrowserPages } from '../useBrowserPages';+import { BrowserPageStrip } from './BrowserPageStrip';const PHONE_QUERY = '(max-width: 639px)';@@ -86,7 +89,8 @@ export interface VirtualMachinePaneProps {terminalLogs?: TerminalLogEntry[];onRefresh?: () => void;onRestartVm?: () => void;- onNavigate?: (url: string) => void;+ /** `page`: the page shown (0.9.3), so the address bar drives that page. */+ onNavigate?: (url: string, page?: string | null) => void;/** Some bot in the space runs without asking (shown next to saved passwords). */approvalsOff?: boolean;/** The CAPTCHA this bot's browser is stuck on (open, or closed a moment ago). */@@ -103,6 +107,10 @@ export interface VirtualMachinePaneProps {showOnceBot?: { id: string; name: string };/** G3 Point at it: where picks go (the composer). Without it there's no Point button. */point?: PointSink;+ /** 0.9.3: show this page of the team's browser (a card's Sign in / Solve); `n` goes up per ask. */+ pagePick?: { page: string; n: number } | null;+ /** Bot names by id, for the page strip. */+ botNames?: Record<string, string>;}type PaneTab = 'browser' | 'terminal' | 'vault';@@ -123,6 +131,11 @@ export function rememberPaneTab(teamId: string | undefined, tab: PaneTab): voidif (teamId) chosenTabs.set(teamId, tab);}+// 0.9.3: the page the person picked, per team, for the same reason as the tab: the pane remounts.+// `at` is when it was picked, so a page list asked for before that can't call it closed.+const pickedPages = new Map<string, { page: string; at: number }>();+let handledPagePick = 0;+export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({isOpen,onClose,@@ -145,6 +158,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({point,switcher,showOnceBot,+ pagePick = null,+ botNames,}) => {const [activeTab, setActiveTab] = useState<PaneTab>(() => chosenPaneTab(teamId));useEffect(() => rememberPaneTab(teamId, activeTab), [teamId, activeTab]);@@ -161,8 +176,50 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({const isLocal = computer.state.settings?.mode === 'local';const isWindow = showsLocalWindow(computer.state.settings);+ // 0.9.3: which of the team's pages to show. The person's pick wins while it exists; else the newest+ // open step's page; else the server's default. A new step only marks its tab (Ada's brief, §3).+ const pages = useBrowserPages(teamId, isOpen && !isWindow);+ const [picked, setPickedState] = useState<{ page: string; at: number } | null>(() => (teamId && pickedPages.get(teamId)) || null);+ const setPicked = useCallback(+ (page: string | null) => {+ const next = page ? { page, at: Date.now() } : null;+ if (teamId) {+ if (next) pickedPages.set(teamId, next);+ else pickedPages.delete(teamId);+ }+ setPickedState(next);+ },+ [teamId],+ );+ // A card's Sign in / Solve, or a step notification: that step's page, if it is this team's+ useEffect(() => {+ if (!pagePick || pagePick.n <= handledPagePick || !teamId || pageTeam(pagePick.page) !== teamId) return;+ handledPagePick = pagePick.n;+ setPicked(pagePick.page);+ pages.reload();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [pagePick?.n, teamId]);+ const pageKeys = useMemo(() => pages.list?.pages.map((p) => p.page) ?? null, [pages.list]);+ // A list asked for before the pick can't know the picked page yet+ const knownPages = pageKeys && (!picked || (pages.list?.at ?? 0) >= picked.at) ? pageKeys : null;+ const openStep = humanStep?.status === 'open' ? humanStep : captchaStep?.status === 'open' ? captchaStep : null;+ const chosenPage = choosePage({ picked: picked?.page ?? null, stepPage: stepPage(openStep), pages: knownPages });+ // The picked page closed (idle, or the cap made room): forget it, so it never comes back by itself+ useEffect(() => {+ if (picked && knownPages && !knownPages.includes(picked.page)) setPicked(null);+ }, [picked, knownPages, setPicked]);+ const pageOnScreen = shownPage(chosenPage, pages.list, teamId);+ const pageInfo = pages.list?.pages.find((p) => p.page === pageOnScreen) ?? null;+ // A step or CAPTCHA is only this view's when it holds the page on screen+ const onScreen = (s: HumanStep | null | undefined) => (s && stepPage(s) === pageOnScreen ? s : null);+ humanStep = onScreen(humanStep);+ captchaStep = onScreen(captchaStep);+ 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;+// Interactive Remote Control State- const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending);+ const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending, chosenPage);const isControlMode = stream.controlling;const isInteracting = stream.busy;const narrow = useNarrow();@@ -176,9 +233,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({const [solvedNote, setSolvedNote] = useState(false);// Once the stream reports where the tab is, trust it; before that, the last URL the app heard of.- const pageUrl = stream.location ? stream.location.url : activeUrl;+ const pageUrl = stream.location ? stream.location.url : chosenPage ? pageInfo?.url ?? '' : activeUrl;// The same for the title: a new page's empty title must not fall back to the previous page's.- const shownTitle = stream.location ? stream.location.title : pageTitle;+ const shownTitle = stream.location ? stream.location.title : chosenPage ? pageInfo?.title ?? '' : pageTitle;const currentScreenshot = isBlankPage(pageUrl) ? null : stream.frame?.image || screenshotBase64;const frameSrc = currentScreenshot ? (currentScreenshot.startsWith('data:') ? currentScreenshot : `data:image/jpeg;base64,${currentScreenshot}`) : null;// A hidden frame never loads, so acknowledge it here or the stream stalls waiting for the ack.@@ -210,10 +267,11 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({}, [solveRequest]);const { connected, controlling, send } = stream;useEffect(() => {- if (!wantsControl || !connected) return;+ // On the chosen page only: a card's Solve switches page and asks for control in one go+ if (!wantsControl || !connected || stream.page !== chosenPage) return;setWantsControl(false);if (!controlling) send({ action: 'take_control' });- }, [wantsControl, connected, controlling, send]);+ }, [wantsControl, connected, controlling, send, stream.page, chosenPage]);// The CAPTCHA went away: by itself it says so, then hands the browser back; any other way just closesconst captchaStatus = captchaStep?.status;@@ -292,11 +350,13 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({const takeOver = useCallback(() => {playSfx('click');setWaitBot(null);+ // Taking over a page picks it: a step on another page must not pull the view (and the control) away+ if (!picked && pageKeys && pageKeys.length >= 2 && pageOnScreen) setPicked(pageOnScreen);setActiveTab('browser');setFullScreen(true);if (connected) send({ action: 'take_control' });else setWantsControl(true);- }, [connected, send]);+ }, [connected, send, picked, pageKeys, pageOnScreen, setPicked]);// The server let go (timeout, the bot's turn ended it, another tab): the stage closes with itconst wasControlling = useRef(false);@@ -564,6 +624,19 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({</div>) : activeTab === 'browser' ? (<div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden">+ {pages.list && (+ <BrowserPageStrip+ pages={pages.list.pages}+ current={pageOnScreen}+ botName={botName}+ disabled={isControlMode}+ narrow={narrow}+ onPick={(page) => {+ playSfx('click');+ setPicked(page);+ }}+ />+ )}{/* Browser Address Bar */}<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" />@@ -579,7 +652,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({target = `https://${target}`;}if (isControlMode) stream.send({ action: 'navigate', url: target }, true);- else onNavigate(target);+ else onNavigate(target, chosenPage);}}}placeholder="https://..."@@ -629,7 +702,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({}`}>{solvedNote ? <CheckCircle2 size={13} aria-hidden="true" /> : <Puzzle size={13} aria-hidden="true" />}- <span className="flex-1">{solvedNote ? `Solved, ${teamName} continues` : `Solve the puzzle, ${teamName} continues by itself`}</span>+ <span className="flex-1">{solvedNote ? `Solved, ${pageBot} continues` : `Solve the puzzle, ${pageBot} continues by itself`}</span>{!solvedNote && (!isControlMode || narrow) && (<buttontype="button"@@ -656,11 +729,11 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({)}<div className="flex-1 min-w-0">{waitBot.gaveUp ? (- <p className="text-[13px] leading-[18px] text-zinc-100">@{teamName} is finishing a step, try again in a moment.</p>+ <p className="text-[13px] leading-[18px] text-zinc-100">@{pageBot} is finishing a step, try again in a moment.</p>) : (<><p className="text-[13px] leading-[18px] text-zinc-100">- <span className="font-semibold">@{teamName} is finishing a step.</span> Taking over as soon as it’s done.+ <span className="font-semibold">@{pageBot} is finishing a step.</span> Taking over as soon as it’s done.</p><p className="mt-0.5 text-xs text-[#a39dcc]">Trying every second for 10 seconds.</p></>@@ -768,7 +841,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({>{needsYou && !waitingForBot && (<span className="inline-flex items-center gap-1.5 text-xs font-semibold text-[#fcd34d]">- <Hand size={14} aria-hidden="true" /> @{teamName} {needsYou}+ <Hand size={14} aria-hidden="true" /> @{pageBot} {needsYou}</span>)}<span@@ -777,14 +850,14 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({}`}>{waitingForBot ? (- <>Waiting for @{teamName}…</>+ <>Waiting for @{pageBot}…</>) : (<><MousePointerClick size={15} aria-hidden="true" /> {waitBot?.gaveUp ? 'Try again' : 'Take over'}</>)}</span>- {!needsYou && !waitingForBot && !waitBot?.gaveUp && <span className="text-xs text-zinc-200">Click anywhere to take over. @{teamName} pauses.</span>}+ {!needsYou && !waitingForBot && !waitBot?.gaveUp && <span className="text-xs text-zinc-200">Click anywhere to take over. @{pageBot} pauses.</span>}</button>)}</>@@ -834,7 +907,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({onNavigate? (origin) => {playSfx('click');- onNavigate(origin);+ onNavigate(origin, chosenPage);setActiveTab('browser');}: undefined@@ -848,7 +921,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({{showFullScreen && (<BrowserControlOverlay- botName={teamName}+ botName={pageBot}pageUrl={pageUrl}image={frameSrc}page={stream.frame ? { width: stream.frame.width, height: stream.frame.height } : undefined}@@ -879,7 +952,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({{showStage && (<BrowserTakeoverStage- botName={teamName}+ botName={pageBot}othersBrowsing={switching}pageUrl={pageUrl}pageTitle={shownTitle}@@ -888,12 +961,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({step={stepForStage}notice={solvedNote- ? { tone: 'success', text: `Solved, ${teamName} continues` }+ ? { tone: 'success', text: `Solved, ${pageBot} continues` }: captchaOpen- ? { tone: 'warn', text: `Solve the puzzle, ${teamName} continues by itself` }+ ? { tone: 'warn', text: `Solve the puzzle, ${pageBot} continues by itself` }: null}- onNavigate={onNavigate}+ onNavigate={onNavigate ? (url) => onNavigate(url, chosenPage) : undefined}onHandBack={handBackOrStop}onRetryControl={takeOver}extraAction={recordSteps}diff --git a/frontend/src/humanSteps.ts b/frontend/src/humanSteps.tsindex 98326f82..bbc6c73d 100644--- a/frontend/src/humanSteps.ts+++ b/frontend/src/humanSteps.ts@@ -26,6 +26,8 @@ export interface HumanStep {reason: string;url: string | null;sandbox_target: string | null;+ /** 0.9.3: the browser page the step holds (`team#bot#chat`); null on older steps, which hold the team page. */+ page_key?: string | null;/** CAPTCHA steps: the widget's box, while known. */target?: CaptchaTarget | null;source: 'bot' | 'auto';@@ -43,6 +45,8 @@ export interface HumanStepMeta {reason: string;url: string | null;sandbox_target: string | null;+ /** 0.9.3: the page to show for this step (the card's Sign in / Solve opens it). */+ page_key: string | null;target: CaptchaTarget | null;source: 'bot' | 'auto';status: HumanStepStatus;@@ -73,6 +77,7 @@ export function parseHumanStepMeta(raw: unknown): HumanStepMeta | null {reason: typeof m.reason === 'string' ? m.reason : '',url: typeof m.url === 'string' && m.url ? m.url : null,sandbox_target: typeof m.sandbox_target === 'string' && m.sandbox_target ? m.sandbox_target : null,+ page_key: typeof m.page_key === 'string' && m.page_key ? m.page_key : null,target: parseCaptchaTarget(m.target),source: m.source === 'auto' ? 'auto' : 'bot',status: statusOf(m.status),@@ -87,6 +92,7 @@ export function humanStepView(meta: HumanStepMeta, live?: HumanStep | null): Humstatus: live.status,url: live.url ?? meta.url,sandbox_target: live.sandbox_target ?? meta.sandbox_target,+ page_key: live.page_key ?? meta.page_key,target: parseCaptchaTarget(live.target) ?? meta.target,};}diff --git a/frontend/src/useBrowserPages.ts b/frontend/src/useBrowserPages.tsnew file mode 100644index 00000000..f419cd0b--- /dev/null+++ b/frontend/src/useBrowserPages.ts@@ -0,0 +1,61 @@+import { useCallback, useEffect, useRef, useState } from 'react';++import { BrowserPageList, fetchBrowserPages, onBrowserPagesChanged } from './browserPages';++/** How often the strip asks for the team's pages while the pane is open. */+export const PAGES_REFRESH_MS = 10_000;++/**+ * The team's browser pages (0.9.3), for the pane's strip: loaded while `visible`, again on every+ * BrowserNavigated, SandboxStatusChanged and human_step_updated for the team, and every 10 s.+ * `at` is when the list was asked for, so a page picked after that isn't judged closed by it.+ * An older server without the route leaves it null (no strip).+ */+export function useBrowserPages(team: string | undefined, visible: boolean) {+ const [list, setList] = useState<(BrowserPageList & { at: number }) | null>(null);+ const seq = useRef(0);+ const live = !!team && team !== 'default' && visible;+ // Another team's list must never show under this one (the pane is keyed by team, so this is a guard)+ const shownTeam = useRef(team);+ if (shownTeam.current !== team) {+ shownTeam.current = team;+ seq.current++;+ if (list) setList(null);+ }++ const load = useCallback(() => {+ if (!team || team === 'default') return;+ const n = ++seq.current;+ const at = Date.now();+ fetchBrowserPages(team)+ .then((l) => {+ if (n !== seq.current) return;+ setList(l && l.team_id === team ? { ...l, at } : null);+ })+ .catch(() => {+ // offline for a moment: keep the last list until the next refresh+ });+ }, [team]);++ useEffect(() => {+ if (!live) return;+ load();+ let soon: ReturnType<typeof setTimeout> | undefined;+ // Events come in bursts (a bot navigating fires several): one load for each burst+ const off = onBrowserPagesChanged((t) => {+ if (t !== team) return;+ clearTimeout(soon);+ soon = setTimeout(load, 250);+ });+ const tick = setInterval(() => {+ if (typeof document === 'undefined' || !document.hidden) load();+ }, PAGES_REFRESH_MS);+ return () => {+ off();+ clearTimeout(soon);+ clearInterval(tick);+ };+ }, [live, team, load]);++ return { list, reload: load };+}diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.tsindex ba5a644b..c773445d 100644--- a/frontend/src/useBrowserStream.ts+++ b/frontend/src/useBrowserStream.ts@@ -30,13 +30,16 @@ export function takeoverRefusedText(message: { code?: unknown; error?: unknown }return BOT_BUSY_TEXT;}-export function useBrowserStream(id: string | undefined, visible: boolean) {+/** `page` (0.9.3): which of the team's pages to show; null or undefined is the server's default. A change reconnects. */+export function useBrowserStream(id: string | undefined, visible: boolean, page?: string | null) {const socket = useRef<WebSocket | null>(null);const sequence = useRef(0);const pending = useRef(new Set<number>());const takingControl = useRef(false);const lastImage = useRef<string | null>(null);const [connected, setConnected] = useState(false);+ // The page the open stream shows (null: the server's default), set with its first frame+ const [livePage, setLivePage] = useState<string | null>(null);const [controlling, setControlling] = useState(false);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -69,7 +72,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {let reconnect: ReturnType<typeof setTimeout>;let attempts = 0;const connect = () => {- const ws = new WebSocket(browserStreamUrl(window.location, id));+ const ws = new WebSocket(browserStreamUrl(window.location, id, page));socket.current = ws;ws.onopen = () => {if (disposed) { ws.close(); return; }@@ -97,6 +100,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {case 'frame': {attempts = 0;setConnected(true);+ setLivePage(page ?? null);const width = Number(message.width) > 0 ? Number(message.width) : 1280;const height = Number(message.height) > 0 ? Number(message.height) : 800;// An identical picture leaves <img src> unchanged, so no load event comes to acknowledge it@@ -175,6 +179,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {actionsById.current.clear();failWaiters();setConnected(false);+ setLivePage(null);setControlling(false);setBusy(false);setFrame(null);@@ -185,7 +190,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {setViewport(null);setResizeIgnored(false);};- }, [id, visible]);+ }, [id, visible, page]);/*** `input` marks a discrete action that waits for the page's ack (and shows "Relaying…").@@ -247,6 +252,8 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {const clearError = useCallback(() => setError(null), []);return {+ /** The page the connected stream shows, null for the server's default (meaningful while `connected`). */+ page: livePage,connected, controlling, busy, error, frame, location, tapFocus, viewport, select, dialog, cursor, unsupported, resizeIgnored,send, request, acknowledgeFrame, restoreViewport, clearSelect, clearDialog, clearError,};diff --git a/frontend/tests/browserPages.test.mjs b/frontend/tests/browserPages.test.mjsnew file mode 100644index 00000000..a233feb4--- /dev/null+++ b/frontend/tests/browserPages.test.mjs@@ -0,0 +1,122 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import test from 'node:test';+import ts from 'typescript';++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 { choosePage, shownPage, stepPage, pageLabel, pageOwner, pageWhere, parsePageList, pageTeam, notifyBrowserPages, onBrowserPagesChanged } =+ await load('../src/browserPages.ts');+const { browserStreamUrl } = await load('../src/browserViewport.ts');++const TEAM = 'team-1';+const ARCHITECT = 'team-1#architect#chat-a';+const COMMUNITY = 'team-1#community#chat-c';+const all = [COMMUNITY, ARCHITECT, TEAM];++test('choosePage: the page the person picked wins', () => {+ assert.equal(choosePage({ picked: COMMUNITY, stepPage: ARCHITECT, pages: all }), COMMUNITY);+});++test('choosePage: with no pick, the open step\'s page', () => {+ assert.equal(choosePage({ picked: null, stepPage: ARCHITECT, pages: all }), ARCHITECT);+});++test('choosePage: with no pick and no step, the server default (no ?page=)', () => {+ assert.equal(choosePage({ picked: null, stepPage: null, pages: all }), null);+});++test('choosePage: a picked page that closed falls back to the step page, then the default', () => {+ const left = [ARCHITECT, TEAM];+ assert.equal(choosePage({ picked: COMMUNITY, stepPage: ARCHITECT, pages: left }), ARCHITECT);+ assert.equal(choosePage({ picked: COMMUNITY, stepPage: null, pages: left }), null);+ // a step on a page that is gone is no reason to ask for it either+ assert.equal(choosePage({ picked: null, stepPage: COMMUNITY, pages: left }), null);+});++test('choosePage: a new step never pulls the view off a picked page', () => {+ const before = choosePage({ picked: COMMUNITY, stepPage: null, pages: all });+ const after = choosePage({ picked: COMMUNITY, stepPage: ARCHITECT, pages: all });+ assert.equal(before, COMMUNITY);+ assert.equal(after, COMMUNITY);+});++test('choosePage: before the first list loads, a pick or step page is trusted as is', () => {+ assert.equal(choosePage({ picked: ARCHITECT, stepPage: null, pages: null }), ARCHITECT);+ assert.equal(choosePage({ picked: null, stepPage: ARCHITECT, pages: null }), ARCHITECT);+ assert.equal(choosePage({ picked: null, stepPage: null, pages: null }), null);+});++test('shownPage: the chosen page, else the server\'s live page, else the team page', () => {+ assert.equal(shownPage(ARCHITECT, { live: COMMUNITY }, TEAM), ARCHITECT);+ assert.equal(shownPage(null, { live: COMMUNITY }, TEAM), COMMUNITY);+ assert.equal(shownPage(null, null, TEAM), TEAM);+});++test('stepPage: its own page, else (an older step) the team page', () => {+ assert.equal(stepPage({ page_key: ARCHITECT, sandbox_target: TEAM }), ARCHITECT);+ assert.equal(stepPage({ page_key: null, sandbox_target: TEAM }), TEAM);+ assert.equal(stepPage({ sandbox_target: TEAM }), TEAM);+ assert.equal(stepPage(null), null);+ assert.equal(pageTeam(ARCHITECT), TEAM);+ assert.equal(pageTeam(TEAM), TEAM);+});++test('tab words: bot and site, "Shared" for the team page, and the waiting mark', () => {+ const names = { architect: 'Architect' };+ const name = (id) => names[id];+ const held = { page: ARCHITECT, team_id: TEAM, kwant_id: 'architect', chat_id: 'chat-a', job: true, url: 'https://www.tiktok.com/login', title: 'Log in | TikTok', held: true, idle_seconds: 3 };+ assert.equal(pageLabel(held, name), "Architect's page: tiktok.com (needs you)");+ const team = { ...held, page: TEAM, kwant_id: null, chat_id: null, job: false, url: 'about:blank', title: '', held: false };+ assert.equal(pageOwner(team, name), 'Shared');+ assert.equal(pageLabel(team, name), 'Shared page: nothing open');+ assert.equal(pageOwner({ job: true, kwant_id: 'gone' }, name), 'A bot');+ assert.equal(pageWhere({ url: null, title: 'Flow' }), 'Flow');+ assert.equal(pageWhere({ url: 'about:blank', title: 'about:blank' }), 'nothing open');+});++test('parsePageList: keeps the server\'s list and drops what it cannot read', () => {+ assert.equal(parsePageList(null), null);+ assert.equal(parsePageList({ error: 'Not found' }), null);+ const list = parsePageList({+ team_id: TEAM,+ live: ARCHITECT,+ max_job_pages: 4,+ pages: [{ page: ARCHITECT, kwant_id: 'architect', chat_id: 'chat-a', job: true, url: 'https://tiktok.com', title: 'TikTok', held: true, idle_seconds: 1 }, { nope: 1 }, { page: TEAM, kwant_id: null, job: false }],+ });+ assert.equal(list.live, ARCHITECT);+ assert.deepEqual(list.pages.map((p) => [p.page, p.held, p.job]), [[ARCHITECT, true, true], [TEAM, false, false]]);+});++test('notifyBrowserPages: a page key wakes its team\'s strip', () => {+ const heard = [];+ const off = onBrowserPagesChanged((t) => heard.push(t));+ notifyBrowserPages(ARCHITECT);+ notifyBrowserPages(TEAM);+ notifyBrowserPages(null);+ off();+ notifyBrowserPages(TEAM);+ assert.deepEqual(heard, [TEAM, TEAM]);+});++test('browserStreamUrl: ?page= with the # of a job page encoded', () => {+ const loc = { protocol: 'https:', host: 'bots.example.com' };+ assert.equal(browserStreamUrl(loc, TEAM), 'wss://bots.example.com/api/sandbox/team-1/stream');+ assert.equal(browserStreamUrl(loc, TEAM, null), 'wss://bots.example.com/api/sandbox/team-1/stream');+ assert.equal(browserStreamUrl(loc, TEAM, ARCHITECT), 'wss://bots.example.com/api/sandbox/team-1/stream?page=team-1%23architect%23chat-a');+});++test('the pane picks the page by choosePage and streams it; the card\'s Sign in / Solve sends the step\'s page', async () => {+ const pane = await readFile(new URL('../src/components/VirtualMachinePane.tsx', import.meta.url), 'utf8');+ assert.match(pane, /choosePage\(\{ picked: picked\?\.page \?\? null, stepPage: stepPage\(openStep\), pages: knownPages \}\)/);+ assert.match(pane, /useBrowserStream\([^)]*, chosenPage\)/);+ assert.match(pane, /stream\.page !== chosenPage/, 'Solve takes control only once the chosen page is on screen');+ const card = await readFile(new URL('../src/components/HumanStepCard.tsx', import.meta.url), 'utf8');+ assert.equal((card.match(/onOpenBrowser\(view\.sandbox_target, true, view\.page_key \?\? view\.sandbox_target\)/g) || []).length, 2);+ 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');+});