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.

Browser pane: switching to another page's tab holds the dark pane, not a grey Finished card (28e) (#795)

Oleksandr Ivanchenko7fcd98097c12
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index cdb5b3a1..57c8991a 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -19,7 +19,7 @@ import {
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 { useSteadyFrame } from '../steadyFrame';
+import { paneFrame, useSteadyFrame } from '../steadyFrame';
import { browserFooterLabel, browserOwnerWord, isBlankPage, showsLocalWindow } from '../computerMode';
import { paneStatus } from '../browserPanel';
import { ModernAvatar } from './ModernAvatar';
@@ -251,7 +251,11 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
const touch = useCallback(() => onTouch?.(), [onTouch]);
// Interactive Remote Control State
- const stream = useBrowserStream(teamId, isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending, chosenPage);
+ const streaming = isOpen && activeTab === 'browser' && !isWindow && !computer.windowPending;
+ const stream = useBrowserStream(teamId, streaming, 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]);
const isControlMode = stream.controlling;
const isInteracting = stream.busy;
const narrow = useNarrow();
@@ -270,7 +274,12 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
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
const steady = useSteadyFrame(stream.frame, stream.acknowledgeFrame);
- const currentScreenshot = isBlankPage(pageUrl) ? null : steady.frame?.image || screenshotBase64;
+ const controlError = stream.error || (!stream.connected ? browserError : null);
+ // 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 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.
const blankFrameId = isBlankPage(pageUrl) ? stream.frame?.id : undefined;
@@ -278,9 +287,6 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
useEffect(() => {
if (blankFrameId !== undefined) acknowledgeFrame(blankFrameId);
}, [blankFrameId, acknowledgeFrame]);
- const controlError = stream.error || (!stream.connected ? browserError : null);
- // A live stream is ready; otherwise trust isRunning only while no error says the service is down.
- const browserReady = stream.connected || (isRunning && !controlError);
useEffect(() => {
if (stream.location?.url) setInputUrl(stream.location.url);
}, [stream.location]);
@@ -965,7 +971,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
</button>
)}
</>
- ) : steady.holding && !isBlankPage(pageUrl) ? (
+ ) : 'hold' in panePicture ? (
/* The first picture of this view is blank or still being checked: the dark pane, not "Browser idle" */
<div data-frame-holding="" aria-hidden="true" className="absolute inset-0" />
) : (
diff --git a/frontend/src/steadyFrame.ts b/frontend/src/steadyFrame.ts
index cfc5289c..795998b0 100644
--- a/frontend/src/steadyFrame.ts
+++ b/frontend/src/steadyFrame.ts
@@ -114,3 +114,38 @@ export function useSteadyFrame(
// While a frame is checked or held, the last good picture of this stream stays up (or the dark pane)
return { frame: shown, holding: !shown };
}
+
+/** What the browser pane shows: a picture, the dark pane while one is on its way, or the idle card. */
+export type PaneFrame = { image: string } | { hold: true } | { idle: true };
+
+/**
+ * 28e: the picture for the pane. After a switch to another page's tab the new stream has no frame for
+ * a moment; the app-level screenshot (not tied to any page, often the blank one dimmed to grey) used
+ * to fill that gap. While a chosen page's stream hasn't shown its own good frame, the dark pane holds.
+ * `streaming`: the page stream is in use (not a real window, not one on its way). `switching`: the
+ * chosen page changed and the stream still belongs to the last one. Without a chosen page,
+ * or with no stream, the app-level screenshot is still the fallback, as before.
+ */
+export function paneFrame(input: {
+ blank: boolean;
+ frame: BrowserFrame | null;
+ holding: boolean;
+ streaming: boolean;
+ /** The chosen page changed and the stream hasn't reconnected for it yet. */
+ switching: boolean;
+ streamPage: string | null;
+ chosenPage: string | null;
+ screenshot: string | null | undefined;
+}): PaneFrame {
+ const { blank, frame, holding, streaming, switching, streamPage, chosenPage, screenshot } = input;
+ // The renders right after the click still have the last page's stream (its address, its frame): hold
+ if (streaming && switching) return { hold: true };
+ if (blank) return { idle: true };
+ if (streaming && chosenPage !== null) {
+ // Only this page's own picture: never the app-level screenshot, never the last page's frame
+ return frame?.image && streamPage === chosenPage ? { image: frame.image } : { hold: true };
+ }
+ const image = frame?.image || screenshot;
+ if (image) return { image };
+ return holding ? { hold: true } : { idle: true };
+}
diff --git a/frontend/tests/browserPreviewNoFlash.test.mjs b/frontend/tests/browserPreviewNoFlash.test.mjs
index a1035b8d..c8a41be2 100644
--- a/frontend/tests/browserPreviewNoFlash.test.mjs
+++ b/frontend/tests/browserPreviewNoFlash.test.mjs
@@ -111,7 +111,9 @@ test('a sparse white page: after the first picture, typing frames show at once',
test('every browser view gets its picture through the steady frame, on the dark surface', () => {
const src = readFileSync(new URL('../src/components/VirtualMachinePane.tsx', import.meta.url), 'utf8');
assert.match(src, /const steady = useSteadyFrame\(stream\.frame, stream\.acknowledgeFrame\)/);
- assert.match(src, /const currentScreenshot = isBlankPage\(pageUrl\) \? null : steady\.frame\?\.image/);
+ // 28e: the picture goes through paneFrame, which gets the steady frame (never the raw one) and its holding
+ assert.match(src, /const panePicture = paneFrame\(\{ blank: isBlankPage\(pageUrl\), frame: steady\.frame, holding: steady\.holding,/);
+ assert.match(src, /const currentScreenshot = 'image' in panePicture \? panePicture\.image : null/);
assert.match(src, /paneFrameId\.current = steady\.frame\?\.id/);
assert.doesNotMatch(src, /stream\.frame\?\.image/, 'no view reads the raw frame picture');
const watch = src.slice(src.indexOf('data-browser-watch'), src.indexOf('data-browser-watch') + 400);
diff --git a/frontend/tests/browserSwitchNoFlash.test.mjs b/frontend/tests/browserSwitchNoFlash.test.mjs
new file mode 100644
index 00000000..d903aa90
--- /dev/null
+++ b/frontend/tests/browserSwitchNoFlash.test.mjs
@@ -0,0 +1,176 @@
+// 28e: switching the bot browser pane to another page's tab showed a light-grey empty card with the
+// "Finished" pill for about 233 ms before the page appeared (Mira, site-clips-0922 design-check :116).
+// The new page's stream had no frame yet, so the pane fell back to the app-level screenshot, which isn't
+// tied to any page (the blank one, dimmed to grey). While a chosen page's stream hasn't shown its own good
+// frame, the pane now holds the dark pane instead. With no page stream, the screenshot is still the fallback.
+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() {} });
+
+const TEAM = 'k1';
+const BEN_PAGE = 'k1#ben#c1';
+const PAGES = {
+ team_id: TEAM,
+ live: TEAM,
+ max_job_pages: 4,
+ pages: [
+ { page: TEAM, team_id: TEAM, kwant_id: null, chat_id: null, job: false, url: 'about:blank', title: '', held: false, idle_seconds: 3 },
+ { page: BEN_PAGE, 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 },
+ ],
+};
+g.fetch = g.window.fetch = async (url) => (String(url).includes('/pages')
+ ? { ok: true, status: 200, json: async () => PAGES, text: async () => '' }
+ : { ok: false, status: 404, json: async () => ({}), 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;
+
+// Bundled apart, so on main (no helper yet) the pane test still runs and fails on what it shows
+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';
+`);
+const steady = await loadBundled(`export * from './src/steadyFrame';`);
+const settle = async () => { for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0)); };
+
+// The app-level screenshot: not tied to any page (here the blank one the clip showed dimmed)
+const APP_SHOT = 'APPLEVELBLANKSHOT';
+const SHOP = 'SHOPFRAMEOFBENSPAGE';
+const OLD = 'SHAREDPAGEFRAME';
+
+const pictures = (host) => [...host.querySelectorAll('img')].map((i) => i.getAttribute('src') || '');
+const showsOnly = (host) => ({
+ appShot: pictures(host).some((s) => s.includes(APP_SHOT)),
+ oldFrame: pictures(host).some((s) => s.includes(OLD)),
+ shop: pictures(host).some((s) => s.includes(SHOP)),
+ hold: !!host.querySelector('[data-frame-holding]'),
+ idle: /Browser idle|Browser unavailable/.test(host.textContent),
+});
+
+test('a switch to another page\'s tab: the dark pane until that page\'s own frame, never the app-level screenshot', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = pane.createRoot(host);
+ 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: 'about:blank',
+ })));
+ try {
+ await settle();
+ const first = sockets.at(-1);
+ assert.ok(first, 'the pane opened a live-view socket');
+ first.onopen?.();
+ first.receive({ type: 'location', url: 'https://example.com/shared', title: 'Shared' });
+ first.receive({ type: 'frame', id: 1, image: OLD, width: 1280, height: 800 });
+ await settle();
+
+ const ben = host.querySelector(`[data-page-tab="${BEN_PAGE}"]`);
+ assert.ok(ben && /^Ben's page:/.test(ben.getAttribute('aria-label')), "Ben's tab is in the strip");
+ ben.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ assert.equal(showsOnly(host).appShot, false, 'right after the click: no app-level screenshot');
+
+ const second = sockets.at(-1);
+ assert.notEqual(second, first, "the pane reconnected to Ben's page");
+ assert.match(second.url, /page=k1%23ben%23c1/);
+ second.onopen?.();
+ await settle();
+
+ // Between the click and Ben's first frame (frames 122 to 128 of the clip)
+ let now = showsOnly(host);
+ assert.equal(now.appShot, false, 'the app-level screenshot (the grey "Finished" card) must not show');
+ assert.equal(now.oldFrame, false, "the last page's picture must not show either");
+ assert.equal(now.idle, false, 'not "Browser idle"');
+ assert.equal(now.hold, true, 'the dark pane holds');
+ assert.equal(host.querySelector('[data-pane-pill]'), null, 'no "Finished" pill over an empty card');
+
+ // The address arrives before the picture (frames 126 to 128): still the dark pane
+ second.receive({ type: 'location', url: 'https://shop.example.com/trail/ridgeline-2p', title: 'Ridgeline 2P Tent' });
+ await settle();
+ now = showsOnly(host);
+ assert.equal(now.appShot, false, 'still no app-level screenshot once the URL is known');
+ assert.equal(now.hold, true);
+
+ // Ben's own first good frame: shown
+ second.receive({ type: 'frame', id: 1, image: SHOP, width: 1280, height: 800 });
+ await settle();
+ now = showsOnly(host);
+ assert.equal(now.shop, true, "Ben's page shows");
+ assert.equal(now.appShot, false);
+ assert.equal(now.hold, false);
+ } finally {
+ pane.flushSync(() => root.unmount());
+ host.remove();
+ }
+});
+
+test('with no page stream, the app-level screenshot is still the picture', async () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = pane.createRoot(host);
+ // An older server: no pages route, no chosen page, and a stream that hasn't sent a frame
+ const fetchWas = g.fetch;
+ g.fetch = g.window.fetch = async () => ({ ok: false, status: 404, json: async () => ({}), text: async () => '' });
+ pane.flushSync(() => root.render(pane.React.createElement(pane.VirtualMachinePane, {
+ isOpen: true, onClose: () => {}, teamId: 'k2', teamName: 'Trailhead', isRunning: true,
+ screenshotBase64: APP_SHOT, activeUrl: 'https://example.com/',
+ })));
+ try {
+ await settle();
+ assert.equal(showsOnly(host).appShot, true, 'the screenshot fallback still works');
+ } finally {
+ pane.flushSync(() => root.unmount());
+ host.remove();
+ g.fetch = g.window.fetch = fetchWas;
+ }
+});
+
+test('paneFrame: the decision, case by case', () => {
+ assert.equal(typeof steady.paneFrame, 'function', 'steadyFrame.ts exports paneFrame');
+ const f = (image, id = 1) => ({ id, image, width: 1280, height: 800 });
+ const base = { blank: false, frame: null, holding: false, streaming: true, switching: false, streamPage: null, chosenPage: BEN_PAGE, screenshot: APP_SHOT };
+ const pf = (o) => steady.paneFrame({ ...base, ...o });
+
+ // A switch, with a screenshot and no stream frame yet: hold
+ assert.deepEqual(pf({}), { hold: true });
+ // The new stream's first frame being probed or held (useSteadyFrame: frame null, holding): still hold
+ assert.deepEqual(pf({ holding: true, streamPage: BEN_PAGE }), { hold: true });
+ // The last page's frame, before the new stream answers: hold, not that picture
+ assert.deepEqual(pf({ frame: f(OLD), streamPage: TEAM }), { hold: true });
+ // Ben's own first good frame: shown
+ assert.deepEqual(pf({ frame: f(SHOP), streamPage: BEN_PAGE }), { image: SHOP });
+ // The render right after the click: the last page's stream is still there, blank or not: hold, not "Browser idle"
+ assert.deepEqual(pf({ switching: true, blank: true, frame: f(OLD), streamPage: TEAM }), { hold: true });
+ assert.deepEqual(pf({ switching: true, blank: true }), { hold: true }, 'the last page sent no frame (blank Shared): still hold');
+ assert.deepEqual(pf({ switching: true, chosenPage: null, screenshot: APP_SHOT }), { hold: true }, 'to the server default page: hold too');
+ // An about:blank page: idle, as before
+ assert.deepEqual(pf({ blank: true, frame: f(SHOP), streamPage: BEN_PAGE }), { idle: true });
+
+ // No page stream in use (a real window, one on its way, or the browser not ready): the old fallback
+ assert.deepEqual(pf({ streaming: false }), { image: APP_SHOT });
+ assert.deepEqual(pf({ streaming: false, screenshot: null }), { idle: true });
+ // No chosen page (the server's default): as before 28e
+ assert.deepEqual(pf({ chosenPage: null }), { image: APP_SHOT });
+ assert.deepEqual(pf({ chosenPage: null, frame: f(SHOP) }), { image: SHOP });
+ assert.deepEqual(pf({ chosenPage: null, screenshot: '', holding: true }), { hold: true }, "22o: a held first frame is the dark pane, not 'Browser idle'");
+ assert.deepEqual(pf({ chosenPage: null, screenshot: '' }), { idle: true });
+});