@myrialabs/clopen 0.4.14 → 0.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/backend/auth/permissions.ts +2 -0
  2. package/backend/database/migrations/056_support_mssql_driver.ts +137 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/engine-queries.ts +13 -0
  5. package/backend/database/queries/message-queries.ts +43 -1
  6. package/backend/db-client/connection-manager.ts +8 -2
  7. package/backend/db-client/drivers/mssql.ts +829 -0
  8. package/backend/db-client/drivers/mysql.ts +33 -4
  9. package/backend/db-client/drivers/postgres.ts +55 -5
  10. package/backend/db-client/drivers/sql-builders.test.ts +70 -0
  11. package/backend/db-client/drivers/sql-builders.ts +9 -2
  12. package/backend/db-client/pool-config.ts +32 -0
  13. package/backend/db-client/query-executor.test.ts +42 -0
  14. package/backend/db-client/query-executor.ts +47 -3
  15. package/backend/engine/adapters/opencode/config.ts +9 -0
  16. package/backend/engine/adapters/opencode/models.ts +10 -1
  17. package/backend/engine/adapters/opencode/server.ts +110 -2
  18. package/backend/index.ts +6 -0
  19. package/backend/preview/browser/browser-preview-service.ts +15 -6
  20. package/backend/preview/browser/browser-video-capture.ts +232 -100
  21. package/backend/preview/browser/scripts/video-stream.ts +216 -56
  22. package/backend/preview/browser/types.ts +24 -12
  23. package/backend/ws/chat/stream.ts +12 -4
  24. package/backend/ws/db-client/connections.ts +2 -1
  25. package/backend/ws/db-client/query.ts +41 -4
  26. package/backend/ws/db-client/schema.ts +45 -1
  27. package/backend/ws/engine/claude/accounts.ts +37 -13
  28. package/backend/ws/engine/codex/accounts.ts +36 -4
  29. package/backend/ws/engine/copilot/accounts.ts +12 -0
  30. package/backend/ws/engine/opencode/providers.ts +72 -1
  31. package/backend/ws/engine/qwen/accounts.ts +22 -0
  32. package/backend/ws/messages/crud.ts +13 -0
  33. package/backend/ws/preview/browser/interact.ts +10 -8
  34. package/backend/ws/preview/browser/webcodecs.ts +26 -2
  35. package/dist/assets/{index-BWf-DDJN.js → index-ChF_jIXj.js} +1 -1
  36. package/dist/assets/{index-CDZf6lfv.js → index-EunAFLxP.js} +1 -1
  37. package/dist/assets/{main-C15mQTCW.js → main-CTs4NXwP.js} +407 -367
  38. package/dist/assets/main-moCAkEwm.css +1 -0
  39. package/dist/index.html +2 -2
  40. package/package.json +5 -1
  41. package/shared/types/db-client/connection.ts +1 -1
  42. package/shared/types/db-client/query.ts +4 -1
  43. package/shared/utils/db-client/split-sql.test.ts +13 -0
  44. package/shared/utils/db-client/split-sql.ts +38 -1
  45. package/shared/utils/subagent-wire-trim.ts +87 -0
  46. package/dist/assets/main-Ba5ZGlY4.css +0 -1
@@ -3,11 +3,15 @@
3
3
  *
4
4
  * Handles WebCodecs-based video streaming with WebRTC DataChannel transport.
5
5
  *
6
- * Video Architecture:
7
- * 1. CDP captures JPEG frames via Page.screencastFrame
6
+ * Video Architecture (Chrome-Remote-Desktop-style adaptive quality):
7
+ * 1. CDP captures JPEG frames via Page.screencastFrame at native viewport resolution
8
8
  * 2. Direct CDP Runtime.evaluate sends base64 to page (bypasses Puppeteer IPC)
9
- * 3. Page decodes JPEG via createImageBitmap, encodes with VP8 VideoEncoder
10
- * 4. Send encoded chunks via RTCDataChannel
9
+ * 3. Page decodes via createImageBitmap, encodes with VideoEncoder —
10
+ * preferred VP9 quantizer mode (cheap during motion), VP8 bitrate fallback
11
+ * 4. When the page goes still, a lossless PNG screenshot is pushed through the
12
+ * encoder near-losslessly (top-off) so text sharpens after motion stops
13
+ * 5. Send encoded chunks via reliable ordered RTCDataChannel; latency is
14
+ * bounded by source-side frame dropping (bufferedAmount backpressure)
11
15
  *
12
16
  * Audio Architecture:
13
17
  * 1. AudioContext interception (handled by BrowserAudioCapture)
@@ -43,6 +47,7 @@ interface VideoStreamSession {
43
47
  scriptInjected: boolean; // Track if persistent script was injected
44
48
  scriptsPreInjected: boolean; // Track if scripts were pre-injected during tab creation
45
49
  audioOnNewDocumentInjected: boolean; // Track if evaluateOnNewDocument was registered for audio
50
+ allowVp9: boolean; // Client decode capability (negotiated at stream start)
46
51
  stats: {
47
52
  videoBytesSent: number;
48
53
  audioBytesSent: number;
@@ -52,7 +57,31 @@ interface VideoStreamSession {
52
57
  };
53
58
  }
54
59
 
60
+ /**
61
+ * Scale encoder bitrate with capture resolution to keep bits-per-pixel
62
+ * constant. Capture always runs at native viewport size (display fit-scale
63
+ * is a CSS-only concern on the frontend), so a fixed bitrate would starve
64
+ * larger viewports during motion.
65
+ * 0.045 bpp at 1280×800@24fps ≈ 1.1 Mbps (comparable to the previous fixed 1 Mbps).
66
+ */
67
+ const BITS_PER_PIXEL = 0.045;
68
+
69
+ function computeBitrate(width: number, height: number, framerate: number): number {
70
+ return Math.max(
71
+ DEFAULT_STREAMING_CONFIG.video.bitrate,
72
+ Math.round(width * height * framerate * BITS_PER_PIXEL)
73
+ );
74
+ }
75
+
55
76
  export class BrowserVideoCapture extends EventEmitter {
77
+ /**
78
+ * How long the screencast must be silent (no damage → no frames) before
79
+ * the page is considered still and a near-lossless top-off frame is sent.
80
+ * Long enough to skip inter-frame gaps of animations, short enough that
81
+ * text sharpens almost immediately after scrolling stops.
82
+ */
83
+ private static readonly TOP_OFF_DELAY_MS = 300;
84
+
56
85
  private sessions = new Map<string, VideoStreamSession>();
57
86
  private preInjectPromises = new Map<string, Promise<boolean>>();
58
87
 
@@ -78,15 +107,15 @@ export class BrowserVideoCapture extends EventEmitter {
78
107
  const page = session.page;
79
108
  const viewport = page.viewport()!;
80
109
  const config = DEFAULT_STREAMING_CONFIG;
81
- const scale = session.scale || 1;
82
-
83
- const scaledWidth = Math.round(viewport.width * scale);
84
- const scaledHeight = Math.round(viewport.height * scale);
85
110
 
111
+ // Capture at native viewport resolution. Capturing below viewport
112
+ // size (old behavior: viewport × display fit-scale) forced the
113
+ // client to upscale frames, which made the preview blurry.
86
114
  const videoConfig: StreamingConfig['video'] = {
87
115
  ...config.video,
88
- width: scaledWidth,
89
- height: scaledHeight
116
+ width: viewport.width,
117
+ height: viewport.height,
118
+ bitrate: computeBitrate(viewport.width, viewport.height, config.video.framerate)
90
119
  };
91
120
 
92
121
  // Create session tracking
@@ -99,6 +128,7 @@ export class BrowserVideoCapture extends EventEmitter {
99
128
  scriptInjected: true,
100
129
  scriptsPreInjected: false, // Set to true only after injection completes
101
130
  audioOnNewDocumentInjected: false,
131
+ allowVp9: true,
102
132
  stats: {
103
133
  videoBytesSent: 0,
104
134
  audioBytesSent: 0,
@@ -184,9 +214,10 @@ export class BrowserVideoCapture extends EventEmitter {
184
214
  async startStreaming(
185
215
  sessionId: string,
186
216
  session: BrowserTab,
187
- isValidSession: () => boolean
217
+ isValidSession: () => boolean,
218
+ allowVp9 = true
188
219
  ): Promise<boolean> {
189
- debug.log('webcodecs', `Starting streaming for session ${sessionId}`);
220
+ debug.log('webcodecs', `Starting streaming for session ${sessionId} (client vp9: ${allowVp9})`);
190
221
 
191
222
  // Wait for any pending pre-injection to complete
192
223
  const pendingPreInject = this.preInjectPromises.get(sessionId);
@@ -214,10 +245,6 @@ export class BrowserVideoCapture extends EventEmitter {
214
245
  const viewport = page.viewport()!;
215
246
  const config = DEFAULT_STREAMING_CONFIG;
216
247
 
217
- // Get scale from session (default to 1 if not set)
218
- const scale = session.scale || 1;
219
- debug.log('webcodecs', `Using scale: ${scale} for session ${sessionId}`);
220
-
221
248
  // Get or create session tracking
222
249
  let videoSession = this.sessions.get(sessionId);
223
250
  const isRestart = !!videoSession;
@@ -232,6 +259,7 @@ export class BrowserVideoCapture extends EventEmitter {
232
259
  scriptInjected: false,
233
260
  scriptsPreInjected: false,
234
261
  audioOnNewDocumentInjected: false,
262
+ allowVp9,
235
263
  stats: {
236
264
  videoBytesSent: 0,
237
265
  audioBytesSent: 0,
@@ -241,16 +269,16 @@ export class BrowserVideoCapture extends EventEmitter {
241
269
  }
242
270
  };
243
271
  this.sessions.set(sessionId, videoSession);
272
+ } else {
273
+ videoSession.allowVp9 = allowVp9;
244
274
  }
245
275
 
246
- // Calculate scaled dimensions
247
- const scaledWidth = Math.round(viewport.width * scale);
248
- const scaledHeight = Math.round(viewport.height * scale);
249
-
276
+ // Capture at native viewport resolution (see doPreInject)
250
277
  const videoConfig: StreamingConfig['video'] = {
251
278
  ...config.video,
252
- width: scaledWidth,
253
- height: scaledHeight
279
+ width: viewport.width,
280
+ height: viewport.height,
281
+ bitrate: computeBitrate(viewport.width, viewport.height, config.video.framerate)
254
282
  };
255
283
 
256
284
  // Skip script injection if already pre-injected during tab creation
@@ -263,13 +291,13 @@ export class BrowserVideoCapture extends EventEmitter {
263
291
 
264
292
  // Single batched call: verify peer + start streaming + init audio
265
293
  // (saves ~60ms of IPC overhead vs 4 separate page.evaluate calls)
266
- const initResult = await page.evaluate(async () => {
294
+ const initResult = await page.evaluate(async (clientAllowsVp9) => {
267
295
  const peer = (window as any).__webCodecsPeer;
268
296
  if (typeof peer?.startStreaming !== 'function') {
269
297
  return { peerExists: false, started: false, audioInitialized: false };
270
298
  }
271
299
 
272
- const started = await peer.startStreaming();
300
+ const started = await peer.startStreaming(clientAllowsVp9);
273
301
  if (!started) {
274
302
  return { peerExists: true, started: false, audioInitialized: false };
275
303
  }
@@ -287,7 +315,7 @@ export class BrowserVideoCapture extends EventEmitter {
287
315
  }
288
316
 
289
317
  return { peerExists: true, started: true, audioInitialized };
290
- });
318
+ }, allowVp9);
291
319
 
292
320
  if (!initResult.peerExists) {
293
321
  debug.error('webcodecs', `Peer script injected but __webCodecsPeer not available`);
@@ -335,13 +363,73 @@ export class BrowserVideoCapture extends EventEmitter {
335
363
  const page = session.page;
336
364
  const viewport = page.viewport()!;
337
365
 
338
- // Get scale from session (default to 1 if not set)
339
- const scale = session.scale || 1;
340
-
341
366
  const cdp = await page.createCDPSession();
342
367
 
343
368
  let cdpFrameCount = 0;
344
369
 
370
+ // Rate-limit encoding to the configured framerate. CDP screencast fires
371
+ // at compositor rate (up to 60fps) — encoding every frame wastes CPU on
372
+ // the host and bandwidth on the wire without visible benefit.
373
+ //
374
+ // Trailing edge matters: the LAST frame of a burst must always be
375
+ // encoded. Plain dropping left a stale frame on screen until the
376
+ // top-off fired (~300ms later), which felt like input lag on every
377
+ // click/keystroke.
378
+ const minFrameIntervalMs = Math.floor(1000 / config.video.framerate);
379
+ let lastEncodeTime = 0;
380
+ let pendingFrameData: string | null = null;
381
+ let pendingFrameTimer: ReturnType<typeof setTimeout> | null = null;
382
+
383
+ const encodeMotionFrame = (frameData: string) => {
384
+ lastEncodeTime = Date.now();
385
+ // Send frame to encoder via direct CDP (bypasses Puppeteer's
386
+ // ExecutionContext lookup, function serialization, Runtime.callFunctionOn
387
+ // overhead, and result deserialization). Base64 charset [A-Za-z0-9+/=]
388
+ // is safe to embed in a JS double-quoted string literal.
389
+ cdp.send('Runtime.evaluate', {
390
+ expression: `window.__webCodecsPeer?.encodeFrame("${frameData}")`,
391
+ awaitPromise: false,
392
+ returnByValue: false
393
+ }).catch(() => {});
394
+ };
395
+
396
+ // Static top-off (Chrome-Remote-Desktop-style): screencastFrame only
397
+ // fires on damage, so when no frame arrives for TOP_OFF_DELAY_MS the
398
+ // page has gone still. Capture one lossless PNG screenshot and encode
399
+ // it near-losslessly so the last (motion-degraded) frame doesn't stay
400
+ // blurry on screen. One frame per still period — idle costs nothing.
401
+ let topOffTimer: ReturnType<typeof setTimeout> | null = null;
402
+ let capturingTopOff = false;
403
+
404
+ const scheduleTopOff = () => {
405
+ if (topOffTimer) clearTimeout(topOffTimer);
406
+ topOffTimer = setTimeout(async () => {
407
+ topOffTimer = null;
408
+ const videoSession = this.sessions.get(sessionId);
409
+ if (!videoSession?.isActive || session.isDestroyed || capturingTopOff) return;
410
+
411
+ capturingTopOff = true;
412
+ const frameCountAtCapture = cdpFrameCount;
413
+ try {
414
+ const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png' });
415
+
416
+ // Discard if the page moved again while capturing —
417
+ // new screencast frames already rescheduled the top-off
418
+ if (cdpFrameCount !== frameCountAtCapture) return;
419
+
420
+ cdp.send('Runtime.evaluate', {
421
+ expression: `window.__webCodecsPeer?.encodeFrame("${screenshot.data}", true)`,
422
+ awaitPromise: false,
423
+ returnByValue: false
424
+ }).catch(() => {});
425
+ } catch {
426
+ // Page may be navigating/closing — top-off is best-effort
427
+ } finally {
428
+ capturingTopOff = false;
429
+ }
430
+ }, BrowserVideoCapture.TOP_OFF_DELAY_MS);
431
+ };
432
+
345
433
  cdp.on('Page.screencastFrame', async (event: any) => {
346
434
  cdpFrameCount++;
347
435
 
@@ -359,31 +447,60 @@ export class BrowserVideoCapture extends EventEmitter {
359
447
  // ACK immediately
360
448
  cdp.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => {});
361
449
 
362
- // Send frame to encoder via direct CDP (bypasses Puppeteer's
363
- // ExecutionContext lookup, function serialization, Runtime.callFunctionOn
364
- // overhead, and result deserialization). Base64 charset [A-Za-z0-9+/=]
365
- // is safe to embed in a JS double-quoted string literal.
366
- cdp.send('Runtime.evaluate', {
367
- expression: `window.__webCodecsPeer?.encodeFrame("${event.data}")`,
368
- awaitPromise: false,
369
- returnByValue: false
370
- }).catch(() => {});
371
- });
450
+ const now = Date.now();
451
+ const elapsed = now - lastEncodeTime;
452
+
453
+ if (elapsed < minFrameIntervalMs) {
454
+ // Too soon — hold the LATEST frame and encode it when the slot
455
+ // opens (trailing edge). Newer frames overwrite the pending one.
456
+ pendingFrameData = event.data;
457
+ if (!pendingFrameTimer) {
458
+ pendingFrameTimer = setTimeout(() => {
459
+ pendingFrameTimer = null;
460
+ if (!pendingFrameData) return;
461
+ const frameData = pendingFrameData;
462
+ pendingFrameData = null;
463
+
464
+ const vs = this.sessions.get(sessionId);
465
+ if (!vs?.isActive || session.isDestroyed) return;
466
+
467
+ encodeMotionFrame(frameData);
468
+ scheduleTopOff();
469
+ }, minFrameIntervalMs - elapsed);
470
+ }
471
+ scheduleTopOff();
472
+ return;
473
+ }
372
474
 
373
- // Start screencast with scaled dimensions
374
- const scaledWidth = Math.round(viewport.width * scale);
375
- const scaledHeight = Math.round(viewport.height * scale);
475
+ // This frame supersedes any pending trailing frame
476
+ pendingFrameData = null;
477
+
478
+ encodeMotionFrame(event.data);
479
+ scheduleTopOff();
480
+ });
376
481
 
482
+ // Start screencast at native viewport resolution
377
483
  await cdp.send('Page.startScreencast', {
378
484
  format: 'jpeg',
379
485
  quality: config.video.screenshotQuality,
380
- maxWidth: scaledWidth,
381
- maxHeight: scaledHeight,
486
+ maxWidth: viewport.width,
487
+ maxHeight: viewport.height,
382
488
  everyNthFrame: 1
383
489
  });
384
490
 
385
- debug.log('webcodecs', `CDP screencast started with scaled dimensions: ${scaledWidth}x${scaledHeight} (scale: ${scale})`);
491
+ debug.log('webcodecs', `CDP screencast started at ${viewport.width}x${viewport.height}`);
386
492
  (session as any).__webCodecsCdp = cdp;
493
+ (session as any).__webCodecsTopOffCancel = () => {
494
+ if (topOffTimer) {
495
+ clearTimeout(topOffTimer);
496
+ topOffTimer = null;
497
+ }
498
+ if (pendingFrameTimer) {
499
+ clearTimeout(pendingFrameTimer);
500
+ pendingFrameTimer = null;
501
+ }
502
+ pendingFrameData = null;
503
+ };
387
504
  }
388
505
 
389
506
  /**
@@ -488,9 +605,9 @@ export class BrowserVideoCapture extends EventEmitter {
488
605
  }
489
606
 
490
607
  /**
491
- * Update viewport and scale without reconnection (hot-swap)
608
+ * Update viewport without reconnection (hot-swap)
492
609
  */
493
- async updateViewport(sessionId: string, session: BrowserTab, width: number, height: number, newScale: number): Promise<boolean> {
610
+ async updateViewport(sessionId: string, session: BrowserTab, width: number, height: number): Promise<boolean> {
494
611
  const videoSession = this.sessions.get(sessionId);
495
612
  if (!videoSession?.isActive || !session.page || session.page.isClosed()) {
496
613
  debug.warn('webcodecs', `Cannot update viewport: session not active`);
@@ -501,21 +618,18 @@ export class BrowserVideoCapture extends EventEmitter {
501
618
  const page = session.page;
502
619
  const config = DEFAULT_STREAMING_CONFIG;
503
620
 
504
- // Calculate scaled dimensions
505
- const scaledWidth = Math.round(width * newScale);
506
- const scaledHeight = Math.round(height * newScale);
507
-
508
- debug.log('webcodecs', `🔄 Hot-swapping viewport to ${width}x${height} (scaled: ${scaledWidth}x${scaledHeight}, scale: ${newScale})`);
621
+ debug.log('webcodecs', `🔄 Hot-swapping viewport to ${width}x${height}`);
509
622
 
510
623
  // Step 1: Update viewport via CDP (without page reload)
511
624
  await page.setViewport({ width, height });
512
625
 
513
- // Step 2: Reconfigure VideoEncoder with scaled dimensions
514
- const reconfigured = await page.evaluate((dimensions) => {
626
+ // Step 2: Reconfigure VideoEncoder with new dimensions and bitrate
627
+ const bitrate = computeBitrate(width, height, config.video.framerate);
628
+ const reconfigured = await page.evaluate((params) => {
515
629
  const peer = (window as any).__webCodecsPeer;
516
630
  if (!peer || !peer.reconfigureEncoder) return false;
517
- return peer.reconfigureEncoder(dimensions.width, dimensions.height);
518
- }, { width: scaledWidth, height: scaledHeight });
631
+ return peer.reconfigureEncoder(params.width, params.height, params.bitrate);
632
+ }, { width, height, bitrate });
519
633
 
520
634
  if (!reconfigured) {
521
635
  debug.error('webcodecs', `Failed to reconfigure encoder`);
@@ -529,12 +643,12 @@ export class BrowserVideoCapture extends EventEmitter {
529
643
  await cdp.send('Page.startScreencast', {
530
644
  format: 'jpeg',
531
645
  quality: config.video.screenshotQuality,
532
- maxWidth: scaledWidth,
533
- maxHeight: scaledHeight,
646
+ maxWidth: width,
647
+ maxHeight: height,
534
648
  everyNthFrame: 1
535
649
  });
536
650
 
537
- debug.log('webcodecs', `✅ Viewport hot-swapped successfully to ${width}x${height} (scale: ${newScale})`);
651
+ debug.log('webcodecs', `✅ Viewport hot-swapped successfully to ${width}x${height}`);
538
652
  }
539
653
 
540
654
  return true;
@@ -545,12 +659,15 @@ export class BrowserVideoCapture extends EventEmitter {
545
659
  }
546
660
 
547
661
  /**
548
- * Update scale without reconnection (hot-swap)
662
+ * Restart the CDP screencast at native viewport resolution.
663
+ * Used as a refresh/recovery path when the frontend detects a stuck stream
664
+ * (sent as a scale-update action). Display fit-scale no longer affects
665
+ * capture resolution, so no encoder reconfiguration is needed.
549
666
  */
550
- async updateScale(sessionId: string, session: BrowserTab, newScale: number): Promise<boolean> {
667
+ async refreshScreencast(sessionId: string, session: BrowserTab): Promise<boolean> {
551
668
  const videoSession = this.sessions.get(sessionId);
552
669
  if (!videoSession?.isActive || !session.page || session.page.isClosed()) {
553
- debug.warn('webcodecs', `Cannot update scale: session not active`);
670
+ debug.warn('webcodecs', `Cannot refresh screencast: session not active`);
554
671
  return false;
555
672
  }
556
673
 
@@ -559,45 +676,59 @@ export class BrowserVideoCapture extends EventEmitter {
559
676
  const viewport = page.viewport()!;
560
677
  const config = DEFAULT_STREAMING_CONFIG;
561
678
 
562
- // Calculate new scaled dimensions
563
- const scaledWidth = Math.round(viewport.width * newScale);
564
- const scaledHeight = Math.round(viewport.height * newScale);
565
-
566
- debug.log('webcodecs', `🔄 Hot-swapping resolution to ${scaledWidth}x${scaledHeight} (scale: ${newScale})`);
567
-
568
- // Step 1: Reconfigure VideoEncoder in headless browser
569
- const reconfigured = await page.evaluate((dimensions) => {
570
- const peer = (window as any).__webCodecsPeer;
571
- if (!peer || !peer.reconfigureEncoder) return false;
572
- return peer.reconfigureEncoder(dimensions.width, dimensions.height);
573
- }, { width: scaledWidth, height: scaledHeight });
574
-
575
- if (!reconfigured) {
576
- debug.error('webcodecs', `Failed to reconfigure encoder`);
577
- return false;
578
- }
579
-
580
- // Step 2: Restart CDP screencast with new dimensions
581
679
  const cdp = (session as any).__webCodecsCdp;
582
680
  if (cdp) {
583
- // Stop current screencast
584
681
  await cdp.send('Page.stopScreencast').catch(() => {});
585
-
586
- // Start with new dimensions
587
682
  await cdp.send('Page.startScreencast', {
588
683
  format: 'jpeg',
589
684
  quality: config.video.screenshotQuality,
590
- maxWidth: scaledWidth,
591
- maxHeight: scaledHeight,
685
+ maxWidth: viewport.width,
686
+ maxHeight: viewport.height,
592
687
  everyNthFrame: 1
593
688
  });
594
689
 
595
- debug.log('webcodecs', `✅ Scale hot-swapped successfully to ${scaledWidth}x${scaledHeight}`);
690
+ debug.log('webcodecs', `✅ Screencast refreshed at ${viewport.width}x${viewport.height}`);
596
691
  }
597
692
 
598
693
  return true;
599
694
  } catch (error) {
600
- debug.error('webcodecs', `Failed to update scale:`, error);
695
+ debug.error('webcodecs', `Failed to refresh screencast:`, error);
696
+ return false;
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Client-driven keyframe request (PLI equivalent).
702
+ * Forces the next encoded frame to be a keyframe AND immediately pushes a
703
+ * high-quality screenshot through the encoder — so it works even on still
704
+ * pages where no screencast frames are flowing. Called when the frontend
705
+ * decoder errors or joins mid-stream and needs a sync point.
706
+ */
707
+ async requestKeyframe(sessionId: string, session: BrowserTab): Promise<boolean> {
708
+ const videoSession = this.sessions.get(sessionId);
709
+ if (!videoSession?.isActive || !session.page || session.page.isClosed()) {
710
+ return false;
711
+ }
712
+
713
+ try {
714
+ await session.page.evaluate(() => {
715
+ (window as any).__webCodecsPeer?.forceKeyframe();
716
+ });
717
+
718
+ const cdp = (session as any).__webCodecsCdp;
719
+ if (cdp) {
720
+ const screenshot = await cdp.send('Page.captureScreenshot', { format: 'png' });
721
+ cdp.send('Runtime.evaluate', {
722
+ expression: `window.__webCodecsPeer?.encodeFrame("${screenshot.data}", true)`,
723
+ awaitPromise: false,
724
+ returnByValue: false
725
+ }).catch(() => {});
726
+ }
727
+
728
+ debug.log('webcodecs', `Keyframe requested for ${sessionId}`);
729
+ return true;
730
+ } catch (error) {
731
+ debug.warn('webcodecs', `Failed to request keyframe:`, error);
601
732
  return false;
602
733
  }
603
734
  }
@@ -617,18 +748,15 @@ export class BrowserVideoCapture extends EventEmitter {
617
748
  const page = session.page;
618
749
  const viewport = page.viewport()!;
619
750
  const config = DEFAULT_STREAMING_CONFIG;
620
- const scale = session.scale || 1;
621
751
 
622
752
  debug.log('webcodecs', `🔄 Handling navigation for ${sessionId} - re-injecting peer script and restarting screencast`);
623
753
 
624
- // Calculate scaled dimensions
625
- const scaledWidth = Math.round(viewport.width * scale);
626
- const scaledHeight = Math.round(viewport.height * scale);
627
-
754
+ // Capture at native viewport resolution (see doPreInject)
628
755
  const videoConfig: StreamingConfig['video'] = {
629
756
  ...config.video,
630
- width: scaledWidth,
631
- height: scaledHeight
757
+ width: viewport.width,
758
+ height: viewport.height,
759
+ bitrate: computeBitrate(viewport.width, viewport.height, config.video.framerate)
632
760
  };
633
761
 
634
762
  // Re-inject video encoder and audio capture scripts to new page context
@@ -636,13 +764,13 @@ export class BrowserVideoCapture extends EventEmitter {
636
764
  await page.evaluate(audioCaptureScript, config.audio);
637
765
 
638
766
  // Single batched call: verify peer + start streaming + init audio
639
- const initResult = await page.evaluate(async () => {
767
+ const initResult = await page.evaluate(async (clientAllowsVp9) => {
640
768
  const peer = (window as any).__webCodecsPeer;
641
769
  if (typeof peer?.startStreaming !== 'function') {
642
770
  return { peerExists: false, started: false, audioInitialized: false };
643
771
  }
644
772
 
645
- const started = await peer.startStreaming();
773
+ const started = await peer.startStreaming(clientAllowsVp9);
646
774
  if (!started) {
647
775
  return { peerExists: true, started: false, audioInitialized: false };
648
776
  }
@@ -659,7 +787,7 @@ export class BrowserVideoCapture extends EventEmitter {
659
787
  }
660
788
 
661
789
  return { peerExists: true, started: true, audioInitialized };
662
- });
790
+ }, videoSession.allowVp9);
663
791
 
664
792
  if (!initResult.peerExists) {
665
793
  debug.error('webcodecs', `Peer script re-injection failed - peer not available`);
@@ -687,12 +815,12 @@ export class BrowserVideoCapture extends EventEmitter {
687
815
  await cdp.send('Page.startScreencast', {
688
816
  format: 'jpeg',
689
817
  quality: config.video.screenshotQuality,
690
- maxWidth: scaledWidth,
691
- maxHeight: scaledHeight,
818
+ maxWidth: viewport.width,
819
+ maxHeight: viewport.height,
692
820
  everyNthFrame: 1
693
821
  });
694
822
 
695
- debug.log('webcodecs', `✅ Navigation handled - screencast restarted at ${scaledWidth}x${scaledHeight}`);
823
+ debug.log('webcodecs', `✅ Navigation handled - screencast restarted at ${viewport.width}x${viewport.height}`);
696
824
  }
697
825
 
698
826
  // Emit event to notify frontend that streaming is ready
@@ -718,6 +846,10 @@ export class BrowserVideoCapture extends EventEmitter {
718
846
 
719
847
  if (session?.page && !session.page.isClosed()) {
720
848
  try {
849
+ // Cancel any pending top-off capture
850
+ (session as any).__webCodecsTopOffCancel?.();
851
+ (session as any).__webCodecsTopOffCancel = null;
852
+
721
853
  // Stop audio + peer in one IPC round-trip
722
854
  await session.page.evaluate(() => {
723
855
  (window as any).__audioEncoder?.stop();