@myrialabs/clopen 0.4.23 → 0.4.24

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 (32) hide show
  1. package/backend/chat/stream-manager.ts +41 -13
  2. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
  3. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
  4. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
  5. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +8 -0
  6. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +10 -0
  7. package/backend/mcp/internal/servers/browser-automation/context.ts +6 -0
  8. package/backend/mcp/internal/servers/browser-automation/description.ts +1 -1
  9. package/backend/mcp/internal/servers/browser-automation/runner.ts +21 -1
  10. package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
  11. package/backend/module-shadowing.test.ts +135 -0
  12. package/backend/preview/browser/browser-host-bridge.ts +8 -2
  13. package/backend/preview/browser/browser-interaction-handler.ts +70 -0
  14. package/backend/preview/browser/browser-mcp-control.ts +247 -13
  15. package/backend/preview/browser/browser-preview-service.ts +146 -8
  16. package/backend/preview/browser/browser-video-capture.ts +551 -247
  17. package/backend/preview/browser/scripts/host-bridge.ts +61 -89
  18. package/backend/preview/browser/scripts/video-stream.ts +32 -0
  19. package/backend/preview/browser/types.ts +22 -0
  20. package/backend/preview/index.ts +6 -1
  21. package/backend/ws/preview/browser/interact.ts +16 -2
  22. package/backend/ws/preview/browser/native-ui.ts +22 -1
  23. package/backend/ws/preview/browser/tab-info.ts +20 -2
  24. package/backend/ws/preview/browser/webcodecs.ts +6 -1
  25. package/backend/ws/preview/index.ts +22 -0
  26. package/dist/assets/{index-DH_GO0Lf.js → index-CNDHpafl.js} +1 -1
  27. package/dist/assets/{index-igSQ3JaM.js → index-NF77n8kP.js} +1 -1
  28. package/dist/assets/{main-D-d8SFfW.js → main-BJ0PUVTW.js} +381 -376
  29. package/dist/assets/main-DSirC670.css +1 -0
  30. package/dist/index.html +2 -2
  31. package/package.json +1 -1
  32. package/dist/assets/main-BD3-qPfT.css +0 -1
@@ -35,6 +35,7 @@ import type {
35
35
  ClientCodecSupport,
36
36
  ClientDisplayMetrics,
37
37
  ClientStreamFeedback,
38
+ PeerHealth,
38
39
  StreamingConfig
39
40
  } from './types';
40
41
  import { DEFAULT_STREAMING_CONFIG, resolveCodecCandidates } from './types';
@@ -117,6 +118,39 @@ interface StreamViewer {
117
118
  visible: boolean;
118
119
  /** Latest decoder verdict — the ladder follows the worst viewer. */
119
120
  decoderSaturated: boolean;
121
+ /**
122
+ * When this viewer last handshook. A viewer that never reaches `connected`
123
+ * has to expire: entries only ever left this table on an explicit stop, a
124
+ * `closed`/`failed` state or a socket teardown, so a handshake that simply
125
+ * never completed — a host browser refreshed hard, a laptop closed
126
+ * mid-negotiation — stayed forever and made the session look watched.
127
+ */
128
+ attachedAt: number;
129
+ }
130
+
131
+ /**
132
+ * Per-tab injection bookkeeping.
133
+ *
134
+ * Deliberately *not* on the stream session: `stopStreaming` deletes that
135
+ * record, so every stop/start cycle — i.e. every switch away from a preview
136
+ * tab and back — believed it had never injected anything. Puppeteer's
137
+ * `exposeFunction` then threw ("already exists") and the whole handshake
138
+ * failed, while `evaluateOnNewDocument` happily registered another copy of
139
+ * the audio tap that nothing ever removed. This lives as long as the tab.
140
+ */
141
+ interface TabInjectionState {
142
+ /** Signalling bindings installed on the page (survive navigation). */
143
+ bindingsExposed: boolean;
144
+ /** Identifier of the registered on-new-document audio script, if any. */
145
+ audioScriptId: string | null;
146
+ /** Id stamped on the most recent peer injection — compared to PeerHealth. */
147
+ epoch: string;
148
+ /**
149
+ * Codec order the injected encoder was built with. The page decides its
150
+ * codec once, at injection, so a viewer arriving with different decode
151
+ * capabilities needs a rebuild rather than a reconfigure.
152
+ */
153
+ codecSignature: string;
120
154
  }
121
155
 
122
156
  interface VideoStreamSession {
@@ -127,7 +161,14 @@ interface VideoStreamSession {
127
161
  viewers: Map<string, StreamViewer>;
128
162
  scriptInjected: boolean; // Track if persistent script was injected
129
163
  scriptsPreInjected: boolean; // Track if scripts were pre-injected during tab creation
130
- audioOnNewDocumentInjected: boolean; // Track if evaluateOnNewDocument was registered for audio
164
+ /**
165
+ * When the page last reported frames reaching its encoder. A connected
166
+ * viewer while this stands still is watching a stream that has stopped
167
+ * producing — which looks identical, from the client, to a slow page.
168
+ */
169
+ lastEncodedAt: number;
170
+ /** Guards the watchdog against re-entering while a repair is in flight. */
171
+ repairing: boolean;
131
172
  /** Codecs every viewer can decode — one encoder serves them all. */
132
173
  codecSupport: ClientCodecSupport;
133
174
  /** Display metrics of the most demanding viewer. */
@@ -196,8 +237,12 @@ const DEFAULT_CODEC_SUPPORT: ClientCodecSupport = {
196
237
  * saves work: before the frame is produced.
197
238
  */
198
239
  class ScreencastFeeder {
240
+ /** Attempts to re-deliver a still-page refresh frame before giving up. */
241
+ private static readonly MAX_TOP_OFF_RETRIES = 3;
242
+
199
243
  private ackTimer: ReturnType<typeof setTimeout> | null = null;
200
244
  private topOffTimer: ReturnType<typeof setTimeout> | null = null;
245
+ private topOffRetries = 0;
201
246
  private peerObjectId: string | null = null;
202
247
  private acquiringPeer = false;
203
248
  private capturingTopOff = false;
@@ -290,12 +335,12 @@ class ScreencastFeeder {
290
335
  * single frame — hundreds of kilobytes of compilation per frame, for a
291
336
  * call that never changes.
292
337
  */
293
- private dispatch(data: string, isTopOff: boolean, mimeType: string): void {
294
- if (this.destroyed) return;
338
+ private dispatch(data: string, isTopOff: boolean, mimeType: string): boolean {
339
+ if (this.destroyed) return false;
295
340
 
296
341
  if (!this.peerObjectId) {
297
342
  void this.acquirePeerHandle();
298
- return;
343
+ return false;
299
344
  }
300
345
 
301
346
  this.cdp
@@ -311,6 +356,8 @@ class ScreencastFeeder {
311
356
  // Stale handle (navigation) — the next frame re-acquires it.
312
357
  this.peerObjectId = null;
313
358
  });
359
+
360
+ return true;
314
361
  }
315
362
 
316
363
  private ack(cdpSessionId: number): void {
@@ -362,7 +409,7 @@ class ScreencastFeeder {
362
409
  }
363
410
 
364
411
  this.lastDispatchAt = now;
365
- this.dispatch(event.data, false, 'image/jpeg');
412
+ if (this.dispatch(event.data, false, 'image/jpeg')) this.topOffRetries = 0;
366
413
  this.scheduleTopOff();
367
414
  } finally {
368
415
  // Self-calibrating hold. The period the viewer actually sees is
@@ -454,11 +501,26 @@ class ScreencastFeeder {
454
501
  // screencast frames already rescheduled the top-off.
455
502
  if (this.frameSeq !== seqAtCapture || this.destroyed) return;
456
503
 
457
- this.dispatch(
504
+ const sent = this.dispatch(
458
505
  screenshot.data,
459
506
  true,
460
507
  profile.topOffFormat === 'jpeg' ? 'image/jpeg' : 'image/png'
461
508
  );
509
+
510
+ // A dropped top-off used to be the end of the line. The encoder
511
+ // handle goes stale on every navigation and re-injection, and the
512
+ // screencast only fires on damage — so on a page that is not
513
+ // moving (a preview the user has just come back to) the one frame
514
+ // that would have cleared "Loading preview…" was lost and nothing
515
+ // would ever produce another. Retry while the handle is being
516
+ // re-acquired, then give up rather than spin.
517
+ if (!sent && this.topOffRetries < ScreencastFeeder.MAX_TOP_OFF_RETRIES) {
518
+ this.topOffRetries++;
519
+ this.capturingTopOff = false;
520
+ this.scheduleTopOff();
521
+ return;
522
+ }
523
+ this.topOffRetries = 0;
462
524
  } catch {
463
525
  // Page may be navigating/closing — top-off is best-effort
464
526
  } finally {
@@ -474,6 +536,7 @@ class ScreencastFeeder {
474
536
  this.flushPendingAck();
475
537
  this.lastDispatchAt = 0;
476
538
  this.lastAckAt = 0;
539
+ this.topOffRetries = 0;
477
540
 
478
541
  if (this.topOffTimer) {
479
542
  clearTimeout(this.topOffTimer);
@@ -509,15 +572,56 @@ export class BrowserVideoCapture extends EventEmitter {
509
572
  */
510
573
  private static readonly CLIENT_ADAPT_INTERVAL_MS = 1500;
511
574
 
575
+ /**
576
+ * How long a viewer may sit in the table without ever connecting.
577
+ * Generous — a slow network can take seconds to finish ICE — but finite,
578
+ * which is the point: a viewer that never completes must not keep the
579
+ * session looking watched forever.
580
+ */
581
+ private static readonly VIEWER_HANDSHAKE_TTL_MS = 45_000;
582
+
583
+ /**
584
+ * Silence tolerated from a connected viewer's stream before the watchdog
585
+ * repairs it. Two encoder-stat windows plus slack — long enough that a
586
+ * genuinely idle page (which still tops off) never trips it.
587
+ */
588
+ private static readonly STREAM_STALL_MS = 6_000;
589
+
512
590
  private sessions = new Map<string, VideoStreamSession>();
513
591
  private feeders = new Map<string, ScreencastFeeder>();
514
592
  private preInjectPromises = new Map<string, Promise<boolean>>();
515
593
  private displayMetricsTimers = new Map<string, ReturnType<typeof setTimeout>>();
594
+ /** Injection bookkeeping, per tab — outlives the stream session. */
595
+ private tabInjection = new Map<string, TabInjectionState>();
596
+ private epochCounter = 0;
597
+ private watchdogTimer: ReturnType<typeof setInterval> | null = null;
516
598
 
517
599
  constructor() {
518
600
  super();
519
601
  }
520
602
 
603
+ /** Injection bookkeeping for a tab, created on first use. */
604
+ private injectionState(sessionId: string): TabInjectionState {
605
+ let state = this.tabInjection.get(sessionId);
606
+ if (!state) {
607
+ state = { bindingsExposed: false, audioScriptId: null, epoch: '', codecSignature: '' };
608
+ this.tabInjection.set(sessionId, state);
609
+ }
610
+ return state;
611
+ }
612
+
613
+ private nextEpoch(sessionId: string): string {
614
+ return `${sessionId}:${++this.epochCounter}:${Date.now().toString(36)}`;
615
+ }
616
+
617
+ /**
618
+ * Forget everything remembered about a tab. Called when the tab is closed —
619
+ * its page is gone, so the bindings and on-new-document scripts go with it.
620
+ */
621
+ disposeTab(sessionId: string): void {
622
+ this.tabInjection.delete(sessionId);
623
+ }
624
+
521
625
  // ------------------------------------------------------------------
522
626
  // Session configuration
523
627
  // ------------------------------------------------------------------
@@ -550,6 +654,7 @@ export class BrowserVideoCapture extends EventEmitter {
550
654
 
551
655
  return {
552
656
  ...DEFAULT_STREAMING_CONFIG.video,
657
+ epoch: this.injectionState(videoSession.sessionId).epoch,
553
658
  width,
554
659
  height,
555
660
  framerate: videoSession.targetFramerate,
@@ -622,7 +727,8 @@ export class BrowserVideoCapture extends EventEmitter {
622
727
  viewers: new Map(),
623
728
  scriptInjected: false,
624
729
  scriptsPreInjected: false,
625
- audioOnNewDocumentInjected: false,
730
+ lastEncodedAt: 0,
731
+ repairing: false,
626
732
  codecSupport: { ...DEFAULT_CODEC_SUPPORT },
627
733
  display: {},
628
734
  profile,
@@ -669,7 +775,7 @@ export class BrowserVideoCapture extends EventEmitter {
669
775
  videoSession.scriptInjected = true;
670
776
  this.sessions.set(sessionId, videoSession);
671
777
 
672
- await this.injectScripts(sessionId, page, this.buildVideoConfig(videoSession, viewport), this.buildAudioConfig(videoSession));
778
+ await this.injectScripts(sessionId, page, videoSession, viewport);
673
779
 
674
780
  // Mark as pre-injected only after successful completion
675
781
  videoSession.scriptsPreInjected = true;
@@ -687,85 +793,299 @@ export class BrowserVideoCapture extends EventEmitter {
687
793
  }
688
794
 
689
795
  /**
690
- * Inject signaling bindings + encoder scripts into page
796
+ * Expose the signalling bindings, once per tab.
797
+ *
798
+ * Every one of these is bound to the tab whose page it was injected into.
799
+ * They used to resolve their session by picking the first active one in
800
+ * the whole project, which is correct only while exactly one tab streams:
801
+ * with several open, one page's ICE candidates, connection states, cursor
802
+ * and encoder stats were all attributed to a different tab.
803
+ *
804
+ * Whether they are already installed is remembered here rather than probed
805
+ * from the page. `typeof window.__sendIceCandidate === 'function'` describes
806
+ * the *current document*, and Puppeteer re-installs bindings on each new
807
+ * one — so mid-navigation the probe says "absent" while Puppeteer's own
808
+ * registry says "present", and `exposeFunction` throws. That threw out of
809
+ * the whole handshake, and every client retry hit the same window: the
810
+ * preview sat on "Loading preview…" until something else moved the page.
811
+ */
812
+ private async exposeBindings(sessionId: string, page: Page): Promise<void> {
813
+ const state = this.injectionState(sessionId);
814
+ if (state.bindingsExposed) return;
815
+
816
+ /** Already-registered is success, not failure — see above. */
817
+ const expose = async (name: string, fn: (...args: any[]) => void) => {
818
+ try {
819
+ await page.exposeFunction(name, fn);
820
+ } catch (error) {
821
+ const message = error instanceof Error ? error.message : String(error);
822
+ if (!message.includes('already exists')) throw error;
823
+ }
824
+ };
825
+
826
+ await expose('__sendIceCandidate', (viewerId: string, candidate: RTCIceCandidateInit) => {
827
+ this.emit('ice-candidate', { sessionId, viewerId, candidate, from: 'headless' });
828
+ });
829
+
830
+ await expose('__sendConnectionState', (viewerId: string, state: string) => {
831
+ const videoSession = this.sessions.get(sessionId);
832
+ if (!videoSession) return;
833
+
834
+ videoSession.stats.connectionState = state;
835
+ this.emit('connection-state', { sessionId, viewerId, state });
836
+
837
+ const viewer = videoSession.viewers.get(viewerId);
838
+ if (viewer && state === 'connected') viewer.connected = true;
839
+
840
+ // Capture sources only produce frames on damage, so a viewer
841
+ // that connects to an already-still page would otherwise wait
842
+ // for the first mouse move to see anything. Push one refresh
843
+ // frame as soon as the peer is up.
844
+ if (state === 'connected' && videoSession.tab) {
845
+ videoSession.lastEncodedAt = Date.now();
846
+ void this.requestKeyframe(sessionId, videoSession.tab);
847
+ }
848
+
849
+ if (state === 'closed' || state === 'failed') {
850
+ videoSession.viewers.delete(viewerId);
851
+ }
852
+ });
853
+
854
+ // A channel that has just opened has no frame to show yet on a still
855
+ // page — see the matching comment in video-stream.ts.
856
+ await expose('__requestRefreshFrame', (viewerId: string) => {
857
+ const videoSession = this.sessions.get(sessionId);
858
+ if (!videoSession?.tab) return;
859
+ debug.log('webcodecs', `Refresh frame requested by viewer ${viewerId} on ${sessionId}`);
860
+ void this.requestKeyframe(sessionId, videoSession.tab);
861
+ });
862
+
863
+ await expose('__sendCursorChange', (cursor: string) => {
864
+ this.emit('cursor-change', { sessionId, cursor });
865
+ });
866
+
867
+ await expose('__sendEncoderStats', (stats: EncoderStats) => {
868
+ this.applyEncoderStats(sessionId, stats);
869
+ });
870
+
871
+ state.bindingsExposed = true;
872
+ }
873
+
874
+ /**
875
+ * Inject signalling bindings + encoder scripts into the page.
876
+ *
877
+ * Mints a fresh epoch for the peer object it creates, so a later health
878
+ * check can tell this injection apart from one left behind by a document
879
+ * the page has since navigated away from.
691
880
  */
692
881
  private async injectScripts(
693
882
  sessionId: string,
694
883
  page: Page,
695
- videoConfig: StreamingConfig['video'],
696
- audioConfig: StreamingConfig['audio']
884
+ videoSession: VideoStreamSession,
885
+ viewport: { width: number; height: number }
697
886
  ): Promise<void> {
698
- // Check if bindings exist
699
- const bindingsExist = await page.evaluate(() => {
700
- return typeof (window as any).__sendIceCandidate === 'function';
701
- });
887
+ await this.exposeBindings(sessionId, page);
702
888
 
703
- // Expose signaling functions (persists across navigations).
889
+ const state = this.injectionState(sessionId);
890
+ const audioConfig = this.buildAudioConfig(videoSession);
891
+
892
+ // Register audio capture as a startup script — runs before page scripts on
893
+ // every new document load. Critical for SPAs that create AudioContext
894
+ // during initialization (before page.evaluate runs).
704
895
  //
705
- // Every one of these is bound to the tab whose page it was injected into.
706
- // They used to resolve their session by picking the first active one in
707
- // the whole project, which is correct only while exactly one tab streams:
708
- // with several open, one page's ICE candidates, connection states, cursor
709
- // and encoder stats were all attributed to a different tab. The viewer
710
- // filters those by tab, so its candidates were silently discarded and the
711
- // connection never completed — and because the first refresh frame is
712
- // pushed from the `connected` state, a still page also never produced a
713
- // first frame. That is the "Loading preview…" that never resolves.
714
- if (!bindingsExist) {
715
- await page.exposeFunction('__sendIceCandidate', (viewerId: string, candidate: RTCIceCandidateInit) => {
716
- this.emit('ice-candidate', { sessionId, viewerId, candidate, from: 'headless' });
717
- });
896
+ // Registered exactly once for the tab. This used to be tracked on the
897
+ // stream session, which `stopStreaming` deletes, so every switch away
898
+ // from a preview tab and back added another copy that nothing removed —
899
+ // after enough switches each page load ran a stack of them, and the only
900
+ // cure was restarting the server.
901
+ if (!state.audioScriptId) {
902
+ const registered = await page.evaluateOnNewDocument(audioCaptureScript, audioConfig);
903
+ state.audioScriptId = (registered as { identifier?: string })?.identifier ?? 'registered';
904
+ }
718
905
 
719
- await page.exposeFunction('__sendConnectionState', (viewerId: string, state: string) => {
720
- const videoSession = this.sessions.get(sessionId);
721
- if (!videoSession) return;
906
+ state.epoch = this.nextEpoch(sessionId);
722
907
 
723
- videoSession.stats.connectionState = state;
724
- this.emit('connection-state', { sessionId, viewerId, state });
908
+ // Inject video encoder + audio capture scripts into the current page context
909
+ const videoConfig = this.buildVideoConfig(videoSession, viewport);
910
+ state.codecSignature = this.codecSignature(videoSession);
725
911
 
726
- // Capture sources only produce frames on damage, so a viewer
727
- // that connects to an already-still page would otherwise wait
728
- // for the first mouse move to see anything. Push one refresh
729
- // frame as soon as the peer is up.
730
- if (state === 'connected' && videoSession.tab) {
731
- void this.requestKeyframe(sessionId, videoSession.tab);
732
- }
912
+ await page.evaluate(videoEncoderScript, videoConfig);
913
+ await injectAudioCaptureIntoAllFrames(page, audioConfig);
914
+ }
733
915
 
734
- if (state === 'closed' || state === 'failed') {
735
- videoSession.viewers.delete(viewerId);
736
- }
737
- });
916
+ /** Which encoder candidates the current viewer set implies. */
917
+ private codecSignature(videoSession: VideoStreamSession): string {
918
+ return resolveCodecCandidates(videoSession.codecSupport)
919
+ .map((candidate) => candidate.name)
920
+ .join(',');
921
+ }
738
922
 
739
- // A channel that has just opened has no frame to show yet on a still
740
- // page — see the matching comment in video-stream.ts.
741
- await page.exposeFunction('__requestRefreshFrame', (viewerId: string) => {
742
- const videoSession = this.sessions.get(sessionId);
743
- if (!videoSession?.tab) return;
744
- debug.log('webcodecs', `Refresh frame requested by viewer ${viewerId} on ${sessionId}`);
745
- void this.requestKeyframe(sessionId, videoSession.tab);
746
- });
923
+ // ------------------------------------------------------------------
924
+ // Liveness
925
+ // ------------------------------------------------------------------
747
926
 
748
- await page.exposeFunction('__sendCursorChange', (cursor: string) => {
749
- this.emit('cursor-change', { sessionId, cursor });
927
+ /** What the page says about its own peer, or null when it has none. */
928
+ private async readPeerHealth(page: Page): Promise<PeerHealth | null> {
929
+ if (page.isClosed()) return null;
930
+ try {
931
+ return await page.evaluate(() => {
932
+ const peer = (window as any).__webCodecsPeer;
933
+ return typeof peer?.health === 'function' ? peer.health() : null;
750
934
  });
935
+ } catch {
936
+ // Execution context torn down mid-navigation — treat as "no peer",
937
+ // which is exactly what it will be a moment from now.
938
+ return null;
939
+ }
940
+ }
751
941
 
752
- await page.exposeFunction('__sendEncoderStats', (stats: EncoderStats) => {
753
- this.applyEncoderStats(sessionId, stats);
754
- });
942
+ /**
943
+ * Bring the page's capture in line with what the backend believes.
944
+ *
945
+ * This replaces the old fork in `startStreaming`, which chose between a
946
+ * clean restart and a bare attach purely on how many *other* viewers were
947
+ * registered. That choice was made from the backend's own record, and the
948
+ * record is exactly the thing that goes stale: with another viewer present
949
+ * the attach path never re-injected the peer script, so a page whose peer
950
+ * had died with a navigation stayed dead, `createOffer` returned null
951
+ * forever, and every client retry took the same doomed branch. Reloading
952
+ * the page was the only way out, because that re-injected by another route.
953
+ *
954
+ * Asking the page instead makes both cases converge: cheap when it is
955
+ * healthy (one evaluate), correct when it is not.
956
+ */
957
+ private async ensureLive(
958
+ sessionId: string,
959
+ session: BrowserTab,
960
+ isValidSession: () => boolean,
961
+ options: { force?: boolean } = {}
962
+ ): Promise<boolean> {
963
+ const videoSession = this.sessions.get(sessionId);
964
+ if (!videoSession) return false;
965
+ if (!session.page || session.page.isClosed()) return false;
966
+
967
+ const page = session.page;
968
+ const viewport = page.viewport()!;
969
+ videoSession.tab = session;
970
+
971
+ const health = options.force ? null : await this.readPeerHealth(page);
972
+ const injection = this.injectionState(sessionId);
973
+
974
+ // A peer from a different injection answers every call and encodes into
975
+ // a page that is no longer on screen — indistinguishable from a healthy
976
+ // one without the epoch.
977
+ const epochMismatch = !health || !health.epoch || health.epoch !== injection.epoch;
978
+ const codecChanged = injection.codecSignature !== this.codecSignature(videoSession);
979
+ const needsInjection = epochMismatch || codecChanged;
980
+
981
+ if (needsInjection) {
982
+ const reason = options.force
983
+ ? 'forced'
984
+ : !health
985
+ ? 'no peer in page'
986
+ : epochMismatch
987
+ ? 'epoch mismatch'
988
+ : 'codec set changed';
989
+ debug.log('webcodecs', `Rebuilding peer for ${sessionId} (${reason})`);
990
+ await this.injectScripts(sessionId, page, videoSession, viewport);
991
+ videoSession.scriptInjected = true;
992
+ // The old page's encoder handle died with its execution context.
993
+ this.feeders.get(sessionId)?.invalidatePeerHandle();
755
994
  }
756
995
 
757
- // Register audio capture as a startup script — runs before page scripts on every new document load.
758
- // Critical for SPAs that create AudioContext during initialization (before page.evaluate runs).
759
- // The idempotency guard in audioCaptureScript prevents double-injection.
760
- const session = this.sessions.get(sessionId);
761
- if (session && !session.audioOnNewDocumentInjected) {
762
- await page.evaluateOnNewDocument(audioCaptureScript, audioConfig);
763
- session.audioOnNewDocumentInjected = true;
996
+ if (needsInjection || !health?.capturing) {
997
+ const started = await this.startPageCapture(page);
998
+ if (!started) {
999
+ debug.error('webcodecs', `Page refused to start capturing for ${sessionId}`);
1000
+ return false;
1001
+ }
1002
+ videoSession.isActive = true;
1003
+ videoSession.headlessReady = true;
1004
+ videoSession.paused = false;
1005
+ videoSession.captureMode = 'push';
1006
+ videoSession.healthyWindows = 0;
1007
+ await this.setupCapture(sessionId, session, isValidSession);
1008
+ } else {
1009
+ // Healthy: keep the backend's view of the page honest anyway, since
1010
+ // the page may have switched capture source on its own.
1011
+ videoSession.isActive = true;
1012
+ videoSession.headlessReady = true;
1013
+ videoSession.captureMode = health.captureMode;
1014
+ this.reconcileViewers(videoSession, health);
764
1015
  }
765
1016
 
766
- // Inject video encoder + audio capture scripts into the current page context
767
- await page.evaluate(videoEncoderScript, videoConfig);
768
- await injectAudioCaptureIntoAllFrames(page, audioConfig);
1017
+ videoSession.lastEncodedAt = Date.now();
1018
+ this.ensureWatchdog();
1019
+ return true;
1020
+ }
1021
+
1022
+ /**
1023
+ * Start (or confirm) the page-side encoder and audio tap in one round-trip.
1024
+ */
1025
+ private async startPageCapture(page: Page): Promise<boolean> {
1026
+ const initResult = await page.evaluate(async () => {
1027
+ const peer = (window as any).__webCodecsPeer;
1028
+ if (typeof peer?.startStreaming !== 'function') {
1029
+ return { peerExists: false, started: false, audioInitialized: false };
1030
+ }
1031
+
1032
+ const started = await peer.startStreaming();
1033
+ if (!started) {
1034
+ return { peerExists: true, started: false, audioInitialized: false };
1035
+ }
1036
+
1037
+ // Initialize audio encoder if available
1038
+ let audioInitialized = false;
1039
+ const encoder = (window as any).__audioEncoder;
1040
+ if (typeof encoder?.init === 'function') {
1041
+ try {
1042
+ const initiated = await encoder.init();
1043
+ if (initiated) {
1044
+ audioInitialized = !!encoder.start();
1045
+ }
1046
+ } catch {}
1047
+ }
1048
+
1049
+ return { peerExists: true, started: true, audioInitialized };
1050
+ });
1051
+
1052
+ if (!initResult.peerExists || !initResult.started) return false;
1053
+
1054
+ if (!initResult.audioInitialized) {
1055
+ debug.warn('webcodecs', 'Audio not available, continuing with video only');
1056
+ }
1057
+
1058
+ return true;
1059
+ }
1060
+
1061
+ /**
1062
+ * Drop viewers the page has never heard of and handshakes that never
1063
+ * completed. Without this a viewer that vanished mid-negotiation — a host
1064
+ * browser refreshed, a laptop closed — stayed in the table forever, and the
1065
+ * session went on looking watched by an audience of nobody.
1066
+ */
1067
+ private reconcileViewers(videoSession: VideoStreamSession, health: PeerHealth): void {
1068
+ const livePeers = new Set(health.viewers);
1069
+ const now = Date.now();
1070
+ let dropped = 0;
1071
+
1072
+ for (const [viewerId, viewer] of videoSession.viewers) {
1073
+ if (livePeers.has(viewerId)) continue;
1074
+ // Still negotiating — its peer is created by createOffer, which may
1075
+ // not have run yet.
1076
+ if (now - viewer.attachedAt < BrowserVideoCapture.VIEWER_HANDSHAKE_TTL_MS) continue;
1077
+
1078
+ videoSession.viewers.delete(viewerId);
1079
+ dropped++;
1080
+ }
1081
+
1082
+ if (dropped > 0) {
1083
+ debug.log(
1084
+ 'webcodecs',
1085
+ `Dropped ${dropped} stale viewer(s) from ${videoSession.sessionId}, ${videoSession.viewers.size} left`
1086
+ );
1087
+ this.refreshViewerConfig(videoSession);
1088
+ }
769
1089
  }
770
1090
 
771
1091
  // ------------------------------------------------------------------
@@ -792,7 +1112,8 @@ export class BrowserVideoCapture extends EventEmitter {
792
1112
  connected: false,
793
1113
  pendingCandidates: [],
794
1114
  visible: true,
795
- decoderSaturated: false
1115
+ decoderSaturated: false,
1116
+ attachedAt: Date.now()
796
1117
  };
797
1118
 
798
1119
  if (options.codecSupport) viewer.codecSupport = options.codecSupport;
@@ -802,6 +1123,7 @@ export class BrowserVideoCapture extends EventEmitter {
802
1123
  viewer.connected = false;
803
1124
  viewer.pendingCandidates = [];
804
1125
  viewer.visible = true;
1126
+ viewer.attachedAt = Date.now();
805
1127
 
806
1128
  videoSession.viewers.set(viewer.id, viewer);
807
1129
  this.refreshViewerConfig(videoSession);
@@ -809,35 +1131,6 @@ export class BrowserVideoCapture extends EventEmitter {
809
1131
  return viewer;
810
1132
  }
811
1133
 
812
- /**
813
- * Add a viewer to a stream that is already running.
814
- *
815
- * Nothing about the capture is disturbed — the existing viewers keep their
816
- * channels. Only the shared geometry is re-derived, in case the newcomer has
817
- * a sharper screen than anyone already watching.
818
- */
819
- private async attachViewer(
820
- sessionId: string,
821
- session: BrowserTab,
822
- options: {
823
- viewerId: string;
824
- codecSupport?: ClientCodecSupport;
825
- display?: ClientDisplayMetrics;
826
- }
827
- ): Promise<boolean> {
828
- const videoSession = this.sessions.get(sessionId);
829
- if (!videoSession?.isActive) return false;
830
-
831
- this.registerViewer(videoSession, options);
832
- videoSession.tab = session;
833
-
834
- // The stream may have been paused because everyone watching had it off
835
- // screen; someone is watching again.
836
- await this.setPaused(sessionId, session, false);
837
- await this.applyCaptureGeometry(sessionId, session);
838
- return true;
839
- }
840
-
841
1134
  /**
842
1135
  * Drop a viewer. The capture only stops once the last one is gone —
843
1136
  * otherwise closing one device's panel would blank every other device.
@@ -878,7 +1171,14 @@ export class BrowserVideoCapture extends EventEmitter {
878
1171
  // ------------------------------------------------------------------
879
1172
 
880
1173
  /**
881
- * Start video streaming for a session
1174
+ * Attach a viewer to a tab's stream, bringing the stream up if it isn't.
1175
+ *
1176
+ * One path for both cases. The old code chose between "restart everything"
1177
+ * and "just attach" from its own viewer count, which meant a stale entry
1178
+ * could route a perfectly ordinary reconnect into the attach branch and
1179
+ * leave a dead page untouched. Here the page decides (see `ensureLive`),
1180
+ * and the difference between a first viewer and a fifth is only how much
1181
+ * work that check turns out to imply.
882
1182
  */
883
1183
  async startStreaming(
884
1184
  sessionId: string,
@@ -900,37 +1200,12 @@ export class BrowserVideoCapture extends EventEmitter {
900
1200
  await pendingPreInject.catch(() => {});
901
1201
  }
902
1202
 
903
- // A viewer re-handshaking (its own recovery path) gets a clean restart
904
- // only when it is the sole viewer — that is the case the recovery logic
905
- // was written for. Tearing the capture down because a *second* viewer
906
- // arrived is what made two devices fight over one tab: each new
907
- // handshake killed the other side's channel, whose health check
908
- // reconnected and killed this one straight back.
909
- const existingSession = this.sessions.get(sessionId);
910
- if (existingSession?.isActive) {
911
- const others = Array.from(existingSession.viewers.keys()).filter((id) => id !== viewerId);
912
- if (others.length === 0) {
913
- debug.log('webcodecs', `Session ${sessionId} already active for its only viewer, restarting clean`);
914
- await this.stopStreaming(sessionId, session);
915
- } else {
916
- debug.log(
917
- 'webcodecs',
918
- `Session ${sessionId} already streaming to ${others.length} other viewer(s), attaching ${viewerId}`
919
- );
920
- return this.attachViewer(sessionId, session, options);
921
- }
922
- }
923
-
924
1203
  if (!session.page || session.page.isClosed()) {
925
1204
  debug.error('webcodecs', `Cannot start: page is closed`);
926
1205
  return false;
927
1206
  }
928
1207
 
929
1208
  try {
930
- const page = session.page;
931
- const viewport = page.viewport()!;
932
-
933
- // Get or create session tracking
934
1209
  let videoSession = this.sessions.get(sessionId);
935
1210
  if (!videoSession) {
936
1211
  videoSession = this.createSessionState(sessionId);
@@ -939,80 +1214,28 @@ export class BrowserVideoCapture extends EventEmitter {
939
1214
 
940
1215
  videoSession.tab = session;
941
1216
  this.registerViewer(videoSession, options);
942
- videoSession.paused = false;
943
- videoSession.captureMode = 'push';
944
- videoSession.healthyWindows = 0;
945
-
946
- const videoConfig = this.buildVideoConfig(videoSession, viewport);
947
- const audioConfig = this.buildAudioConfig(videoSession);
948
-
949
- // The pre-injected script was configured before the viewer's codec
950
- // support and display metrics were known, so re-inject whenever the
951
- // handshake carried either.
952
- const mustReinject = !videoSession.scriptsPreInjected || !!options?.codecSupport || !!options?.display;
953
- if (mustReinject) {
954
- await this.injectScripts(sessionId, page, videoConfig, audioConfig);
955
- videoSession.scriptInjected = true;
956
- } else {
957
- debug.log('webcodecs', `Scripts already pre-injected for ${sessionId}, skipping injection`);
958
- }
959
-
960
- // Single batched call: verify peer + start streaming + init audio
961
- // (saves ~60ms of IPC overhead vs 4 separate page.evaluate calls)
962
- const initResult = await page.evaluate(async () => {
963
- const peer = (window as any).__webCodecsPeer;
964
- if (typeof peer?.startStreaming !== 'function') {
965
- return { peerExists: false, started: false, audioInitialized: false };
966
- }
967
1217
 
968
- const started = await peer.startStreaming();
969
- if (!started) {
970
- return { peerExists: true, started: false, audioInitialized: false };
971
- }
972
-
973
- // Initialize audio encoder if available
974
- let audioInitialized = false;
975
- const encoder = (window as any).__audioEncoder;
976
- if (typeof encoder?.init === 'function') {
977
- try {
978
- const initiated = await encoder.init();
979
- if (initiated) {
980
- audioInitialized = !!encoder.start();
981
- }
982
- } catch {}
983
- }
984
-
985
- return { peerExists: true, started: true, audioInitialized };
986
- });
1218
+ // The pre-injected peer was built before any viewer's capabilities
1219
+ // were known; `ensureLive` re-injects if this one needs a different
1220
+ // codec set, and reuses it otherwise. Display metrics never need a
1221
+ // rebuild — `applyCaptureGeometry` reconfigures the live encoder.
1222
+ const live = await this.ensureLive(sessionId, session, isValidSession);
987
1223
 
988
- if (!initResult.peerExists) {
989
- debug.error('webcodecs', `Peer script injected but __webCodecsPeer not available`);
990
- this.sessions.delete(sessionId);
1224
+ if (!live) {
1225
+ debug.error('webcodecs', `Failed to bring up capture for ${sessionId}`);
991
1226
  return false;
992
1227
  }
993
1228
 
994
- if (!initResult.started) {
995
- debug.error('webcodecs', `startStreaming returned false`);
996
- this.sessions.delete(sessionId);
997
- return false;
998
- }
999
-
1000
- videoSession.isActive = true;
1001
-
1002
- if (initResult.audioInitialized) {
1003
- debug.log('webcodecs', 'Audio encoder initialized and started');
1004
- } else {
1005
- debug.warn('webcodecs', 'Audio not available, continuing with video only');
1006
- }
1007
-
1008
- videoSession.headlessReady = true;
1009
-
1010
- await this.setupCapture(sessionId, session, isValidSession);
1229
+ // Someone is watching again — the stream may have been paused because
1230
+ // everyone who had it open put it off screen.
1231
+ await this.setPaused(sessionId, session, false);
1232
+ await this.applyCaptureGeometry(sessionId, session);
1011
1233
 
1012
1234
  debug.log(
1013
1235
  'webcodecs',
1014
- `Streaming started for ${sessionId} — ${videoSession.capture.width}x${videoSession.capture.height} ` +
1015
- `@${videoSession.targetFramerate}fps (${videoSession.captureMode}, ${videoSession.profile.tier})`
1236
+ `Streaming ready for ${sessionId} — ${videoSession.capture.width}x${videoSession.capture.height} ` +
1237
+ `@${videoSession.targetFramerate}fps (${videoSession.captureMode}, ${videoSession.profile.tier}, ` +
1238
+ `${videoSession.viewers.size} viewer(s))`
1016
1239
  );
1017
1240
  return true;
1018
1241
  } catch (error) {
@@ -1283,6 +1506,107 @@ export class BrowserVideoCapture extends EventEmitter {
1283
1506
  }
1284
1507
  }
1285
1508
 
1509
+ /**
1510
+ * Watch every live session for a stream that has stopped producing.
1511
+ *
1512
+ * On a timer rather than driven by encoder stats, because the failures that
1513
+ * matter are the ones where the page stops reporting altogether — a peer
1514
+ * that died with a navigation sends nothing, so anything event-driven would
1515
+ * wait forever for a signal that is never coming. Runs only while sessions
1516
+ * exist, and does nothing at all unless one has actually gone quiet.
1517
+ */
1518
+ private ensureWatchdog(): void {
1519
+ if (this.watchdogTimer || this.sessions.size === 0) return;
1520
+
1521
+ this.watchdogTimer = setInterval(() => {
1522
+ if (this.sessions.size === 0) {
1523
+ clearInterval(this.watchdogTimer!);
1524
+ this.watchdogTimer = null;
1525
+ return;
1526
+ }
1527
+
1528
+ for (const videoSession of [...this.sessions.values()]) {
1529
+ if (!videoSession.isActive) continue;
1530
+ if (this.reapStaleViewers(videoSession)) continue;
1531
+ this.checkForStall(videoSession);
1532
+ }
1533
+ }, BrowserVideoCapture.STREAM_STALL_MS);
1534
+
1535
+ // Nothing here should hold the process open on its own.
1536
+ this.watchdogTimer.unref?.();
1537
+ }
1538
+
1539
+ /**
1540
+ * Drop viewers that handshook and never connected, and tear the capture
1541
+ * down if that leaves nobody watching. Returns whether the session ended.
1542
+ *
1543
+ * The page-informed pass in `reconcileViewers` only runs when someone
1544
+ * handshakes, which is precisely what a tab nobody is watching any more
1545
+ * never gets — so without this a viewer that vanished mid-negotiation kept
1546
+ * a headless renderer and an encoder busy for an audience of nobody.
1547
+ */
1548
+ private reapStaleViewers(videoSession: VideoStreamSession): boolean {
1549
+ const now = Date.now();
1550
+ let dropped = 0;
1551
+
1552
+ for (const [viewerId, viewer] of videoSession.viewers) {
1553
+ if (viewer.connected) continue;
1554
+ if (now - viewer.attachedAt < BrowserVideoCapture.VIEWER_HANDSHAKE_TTL_MS) continue;
1555
+
1556
+ videoSession.viewers.delete(viewerId);
1557
+ dropped++;
1558
+ }
1559
+
1560
+ if (dropped === 0) return false;
1561
+
1562
+ debug.log(
1563
+ 'webcodecs',
1564
+ `Reaped ${dropped} viewer(s) that never connected on ${videoSession.sessionId}, ` +
1565
+ `${videoSession.viewers.size} left`
1566
+ );
1567
+
1568
+ if (videoSession.viewers.size > 0) {
1569
+ this.refreshViewerConfig(videoSession);
1570
+ return false;
1571
+ }
1572
+
1573
+ void this.stopStreaming(videoSession.sessionId, videoSession.tab);
1574
+ return true;
1575
+ }
1576
+
1577
+ /**
1578
+ * Repair a stream that has stopped producing while someone is watching it.
1579
+ *
1580
+ * Recovery used to live entirely in the viewer: it noticed no first frame,
1581
+ * asked for a screencast refresh, then re-handshook. That only works while
1582
+ * the *client's* view of the problem is right — and the failures that stuck
1583
+ * were the ones where the client did everything correctly and the source
1584
+ * was the broken half. Repairing from here closes that gap, and costs
1585
+ * nothing on a healthy stream because even an idle page still tops off.
1586
+ */
1587
+ private checkForStall(videoSession: VideoStreamSession): void {
1588
+ if (videoSession.paused || videoSession.repairing || !videoSession.tab) return;
1589
+ if (videoSession.viewers.size === 0) return;
1590
+ if (!Array.from(videoSession.viewers.values()).some((viewer) => viewer.connected)) return;
1591
+
1592
+ const silentFor = Date.now() - videoSession.lastEncodedAt;
1593
+ if (videoSession.lastEncodedAt === 0 || silentFor < BrowserVideoCapture.STREAM_STALL_MS) return;
1594
+
1595
+ const { sessionId, tab } = videoSession;
1596
+ debug.warn('webcodecs', `Stream for ${sessionId} produced nothing for ${silentFor}ms — repairing`);
1597
+
1598
+ videoSession.repairing = true;
1599
+ void this.ensureLive(sessionId, tab, () => !tab.isDestroyed)
1600
+ .then((live) => {
1601
+ if (live) return this.requestKeyframe(sessionId, tab);
1602
+ })
1603
+ .catch((error) => debug.warn('webcodecs', `Stall repair failed for ${sessionId}:`, error))
1604
+ .finally(() => {
1605
+ videoSession.repairing = false;
1606
+ videoSession.lastEncodedAt = Date.now();
1607
+ });
1608
+ }
1609
+
1286
1610
  /**
1287
1611
  * Encoder health from the page. Saturation here means this host cannot
1288
1612
  * produce frames fast enough, which no amount of network headroom fixes.
@@ -1293,6 +1617,11 @@ export class BrowserVideoCapture extends EventEmitter {
1293
1617
 
1294
1618
  videoSession.captureMode = stats.captureMode || videoSession.captureMode;
1295
1619
 
1620
+ // Frames reaching the encoder is the one signal that means the pipeline
1621
+ // is genuinely alive end to end. The counter is per-window, so any
1622
+ // non-zero report is proof of life for this window.
1623
+ if (stats.framesAttempted > 0) videoSession.lastEncodedAt = Date.now();
1624
+
1296
1625
  // In-page capture can end on its own — the captured surface goes away
1297
1626
  // on some navigations — and the page has no way to start a screencast.
1298
1627
  // Detecting the drop here is what keeps the preview from freezing on
@@ -1421,8 +1750,14 @@ export class BrowserVideoCapture extends EventEmitter {
1421
1750
  visible: boolean
1422
1751
  ): Promise<boolean> {
1423
1752
  const videoSession = this.sessions.get(sessionId);
1424
- const viewer = videoSession?.viewers.get(viewerId);
1425
- if (!videoSession || !viewer) return false;
1753
+ if (!videoSession) return false;
1754
+
1755
+ // Registered on demand rather than refused. A viewer whose peer failed
1756
+ // while it was suspended loses its entry, and coming back is exactly
1757
+ // when it needs one: refusing left the tab paused with `isActive` true
1758
+ // and nobody in the table, and nothing else ever re-evaluated that.
1759
+ const viewer =
1760
+ videoSession.viewers.get(viewerId) ?? this.registerViewer(videoSession, { viewerId });
1426
1761
 
1427
1762
  viewer.visible = visible;
1428
1763
  return this.setPaused(sessionId, session, this.allViewersHidden(videoSession));
@@ -1697,8 +2032,14 @@ export class BrowserVideoCapture extends EventEmitter {
1697
2032
  }
1698
2033
 
1699
2034
  /**
1700
- * Handle navigation - re-inject peer script and restart capture
1701
- * Called after page navigation to restore video streaming without full reconnection
2035
+ * Re-establish capture after the page swapped documents.
2036
+ *
2037
+ * The peer object lived in the old execution context, so it is gone; only
2038
+ * the exposed bindings survive. `ensureLive` already knows how to notice
2039
+ * that and rebuild, and routing through it means a navigation and a stalled
2040
+ * stream heal by the same code — a failure here no longer leaves the
2041
+ * session marked active with a dead page behind it, which is the state that
2042
+ * used to be unrecoverable without reloading by hand.
1702
2043
  */
1703
2044
  async handleNavigation(sessionId: string, session: BrowserTab): Promise<boolean> {
1704
2045
  const videoSession = this.sessions.get(sessionId);
@@ -1707,70 +2048,27 @@ export class BrowserVideoCapture extends EventEmitter {
1707
2048
  return false;
1708
2049
  }
1709
2050
 
1710
- try {
1711
- const page = session.page;
1712
- const viewport = page.viewport()!;
1713
-
1714
- debug.log('webcodecs', `🔄 Handling navigation for ${sessionId} - re-injecting peer script and restarting capture`);
1715
-
1716
- const videoConfig = this.buildVideoConfig(videoSession, viewport);
1717
- const audioConfig = this.buildAudioConfig(videoSession);
1718
-
1719
- // Re-inject video encoder and audio capture scripts to new page context
1720
- await page.evaluate(videoEncoderScript, videoConfig);
1721
- await injectAudioCaptureIntoAllFrames(page, audioConfig);
1722
-
1723
- // Single batched call: verify peer + start streaming + init audio
1724
- const initResult = await page.evaluate(async () => {
1725
- const peer = (window as any).__webCodecsPeer;
1726
- if (typeof peer?.startStreaming !== 'function') {
1727
- return { peerExists: false, started: false, audioInitialized: false };
1728
- }
1729
-
1730
- const started = await peer.startStreaming();
1731
- if (!started) {
1732
- return { peerExists: true, started: false, audioInitialized: false };
1733
- }
2051
+ debug.log('webcodecs', `🔄 Handling navigation for ${sessionId} — rebuilding page capture`);
1734
2052
 
1735
- let audioInitialized = false;
1736
- const encoder = (window as any).__audioEncoder;
1737
- if (typeof encoder?.init === 'function') {
1738
- try {
1739
- const initiated = await encoder.init();
1740
- if (initiated) {
1741
- audioInitialized = !!encoder.start();
1742
- }
1743
- } catch {}
1744
- }
1745
-
1746
- return { peerExists: true, started: true, audioInitialized };
2053
+ try {
2054
+ const live = await this.ensureLive(sessionId, session, () => !session.isDestroyed, {
2055
+ force: true
1747
2056
  });
1748
2057
 
1749
- if (!initResult.peerExists) {
1750
- debug.error('webcodecs', `Peer script re-injection failed - peer not available`);
2058
+ if (!live) {
2059
+ // Leave the session marked inactive so the next handshake starts
2060
+ // from scratch instead of attaching to a page that cannot encode.
2061
+ videoSession.isActive = false;
2062
+ debug.error('webcodecs', `Failed to restore streaming after navigation for ${sessionId}`);
1751
2063
  return false;
1752
2064
  }
1753
2065
 
1754
- if (!initResult.started) {
1755
- debug.error('webcodecs', `Failed to start streaming on new page`);
1756
- return false;
1757
- }
1758
-
1759
- if (initResult.audioInitialized) {
1760
- debug.log('webcodecs', 'Audio re-initialized after navigation');
1761
- } else {
1762
- debug.warn('webcodecs', 'Audio not available after navigation, continuing with video only');
1763
- }
1764
-
1765
- // The old page's encoder handle died with its execution context.
1766
- videoSession.captureMode = 'push';
1767
- await this.setupCapture(sessionId, session, () => !session.isDestroyed);
1768
-
1769
2066
  // Emit event to notify frontend that streaming is ready
1770
2067
  this.emit('navigation-streaming-ready', { sessionId });
1771
2068
 
1772
2069
  return true;
1773
2070
  } catch (error) {
2071
+ videoSession.isActive = false;
1774
2072
  debug.error('webcodecs', `Failed to handle navigation:`, error);
1775
2073
  return false;
1776
2074
  }
@@ -1846,10 +2144,16 @@ export class BrowserVideoCapture extends EventEmitter {
1846
2144
  async cleanup(): Promise<void> {
1847
2145
  debug.log('webcodecs', 'Cleaning up all sessions');
1848
2146
 
2147
+ if (this.watchdogTimer) {
2148
+ clearInterval(this.watchdogTimer);
2149
+ this.watchdogTimer = null;
2150
+ }
2151
+
1849
2152
  const sessionIds = Array.from(this.sessions.keys());
1850
2153
  await Promise.all(sessionIds.map((id) => this.stopStreaming(id)));
1851
2154
 
1852
2155
  this.sessions.clear();
2156
+ this.tabInjection.clear();
1853
2157
  }
1854
2158
  }
1855
2159