'use strict'; const { spawn } = require('child_process'); const http = require('http'); const fs = require('fs'); const path = require('path'); const CDP = require('chrome-remote-interface'); const WebSocket = require('ws'); const PORT = parseInt(process.env.PORT || '7860'); const FPS = parseInt(process.env.FPS || '25'); // Single-user optimized: lower quality = lower latency const JPEG_QUALITY = parseInt(process.env.JPEG_QUALITY || '40'); const VIEWPORT = { width: 1280, height: 720 }; const FRAME_MS = Math.floor(1000 / FPS); const CHROME_BIN = process.env.CHROME_BIN || '/usr/bin/chromium'; const sleep = ms => new Promise(r => setTimeout(r, ms)); // ── State ───────────────────────────────────────────────────────────────────── let cdpClient = null; let chromeProc = null; let chromeReady = false; // Single session for single user let session = null; // Screenshot loop state let loopTimer = null; let capturing = false; let pendingInput = false; // flag: user just interacted → capture ASAP let lastFrameTs = 0; // ── Chrome Launch ───────────────────────────────────────────────────────────── function launchChrome() { chromeReady = false; cdpClient = null; console.log('Starting Chrome...'); chromeProc = spawn(CHROME_BIN, [ '--remote-debugging-port=9222', '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu', '--headless=new', '--no-first-run', '--no-zygote', '--disable-extensions', '--disable-background-networking', '--disable-sync', '--disable-translate', '--disable-default-apps', '--disable-features=TranslateUI,BlinkGenPropertyTrees,VizDisplayCompositor', '--mute-audio', '--hide-scrollbars', '--metrics-recording-only', '--use-mock-keychain', // Performance: disable unnecessary rendering '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', `--window-size=${VIEWPORT.width},${VIEWPORT.height}`, ], { stdio: ['ignore', 'pipe', 'pipe'] }); chromeProc.stdout.on('data', d => process.stdout.write(d)); chromeProc.stderr.on('data', d => process.stderr.write(d)); chromeProc.on('exit', async (code) => { console.error(`Chrome exited (code=${code}). Restarting...`); chromeReady = false; cdpClient = null; stopLoop(); if (session) { try { if (session.ws.readyState === WebSocket.OPEN) { session.ws.send(JSON.stringify({ type: 'error', message: 'Browser restarted – please reload.' })); session.ws.close(); } } catch {} session = null; } await sleep(2000); launchChrome(); await connectBrowser(); }); } // ── CDP Connection ──────────────────────────────────────────────────────────── async function connectBrowser(retries = 25) { for (let i = 0; i < retries; i++) { try { cdpClient = await CDP({ port: 9222 }); chromeReady = true; console.log('CDP connected'); return true; } catch { process.stdout.write('.'); await sleep(500); } } console.error('CDP connection failed'); return false; } // ── Tab Creation ────────────────────────────────────────────────────────────── async function createTab(url = 'https://duckduckgo.com') { const { targetId } = await cdpClient.Target.createTarget({ url: 'about:blank' }); const tab = await CDP({ port: 9222, target: targetId }); await Promise.all([ tab.Network.enable(), tab.Page.enable(), tab.Emulation.setDeviceMetricsOverride({ width: VIEWPORT.width, height: VIEWPORT.height, deviceScaleFactor: 1, mobile: false, }), ]); await tab.Page.addScriptToEvaluateOnNewDocument({ source: 'window.open=()=>null;window.alert=()=>null;window.confirm=()=>false;window.prompt=()=>null;' }); await tab.Page.navigate({ url }); return { targetId, tab }; } // ── Screenshot Loop ─────────────────────────────────────────────────────────── // Key optimization: after user input → capture immediately (don't wait for next tick) // Otherwise use steady FPS timer so we don't saturate the event loop function stopLoop() { if (loopTimer) { clearTimeout(loopTimer); loopTimer = null; } capturing = false; } async function captureNow() { if (!session || capturing) return; const s = session; if (s.ws.readyState !== WebSocket.OPEN) return; capturing = true; try { const { data } = await s.tab.Page.captureScreenshot({ format: 'jpeg', quality: JPEG_QUALITY, clip: { x: 0, y: 0, width: VIEWPORT.width, height: VIEWPORT.height, scale: 1 }, }); if (s.ws.readyState === WebSocket.OPEN) { const buf = Buffer.concat([Buffer.from([0x01]), Buffer.from(data, 'base64')]); s.ws.send(buf); lastFrameTs = Date.now(); } } catch { // silent } finally { capturing = false; } } function scheduleNext() { if (!session) return; const elapsed = Date.now() - lastFrameTs; const delay = Math.max(0, FRAME_MS - elapsed); loopTimer = setTimeout(tick, delay); } async function tick() { loopTimer = null; if (!session) return; await captureNow(); scheduleNext(); } function startLoop() { stopLoop(); lastFrameTs = 0; scheduleNext(); } // ── Input Handler ───────────────────────────────────────────────────────────── // After every click/key: immediately queue a fast screenshot async function handleInput(s, m) { const needsFastCapture = ['mousedown','mouseup','keydown','char','navigate','back','forward','reload','scroll'].includes(m.type); try { const I = s.tab.Input, P = s.tab.Page; switch (m.type) { case 'mousemove': await I.dispatchMouseEvent({ type: 'mouseMoved', x: m.x, y: m.y }); break; case 'mousedown': await I.dispatchMouseEvent({ type: 'mousePressed', x: m.x, y: m.y, button: 'left', clickCount: 1 }); break; case 'mouseup': await I.dispatchMouseEvent({ type: 'mouseReleased', x: m.x, y: m.y, button: 'left', clickCount: 1 }); break; case 'scroll': await I.dispatchMouseEvent({ type: 'mouseWheel', x: m.x, y: m.y, deltaX: 0, deltaY: m.dy }); break; case 'keydown': await I.dispatchKeyEvent({ type: 'keyDown', key: m.key, code: m.code, windowsVirtualKeyCode: m.keyCode || 0 }); break; case 'keyup': await I.dispatchKeyEvent({ type: 'keyUp', key: m.key, code: m.code, windowsVirtualKeyCode: m.keyCode || 0 }); break; case 'char': await I.dispatchKeyEvent({ type: 'char', text: m.text }); break; case 'navigate': { let url = m.url.trim(); if (!/^https?:\/\//i.test(url)) url = 'https://duckduckgo.com/?q=' + encodeURIComponent(url); await P.navigate({ url }); break; } case 'back': await P.goBack().catch(() => {}); break; case 'forward': await P.goForward().catch(() => {}); break; case 'reload': await P.reload(); break; } } catch {} // After any meaningful interaction → immediately capture (skip waiting for the timer) if (needsFastCapture) { // Small delay so Chrome can render the interaction result setTimeout(async () => { if (loopTimer) { clearTimeout(loopTimer); loopTimer = null; } await captureNow(); scheduleNext(); }, 60); // 60ms: Chrome needs ~1-2 paint cycles to reflect click state } } // ── HTTP ────────────────────────────────────────────────────────────────────── const MIME = { '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css' }; const server = http.createServer((req, res) => { if (req.url === '/status') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ active: !!session, ready: chromeReady })); } const file = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url); fs.readFile(file, (err, data) => { if (err) { res.writeHead(404); return res.end('Not found'); } res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'text/plain' }); res.end(data); }); }); // ── WebSocket ───────────────────────────────────────────────────────────────── const wss = new WebSocket.Server({ server, perMessageDeflate: false }); // no deflate = lower latency wss.on('connection', async (ws) => { if (!chromeReady) { ws.send(JSON.stringify({ type: 'error', message: 'Browser starting – please wait 10s and reload.' })); return ws.close(); } // Single user: close any existing session if (session) { console.log('Replacing existing session'); try { session.ws.close(); } catch {} stopLoop(); try { await cdpClient.Target.closeTarget({ targetId: session.targetId }); } catch {} session = null; await sleep(200); } console.log('New session'); let tabData; try { tabData = await createTab(); } catch (e) { console.error('Tab error:', e.message); ws.send(JSON.stringify({ type: 'error', message: 'Could not start tab.' })); return ws.close(); } session = { targetId: tabData.targetId, tab: tabData.tab, ws }; tabData.tab.Page.on('frameNavigated', ({ frame }) => { if (frame.parentId) return; if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'url', url: frame.url })); }); startLoop(); ws.send(JSON.stringify({ type: 'ready' })); ws.on('message', raw => { try { handleInput(session, JSON.parse(raw)); } catch {} }); const cleanup = async () => { if (session && session.ws === ws) { console.log('Session closed'); stopLoop(); try { await cdpClient.Target.closeTarget({ targetId: session.targetId }); } catch {} session = null; } }; ws.on('close', cleanup); ws.on('error', () => { try { ws.close(); } catch {} }); }); // ── Start ───────────────────────────────────────────────────────────────────── (async () => { launchChrome(); await sleep(2500); await connectBrowser(); server.listen(PORT, () => { console.log(`Running on :${PORT} fps=${FPS} quality=${JPEG_QUALITY}`); }); })();