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
Browser pane: opening the panel after a run stays on one tab (28l, stacked on #795) (#804)
Oleksandr Ivanchenko8123822a824b
diff --git a/frontend/src/browserPages.ts b/frontend/src/browserPages.tsindex ffd9abae..49aa7e37 100644--- a/frontend/src/browserPages.ts+++ b/frontend/src/browserPages.ts@@ -55,6 +55,33 @@ export function choosePage(input: { picked: string | null; stepPage: string | nureturn null;}+/**+ * 28l: the page the pane rests on when nothing is chosen (no pick, no open step), once the pages+ * list is known. It stays on `held`, the page it was already showing, while that page is still+ * listed, so the server's default moving after a run (from the bot's page back to the team page, or+ * the other way when a page is merely used) never swaps the tab under the person. Else the server's+ * default. With no list (an older server with no pages route, or before the first answer) it is+ * null: the old fallback. The pane lets go of `held` when a page opens (see pageOpened).+ */+export function restingPage(held: string | null, list: Pick<BrowserPageList, 'live' | 'pages'> | null): string | null {+ if (!list) return null;+ if (held && list.pages.some((p) => p.page === held)) return held;+ return list.live;+}++/**+ * 28l: whether a page opened between two lists: a page that is new, or one at a new address (a bot's+ * open or navigate step). Then the pane follows the server's default again, the page just used.+ * A page that was only used, closed or retitled doesn't count.+ */+export function pageOpened(before: Pick<BrowserPageList, 'pages'> | null, after: Pick<BrowserPageList, 'pages'> | null): boolean {+ if (!before || !after) return false;+ const was = new Map(before.pages.map((p) => [p.page, p.url]));+ return after.pages.some((p) => !was.has(p.page) || (p.url !== was.get(p.page) && !isBlankUrl(p.url)));+}++const isBlankUrl = (url: string | null) => !url || url === 'about:blank';+/** 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;diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex 57c8991a..5106ad9a 100644--- a/frontend/src/components/VirtualMachinePane.tsx+++ b/frontend/src/components/VirtualMachinePane.tsx@@ -35,7 +35,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, noteTitle, pageTeam, pageTitleOf, shownPage, stepPage, trailTime, type ReplyPage } from '../browserPages';+import { choosePage, noteTitle, pageOpened, pageTeam, pageTitleOf, restingPage, shownPage, stepPage, trailTime, type ReplyPage } from '../browserPages';import { useBrowserPages } from '../useBrowserPages';import { BrowserPageStrip } from './BrowserPageStrip';import { secondsText } from '../clock';@@ -230,7 +230,21 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({// A list asked for before the pick can't know the picked page yetconst 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 });+ // 28l: with nothing chosen, the page the pane already shows, kept while it is open. It lets go when a+ // page opens (a bot's open or navigate step), then rests on the server's default, the page just used.+ // Once the list is known this is never null, so the stream always names its page.+ const [heldPage, setHeldPage] = useState<string | null>(null);+ const lastList = useRef(pages.list);+ const opened = pages.list !== lastList.current && pageOpened(lastList.current, pages.list);+ const chosenPage =+ choosePage({ picked: picked?.page ?? null, stepPage: stepPage(openStep), pages: knownPages }) ??+ restingPage(opened ? null : heldPage, pages.list);+ useEffect(() => {+ lastList.current = pages.list;+ }, [pages.list]);+ useEffect(() => setHeldPage(isOpen ? chosenPage : null), [isOpen, chosenPage]);+ // Until the first list answers, the stream waits (a stream to the default, then to the named page, blinks)+ const pagesKnown = pages.checked || !teamId || teamId === 'default';// The picked page closed (idle, or the cap made room): forget it, so it never comes back by itselfuseEffect(() => {if (picked && knownPages && !knownPages.includes(picked.page)) setPicked(null);@@ -252,7 +266,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({// Interactive Remote Control Stateconst streaming = isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending;- const stream = useBrowserStream(teamId, streaming, chosenPage);+ const stream = useBrowserStream(teamId, streaming && pagesKnown, chosenPage);// 28e: the page the stream belongs to. Until the stream reconnects, it still shows the last page.const [streamFor, setStreamFor] = useState(chosenPage);useEffect(() => setStreamFor(chosenPage), [chosenPage]);@@ -278,7 +292,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({// A live stream is ready; otherwise trust isRunning only while no error says the service is down.const browserReady = stream.connected || (isRunning && !controlError);// 28e: after a switch to another page's tab, the dark pane until that page's own frame, never another picture- const panePicture = paneFrame({ blank: isBlankPage(pageUrl), frame: steady.frame, holding: steady.holding, streaming: streaming && browserReady, switching: streamFor !== chosenPage, streamPage: stream.page, chosenPage, screenshot: screenshotBase64 });+ const panePicture = paneFrame({ blank: isBlankPage(pageUrl), frame: steady.frame, holding: steady.holding, streaming: streaming && browserReady, switching: streamFor !== chosenPage || !pagesKnown, streamPage: stream.page, chosenPage, screenshot: screenshotBase64 });const currentScreenshot = 'image' in panePicture ? panePicture.image : null;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.diff --git a/frontend/src/useBrowserPages.ts b/frontend/src/useBrowserPages.tsindex f419cd0b..fde827e1 100644--- a/frontend/src/useBrowserPages.ts+++ b/frontend/src/useBrowserPages.ts@@ -5,14 +5,28 @@ import { BrowserPageList, fetchBrowserPages, onBrowserPagesChanged } from './bro/** How often the strip asks for the team's pages while the pane is open. */export const PAGES_REFRESH_MS = 10_000;+/** 28l: how long the pane waits for the first list before it streams the server's default anyway. */+export const PAGES_WAIT_MS = 1_500;+/*** 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).+ * `checked` (28l) is false from the moment the pane shows until the first answer since then, so the+ * pane knows whether to wait for the list or use its older fallback; the list is dropped when it hides.*/+// 28l: teams whose server answered with no pages list (an older server): the pane doesn't wait for it again+const noPagesRoute = new Set<string>();++/** Marks a team's server as having no pages route (as its first answer would); for tests that render once. */+export function noteNoPagesRoute(team: string): void {+ noPagesRoute.add(team);+}+export function useBrowserPages(team: string | undefined, visible: boolean) {const [list, setList] = useState<(BrowserPageList & { at: number }) | null>(null);+ const [checked, setChecked] = useState(() => !!team && noPagesRoute.has(team));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)@@ -31,15 +45,21 @@ export function useBrowserPages(team: string | undefined, visible: boolean) {.then((l) => {if (n !== seq.current) return;setList(l && l.team_id === team ? { ...l, at } : null);+ if (l) noPagesRoute.delete(team);+ else noPagesRoute.add(team);+ setChecked(true);}).catch(() => {// offline for a moment: keep the last list until the next refresh+ if (n === seq.current) setChecked(true);});}, [team]);useEffect(() => {if (!live) return;load();+ // A slow answer must not keep the pane waiting: after this, the older fallback+ const giveUp = setTimeout(() => setChecked(true), PAGES_WAIT_MS);let soon: ReturnType<typeof setTimeout> | undefined;// Events come in bursts (a bot navigating fires several): one load for each burstconst off = onBrowserPagesChanged((t) => {@@ -53,9 +73,15 @@ export function useBrowserPages(team: string | undefined, visible: boolean) {return () => {off();clearTimeout(soon);+ clearTimeout(giveUp);+ // The pane closed: its list goes stale (a run may move pages before it opens again), so the next+ // open starts with none and waits for a fresh one, rather than showing this one for a moment+ seq.current++;+ setList(null);+ setChecked(!!team && noPagesRoute.has(team));clearInterval(tick);};}, [live, team, load]);- return { list, reload: load };+ return { list, checked, reload: load };}diff --git a/frontend/tests/browserPanel.test.mjs b/frontend/tests/browserPanel.test.mjsindex e7b24048..8d0560e2 100644--- a/frontend/tests/browserPanel.test.mjs+++ b/frontend/tests/browserPanel.test.mjs@@ -8,6 +8,7 @@ globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };const m = await loadBundled(`export { isBlankPage, browserFooterLabel } from './src/computerMode';export { VirtualMachinePane, chosenPaneTab, rememberPaneTab } from './src/components/VirtualMachinePane';+ export { noteNoPagesRoute } from './src/useBrowserPages';export { renderToStaticMarkup } from 'react-dom/server.browser';export { createElement } from 'react';`);@@ -19,6 +20,9 @@ const settings = (mode, visible = false) => ({window: { visible, available: true, reason: null },isolates: ['browser', 'kwnt_shell'],});+// One static render runs no effects, so no pages list ever answers. 28l: until it does, the pane holds the dark+// pane; these tests are about the picture without page streams, so team k1 is an older server with no pages route.+m.noteNoPagesRoute('k1');const pane = (props) =>m.renderToStaticMarkup(m.createElement(m.VirtualMachinePane, { isOpen: true, onClose: () => {}, teamId: 'k1', screenshotBase64: 'AAAA', ...props }));diff --git a/frontend/tests/panelOpenNoBlink.test.mjs b/frontend/tests/panelOpenNoBlink.test.mjsnew file mode 100644index 00000000..4603f2f9--- /dev/null+++ b/frontend/tests/panelOpenNoBlink.test.mjs@@ -0,0 +1,244 @@+// 28l: right after a bot's run, opening the bot browser panel showed Ben's tab with the lit shop, then the+// strip moved to Shared and dropped to "Browser idle" (Mira, site-clips-0922 design-check :115; frames 46-50).+// With nothing chosen, the pane followed the server's default page (`live`), which still pointed at Ben's job+// page and flipped back to the team page a moment later, and with no named page the picture could be the+// app-level screenshot (Ben's last shot) under any tab. Now, once the pages list is known, the pane always+// names its page (restingPage): the one it already shows, while it is listed, until a page opens (pageOpened).+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLImageElement', 'Element', 'Node', 'Event', 'FocusEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.ResizeObserver = g.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };+g.window.matchMedia = (q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });++// A team's pages, as the server lists them (each test has its own team: a pick is remembered per team)+const teamPages = (team) => {+ const shared = { page: team, team_id: team, kwant_id: null, chat_id: null, job: false, url: 'about:blank', title: '', held: false, idle_seconds: 3 };+ const ben = { page: `${team}#ben#c1`, team_id: team, kwant_id: 'ben', chat_id: 'c1', job: true, url: 'https://shop.example.com/trail/ridgeline-2p', title: 'Ridgeline 2P Tent', held: false, idle_seconds: 1 };+ return {+ SHARED: shared,+ BEN: ben,+ // Just after Ben's run: the default is still his page, newest first+ AFTER_RUN: { team_id: team, live: ben.page, max_job_pages: 4, pages: [ben, shared] },+ // A moment later: the team page was used last, so it is the default and comes first+ MOMENT_LATER: { team_id: team, live: team, max_job_pages: 4, pages: [shared, ben] },+ };+};+const TEAM = 'k1';+const BEN_PAGE = 'k1#ben#c1';+const { SHARED, BEN, AFTER_RUN, MOMENT_LATER } = teamPages(TEAM);++let answer = AFTER_RUN;+let gate = null; // when set, the pages route waits for it+g.fetch = g.window.fetch = async (url) => {+ if (!String(url).includes('/pages')) return { ok: false, status: 404, json: async () => ({}), text: async () => '' };+ if (gate) await gate;+ const body = answer;+ return { ok: true, status: 200, json: async () => body, text: async () => '' };+};++const sockets = [];+class FakeWebSocket {+ static OPEN = 1;+ constructor(url) { this.url = url; this.readyState = 1; this.sent = []; this.bufferedAmount = 0; sockets.push(this); }+ send(text) { this.sent.push(JSON.parse(text)); }+ close() { this.readyState = 3; }+ receive(message) { this.onmessage?.({ data: JSON.stringify(message) }); }+}+g.WebSocket = g.window.WebSocket = FakeWebSocket;++const pane = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export { flushSync } from 'react-dom';+ export { VirtualMachinePane } from './src/components/VirtualMachinePane';+ export { notifyBrowserPages, pageOpened, restingPage } from './src/browserPages';+`);+const settle = async (ms = 0) => { for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0)); if (ms) await new Promise((r) => setTimeout(r, ms)); };++const APP_SHOT = 'APPLEVELSHOTOFBENSSHOP';+const SHOP = 'SHOPFRAMEOFBENSPAGE';+const pictures = (host) => [...host.querySelectorAll('img')].map((i) => i.getAttribute('src') || '');+const currentTab = (host) => host.querySelector('[data-page-tab][aria-current="true"]')?.getAttribute('data-page-tab') ?? null;++function mount(props) {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = pane.createRoot(host);+ const render = (p) => pane.flushSync(() => root.render(pane.React.createElement(pane.VirtualMachinePane, {+ isOpen: true, onClose: () => {}, teamId: TEAM, teamName: 'Trailhead', isRunning: true,+ screenshotBase64: APP_SHOT, botNames: { ben: 'Ben' }, activeUrl: 'https://shop.example.com/trail/ridgeline-2p', ...props, ...p,+ })));+ render({});+ return { host, render: (p) => render(p), done: () => { pane.flushSync(() => root.unmount()); host.remove(); } };+}++test('restingPage: the page already shown while it is listed, else the default; null with no list', () => {+ const { restingPage } = pane;+ assert.equal(typeof restingPage, 'function', 'browserPages.ts exports restingPage');+ // No list (an older server, or before the first answer): the old fallback+ assert.equal(restingPage(null, null), null);+ assert.equal(restingPage(BEN_PAGE, null), null);+ // Nothing held yet (the pane just opened): the server's default+ assert.equal(restingPage(null, AFTER_RUN), BEN_PAGE);+ assert.equal(restingPage(null, MOMENT_LATER), TEAM);+ // The default moved a moment later: stays on the page it opened on+ assert.equal(restingPage(BEN_PAGE, MOMENT_LATER), BEN_PAGE);+ assert.equal(restingPage(TEAM, AFTER_RUN), TEAM);+ // That page closed (idle, or the cap made room): the default+ assert.equal(restingPage(BEN_PAGE, { live: TEAM, pages: [SHARED] }), TEAM);+});++test('opened right after a run: one tab from the first frame, never the app-level screenshot, no jump when the default moves', async () => {+ answer = AFTER_RUN;+ let open;+ gate = new Promise((r) => { open = r; });+ const before = sockets.length;+ const m = mount({ running: false });+ try {+ await settle();+ // Before the list answers: no stream to "whatever the default is", and no stale picture+ assert.equal(sockets.length, before, 'the stream waits for the pages list');+ assert.equal(pictures(m.host).some((s) => s.includes(APP_SHOT)), false, 'no app-level screenshot while the list loads');+ assert.ok(m.host.querySelector('[data-frame-holding]'), 'the dark pane while the list loads');+ open(); gate = null;+ await settle();++ assert.equal(sockets.length, before + 1, 'one stream, opened once');+ const ws = sockets.at(-1);+ assert.match(ws.url, /page=k1%23ben%23c1/, "it names Ben's page");+ assert.equal(currentTab(m.host), BEN_PAGE, "Ben's tab is current");+ ws.onopen?.();+ await settle();+ assert.equal(pictures(m.host).some((s) => s.includes(APP_SHOT)), false, "before Ben's first frame: the dark pane, not the app-level shot");+ ws.receive({ type: 'location', url: BEN.url, title: BEN.title });+ ws.receive({ type: 'frame', id: 1, image: SHOP, width: 1280, height: 800 });+ await settle();+ assert.ok(pictures(m.host).some((s) => s.includes(SHOP)), "Ben's own frame shows");++ // A moment later the server's default flips to the team page, and the strip's list reorders+ answer = MOMENT_LATER;+ pane.notifyBrowserPages(TEAM);+ await settle(300);+ assert.equal(currentTab(m.host), BEN_PAGE, "still Ben's tab");+ assert.equal(sockets.length, before + 1, 'no reconnect');+ assert.equal(/Browser idle/.test(m.host.textContent), false, 'not "Browser idle"');+ assert.ok(pictures(m.host).some((s) => s.includes(SHOP)), "still Ben's page");++ // The person picks Shared: that wins+ m.host.querySelector(`[data-page-tab="${TEAM}"]`).dispatchEvent(new window.MouseEvent('click', { bubbles: true }));+ await settle();+ assert.equal(currentTab(m.host), TEAM);+ assert.match(sockets.at(-1).url, /page=k1(&|$)/);+ } finally {+ m.done();+ gate = null;+ }+});++test('the page it rests on closes: it moves to the default', async () => {+ const k = teamPages('k3');+ answer = k.AFTER_RUN;+ const m = mount({ running: false, teamId: 'k3' });+ try {+ await settle();+ assert.equal(currentTab(m.host), 'k3#ben#c1');+ answer = { team_id: 'k3', live: 'k3', max_job_pages: 4, pages: [k.SHARED, { ...k.BEN, page: 'k3#ann#c2', kwant_id: 'ann', chat_id: 'c2' }] };+ pane.notifyBrowserPages('k3');+ await settle(300);+ assert.equal(currentTab(m.host), 'k3', "Ben's page closed: Shared");+ assert.match(sockets.at(-1).url, /page=k3(&|$)/);+ } finally {+ m.done();+ }+});++test('pageOpened: a new page or a new address; not a page only used, closed or retitled', () => {+ const k = teamPages('u');+ const before = { pages: [k.SHARED, k.BEN] };+ assert.equal(pane.pageOpened(null, before), false);+ assert.equal(pane.pageOpened(before, null), false);+ assert.equal(pane.pageOpened(before, { pages: [k.BEN, k.SHARED] }), false, 'reordered');+ assert.equal(pane.pageOpened(before, { pages: [k.SHARED] }), false, 'closed');+ assert.equal(pane.pageOpened(before, { pages: [k.SHARED, { ...k.BEN, title: 'Other', idle_seconds: 0 }] }), false, 'retitled, used');+ assert.equal(pane.pageOpened(before, { pages: [k.SHARED, { ...k.BEN, url: 'about:blank' }] }), false, 'blanked');+ assert.equal(pane.pageOpened(before, { pages: [k.SHARED, { ...k.BEN, url: 'https://shop.example.com/trail/cart' }] }), true, 'navigated');+ assert.equal(pane.pageOpened({ pages: [k.SHARED] }, before), true, 'new page');+});++test('a bot opens a page while the pane is open: it follows; the default moving back later does not', async () => {+ const k = teamPages('k4');+ answer = { team_id: 'k4', live: 'k4', max_job_pages: 4, pages: [k.SHARED] };+ const m = mount({ running: true, teamId: 'k4' });+ try {+ await settle();+ assert.match(sockets.at(-1).url, /page=k4(&|$)/, 'one page (no strip yet): the team page');+ answer = k.AFTER_RUN;+ pane.notifyBrowserPages('k4');+ await settle(300);+ assert.equal(currentTab(m.host), 'k4#ben#c1', 'the bot opened its page: the pane follows it');+ assert.match(sockets.at(-1).url, /page=k4%23ben%23c1/);+ // The run ends; the default moves back to the team page: the pane stays+ m.render({ running: false });+ answer = k.MOMENT_LATER;+ pane.notifyBrowserPages('k4');+ await settle(300);+ assert.equal(currentTab(m.host), 'k4#ben#c1', 'the default moved, nothing opened: it stays');+ // The team page navigates (a bot opens a page there): it follows+ answer = { ...k.MOMENT_LATER, pages: [{ ...k.SHARED, url: 'https://shop.example.com/' }, k.BEN] };+ pane.notifyBrowserPages('k4');+ await settle(300);+ assert.equal(currentTab(m.host), 'k4', 'a page opened on Shared: it follows');+ } finally {+ m.done();+ }+});++test('reopened after a run: no strip or picture from the last time it was open, then the fresh list', async () => {+ const k = teamPages('k5');+ answer = k.MOMENT_LATER;+ const m = mount({ running: false, teamId: 'k5' });+ try {+ await settle();+ assert.equal(currentTab(m.host), 'k5');+ m.render({ isOpen: false });+ await settle();+ // Ben ran meanwhile; the person opens the panel while the new list is on its way+ answer = k.AFTER_RUN;+ let open;+ gate = new Promise((r) => { open = r; });+ m.render({ isOpen: true });+ assert.equal(m.host.querySelector('[data-page-tab]'), null, 'no tab strip from before');+ await settle();+ assert.equal(m.host.querySelector('[data-page-tab]'), null, 'still none while the list loads');+ open(); gate = null;+ await settle();+ assert.equal(currentTab(m.host), 'k5#ben#c1', 'the fresh list: the default, Ben\'s page');+ } finally {+ m.done();+ gate = null;+ }+});++test('an older server with no pages route: no wait past its answer, and the app-level screenshot is the picture', async () => {+ const fetchWas = g.fetch;+ g.fetch = g.window.fetch = async () => ({ ok: false, status: 404, json: async () => ({}), text: async () => '' });+ const before = sockets.length;+ const m = mount({ running: false, teamId: 'k2' });+ try {+ await settle();+ assert.equal(sockets.length, before + 1, 'the stream opens once the route answered');+ assert.doesNotMatch(sockets.at(-1).url, /page=/, "the server's default");+ assert.ok(pictures(m.host).some((s) => s.includes(APP_SHOT)), 'the screenshot fallback still works');+ } finally {+ m.done();+ g.fetch = g.window.fetch = fetchWas;+ }+});