The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Shared viewer: wait for the page to paint before the first frame
0xdiego2571b34d442b4d
diff --git a/cli/src/sharing/viewer.spec.ts b/cli/src/sharing/viewer.spec.tsindex 5b3a092b0..dcf99f4b2 100644--- a/cli/src/sharing/viewer.spec.ts+++ b/cli/src/sharing/viewer.spec.ts@@ -1,5 +1,5 @@import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'-const m = vi.hoisted(() => ({ spawn: vi.fn(), exists: vi.fn(), directory: vi.fn(), rm: vi.fn(), sockets: [] as any[], reply: vi.fn() }))+const m = vi.hoisted(() => ({ spawn: vi.fn(), exists: vi.fn(), directory: vi.fn(), rm: vi.fn(), sockets: [] as any[], reply: vi.fn(), noLoad: false }))vi.mock('node:child_process', () => ({ spawn: m.spawn }))vi.mock('node:fs', async actual => ({ ...await actual<typeof import('node:fs')>(), existsSync: m.exists }))vi.mock('node:fs/promises', () => ({ mkdtemp: m.directory, rm: m.rm }))@@ -11,6 +11,11 @@ vi.mock('ws', async () => {send = vi.fn((raw: string) => {const request = JSON.parse(raw), response = m.reply(request)if (response !== undefined) queueMicrotask(() => this.emit('message', Buffer.from(JSON.stringify({ id: request.id, ...response }))))+ // Chrome fires the page's load event on the session once a navigation lands; start() waits for it+ // (bounded) before the first screenshot. `m.noLoad` keeps it silent, for the bound itself.+ if (request.method === 'Page.navigate' && !m.noLoad) {+ queueMicrotask(() => this.emit('message', Buffer.from(JSON.stringify({ method: 'Page.loadEventFired', sessionId: request.sessionId, params: {} }))))+ }})terminate = vi.fn(() => this.emit('close'))constructor(..._args: unknown[]) { super(); m.sockets.push(this); queueMicrotask(() => this.emit('open')) }@@ -27,7 +32,7 @@ const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve()describe('private viewer capture', () => {let capture: ViewerCapture, child: ChildbeforeEach(() => {- vi.useFakeTimers(); vi.clearAllMocks(); m.sockets = []+ vi.useFakeTimers(); vi.clearAllMocks(); m.sockets = []; m.noLoad = falsem.exists.mockReturnValue(true); m.directory.mockResolvedValue('/tmp/share-viewer-fixture'); m.rm.mockResolvedValue(undefined)child = new Child(); m.spawn.mockImplementation(() => {queueMicrotask(() => child.stderr.emit('data', Buffer.from('DevTools listening on ws://127.0.0.1:1234/devtools/browser/test\n')))@@ -68,11 +73,34 @@ describe('private viewer capture', () => {for (const data of [undefined, 'x'.repeat(2 * 1024 * 1024 + 1)]) {m.reply.mockReturnValue({ result: { data } }); await expect(capture.capture()).rejects.toThrow('too large')}+ // A refused screenshot is retried once, a beat later; refused twice, it is the error.m.reply.mockReturnValue({ error: { message: 'render error' } })- await expect(capture.capture()).rejects.toThrow('render this frame')+ const before = m.reply.mock.calls.filter(([r]: any) => r.method === 'Page.captureScreenshot').length+ const refused = capture.capture(); const rejection = expect(refused).rejects.toThrow('render this frame')+ await vi.advanceTimersByTimeAsync(300); await rejection+ expect(m.reply.mock.calls.filter(([r]: any) => r.method === 'Page.captureScreenshot')).toHaveLength(before + 2)m.reply.mockReturnValue({})await expect(capture.capture()).rejects.toThrow('too large')})+ it('waits for the page to paint before the first frame, and takes a second try on a refused one', async () => {+ // Straight after `Page.navigate` Chrome refuses a screenshot ("no frame yet"); asking at once and+ // treating the refusal as a broken renderer is what showed a watcher "could not render" forever.+ m.noLoad = true+ const startup = capture.start('http://localhost:1234')+ await flush()+ expect(m.reply.mock.calls.some(([r]: any) => r.method === 'Page.navigate')).toBe(true)+ let started = false; void startup.then(() => { started = true })+ await flush(); expect(started).toBe(false) // navigated, but the load event has not fired+ await vi.advanceTimersByTimeAsync(10_000); await startup; expect(started).toBe(true) // bounded+ let shots = 0+ m.reply.mockImplementation(({ method }) => method === 'Page.captureScreenshot'+ ? (++shots === 1 ? { error: { message: 'Unable to capture screenshot' } } : { result: { data: 'jpeg' } })+ : { result: {} })+ const frame = capture.capture()+ await vi.advanceTimersByTimeAsync(300)+ await expect(frame).resolves.toBe('jpeg')+ expect(shots).toBe(2)+ })it('bounds startup and capture time and rejects pending work on disconnect', async () => {m.spawn.mockReturnValue(child)const startup = capture.start('http://localhost:1234'); const slow = expect(startup).rejects.toThrow('too long to start')@@ -81,9 +109,11 @@ describe('private viewer capture', () => {m.spawn.mockImplementation(() => { queueMicrotask(() => child.stderr.emit('data', Buffer.from('DevTools listening on ws://localhost:1234/test'))); return child })await capture.start('http://localhost:1234')m.reply.mockReturnValue(undefined)+ // 8 s, a 300 ms beat, and the retry's own 8 s: a silent renderer is given two tries too.const frame = capture.capture(); const timeout = expect(frame).rejects.toThrow('too long to respond')- await vi.advanceTimersByTimeAsync(8000); await timeout+ await vi.advanceTimersByTimeAsync(8000 + 300 + 8000); await timeoutconst pending = capture.capture(); const disconnected = expect(pending).rejects.toThrow('disconnected')+ // The socket dies mid-first-try: no retry against a renderer that is gone.m.sockets.at(-1).emit('error', new Error('gone')); await disconnected})it('handles process startup errors and exits and cancellation before allocating a renderer', async () => {diff --git a/cli/src/sharing/viewer.ts b/cli/src/sharing/viewer.tsindex 2c4317747..c79bcfee4 100644--- a/cli/src/sharing/viewer.ts+++ b/cli/src/sharing/viewer.ts@@ -61,8 +61,9 @@ export class ViewerCapture {this.ws.on('error', () => this.failPending())this.ws.on('close', () => this.failPending())this.ws.on('message', raw => {- let message: { id?: number; result?: Payload; error?: unknown }+ let message: { id?: number; method?: string; sessionId?: string; result?: Payload; error?: unknown }try { message = JSON.parse(raw.toString()) } catch { return }+ if (message.method === 'Page.loadEventFired' && message.sessionId === this.session) this.loaded?.()const entry = this.pending.get(message.id ?? -1)if (!entry) returnthis.pending.delete(message.id!); clearTimeout(entry.timer)@@ -78,9 +79,24 @@ export class ViewerCapture {this.session = String(attached.sessionId)await this.call('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false })await this.call('Page.enable')+ // Arm BEFORE navigating: the load event of a small page can fire before `Page.navigate` even+ // answers, and a listener armed after it would wait out the whole timeout for nothing.+ const loaded = new Promise<void>(resolve => {+ const timer = setTimeout(resolve, 10_000)+ this.loaded = () => { clearTimeout(timer); resolve() }+ })const navigation = await this.call('Page.navigate', { url: target })if (navigation.errorText) throw new Error('The owner’s viewer is not answering yet.')+ // WAIT FOR THE PAGE TO PAINT. `Page.navigate` returns as the navigation starts, and a screenshot+ // asked for before the first frame is refused ("Unable to capture screenshot") — which the pool+ // read as the renderer being broken, tore it down, started it again three seconds later, asked+ // at once, and was refused again: the person watching saw "could not render this frame" forever+ // (owner, 2026-09-18). Measured: the first capture straight after navigate fails; 400 ms later+ // it succeeds. Bounded, so a page that never fires `load` still gets its first attempt.+ await loaded+ this.loaded = null}+ private loaded: (() => void) | null = nullprivate call(method: string, params: Payload = {}): Promise<Payload> {return new Promise((resolve, reject) => {if (this.closed || this.ws?.readyState !== WebSocket.OPEN) { reject(new Error('The viewer renderer disconnected.')); return }@@ -91,11 +107,23 @@ export class ViewerCapture {})}async capture(): Promise<string> {- const result = await this.call('Page.captureScreenshot', { format: 'jpeg', quality: 75, captureBeyondViewport: false })+ // One retry, a beat later: a refused screenshot is almost always "no frame yet" (a viewer+ // re-rendering after an artifact change), not a dead renderer — and the pool tears the renderer+ // down on a thrown error, which costs the watcher three seconds of blank.+ let result: Payload+ try { result = await this.call('Page.captureScreenshot', { format: 'jpeg', quality: 75, captureBeyondViewport: false }) }+ catch (first) {+ if (this.closed || this.dead) throw first // a renderer that went away is not "no frame yet"+ await new Promise(r => setTimeout(r, 300))+ result = await this.call('Page.captureScreenshot', { format: 'jpeg', quality: 75, captureBeyondViewport: false })+ }if (typeof result.data !== 'string' || result.data.length > 2 * 1024 * 1024) throw new Error('This viewer frame is too large.')return result.data}+ /** The renderer's socket or process went away: nothing pending can be answered, nor retried. */+ private dead = falseprivate failPending(): void {+ this.dead = truefor (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error('The viewer renderer disconnected.')) }this.pending.clear()}