The free and privacy-friendly screen recorder with no limits π₯
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Recording stability under tab throttling, tighter auth refresh gate, and editor lock cleanup
Alyssa X3f4ff7130137
diff --git a/package-lock.json b/package-lock.jsonindex 0f75a4c..802dc48 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "screenity",- "version": "4.4.7",+ "version": "4.4.11","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "screenity",- "version": "4.4.7",+ "version": "4.4.11","hasInstallScript": true,"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",diff --git a/package.json b/package.jsonindex 45997dd..d8d66fa 100755--- a/package.json+++ b/package.json@@ -31,7 +31,9 @@"check:i18n": "node scripts/check-i18n.mjs","verify:zip": "node scripts/verify-no-secrets.mjs","release": "node scripts/release.mjs",- "test:unit": "node --test tests/unit/*.test.mjs"+ "test:unit": "node --test tests/unit/*.test.mjs",+ "test:e2e": "playwright test --config tests/playwright.config.ts",+ "test:e2e:fast": "SCREENITY_E2E_HEADLESS=1 playwright test --config tests/playwright.config.ts"},"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",diff --git a/src/pages/Background/listeners/onActionButtonClickedListener.js b/src/pages/Background/listeners/onActionButtonClickedListener.jsindex c8d8ee5..71b3dc7 100644--- a/src/pages/Background/listeners/onActionButtonClickedListener.js+++ b/src/pages/Background/listeners/onActionButtonClickedListener.js@@ -7,6 +7,7 @@ import {import { sendMessageRecord } from "../recording/sendMessageRecord.js";import { loginWithWebsite } from "../auth/loginWithWebsite.js";import { tryResumePendingUploads } from "../recording/resumePendingUploads";+import { clearInMemoryEditorLock } from "../recording/stopRecording";const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";@@ -244,6 +245,7 @@ export const onActionButtonClickedListener = () => {"[Screenity][ActionClick] branch: stale-reset-then-popup.",{ recording, pendingRecording, restarting, sessionRecording, recordingTab, offscreen },);+ clearInMemoryEditorLock();await chrome.storage.local.set({recording: false,pendingRecording: false,diff --git a/src/pages/Background/listeners/onTabUpdatedListener.js b/src/pages/Background/listeners/onTabUpdatedListener.jsindex 51e1c7c..d86221f 100644--- a/src/pages/Background/listeners/onTabUpdatedListener.js+++ b/src/pages/Background/listeners/onTabUpdatedListener.js@@ -13,9 +13,29 @@ const tryAppAuthRefresh = async (url) => {if (!url.startsWith(APP_BASE)) return;const now = Date.now();if (now - lastAppAuthRefreshAt < APP_AUTH_REFRESH_DEBOUNCE_MS) return;- // skip when already authed; AUTH_SUCCESS is the fast path.- const { isLoggedIn } = await chrome.storage.local.get(["isLoggedIn"]);+ const {+ isLoggedIn,+ wasLoggedIn,+ hasSubscribedBefore,+ screenityUser,+ stayLoggedOut,+ } = await chrome.storage.local.get([+ "isLoggedIn",+ "wasLoggedIn",+ "hasSubscribedBefore",+ "screenityUser",+ "stayLoggedOut",+ ]);if (isLoggedIn) return;+ if (stayLoggedOut) return;+ // Only refresh if there's prior evidence of an account, otherwise every+ // logged-out visitor hits /auth/refresh and 401s. Mirrors the priorSignals+ // gate in loginWithWebsite (force:true would bypass it).+ const hasPriorSignals =+ Boolean(wasLoggedIn) ||+ Boolean(hasSubscribedBefore) ||+ Boolean(screenityUser);+ if (!hasPriorSignals) return;lastAppAuthRefreshAt = now;loginWithWebsite({ force: true }).catch(() => {});};diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.jsindex 7330e9c..220be0f 100644--- a/src/pages/Background/messaging/handlers.js+++ b/src/pages/Background/messaging/handlers.js@@ -15,6 +15,7 @@ import { noteCountdownStarted } from "../recording/countdownFallback";import {handleStopRecordingTab,handleStopRecordingTabBackup,+ clearInMemoryEditorLock,} from "../recording/stopRecording";import { sendChunks } from "../recording/sendChunks";import { chunksStore } from "../recording/chunkHandler";@@ -871,10 +872,10 @@ export const setupHandlers = () => {const headers = { "Content-Type": "application/json" };if (screenityToken) headers.Authorization = `Bearer ${screenityToken}`;// No keepalive:true (MV3 SW fetches with it can hang forever).- // 1s abort then fall through to editor-tab proxy; healthy is- // <500ms, >1s means BG-direct is wedged.+ // 3s abort then fall through to editor-tab proxy. Healthy is+ // <500ms, 1s was too tight and tripped on normal latency spikes.const controller = new AbortController();- const abortTimer = setTimeout(() => controller.abort(), 1_000);+ const abortTimer = setTimeout(() => controller.abort(), 3_000);let res;try {res = await fetch(`${API_BASE}/videos/${projectId}/scenes/`, {@@ -1151,6 +1152,7 @@ export const setupHandlers = () => {if (!customRegion) return;diagEvent("region-iframe-destroyed");+ clearInMemoryEditorLock();await chrome.storage.local.set({recording: false,customRegion: false,diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.jsindex 41c8ed1..571d20e 100644--- a/src/pages/Background/recording/recordingHelpers.js+++ b/src/pages/Background/recording/recordingHelpers.js@@ -5,7 +5,7 @@ import {getCurrentTab,} from "../tabManagement";import { sendMessageRecord } from "./sendMessageRecord";-import { stopRecording } from "./stopRecording";+import { stopRecording, clearInMemoryEditorLock } from "./stopRecording";import { addAlarmListener } from "../alarms/addAlarmListener";import { getStreamingData } from "./getStreamingData";import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";@@ -188,6 +188,7 @@ export const handleRecordingError = async (request) => {pendingSceneIndex: [],};+ clearInMemoryEditorLock();await chrome.storage.local.set({recording: false,// Clear pendingRecording at stop. countdownEverShown is per-tabdiff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.jsindex 8804006..7a415f1 100644--- a/src/pages/Background/recording/stopRecording.js+++ b/src/pages/Background/recording/stopRecording.js@@ -52,56 +52,51 @@ const markEditorStartFailed = async (tabId, errorCode, why) => {} catch {}};-// Bound lock acquisition: storage.get + storage.set both block on-// contended IPC and can stall multi-second on many-tab Chrome. The-// lock suppresses duplicate stops racing with editor-open; under-// contention fail-open beats making the user wait. Worst case on-// fail-open is one extra editor tab.+// In-memory dedup so a second caller in the same SW instance bails+// synchronously; storage.local.set can stall multi-second under contention+// and used to let a duplicate editor tab open. Storage stays as SW-restart backstop.+let _inMemoryEditorLockHeld = false;++export const clearInMemoryEditorLock = () => {+ _inMemoryEditorLockHeld = false;+};+const LOCK_ACQUIRE_TIMEOUT_MS = 500;const acquirePostStopEditorLock = async (recordingId = null) => {- const timeoutSentinel = Symbol("acquire-lock-timeout");+ if (_inMemoryEditorLockHeld) return false;+ _inMemoryEditorLockHeld = true;++ // Mirror to storage for SW-restart durability, with a 500ms timeout ++ // fire-and-forget so a stalled IPC doesn't delay tabs.create.+ const writePayload = {+ postStopEditorOpening: true,+ postStopEditorOpened: true,+ postStopRecordingId: recordingId,+ };let timer = null;- const timeoutPromise = new Promise((resolve) => {- timer = setTimeout(() => resolve(timeoutSentinel), LOCK_ACQUIRE_TIMEOUT_MS);- });try {- const result = await Promise.race([- (async () => {- const { postStopEditorOpening } = await chrome.storage.local.get([- "postStopEditorOpening",- ]);- if (postStopEditorOpening) return false;- await chrome.storage.local.set({- postStopEditorOpening: true,- postStopEditorOpened: true,- postStopRecordingId: recordingId,- });- return true;- })(),- timeoutPromise,+ await Promise.race([+ chrome.storage.local.set(writePayload),+ new Promise((_resolve, reject) => {+ timer = setTimeout(+ () => reject(new Error("acquire-lock-timeout")),+ LOCK_ACQUIRE_TIMEOUT_MS,+ );+ }),]);- if (result === timeoutSentinel) {- console.warn(- "[Screenity][BG] acquirePostStopEditorLock timed out; failing open",- );- // Fire-and-forget the writes so the next stop sees the lock- // (without us blocking on it).- chrome.storage.local- .set({- postStopEditorOpening: true,- postStopEditorOpened: true,- postStopRecordingId: recordingId,- })- .catch(() => {});- return true;- }- return result;+ } catch {+ console.warn(+ "[Screenity][BG] acquirePostStopEditorLock storage mirror timed out; in-memory lock holds",+ );+ chrome.storage.local.set(writePayload).catch(() => {});} finally {if (timer) clearTimeout(timer);}+ return true;};const releasePostStopEditorLock = async (overrides = {}) => {+ _inMemoryEditorLockHeld = false;// keep postStopEditorOpened=true so later stopRecording() can detect the duplicateawait chrome.storage.local.set({postStopEditorOpening: false,@@ -238,7 +233,11 @@ export const stopRecording = async () => {chrome.alarms.clear("recording-alarm");discardOffscreenDocuments();chrome.storage.local.remove(["recordingMeta"]);- } else if (postStopEditorOpening || postStopEditorOpened) {+ } else if (+ _inMemoryEditorLockHeld ||+ postStopEditorOpening ||+ postStopEditorOpened+ ) {// editor already opened by stop-recording-tab flow; avoid duplicate} else if (hasWebCodecs) {diagEvent("editor-open", { type: "editorwebcodecs" });diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex 7224cb8..5791d1a 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -11,6 +11,10 @@ import { createVideoProject } from "./createVideoProject";import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";import { shouldAcquireMicAtStart } from "../utils/micAcquisitionPolicy";import { attachAudioContextWatchdog } from "../utils/audioContextWatchdog";+import {+ startTabKeepalive,+ stopTabKeepalive,+} from "../utils/tabKeepalive";import { traceStep } from "../utils/startFlowTrace";import { IS_OFFSCREEN_HOST } from "../utils/recordingHost";import { startPrewarm, stopPrewarm } from "../Recorder/streamWarmup";@@ -306,10 +310,9 @@ const CloudRecorder = () => {const destination = useRef(null);const keepAliveInterval = useRef(null);- const keepAliveAudioCtx = useRef(null);- const keepAliveOscillator = useRef(null);- const keepAliveLockAbort = useRef(null);- const keepAliveMediaSessionActive = useRef(false);+ // Single handle covering audio osc, navigator.locks, mediaSession,+ // and the loopback RTC priority boost (see utils/tabKeepalive.js).+ const keepAliveHandle = useRef(null);const logDebugEvent = async () => {};@@ -1020,61 +1023,11 @@ const CloudRecorder = () => {const startTabKeepAlive = () => {if (IS_OFFSCREEN_HOST) return;- try {- if (!keepAliveAudioCtx.current) {- const ctx = new (window.AudioContext || window.webkitAudioContext)();- keepAliveAudioCtx.current = ctx;- const oscillator = ctx.createOscillator();- const gainNode = ctx.createGain();- oscillator.type = "sine";- oscillator.frequency.value = 20000;- gainNode.gain.value = 0.0001;- oscillator.connect(gainNode);- gainNode.connect(ctx.destination);- oscillator.start();- keepAliveOscillator.current = oscillator;- }- // AudioContext starts suspended without a user gesture; without- // resume() the oscillator emits nothing and Chrome throttles- // the tab (camera + screen drop to ~5fps for the first 15s).- const aCtx = keepAliveAudioCtx.current;- if (aCtx && aCtx.state !== "running" && typeof aCtx.resume === "function") {- aCtx.resume().catch(() => {});- }- } catch (err) {- console.warn("[CloudRecorder] keepalive: audio layer failed:", err);- }-- try {- if (typeof navigator.locks !== "undefined" && !keepAliveLockAbort.current) {- const ac = new AbortController();- keepAliveLockAbort.current = ac;- navigator.locks- .request(- "screenity-recorder-keepalive",- { mode: "exclusive", signal: ac.signal },- () => new Promise(() => {}),- )- .catch(() => {});- }- } catch (err) {- console.warn("[CloudRecorder] keepalive: lock layer failed:", err);- }-- try {- if (navigator.mediaSession && !keepAliveMediaSessionActive.current) {- navigator.mediaSession.metadata = new window.MediaMetadata({- title: "Screenity recording",- artist: "Screenity",- });- navigator.mediaSession.playbackState = "playing";- try {- navigator.mediaSession.setActionHandler("pause", () => {});- } catch {}- keepAliveMediaSessionActive.current = true;- }- } catch (err) {- console.warn("[CloudRecorder] keepalive: mediaSession layer failed:", err);+ // The pinned cloudrecorder tab isn't visible while recording the source+ // tab, so without keepalive the renderer backgrounds and the encode loop+ // lags into VFR. Layers live in utils/tabKeepalive.js.+ if (!keepAliveHandle.current) {+ keepAliveHandle.current = startTabKeepalive();}chrome.runtime.sendMessage({@@ -1088,24 +1041,9 @@ const CloudRecorder = () => {const stopTabKeepAlive = () => {try {- if (keepAliveOscillator.current) {- try { keepAliveOscillator.current.stop(); } catch {}- try { keepAliveOscillator.current.disconnect(); } catch {}- keepAliveOscillator.current = null;- }- if (keepAliveAudioCtx.current) {- try { keepAliveAudioCtx.current.close(); } catch {}- keepAliveAudioCtx.current = null;- }- if (keepAliveLockAbort.current) {- try { keepAliveLockAbort.current.abort(); } catch {}- keepAliveLockAbort.current = null;- }- if (keepAliveMediaSessionActive.current && navigator.mediaSession) {- try { navigator.mediaSession.playbackState = "none"; } catch {}- try { navigator.mediaSession.metadata = null; } catch {}- try { navigator.mediaSession.setActionHandler("pause", null); } catch {}- keepAliveMediaSessionActive.current = false;+ if (keepAliveHandle.current) {+ stopTabKeepalive(keepAliveHandle.current);+ keepAliveHandle.current = null;}chrome.runtime.sendMessage({diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.jsindex 4811fc4..52ee83c 100644--- a/src/pages/CloudRecorder/bunnyTusUploader.js+++ b/src/pages/CloudRecorder/bunnyTusUploader.js@@ -810,7 +810,24 @@ export default class BunnyTusUploader {if (!transient) break;}- if (!res || !res.ok) throw new Error("Failed to create Bunny video");+ if (!res || !res.ok) {+ // PROBE: persist failure shape so post-mortem can see what+ // came back. Removed once Playwright mock race is identified.+ try {+ await chrome.storage.local.set({+ probeBunnyCreateFail: {+ ts: Date.now(),+ resPresent: !!res,+ status: res?.status ?? null,+ type: res?.type ?? null,+ url: res?.url ?? null,+ redirected: res?.redirected ?? null,+ ok: res?.ok ?? null,+ },+ });+ } catch {}+ throw new Error("Failed to create Bunny video");+ }const data = await res.json();this.videoId = data.videoId;this.mediaId = data.mediaId;diff --git a/src/pages/CloudRecorder/encoder/chooseEncoder.js b/src/pages/CloudRecorder/encoder/chooseEncoder.jsindex 4a25c1a..632fe01 100644--- a/src/pages/CloudRecorder/encoder/chooseEncoder.js+++ b/src/pages/CloudRecorder/encoder/chooseEncoder.js@@ -171,12 +171,22 @@ export const chooseTrackEncoder = async ({// WebCodecs path. The MP4 mime type is always video/mp4, regardless of// whether audio is included (AAC fits inside MP4 alongside H.264).+ // forceSoftwareEncoder storage flag biases the encoder candidate list+ // toward prefer-software. Playwright Chromium 1217 hits a documented+ // "encode() accepts, no chunks emit" HW silent-fail (see Windows MFT+ // note in WebCodecsRecorder.js:chooseVideoEncoderConfig) on macOS+ // auto-select-desktop-capture streams; SW H.264 encodes them cleanly.+ let forceSoftware = false;+ try {+ const s = await chrome.storage.local.get(["forceSoftwareEncoder"]);+ forceSoftware = Boolean(s.forceSoftwareEncoder);+ } catch {}const recorder = new WebCodecsTrackRecorder(stream, {mimeType: "video/mp4",videoBitsPerSecond,audioBitsPerSecond,enableAudio,- preferSoftware: Boolean(plan.cameraPreferSoftware),+ preferSoftware: forceSoftware || Boolean(plan.cameraPreferSoftware),trackKind: track,});recorder.ondataavailable = (event) => {diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex f23a7c5..fb1f54c 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -2092,6 +2092,23 @@ const Recorder = () => {typeof err?.code === "string" && err.code? err.code: "webcodecs-error";+ // Late teardown error fired after video-ready already shipped:+ // the recording is finalized on disk and the sandbox is mid+ // OPFS read. Surfacing as recording-error races that read and+ // pops a spurious "Can't load your recording" modal β and+ // would flip the sticky-disable on a recording that succeeded.+ // Log a breadcrumb and drop. (err.finalized handles the salvage+ // path below; this handles the normal-finalize path.)+ if (sentLast.current && !err?.finalized) {+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "recorder-webcodecs-post-finalize-error",+ data: { code: failureCode, err: errStr.slice(0, 200) },+ })+ .catch(() => {});+ return;+ }// Shared with markFastRecorderFailure so the sticky-disable// and the user-setting flip use the same heuristic.const transient = isFastRecorderFailureTransient(diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsxindex 327f02c..312e0ce 100644--- a/src/pages/Region/Recorder.jsx+++ b/src/pages/Region/Recorder.jsx@@ -2,6 +2,10 @@ import React, { useEffect, useRef, useCallback } from "react";import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";import { shouldAcquireMicAtStart } from "../utils/micAcquisitionPolicy";import { attachAudioContextWatchdog } from "../utils/audioContextWatchdog";+import {+ startTabKeepalive,+ stopTabKeepalive,+} from "../utils/tabKeepalive";import {WebCodecsRecorder,preloadWebCodecsModules,@@ -19,7 +23,7 @@ import {getFastRecorderStickyState,markFastRecorderFailure,validateFastRecorderOutputBlob,- isTransientFastRecorderError,+ isFastRecorderFailureTransient,} from "../../media/fastRecorderGate";import { chooseWriter } from "../Recorder/recorderStorage/chooseWriter";import { chooseReader } from "../Recorder/recorderStorage/chooseReader";@@ -121,6 +125,10 @@ const Recorder = () => {const pausedStateRef = useRef(false);const recordingStartTimeRef = useRef(null);const recordingTick = useRef(null);+ // Keeps the host renderer at foreground priority so a tab switch /+ // minimize mid-recording doesn't throttle the encode loop into VFR.+ // See utils/tabKeepalive.js.+ const keepAliveHandle = useRef(null);const liveStream = useRef(null);const prewarmRef = useRef(null);@@ -144,6 +152,12 @@ const Recorder = () => {const recorder = useRef(null);const useWebCodecs = useRef(false);const recdbgSessionRef = useRef(null);+ // MR mid-stream stall watchdog. crbug/343157156: MediaRecorder can silently+ // stop firing ondataavailable mid-recording with no error/stop event.+ // CloudRecorder has the same watchdog; mirror here for the Region MR path.+ const mrLastChunkAt = useRef(0);+ const mrStallTimer = useRef(null);+ const mrStallNotified = useRef(false);const target = useRef(null);@@ -470,6 +484,16 @@ const Recorder = () => {code: err?.code || null,});// OPFS writer death preserves the partial file; quota fail uses a generic toast.+ // Match Recorder.jsx's wider classification: chunk-store backends may+ // surface quota errors as QuotaExceededError or with "quota"/"disk"+ // in the message instead of (or in addition to) the opfs-writer-failed+ // code. Previously these fell through to a generic toast.+ const errName = err?.name || "";+ const errMsg = String(err?.message || err);+ const isQuota =+ errName === "QuotaExceededError" ||+ /quota/i.test(errMsg) ||+ /disk/i.test(errMsg);const isOpfsWriterDead = err?.code === "opfs-writer-failed";if (isOpfsWriterDead && err?.fileName) {chunkBackendRef.current = {@@ -485,7 +509,9 @@ const Recorder = () => {if (!lowStorageAbort.current) {const toastMessage = isOpfsWriterDead? chrome.i18n.getMessage("recordingWriterFailedToast")- : chrome.i18n.getMessage("toastStorageCritical");+ : isQuota+ ? chrome.i18n.getMessage("toastStorageCritical")+ : chrome.i18n.getMessage("toastStorageCritical");chrome.runtime.sendMessage({type: "show-toast",message: toastMessage,@@ -495,7 +521,8 @@ const Recorder = () => {lifecycle("Region.Recorder", "memory-error-flag-set", {reason: "saveChunk-write-failed",isOpfsWriterDead,- err: String(err?.message || err).slice(0, 120),+ isQuota,+ err: errMsg.slice(0, 120),savedCount: savedCount.current,});lowStorageAbort.current = true;@@ -506,7 +533,11 @@ const Recorder = () => {memoryError: true,});sendStopWithReason(- isOpfsWriterDead ? "opfs-writer-failed" : "region-save-chunk-failed",+ isOpfsWriterDead+ ? "opfs-writer-failed"+ : isQuota+ ? "region-quota-exceeded"+ : "region-save-chunk-failed",);window.location.reload();return false;@@ -700,6 +731,27 @@ const Recorder = () => {}persistRegionStartDebug({ stage: "start-recording-enter" });+ if (!keepAliveHandle.current) {+ try {+ keepAliveHandle.current = startTabKeepalive();+ } catch (err) {+ console.warn("[Region.Recorder] tab keepalive failed:", err);+ }+ }++ // BG-coordinated guards: matches what Recorder.jsx + CloudRecorder do.+ // β’ auto-discardable=false β Chrome won't reclaim the host tab+ // (and the iframe with it) under memory pressure mid-record.+ // β’ start-first-chunk-watchdog β 8s BG alarm fires recording-error+ // if no chunks ever land (encoder hang / silent capture freeze).+ // Cancelled on first chunk in handleWebCodecsChunk + saveChunk.+ chrome.runtime+ .sendMessage({ type: "set-tab-auto-discardable", discardable: false })+ .catch(() => {});+ chrome.runtime+ .sendMessage({ type: "start-first-chunk-watchdog" })+ .catch(() => {});+await stopPrewarm(prewarmRef.current);prewarmRef.current = null;@@ -998,6 +1050,14 @@ const Recorder = () => {const handleWebCodecsChunk = async (blob, timestampUs) => {if (lowStorageAbort.current) return;+ // First chunk landed β cancel the BG watchdog so it doesn't fire+ // a spurious recording-error. hasChunks is set later in saveChunk+ // for the MR path; we set it here for WebCodecs.+ if (!hasChunks.current) {+ chrome.runtime+ .sendMessage({ type: "cancel-first-chunk-watchdog" })+ .catch(() => {});+ }const timecodeMs = timestampUs ? Math.floor(timestampUs / 1000) : 0;recdbgChunkCount += 1;recdbgTotalBytes += blob.size || 0;@@ -1210,13 +1270,25 @@ const Recorder = () => {},onError: (err) => {const errStr = String(err);- const transient = isTransientFastRecorderError(errStr);// err.finalized: salvage stop already ran, skip sticky-disable.const fatalFinalized = err?.finalized === true;- markFastRecorderFailure(- fatalFinalized ? "webcodecs-finalized" : "webcodecs-error",- { error: errStr, finalized: fatalFinalized || undefined },+ const failureCode = fatalFinalized+ ? "webcodecs-finalized"+ : "webcodecs-error";+ // Use the 3-arg classifier: it adds the+ // `webcodecs-zero-frames-at-stop + firstChunkSeen=false`+ // heuristic that the 1-arg form misses, so we don't sticky-+ // disable WebCodecs for benign stream-cancel hiccups the+ // desktop path already treats as transient.+ const transient = isFastRecorderFailureTransient(+ failureCode,+ errStr,+ err?.detail,);+ markFastRecorderFailure(failureCode, {+ error: errStr,+ finalized: fatalFinalized || undefined,+ });// Keep useWebCodecsRecorder on for transient stream errors.const persisted = {lastWebCodecsFailureAt: Date.now(),@@ -1578,6 +1650,8 @@ const Recorder = () => {recdbgChunkCount += 1;recdbgTotalBytes += e.data.size || 0;+ mrLastChunkAt.current = Date.now();+ mrStallNotified.current = false;const elapsedSec = Math.max(0.001,(Date.now() - mediaRecorderStartAt) / 1000,@@ -1649,6 +1723,9 @@ const Recorder = () => {}if (!hasChunks.current) {+ chrome.runtime+ .sendMessage({ type: "cancel-first-chunk-watchdog" })+ .catch(() => {});hasChunks.current = true;lastTimecode.current = e.timecode ?? 0;lastSize.current = e.data.size;@@ -1748,6 +1825,28 @@ const Recorder = () => {setTimeout(() => {try { recorder.current?.requestData?.(); } catch (_) {}}, 250);+ mrLastChunkAt.current = Date.now();+ mrStallNotified.current = false;+ if (mrStallTimer.current) clearInterval(mrStallTimer.current);+ mrStallTimer.current = setInterval(() => {+ if (!recorder.current || recorder.current.state !== "recording") return;+ if (pausedStateRef.current) return;+ if (mrStallNotified.current) return;+ if (!mrLastChunkAt.current) return;+ if (Date.now() - mrLastChunkAt.current <= 15000) return;+ mrStallNotified.current = true;+ lifecycle("Region.Recorder", "mr-chunk-stall", {+ sinceLastChunkMs: Date.now() - mrLastChunkAt.current,+ recorderState: recorder.current?.state || null,+ });+ chrome.runtime+ .sendMessage({+ type: "recording-error",+ error: "stream-warning",+ why: "No video data received for 15 seconds. Recording may be stalled.",+ })+ .catch(() => {});+ }, 5000);} catch (err) {persistRegionStartDebug({stage: "mediarecorder-start-throw",@@ -1901,6 +2000,21 @@ const Recorder = () => {async function stopRecording() {clearStartRetry();stopRecordingTick();+ if (keepAliveHandle.current) {+ stopTabKeepalive(keepAliveHandle.current);+ keepAliveHandle.current = null;+ }+ // Release BG guards armed in startRecording.+ chrome.runtime+ .sendMessage({ type: "set-tab-auto-discardable", discardable: true })+ .catch(() => {});+ chrome.runtime+ .sendMessage({ type: "cancel-first-chunk-watchdog" })+ .catch(() => {});+ if (mrStallTimer.current) {+ clearInterval(mrStallTimer.current);+ mrStallTimer.current = null;+ }recordingStartTimeRef.current = null;isFinishing.current = true;regionRef.current = false;@@ -2012,6 +2126,23 @@ const Recorder = () => {const dismissRecording = async () => {clearStartRetry();stopRecordingTick();+ // Match stopRecording teardown: tab keepalive + BG guards must be+ // released here too. Previously dismiss left them running until the+ // iframe unloaded (or reloaded), leaking the loopback PC + osc + lock.+ if (keepAliveHandle.current) {+ stopTabKeepalive(keepAliveHandle.current);+ keepAliveHandle.current = null;+ }+ chrome.runtime+ .sendMessage({ type: "set-tab-auto-discardable", discardable: true })+ .catch(() => {});+ chrome.runtime+ .sendMessage({ type: "cancel-first-chunk-watchdog" })+ .catch(() => {});+ if (mrStallTimer.current) {+ clearInterval(mrStallTimer.current);+ mrStallTimer.current = null;+ }recordingStartTimeRef.current = null;regionRef.current = false;target.current = null;diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsxindex 990d698..1726633 100644--- a/src/pages/Sandbox/context/ContentState.jsx+++ b/src/pages/Sandbox/context/ContentState.jsx@@ -233,6 +233,11 @@ const ContentState = (props) => {const diagMakeVideoAtRef = useRef(null);const editorReadyDiagSentRef = useRef(false);const editorErrorShownRef = useRef(false);+ // True while makeVideoTab is mid-OPFS read. Late recording-error from+ // a post-finalize WCR teardown can race the read and pop the+ // "Can't load your recording" modal; suppress in-flight, and let the+ // read result decide (a real failure surfaces via OPFS_LOAD_FAILED).+ const opfsReadInFlightRef = useRef(false);const diagHeartbeatCountRef = useRef(0);const setContentState = useCallback((updater) => {@@ -1214,6 +1219,7 @@ const ContentState = (props) => {});const readBlobStart = Date.now();diagForward("sandbox-opfs-readblob-start", { attempt });+ opfsReadInFlightRef.current = true;const { blob: rawBlob } = await reader.readBlob({// OPFS file isn't ready yet, recorder still flushing under load.// Surface a labeled loading state so the user knows it's progressing.@@ -1226,6 +1232,7 @@ const ContentState = (props) => {);},});+ opfsReadInFlightRef.current = false;diagForward("sandbox-opfs-readblob-done", {elapsedMs: Date.now() - readBlobStart,rawBlobBytes: rawBlob?.size ?? 0,@@ -1279,6 +1286,7 @@ const ContentState = (props) => {}break;} catch (err) {+ opfsReadInFlightRef.current = false;diagForward("sandbox-opfs-direct-read-fail", {attempt,err: String(err?.message || err).slice(0, 200),@@ -1490,6 +1498,17 @@ const ContentState = (props) => {Boolean(contentStateRef.current?.ready) ||Boolean(contentStateRef.current?.blob);if (editorAlreadyLoaded) return;+ // OPFS read in flight: a post-finalize teardown error (e.g. late+ // WCR failure) can land between readblob-start and -done. Drop it+ // here; if the read truly fails, the OPFS_LOAD_FAILED path below+ // surfaces the same modal with the real cause.+ if (opfsReadInFlightRef.current) {+ diagForward("sandbox-recording-error-suppressed-mid-read", {+ error: String(message?.error || "").slice(0, 120),+ errorCode: message?.errorCode || null,+ });+ return;+ }diagForward("sandbox-recording-error-received", {error: String(message?.error || "").slice(0, 120),why: String(message?.why || "").slice(0, 240),@@ -1835,6 +1854,17 @@ const ContentState = (props) => {payload?.sandboxTab == null ||payload.sandboxTab === tabId)) {+ // Same in-flight-read suppression as the runtime listener+ // above: late post-finalize teardown errors arrive via the+ // editorRecordingError storage fallback too.+ if (opfsReadInFlightRef.current) {+ diagForward("sandbox-recording-error-suppressed-mid-read", {+ error: String(payload?.error || "").slice(0, 120),+ errorCode: payload?.errorCode || null,+ source: "storage",+ });+ return;+ }diagForward("sandbox-recording-error-received", {error: String(payload?.error || "").slice(0, 120),why: String(payload?.why || "").slice(0, 240),diff --git a/src/pages/utils/tabKeepalive.js b/src/pages/utils/tabKeepalive.jsnew file mode 100644index 0000000..8f907fa--- /dev/null+++ b/src/pages/utils/tabKeepalive.js@@ -0,0 +1,180 @@+// Keep a recorder tab/iframe at foreground renderer priority for the+// duration of a recording, so Chrome doesn't throttle the wall-clock-+// driven encode loop and produce VFR output. Four layers, ordered by+// strength of signal to Chrome's renderer scheduler:+//+// 1. Loopback RTCPeerConnection w/ a live captureStream track+// β marks the renderer "in a call", strongest priority signal.+// 2. Silent ultrasonic AudioContext oscillator+// β counts as "playing audio".+// 3. navigator.locks exclusive lock+// β signals "doing work".+// 4. mediaSession metadata + playbackState:"playing"+// β third-party signal that something is in progress.+//+// All four are idempotent and best-effort. Callers receive a handle to+// pass back to `stopTabKeepalive`. Recorder.jsx uses a separate IIFE+// (recorderKeepalive.js) for its own historical reasons; this helper+// covers the CloudRecorder + Region iframe paths.++const startLoopbackPriorityBoost = (state) => {+ if (typeof RTCPeerConnection !== "function") return;+ try {+ const canvas = document.createElement("canvas");+ canvas.width = 2;+ canvas.height = 2;+ const ctx = canvas.getContext("2d");+ if (ctx) ctx.fillRect(0, 0, 2, 2);++ const stream = canvas.captureStream ? canvas.captureStream(0) : null;+ const track = stream ? stream.getVideoTracks()[0] : null;+ if (!track) return;++ const pc1 = new RTCPeerConnection();+ const pc2 = new RTCPeerConnection();+ pc1.onicecandidate = (e) => {+ if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {});+ };+ pc2.onicecandidate = (e) => {+ if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {});+ };+ pc1.addTrack(track, stream);+ pc1+ .createOffer()+ .then((offer) =>+ pc1.setLocalDescription(offer).then(() => pc2.setRemoteDescription(offer)),+ )+ .then(() => pc2.createAnswer())+ .then((answer) =>+ pc2.setLocalDescription(answer).then(() => pc1.setRemoteDescription(answer)),+ )+ .catch(() => {});++ // Periodic redraw + requestFrame keeps the captureStream track from+ // being marked ended after the first frame is consumed.+ const tick = setInterval(() => {+ try {+ if (ctx) {+ ctx.fillStyle = ctx.fillStyle === "#000" ? "#001" : "#000";+ ctx.fillRect(0, 0, 2, 2);+ }+ if (stream && typeof stream.getVideoTracks === "function") {+ const t = stream.getVideoTracks()[0];+ if (t && typeof t.requestFrame === "function") t.requestFrame();+ }+ } catch {}+ }, 2000);++ state.pcTick = tick;+ state.pcTrack = track;+ state.pc1 = pc1;+ state.pc2 = pc2;+ } catch {}+};++const startAudioOscillator = (state) => {+ try {+ const Ctx =+ typeof window !== "undefined"+ ? window.AudioContext || window.webkitAudioContext+ : null;+ if (!Ctx) return;+ const ctx = new Ctx();+ const osc = ctx.createOscillator();+ const gain = ctx.createGain();+ osc.type = "sine";+ // Ultrasonic, near-silent. Chrome still counts it as "playing audio".+ osc.frequency.value = 20000;+ gain.gain.value = 0.0001;+ osc.connect(gain);+ gain.connect(ctx.destination);+ osc.start();+ // AudioContext starts suspended without a user gesture; without+ // resume() the oscillator emits nothing and the keepalive doesn't+ // register.+ if (ctx.state !== "running" && typeof ctx.resume === "function") {+ ctx.resume().catch(() => {});+ }+ state.audioCtx = ctx;+ state.oscillator = osc;+ } catch {}+};++const startLock = (state) => {+ try {+ if (typeof navigator === "undefined" || !navigator.locks) return;+ const ac = new AbortController();+ state.lockAbort = ac;+ navigator.locks+ .request(+ "screenity-recorder-keepalive",+ { mode: "exclusive", signal: ac.signal },+ () => new Promise(() => {}),+ )+ .catch(() => {});+ } catch {}+};++const startMediaSession = (state) => {+ try {+ if (typeof navigator === "undefined" || !navigator.mediaSession) return;+ if (typeof window.MediaMetadata === "function") {+ navigator.mediaSession.metadata = new window.MediaMetadata({+ title: "Screenity recording",+ artist: "Screenity",+ });+ }+ navigator.mediaSession.playbackState = "playing";+ try {+ navigator.mediaSession.setActionHandler("pause", () => {});+ } catch {}+ state.mediaSessionActive = true;+ } catch {}+};++export const startTabKeepalive = () => {+ if (typeof window === "undefined") return null;+ const state = {};+ startLoopbackPriorityBoost(state);+ startAudioOscillator(state);+ startLock(state);+ startMediaSession(state);+ return state;+};++export const stopTabKeepalive = (handle) => {+ if (!handle) return;+ try {+ if (handle.pcTick) clearInterval(handle.pcTick);+ } catch {}+ try {+ if (handle.pcTrack) handle.pcTrack.stop();+ } catch {}+ try {+ if (handle.pc1) handle.pc1.close();+ } catch {}+ try {+ if (handle.pc2) handle.pc2.close();+ } catch {}+ try {+ if (handle.oscillator) {+ try { handle.oscillator.stop(); } catch {}+ try { handle.oscillator.disconnect(); } catch {}+ }+ } catch {}+ try {+ if (handle.audioCtx) handle.audioCtx.close();+ } catch {}+ try {+ if (handle.lockAbort) handle.lockAbort.abort();+ } catch {}+ try {+ if (handle.mediaSessionActive && navigator.mediaSession) {+ navigator.mediaSession.playbackState = "none";+ navigator.mediaSession.metadata = null;+ try {+ navigator.mediaSession.setActionHandler("pause", null);+ } catch {}+ }+ } catch {}+};