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: the address field follows the chosen tab (28r) (#812)
Oleksandr Ivanchenkoa58ae4644b4e
diff --git a/frontend/src/browserPages.ts b/frontend/src/browserPages.tsindex 4e7ffb4a..3165165f 100644--- a/frontend/src/browserPages.ts+++ b/frontend/src/browserPages.ts@@ -329,3 +329,19 @@ export function trailTime(iso: string, locale?: string): string {.replace(/\s?[AaPp]\.?\s?[Mm]\.?$/, '').trim();}++/**+ * 28r: the address the pane shows for the page on screen, one rule for the address field and the picture.+ * The chosen page's own stream first; a `location` from any other stream (the page just left) never counts.+ * Then the chosen page's listed `url` (blank for a page with none). With no page chosen (an older server,+ * no pages route), the app's last known address, as before.+ */+export function addressToShow(o: {+ location: { url: string; page: string | null } | null;+ chosen: string | null;+ listedUrl: string | null | undefined;+ activeUrl: string;+}): string {+ if (o.location && o.location.page === o.chosen) return o.location.url;+ return o.chosen ? o.listedUrl ?? '' : o.activeUrl;+}diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex bdc22607..617a2c9a 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, ownNewestPage, pageOpened, pageTeam, pageTitleOf, restingPage, shownPage, stepPage, trailTime, type ReplyPage } from '../browserPages';+import { addressToShow, choosePage, noteTitle, ownNewestPage, pageOpened, pageTeam, pageTitleOf, restingPage, shownPage, stepPage, trailTime, type ReplyPage } from '../browserPages';import { useBrowserPages } from '../useBrowserPages';import { BrowserPageStrip } from './BrowserPageStrip';import { secondsText } from '../clock';@@ -190,7 +190,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({}) => {const [activeTab, setActiveTab] = useState<PaneTab>(() => chosenPaneTab(teamId));useEffect(() => rememberPaneTab(teamId, activeTab), [teamId, activeTab]);- const [inputUrl, setInputUrl] = useState(activeUrl);+ // 28r: what was last written into the address field, and for which tab (see `fieldKey` below)+ const [written, setWritten] = useState<{ key: string; url: string } | null>(null);// No event fires when the browser catches a login, so a new screenshot or page loads the list again.const passwords = useSavedPasswords(teamId, `${activeUrl}|${screenshotBase64?.length ?? 0}|${screenshotBase64?.slice(-32) ?? ''}`);const savedCount = passwords.logins.length;@@ -285,8 +286,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({// Shown for a moment after the CAPTCHA closes by itself, before control goes back to the botconst [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 : chosenPage ? pageInfo?.url ?? '' : activeUrl;+ // Once the chosen page's own stream reports where the tab is, trust it; before that, that page's listed+ // address; with no page chosen, the last URL the app heard of (28r: one rule, shared with the field).+ const pageUrl = addressToShow({ location: stream.location, chosen: chosenPage, listedUrl: 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 : chosenPage ? pageInfo?.title ?? '' : pageTitle;// A blank light frame from Chrome (a page committing) waits behind the last good picture: no grey flash@@ -304,16 +306,31 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({useEffect(() => {if (blankFrameId !== undefined) acknowledgeFrame(blankFrameId);}, [blankFrameId, acknowledgeFrame]);+ // 28r: the address field follows the tab. A value typed or reported belongs to the tab it was written for;+ // for any other tab the field shows that tab's listed address (none or a blank tab: empty), in the same+ // render as the pick, so the old tab's address never shows under the new one. While the list is still on+ // its way nothing is chosen yet: empty, not another bot's last address. No page chosen: as before.+ const fieldKey = chosenPage ? `page:${chosenPage}` : pagesKnown ? 'default' : 'waiting';+ const inputUrl = written?.key === fieldKey+ ? written.url+ : chosenPage ? (isBlankPage(pageInfo?.url) ? '' : pageInfo?.url ?? '') : pagesKnown ? activeUrl : '';+ const setInputUrl = (url: string) => setWritten({ key: fieldKey, url });+ // Then the stream takes over, but only the chosen page's own: a late message from the page just left+ // never writes its addressuseEffect(() => {- if (stream.location?.url) setInputUrl(stream.location.url);+ if (stream.location?.url && stream.location.page === chosenPage) setWritten({ key: fieldKey, url: stream.location.url });+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [stream.location]);// The pane's own stream knows each page's title too, so the trail can name pages the bot openeduseEffect(() => {noteTitle(stream.location?.url, stream.location?.title);}, [stream.location?.url, stream.location?.title]);+ // The app's last known address is any bot's, not the selected tab's: it writes the field only when no+ // page is chosen (an older server with no pages route)useEffect(() => {- setInputUrl(activeUrl);+ if (!chosenPage && pagesKnown) setWritten({ key: fieldKey, url: activeUrl });+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [activeUrl]);// "Solve it" on the card or a CAPTCHA notification: take control once the stream is updiff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.tsindex b7b6b873..95a4b4ac 100644--- a/frontend/src/useBrowserStream.ts+++ b/frontend/src/useBrowserStream.ts@@ -44,7 +44,9 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);const [frame, setFrame] = useState<BrowserFrame | null>(null);- const [location, setLocation] = useState<{ url: string; title: string } | null>(null);+ // 28r: `page` is the page this location's own stream was opened for (null: the server's default), so the+ // pane can tell a message about the chosen page from one about the page it just left+ const [location, setLocation] = useState<{ url: string; title: string; page: string | null } | null>(null);// After each tap: whether it focused a text field on the page (the phone keyboard follows it)const [tapFocus, setTapFocus] = useState<{ seq: number; editable: boolean } | null>(null);const [viewport, setViewport] = useState<Size | null>(null);@@ -123,7 +125,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean, page?setFrame({ id: message.id, image: message.image, width, height });break;}- case 'location': setLocation({ url: message.url || '', title: message.title || '' }); break;+ case 'location': setLocation({ url: message.url || '', title: message.title || '', page: page ?? null }); break;case 'signin':setSignIn(typeof message.text === 'string' && message.text? { text: message.text, action: typeof message.action === 'string' ? message.action : null }diff --git a/frontend/tests/addressFollowsTheTab.test.mjs b/frontend/tests/addressFollowsTheTab.test.mjsnew file mode 100644index 00000000..199aabfa--- /dev/null+++ b/frontend/tests/addressFollowsTheTab.test.mjs@@ -0,0 +1,165 @@+// 28r address-follows-the-tab: after a pick of another tab the address field kept the old tab's address until+// the new stream's first `location`, and on open it showed `activeUrl` (any bot's last address). Mira's+// browser-switch-no-flash/design-check.md:31 and Rigel's panel-opens-on-the-bot/qa.md follow-up.+// The field now follows the chosen page: its listed url at once, then only that page's own stream.+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 = 'o1';+const BEN_PAGE = 'o1#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, ownNewestPage, fetchBrowserPages, addressToShow } from './src/browserPages';+ export { PAGES_WAIT_MS } from './src/useBrowserPages';+`);+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(); } };+}++++const ANN = (team) => ({ page: `${team}#ann#c2`, team_id: team, kwant_id: 'ann', chat_id: 'c2', job: true, url: 'https://news.example.com/', title: 'News', held: false, idle_seconds: 9 });+const NAMES = { ben: 'Ben', ann: 'Ann' };+const OTHER = 'https://elsewhere.example.org/last-bot-address';+const field = (host) => host.querySelector('input[placeholder="https://..."]');+const click = (host, page) => pane.flushSync(() => host.querySelector(`[data-page-tab="${page}"]`).dispatchEvent(new window.MouseEvent('click', { bubbles: true })));+const threeTabs = (team) => { const k = teamPages(team); return { ...k, ANN: ANN(team), LIST: { team_id: team, live: team, max_job_pages: 4, pages: [k.SHARED, k.BEN, ANN(team)] } }; };++test('addressToShow: the chosen page own stream, else its listed url, else (nothing chosen) activeUrl', () => {+ const { addressToShow } = pane;+ assert.equal(typeof addressToShow, 'function', 'browserPages.ts exports addressToShow');+ const loc = (url, page) => ({ url, page });+ assert.equal(addressToShow({ location: loc('https://shop.example.com/cart', 'p#ben'), chosen: 'p#ben', listedUrl: 'https://shop.example.com/', activeUrl: OTHER }), 'https://shop.example.com/cart');+ assert.equal(addressToShow({ location: loc('https://shop.example.com/cart', 'p#ben'), chosen: 'p', listedUrl: 'about:blank', activeUrl: OTHER }), 'about:blank', "the page just left doesn't count");+ assert.equal(addressToShow({ location: null, chosen: 'p#ann', listedUrl: 'https://news.example.com/', activeUrl: OTHER }), 'https://news.example.com/');+ assert.equal(addressToShow({ location: null, chosen: 'p#ann', listedUrl: undefined, activeUrl: OTHER }), '', 'no listed url: blank, never activeUrl');+ assert.equal(addressToShow({ location: null, chosen: null, listedUrl: undefined, activeUrl: OTHER }), OTHER, 'no page chosen: as before');+ assert.equal(addressToShow({ location: loc('https://a.example/', null), chosen: null, listedUrl: undefined, activeUrl: OTHER }), 'https://a.example/', 'no pages route: the default stream');+});++test("on open the field shows the chosen tab's listed address, not another bot's last one", async () => {+ const k = threeTabs('r1');+ answer = k.LIST;+ const m = mount({ teamId: 'r1', browsingBot: 'Ben', botNames: NAMES, activeUrl: OTHER, onNavigate: () => {} });+ try {+ assert.equal(field(m.host).value, '', 'while the list is on its way: empty, not activeUrl');+ await settle();+ assert.equal(currentTab(m.host), 'r1#ben#c1');+ assert.equal(field(m.host).value, BEN.url, "Ben's listed address before any location");+ } finally { m.done(); }+});++test("a pick shows the new tab's address at once; a blank tab clears it; its own location then takes over", async () => {+ const k = threeTabs('r2');+ answer = k.LIST;+ const m = mount({ teamId: 'r2', browsingBot: 'Ben', botNames: NAMES, activeUrl: OTHER, onNavigate: () => {} });+ try {+ await settle();+ const benSocket = sockets.at(-1);+ benSocket.receive({ type: 'location', url: 'https://shop.example.com/trail/cart', title: 'Cart' });+ await settle();+ assert.equal(field(m.host).value, 'https://shop.example.com/trail/cart', "Ben's own location sets it");+ click(m.host, 'r2#ann#c2');+ assert.equal(field(m.host).value, 'https://news.example.com/', "Ann's listed address in the same frame as the pick");+ await settle();+ const annSocket = sockets.at(-1);+ assert.notEqual(annSocket, benSocket, 'a new stream for Ann');+ assert.equal(field(m.host).value, 'https://news.example.com/', 'still Ann, before her stream speaks');+ // A late message from the stream being closed never writes Ben's address+ benSocket.receive({ type: 'location', url: 'https://shop.example.com/trail/cart', title: 'Cart' });+ await settle();+ assert.equal(field(m.host).value, 'https://news.example.com/', "Ben's late location is ignored");+ annSocket.receive({ type: 'location', url: 'https://news.example.com/story/7', title: 'Story' });+ await settle();+ assert.equal(field(m.host).value, 'https://news.example.com/story/7', "Ann's own location takes over");+ // The team page has no address (about:blank): the field clears, the placeholder shows+ click(m.host, 'r2');+ assert.equal(field(m.host).value, '', 'blank tab: empty field');+ await settle();+ assert.equal(field(m.host).value, '');+ // activeUrl is any bot's last address: it never overwrites the chosen tab's+ m.render({ activeUrl: 'https://another.example.net/' });+ await settle();+ assert.equal(field(m.host).value, '', 'an activeUrl change while a page is chosen is ignored');+ } finally { m.done(); }+});++test('no pages route (404): the field follows activeUrl and the default stream, as before', async () => {+ const saved = g.fetch;+ g.fetch = g.window.fetch = async () => ({ ok: false, status: 404, json: async () => ({}), text: async () => '' });+ const m = mount({ teamId: 'r3', browsingBot: 'Ben', botNames: NAMES, activeUrl: OTHER, onNavigate: () => {} });+ try {+ await settle();+ assert.equal(m.host.querySelector('[data-page-tab]'), null, 'no strip');+ assert.equal(field(m.host).value, OTHER, 'activeUrl, as before');+ m.render({ activeUrl: 'https://next.example.net/' });+ await settle();+ assert.equal(field(m.host).value, 'https://next.example.net/', 'an activeUrl change still writes it');+ sockets.at(-1).receive({ type: 'location', url: 'https://default.example.com/', title: 'D' });+ await settle();+ assert.equal(field(m.host).value, 'https://default.example.com/', "the default stream's location writes it");+ } finally { m.done(); g.fetch = g.window.fetch = saved; }+});