Skip to content

armgit / kwant

Public Imported from GitHub
0

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

Bot browser: the preview never flashes white while a page swaps in (22o) (#726)

Oleksandr Ivanchenko57225c48bfb3
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index 4a0841c3..226f78f0 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -19,6 +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 { browserFooterLabel, browserOwnerWord, isBlankPage, showsLocalWindow } from '../computerMode';
import { paneStatus } from '../browserPanel';
import { ModernAvatar } from './ModernAvatar';
@@ -267,7 +268,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
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 : chosenPage ? pageInfo?.title ?? '' : pageTitle;
- const currentScreenshot = isBlankPage(pageUrl) ? null : stream.frame?.image || screenshotBase64;
+ // 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 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;
@@ -441,7 +444,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
// The frame the side pane shows is acknowledged once drawn; one image, its source swapped
const paneFrameId = useRef<number | null>(null);
- paneFrameId.current = stream.frame?.id ?? null;
+ // The picture on screen: its <img> load acknowledges it (a held one was acknowledged when it came)
+ paneFrameId.current = steady.frame?.id ?? null;
const loginsOnThisPage = useMemo(() => passwords.logins.filter((l) => loginMatchesPage(l, pageUrl)).length, [passwords.logins, pageUrl]);
@@ -961,6 +965,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
</button>
)}
</>
+ ) : steady.holding && !isBlankPage(pageUrl) ? (
+ /* 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" />
) : (
<div className="text-center p-6 text-zinc-500 text-xs">
<Globe size={32} className="mx-auto mb-2 opacity-40 text-zinc-500" />
diff --git a/frontend/src/steadyFrame.ts b/frontend/src/steadyFrame.ts
new file mode 100644
index 00000000..cfc5289c
--- /dev/null
+++ b/frontend/src/steadyFrame.ts
@@ -0,0 +1,116 @@
+import { useEffect, useRef, useState } from 'react';
+import type { BrowserFrame } from './useBrowserStream';
+
+/**
+ * Chrome's screencast sends a blank white picture while a tab commits a new page, before the page
+ * paints its own background (reproduced with the live view's own calls: frame 1 of a navigate to a
+ * dark page is pure white). On the dark pane that read as a light grey flash. The live view keeps
+ * the last good picture while such a frame is in, for at most HOLD_LIGHT_MS, so a page that really
+ * is white still shows.
+ */
+export const HOLD_LIGHT_MS = 1500;
+
+/** Only pictures this small (base64 chars) are checked: a blank 1280x800 frame is about 3.5k, a real page several times more. */
+export const PROBE_MAX_CHARS = 24_000;
+
+/** A picture that is almost one flat light colour (RGBA pixels of a small downscale). */
+export function isBlankLight(px: ArrayLike<number>): boolean {
+ let sum = 0, min = 255, max = 0, n = 0;
+ for (let i = 0; i + 2 < px.length; i += 4) {
+ const y = 0.2126 * px[i] + 0.7152 * px[i + 1] + 0.0722 * px[i + 2];
+ sum += y; n++;
+ if (y < min) min = y;
+ if (y > max) max = y;
+ }
+ return n > 0 && sum / n >= 180 && max - min <= 16;
+}
+
+/** Whether to show an incoming frame now or keep the last good one: a blank light frame is held, but never past HOLD_LIGHT_MS. */
+export function steadyDecision(light: boolean, heldSince: number | null, now: number): 'show' | 'hold' {
+ if (!light) return 'show';
+ return heldSince !== null && now - heldSince >= HOLD_LIGHT_MS ? 'show' : 'hold';
+}
+
+export type Probe = (image: string) => Promise<boolean>;
+
+const canDecode = () => typeof createImageBitmap === 'function' && typeof OffscreenCanvas === 'function';
+
+/** Decodes a frame small and says whether it is a blank light one. Anything that fails counts as a real picture. */
+export const probeBlankLight: Probe = async (image) => {
+ try {
+ const b64 = image.startsWith('data:') ? image.slice(image.indexOf(',') + 1) : image;
+ const bin = atob(b64);
+ const bytes = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ const bitmap = await createImageBitmap(new Blob([bytes], { type: 'image/jpeg' }), { resizeWidth: 32, resizeHeight: 20 });
+ const canvas = new OffscreenCanvas(32, 20);
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return false;
+ ctx.drawImage(bitmap, 0, 0);
+ bitmap.close();
+ return isBlankLight(ctx.getImageData(0, 0, 32, 20).data);
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * The frame the live view shows: the stream's newest, except that a blank light one waits behind the
+ * last good picture (or the dark pane) for up to HOLD_LIGHT_MS. A held frame is acknowledged here,
+ * since no <img> load will do it. `holding`: a frame is in but nothing good is shown yet.
+ */
+export function useSteadyFrame(
+ frame: BrowserFrame | null,
+ acknowledge: (id: number) => void,
+ probe: Probe | null = canDecode() ? probeBlankLight : null,
+): { frame: BrowserFrame | null; holding: boolean } {
+ const [shown, setShown] = useState<BrowserFrame | null>(null);
+ const heldSince = useRef<number | null>(null);
+ const onScreen = useRef<BrowserFrame | null>(null);
+ const shownLight = useRef(false);
+ // A frame with the picture already on screen leaves <img src> unchanged, so no load acknowledges it
+ const put = (f: BrowserFrame | null) => {
+ if (f && onScreen.current && f.id !== onScreen.current.id && f.image === onScreen.current.image) acknowledge(f.id);
+ onScreen.current = f;
+ setShown(f);
+ };
+ const passThrough = !frame || !probe || frame.image.length > PROBE_MAX_CHARS;
+
+ useEffect(() => {
+ if (passThrough) {
+ heldSince.current = null;
+ shownLight.current = false;
+ put(frame);
+ return;
+ }
+ const f = frame as BrowserFrame;
+ let live = true;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const show = (light = false) => {
+ heldSince.current = null;
+ shownLight.current = light;
+ put(f);
+ };
+ (probe as Probe)(f.image).then(
+ (light) => {
+ if (!live) return;
+ const now = Date.now();
+ if (light && heldSince.current === null) heldSince.current = now;
+ if (light && shownLight.current) return show(true);
+ if (steadyDecision(light, heldSince.current, now) === 'show') return show(light);
+ acknowledge(f.id);
+ timer = setTimeout(() => { if (live) show(true); }, HOLD_LIGHT_MS - (now - (heldSince.current ?? now)));
+ },
+ () => { if (live) show(); },
+ );
+ return () => {
+ live = false;
+ if (timer) clearTimeout(timer);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- put only reads refs and acknowledge
+ }, [frame, passThrough, probe, acknowledge]);
+
+ if (passThrough) return { frame, holding: false };
+ // 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 };
+}
diff --git a/frontend/tests/browserPreviewNoFlash.test.mjs b/frontend/tests/browserPreviewNoFlash.test.mjs
new file mode 100644
index 00000000..a1035b8d
--- /dev/null
+++ b/frontend/tests/browserPreviewNoFlash.test.mjs
@@ -0,0 +1,120 @@
+// 22o: the bot browser's preview flashed light grey while a page swapped in. Chrome's screencast sends a
+// blank white picture while a tab commits a new page (before the page paints its own background); the
+// pane showed it. The live view now keeps the last good picture while such a frame is in, for at most
+// 1.5 s, so a page that really is white still shows. These tests fail if the blank frame shows again.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export { isBlankLight, steadyDecision, useSteadyFrame, HOLD_LIGHT_MS, PROBE_MAX_CHARS } from './src/steadyFrame';
+`);
+const settle = async () => { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); };
+
+const pixels = (fill) => { const a = new Uint8ClampedArray(32 * 20 * 4); for (let i = 0; i < a.length; i += 4) { const [r, gg, b] = fill(i / 4); a[i] = r; a[i + 1] = gg; a[i + 2] = b; a[i + 3] = 255; } return a; };
+
+test('a flat white or light grey picture is blank; a dark page or a white page with content is not', () => {
+ assert.equal(m.isBlankLight(pixels(() => [255, 255, 255])), true, "Chrome's blank frame");
+ assert.equal(m.isBlankLight(pixels(() => [0xbf, 0xbf, 0xbf])), true, 'the #bfbfbf Mira saw');
+ assert.equal(m.isBlankLight(pixels((i) => (i % 7 ? [252, 252, 252] : [246, 246, 246]))), true, 'JPEG noise on white');
+ assert.equal(m.isBlankLight(pixels(() => [17, 20, 42])), false, 'the dark tent page');
+ assert.equal(m.isBlankLight(pixels((i) => (i % 32 < 6 && i < 200 ? [30, 30, 30] : [255, 255, 255]))), false, 'a white page with a logo');
+});
+
+test('a blank frame is held, but never past 1.5 s', () => {
+ assert.equal(m.HOLD_LIGHT_MS, 1500);
+ assert.equal(m.steadyDecision(false, null, 0), 'show');
+ assert.equal(m.steadyDecision(true, null, 0), 'hold');
+ assert.equal(m.steadyDecision(true, 1000, 2499), 'hold');
+ assert.equal(m.steadyDecision(true, 1000, 2500), 'show', 'a page that is really white shows');
+});
+
+test('the live view keeps the last good picture while a blank one is in, and acks the held one', async () => {
+ const blank = new Set(['WHITE', 'WHITE2']);
+ const probe = async (image) => blank.has(image);
+ const acks = [];
+ const ack = (id) => acks.push(id);
+ let out;
+ function Pane({ frame }) { out = m.useSteadyFrame(frame, ack, probe); return null; }
+ const root = m.createRoot(document.createElement('div'));
+ const show = async (frame) => { m.flushSync(() => root.render(m.React.createElement(Pane, { frame }))); await settle(); };
+ const f = (id, image) => ({ id, image, width: 1280, height: 800 });
+
+ await show(f(1, 'PAGE'));
+ assert.equal(out.frame?.image, 'PAGE');
+ await show(f(2, 'WHITE'));
+ assert.equal(out.frame?.image, 'PAGE', 'the blank frame never reaches the <img>');
+ assert.deepEqual(acks, [2], 'held, so the hook acknowledges it (no image load will)');
+ await show(f(3, 'PAGE'));
+ assert.equal(out.frame?.image, 'PAGE');
+ assert.deepEqual(acks, [2, 3], 'the same picture again after a held one: no image load, so the hook acks it');
+ await show(f(6, 'PAGE2'));
+ assert.equal(out.frame?.image, 'PAGE2', 'the next real picture shows at once');
+ assert.deepEqual(acks, [2, 3], 'a new picture is acked by its image load, not here');
+
+ // A fresh stream (another tab) whose first picture is blank: the dark pane, not white, not "Browser idle"
+ await show(null);
+ assert.equal(out.frame, null);
+ await show(f(4, 'WHITE2'));
+ assert.equal(out.frame, null);
+ assert.equal(out.holding, true);
+ await new Promise((r) => setTimeout(r, m.HOLD_LIGHT_MS + 100));
+ await settle();
+ assert.equal(out.frame?.image, 'WHITE2', 'after 1.5 s a white page shows: nothing is held forever');
+
+ // A big picture is a real page: it never waits for a check
+ const big = 'x'.repeat(m.PROBE_MAX_CHARS + 1);
+ m.flushSync(() => root.render(m.React.createElement(Pane, { frame: f(5, big) })));
+ assert.equal(out.frame?.image, big);
+ m.flushSync(() => root.unmount());
+});
+
+// QA on #726: a sparse white page (a line of text, a light input) is blank-light on every frame, so typing
+// in it showed only every 1.5 s. Once a blank-light picture is on screen, the next one shows at once.
+test('a sparse white page: after the first picture, typing frames show at once', async () => {
+ const probe = async (image) => image.startsWith('W');
+ let out;
+ function Pane({ frame }) { out = m.useSteadyFrame(frame, () => {}, probe); return null; }
+ const root = m.createRoot(document.createElement('div'));
+ const show = async (frame) => { m.flushSync(() => root.render(m.React.createElement(Pane, { frame }))); await settle(); };
+ const f = (id, image) => ({ id, image, width: 1280, height: 800 });
+
+ await show(f(1, 'DARK'));
+ await show(f(2, 'W0'));
+ assert.equal(out.frame?.image, 'DARK', 'the blank commit frame after a dark page is held');
+ await new Promise((r) => setTimeout(r, m.HOLD_LIGHT_MS + 100));
+ await settle();
+ assert.equal(out.frame?.image, 'W0', 'after 1.5 s the white page shows');
+ await show(f(3, 'W1'));
+ assert.equal(out.frame?.image, 'W1', 'the next sparse-white frame shows at once');
+ await show(f(4, 'W2'));
+ assert.equal(out.frame?.image, 'W2');
+ await show(f(5, 'DARK2'));
+ assert.equal(out.frame?.image, 'DARK2');
+ await show(f(6, 'W3'));
+ assert.equal(out.frame?.image, 'DARK2', 'a blank frame after a dark page is held again');
+ m.flushSync(() => root.unmount());
+});
+
+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/);
+ 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);
+ assert.match(watch, /bg-\[#0a0719\]/, 'the pane behind the picture stays dark');
+ assert.doesNotMatch(watch, /bg-(white|zinc-[1-4]00|gray-|neutral-[1-4])/);
+});