The free and privacy-friendly screen recorder with no limits π₯
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Recorder reliability, camera, upload, and onboarding fixes
Alyssa X155e794b8107
diff --git a/package.json b/package.jsonindex 6d876f9..9fd5316 100755--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "screenity",- "version": "4.4.5",+ "version": "4.4.7","description": "The free and privacy-friendly screen recorder with no sign in needed.","scripts": {"build": "cross-env NODE_ENV=development node utils/build.js",diff --git a/src/manifest.json b/src/manifest.jsonindex 1e8d600..9da944e 100755--- a/src/manifest.json+++ b/src/manifest.json@@ -3,7 +3,7 @@"name": "__MSG_extName__","description": "__MSG_extDesc__","default_locale": "en",- "version": "4.4.5",+ "version": "4.4.7","background": {"service_worker": "background.bundle.js"},diff --git a/src/pages/Background/alarms/handleAlarm.js b/src/pages/Background/alarms/handleAlarm.jsindex a907536..3c116a4 100644--- a/src/pages/Background/alarms/handleAlarm.js+++ b/src/pages/Background/alarms/handleAlarm.js@@ -2,6 +2,7 @@ import { stopRecording } from "../recording/stopRecording.js";import { sendMessageTab } from "../tabManagement";import { sendMessageRecord } from "../recording/sendMessageRecord.js";import { handleRecordingError } from "../recording/recordingHelpers.js";+import { sweepRecorderTabs } from "../recording/sweepRecorderTabs.js";import { diagEvent } from "../../utils/diagnosticLog";import { lifecycle } from "../../utils/lifecycleLog";import { chunksStore } from "../recording/chunkHandler";@@ -103,6 +104,21 @@ export const handleAlarm = async (alarm) => {firstChunkAt: null,lastChunkAt: null,});+ // Backstop: the session is over. Remove any recorder tab still+ // alive β a final guard if both the recorder's own abandonment+ // listener and the teardown sweep somehow missed it. Gated on no+ // active or in-flight recording so a fresh start is never killed.+ if (!snap.recording && !snap.pendingRecording) {+ const { recordingStartingAt } = await chrome.storage.local.get([+ "recordingStartingAt",+ ]);+ const startInFlight =+ typeof recordingStartingAt === "number" &&+ Date.now() - recordingStartingAt < 30_000;+ if (!startInFlight) {+ await sweepRecorderTabs();+ }+ }return;}diff --git a/src/pages/Background/recording/discardRecording.js b/src/pages/Background/recording/discardRecording.jsindex 1af1e4e..9500fe3 100644--- a/src/pages/Background/recording/discardRecording.js+++ b/src/pages/Background/recording/discardRecording.js@@ -3,8 +3,30 @@ import { removeTab } from "../tabManagement/removeTab";import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";import { resetWatchdogState } from "./resetWatchdogState";-export const discardRecording = async () => {- sendMessageRecord({ type: "dismiss-recording" });+export const discardRecording = async ({+ reason = "discard",+ projectId = null,+} = {}) => {+ // Back-to-back cross-talk guard: a discard issued for a previous recording+ // must not tear down the BG state of a newer one. If this discard provably+ // targets a different project than the one currently recording, skip it.+ // Unknown projectId (legacy callers / pre-project dismiss) is honored.+ if (projectId) {+ try {+ const { projectId: currentProjectId } = await chrome.storage.local.get([+ "projectId",+ ]);+ if (currentProjectId && currentProjectId !== projectId) {+ console.warn(+ "[Screenity][BG] discardRecording skipped: project mismatch",+ { reason, target: projectId, current: currentProjectId },+ );+ return;+ }+ } catch {}+ }++ sendMessageRecord({ type: "dismiss-recording", reason, projectId });chrome.action.setIcon({ path: "assets/icon-34.png" });// await teardown before recording:false; otherwise handleAlarm fires against torn-down offscreen@@ -69,7 +91,10 @@ export const discardRecording = async () => {chrome.runtime.sendMessage({ type: "turn-off-pip" });};-export const handleDismissRecordingTab = async () => {+export const handleDismissRecordingTab = async (message = {}) => {chrome.runtime.sendMessage({ type: "discard-backup" });- discardRecording();+ discardRecording({+ reason: message?.reason || "dismiss-recording-tab",+ projectId: message?.projectId || null,+ });};diff --git a/src/pages/Background/recording/openRecorderTab.js b/src/pages/Background/recording/openRecorderTab.jsindex 83b29cc..3c3dacd 100644--- a/src/pages/Background/recording/openRecorderTab.js+++ b/src/pages/Background/recording/openRecorderTab.js@@ -6,6 +6,7 @@ import { loginWithWebsite } from "../auth/loginWithWebsite.js";import { traceStep } from "../../utils/startFlowTrace.js";import { handleGetStreamingData } from "./recordingHelpers.js";import { perfMark, perfSpan } from "../../utils/perfMarks";+import { sweepRecorderTabs } from "./sweepRecorderTabs";const openRecorderTab = async (activeTab,@@ -130,6 +131,11 @@ const openRecorderTab = async (...(isRegion ? { tabRecordedID: activeTab.id } : {}),});+ // Remove any earlier recorder tab the prevRecTab check above could not+ // see (a second tab from a countdown/fallback race). Spare the tab we+ // just created.+ await sweepRecorderTabs({ exceptTabId: tab.id });+// under memory pressure the set can succeed silently while the property stays true;// verify via tabs.get roundtrip and retry with backofflet autoDiscardableApplied = false;@@ -182,7 +188,12 @@ const openRecorderTab = async (chrome.runtime.getURL("playground.html"));perfMark("BG.openRecorderTab loaded.sent");- sendMessageRecord({+ // `loaded` is sent at status:complete, before the recorder's React+ // app has mounted its message listener, so the first send is+ // routinely lost. It carries isTab/tabID for region recordings, so+ // retry until the recorder is listening. (streaming-data no longer+ // depends on `loaded` β the recorder pulls it on mount.)+ const loadedMsg = {type: "loaded",request: request,backup: backup,@@ -193,8 +204,23 @@ const openRecorderTab = async (tabID: activeTab.id,}: {}),- });- // push streaming-data; tab also pulls but pull can drop on cold-SW/late-mount+ };+ (async () => {+ const backoffMs = [0, 200, 500, 1000, 2000];+ for (let attempt = 0; attempt < backoffMs.length; attempt += 1) {+ if (backoffMs[attempt] > 0) {+ await new Promise((r) => setTimeout(r, backoffMs[attempt]));+ }+ try {+ await sendMessageRecord(loadedMsg);+ return;+ } catch {+ // recorder tab not ready yet; retry+ }+ }+ })();+ // Belt-and-suspenders push; the recorder's own pull is the primary+ // path now.setTimeout(() => {handleGetStreamingData().catch(() => {});}, 300);diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.jsindex 9863839..e6abc92 100644--- a/src/pages/Background/recording/recordingHelpers.js+++ b/src/pages/Background/recording/recordingHelpers.js@@ -13,6 +13,7 @@ import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";import { perfMark, perfSpan } from "../../utils/perfMarks";import { classifyError } from "../../utils/errorCodes";import { resetWatchdogState } from "./resetWatchdogState";+import { sweepRecorderTabs } from "./sweepRecorderTabs";// Mirrors CloudRecorder.appendUploadTelemetryEvent so BG-side projectId mutations// land in the same `cloudUploadTelemetryEvents` storage key surfaced by@@ -302,6 +303,9 @@ export const handleRecordingError = async (request) => {}} catch {}}+ // recordingTab names at most one recorder tab; sweep catches any other+ // recorder tab a racing start may have spawned and orphaned.+ await sweepRecorderTabs();chrome.storage.local.set({ recordingTab: null });try {await discardOffscreenDocuments();@@ -309,44 +313,49 @@ export const handleRecordingError = async (request) => {await resetWatchdogState();};-export const handleGetStreamingData = async () => {- perfMark("BG.handleGetStreamingData.enter");- const data = await getStreamingData();- const payload = { type: "streaming-data", data: JSON.stringify(data) };-- // dropped delivery causes REC_START_NO_STREAM_MSG at the tab's 12s gate;- // tab-side is idempotent so retries are safe+// Push streaming-data to the recorder tab. Used for the SW-initiated+// path (openRecorderTab). Dropped delivery causes REC_START_NO_STREAM_MSG+// at the tab's 12s gate; the tab side is idempotent so retries are safe.+const pushStreamingData = async (dataStr) => {+ const payload = { type: "streaming-data", data: dataStr };const backoffMs = [0, 300, 800];for (let attempt = 0; attempt < backoffMs.length; attempt++) {if (backoffMs[attempt] > 0) {await new Promise((r) => setTimeout(r, backoffMs[attempt]));}- const endSend = perfSpan("BG.handleGetStreamingData sendMessageRecord", {- attempt,- });try {await sendMessageRecord(payload);- endSend({ ok: true });if (attempt > 0) {diagEvent("sw-streaming-data-send-ok", { attempt });}return;} catch (err) {- endSend({ ok: false, err: String(err?.message || err).slice(0, 80) });diagEvent("sw-streaming-data-send-fail", {attempt,err: String(err?.message || err).slice(0, 120),});if (attempt === backoffMs.length - 1) {- console.warn(- "handleGetStreamingData: all delivery attempts failed",- err,- );+ console.warn("handleGetStreamingData: all push attempts failed", err);}}}};+export const handleGetStreamingData = async () => {+ perfMark("BG.handleGetStreamingData.enter");+ const data = await getStreamingData();+ const dataStr = JSON.stringify(data);+ // Fire-and-forget push (SW-initiated openRecorderTab path). Not awaited:+ // a `get-streaming-data` pull must get its response immediately, not+ // after the push retry loop.+ void pushStreamingData(dataStr);+ // Returned to a `get-streaming-data` pull as the direct response. This+ // is the robust delivery path β it does not depend on the recorder+ // tab's onMessage listener being registered yet, nor on `recordingTab`+ // routing being correct.+ return { ok: true, data: dataStr };+};+export const videoReady = async () => {perfMark("BG.recordingHelpers videoReady.enter");const { backupTab, recordingDuration, recordingTab, lastRecordingBackendRef } =diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.jsindex 407b221..8d3b452 100644--- a/src/pages/Background/recording/startRecording.js+++ b/src/pages/Background/recording/startRecording.js@@ -4,6 +4,7 @@ import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocumentimport { initDiagSession, diagEvent } from "../../utils/diagnosticLog";import { makeRecordingAttemptId } from "../../utils/errorCodes";import { lifecycle } from "../../utils/lifecycleLog";+import { sweepRecorderTabs } from "./sweepRecorderTabs";// `recording` flag isn't set until the recorder iframe inits (seconds later),// so countdown-finished + 8s fallback can both fire and open two recorder tabs@@ -161,6 +162,29 @@ const _startRecordingInner = async (caller) => {lastStartRecordingCaller: { caller, stack, ts: Date.now() },});+ // A standalone (non-scene, non-multi) recording must not inherit a sceneId+ // from a previous recording. The cloudrecorder reads chrome.storage sceneId+ // at start; a leaked value tags the new recording's telemetry and upload+ // sessions with the prior recording's identity (the back-to-back sceneId+ // leak). Scene and multi-scene recordings legitimately carry sceneId across+ // the boundary. NOTE: only sceneId/sceneIdStatus are cleared β never+ // pendingSceneIndex: it is an array consumed via a `= []` destructuring+ // default (upsertPendingScene), and a default only covers `undefined`, not+ // `null`. Setting it null makes `pendingSceneIndex.includes()` throw and+ // crashes the next recorder. Its own upsert/remove lifecycle manages it.+ try {+ const { recordingToScene, multiMode } = await chrome.storage.local.get([+ "recordingToScene",+ "multiMode",+ ]);+ if (!recordingToScene && !multiMode) {+ await chrome.storage.local.set({+ sceneId: null,+ sceneIdStatus: null,+ });+ }+ } catch {}+const { activeTab, recordingUiTabId } = await chrome.storage.local.get(["activeTab","recordingUiTabId",@@ -297,6 +321,9 @@ const _startRecordingInner = async (caller) => {});// releases the desktopCapture stream so Chrome's "Stop sharing" bar goes awaydiscardOffscreenDocuments({ reason: "start-fail" }).catch(() => {});+ // a recorder tab may have been created before the start failed;+ // sweep it so it can't keep capturing unattended+ sweepRecorderTabs().catch(() => {});chrome.action.setIcon({ path: "assets/icon-34.png" });}, 2500);});diff --git a/src/pages/Background/recording/sweepRecorderTabs.js b/src/pages/Background/recording/sweepRecorderTabs.jsnew file mode 100644index 0000000..74801b3--- /dev/null+++ b/src/pages/Background/recording/sweepRecorderTabs.js@@ -0,0 +1,38 @@+import { removeTab } from "../tabManagement/removeTab";+import { diagEvent } from "../../utils/diagnosticLog";++// Stop and remove every free recorder tab, optionally sparing one.+//+// The single `recordingTab` storage slot can only ever name one recorder+// tab. When a second one is spawned (countdown-finished racing the+// countdownFallback) or the slot is overwritten by the next attempt, the+// earlier recorder tab becomes both unreachable and unkillable: nothing+// holds its id. Its MediaRecorder then runs until the tab is closed by+// hand. This enumerates recorder tabs by URL so none can hide behind a+// lost handle.+//+// Scope: `recorder.html` only. The Pro `cloudrecorder.html` tab has its+// own lifecycle (recorderSession tracking, self-close on TUS finalize,+// multi-scene handoff) and must not be swept here.+export const sweepRecorderTabs = async ({ exceptTabId = null } = {}) => {+ const removed = [];+ try {+ const recorderUrl = chrome.runtime.getURL("recorder.html");+ const tabs = await chrome.tabs.query({});+ for (const tab of tabs) {+ if (tab.id == null || tab.id === exceptTabId) continue;+ const url = tab.url || tab.pendingUrl || "";+ if (!url.startsWith(recorderUrl)) continue;+ try {+ await removeTab(tab.id);+ removed.push(tab.id);+ } catch {}+ }+ } catch (err) {+ console.warn("[Screenity] sweepRecorderTabs failed", err);+ }+ if (removed.length) {+ diagEvent("recorder-tabs-swept", { removed, exceptTabId });+ }+ return removed;+};diff --git a/src/pages/Camera/utils/cameraUtils.js b/src/pages/Camera/utils/cameraUtils.jsindex 9f8715e..02237d9 100644--- a/src/pages/Camera/utils/cameraUtils.js+++ b/src/pages/Camera/utils/cameraUtils.js@@ -261,13 +261,19 @@ export const getCameraStream = async (// 2. tab+camera with bubble failure mid-recording: stay silent;// propagating a recording-error tears down the live recording.try {- const { recording, pendingRecording } = await chrome.storage.local.get([- "recording",- "pendingRecording",- ]);+ const { recording, pendingRecording, recordingType } =+ await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "recordingType",+ ]);const isPermissionDenial =err?.name === "NotAllowedError" ||err?.name === "PermissionDeniedError";+ // For camera-only recordings the webcam is the recording, so a+ // setup failure is fatal. For screen/tab/region it's just a PIP+ // bubble; its failure must not tear down the recording.+ const isCameraOnlyRecording = recordingType === "camera";// Diag fires regardless of fatality; "clicked record and got nothing"// reports need to distinguish permission denials from device-not-found// and getUserMedia hangs.@@ -280,12 +286,17 @@ export const getCameraStream = async (isPermissionDenial,duringSetup: pendingRecording === true && recording !== true,recordingActive: recording === true,+ cameraOnly: isCameraOnlyRecording,message: String(err?.message || err).slice(0, 200),},});} catch {}- if (pendingRecording === true && recording !== true) {- // Setup-time failure: fatal. BG must clear pendingRecording.+ if (+ isCameraOnlyRecording &&+ pendingRecording === true &&+ recording !== true+ ) {+ // Camera-only setup failure: fatal. BG must clear pendingRecording.chrome.runtime.sendMessage({type: "recording-error",error: isPermissionDenial@@ -293,9 +304,9 @@ export const getCameraStream = async (: "camera-stream-error",why: String(err?.message || err),});- } else if (recording === true) {- // Recording is live: don't tear down for a cosmetic camera issue.- // Surface a non-fatal toast via BG -> recorded tab's content script.+ } else if (recording === true || pendingRecording === true) {+ // Screen/tab/region recording: the webcam is just a PIP bubble.+ // Don't tear down the recording; surface a non-fatal toast.chrome.runtime.sendMessage({type: "camera-bubble-unavailable",error: isPermissionDenialdiff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex 368f361..bb1cba6 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -2551,9 +2551,9 @@ const CloudRecorder = () => {);await Promise.allSettled([- screenUploader.current?.abort?.(),- cameraUploader.current?.abort?.(),- audioUploader.current?.abort?.(),+ screenUploader.current?.abort?.(`empty-cleanup-${reason}`),+ cameraUploader.current?.abort?.(`empty-cleanup-${reason}`),+ audioUploader.current?.abort?.(`empty-cleanup-${reason}`),]);try {@@ -2587,7 +2587,7 @@ const CloudRecorder = () => {sendRecordingErrorBase(why, cancel);};- const dismissRecording = async (restarting = false) => {+ const dismissRecording = async (restarting = false, reason = "dismiss") => {clearPendingStart();setInitProject(false);await cleanupIfEmptyUploads(restarting ? "restart" : "dismiss");@@ -2617,9 +2617,9 @@ const CloudRecorder = () => {if (restarting) {await Promise.allSettled([- screenUploader.current?.abort?.(),- cameraUploader.current?.abort?.(),- audioUploader.current?.abort?.(),+ screenUploader.current?.abort?.(`restart-${reason}`),+ cameraUploader.current?.abort?.(`restart-${reason}`),+ audioUploader.current?.abort?.(`restart-${reason}`),]);if (!recordingToScene) {try {@@ -2651,12 +2651,12 @@ const CloudRecorder = () => {isRestarting.current = true;await Promise.allSettled([- screenUploader.current?.abort?.(),- cameraUploader.current?.abort?.(),- audioUploader.current?.abort?.(),+ screenUploader.current?.abort?.(`dismiss-${reason}`),+ cameraUploader.current?.abort?.(`dismiss-${reason}`),+ audioUploader.current?.abort?.(`dismiss-${reason}`),]);- await stopRecording(false);+ await stopRecording(false, `dismiss-${reason}`);const uploadMeta = uploadMetaRef.current;if (!uploadMeta) {@@ -2725,7 +2725,7 @@ const CloudRecorder = () => {hadRegionMode: Boolean(regionRef.current),});isRestarting.current = true;- await dismissRecording(true);+ await dismissRecording(true, "restart");await setCloudRestartPhase("restart-dismissed");// Keep capture streams; only stop recorder instances.await stopAllRecorders({ stopStreams: false });@@ -6101,7 +6101,27 @@ const CloudRecorder = () => {})();} else if (request.type === "dismiss-recording") {if (!isInit.current) return;- dismissRecording();+ const dismissReason = request.reason || "dismiss-recording-msg";+ // Back-to-back cross-talk guard: a dismiss issued for a previous+ // recording can reach this (newer) recorder because dismiss-recording+ // is routed by a single global recordingTab pointer. If the dismiss+ // provably targets a different project than the one this recorder is+ // actively capturing, ignore it β honoring it would discard a healthy+ // recording. Unknown ids (no session yet / legacy sender) are honored.+ const myProjectId = recorderSession.current?.projectId || null;+ const targetProjectId = request.projectId || null;+ if (myProjectId && targetProjectId && myProjectId !== targetProjectId) {+ console.warn(+ "[CloudRecorder] dismiss-recording ignored: project mismatch",+ { myProjectId, targetProjectId, reason: dismissReason },+ );+ void emitUploadTelemetry("dismiss_ignored_project_mismatch", {+ reason: dismissReason,+ targetProjectId,+ });+ return;+ }+ dismissRecording(false, dismissReason);}}, []);diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.jsindex 63cd67c..5c82371 100644--- a/src/pages/CloudRecorder/bunnyTusUploader.js+++ b/src/pages/CloudRecorder/bunnyTusUploader.js@@ -739,23 +739,40 @@ export default class BunnyTusUploader {throw new Error("Missing user token for saving upload metadata");}- const res = await fetch(`${API_BASE}/bunny/videos`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${screenityToken}`,- },- body: JSON.stringify({- title,- projectId,- type,- linkedMediaId,- sceneId,- recordingSessionId: this.sessionId || null,- }),- });+ // Retry transient failures so a backend blip doesn't abort the+ // recording. A 4xx is a real rejection, so don't retry it.+ let res = null;+ for (let attempt = 0; attempt < 3; attempt += 1) {+ if (attempt > 0) {+ await new Promise((r) => setTimeout(r, 500 * attempt));+ }+ try {+ res = await fetch(`${API_BASE}/bunny/videos`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${screenityToken}`,+ },+ body: JSON.stringify({+ title,+ projectId,+ type,+ linkedMediaId,+ sceneId,+ recordingSessionId: this.sessionId || null,+ }),+ });+ } catch (err) {+ // Network failure; retry.+ res = null;+ continue;+ }+ if (res.ok) break;+ const transient = res.status >= 500 || res.status === 429;+ if (!transient) break;+ }- if (!res.ok) throw new Error("Failed to create Bunny video");+ if (!res || !res.ok) throw new Error("Failed to create Bunny video");const data = await res.json();this.videoId = data.videoId;this.mediaId = data.mediaId;@@ -1527,7 +1544,7 @@ export default class BunnyTusUploader {this.scheduleJournalPersist();}- async abort() {+ async abort(reason = null) {this.pause();this.status = "aborted";this.uploadUrl = null;@@ -1536,7 +1553,9 @@ export default class BunnyTusUploader {this.totalBytes = 0;this.pendingUploads = [];this.stopHeartbeat();- this.emitTelemetry("upload_cancelled");+ this.emitTelemetry("upload_cancelled", {+ reason: reason || "uploader-abort",+ });if (this.journalPersistTimer) {clearTimeout(this.journalPersistTimer);this.journalPersistTimer = null;diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsxindex 408e7df..bfc8ea9 100644--- a/src/pages/Content/context/ContentState.jsx+++ b/src/pages/Content/context/ContentState.jsx@@ -343,7 +343,7 @@ const ContentState = (props) => {}));});- const dismissRecording = useCallback(() => {+ const dismissRecording = useCallback((reason = "user-dismiss") => {setStartFlowOutcome("cancelled");suppressStopBeepRef.current = true;chrome.runtime.sendMessage({ type: "clear-recording-alarm" });@@ -355,7 +355,15 @@ const ContentState = (props) => {cursorMode: "none",cursorEffects: [],});- chrome.runtime.sendMessage({ type: "dismiss-recording-tab" });+ // Stamp the dismiss with the project it is meant for, so a stale dismiss+ // can't tear down a different (back-to-back) recording.+ chrome.storage.local.get(["projectId"], (res) => {+ chrome.runtime.sendMessage({+ type: "dismiss-recording-tab",+ reason: typeof reason === "string" ? reason : "user-dismiss",+ projectId: res?.projectId || null,+ });+ });setContentState((prevContentState) => ({...prevContentState,recording: false,@@ -767,14 +775,14 @@ const ContentState = (props) => {chrome.i18n.getMessage("discardModalDiscard"),chrome.i18n.getMessage("discardModalResume"),() => {- contentStateRef.current.dismissRecording();+ contentStateRef.current.dismissRecording("user-discard-confirmed");},() => {contentStateRef.current.resumeRecording();},);} else {- contentStateRef.current.dismissRecording();+ contentStateRef.current.dismissRecording("user-discard");}}, [contentStateRef]);@@ -1097,7 +1105,7 @@ const ContentState = (props) => {showPopup: true,showExtension: true,}));- contentStateRef.current.dismissRecording();+ contentStateRef.current.dismissRecording("countdown-cancelled");},resetCountdown: () => {setContentState((prev) => ({diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.jsindex a940cad..38c1726 100644--- a/src/pages/Content/context/messaging/handlers.js+++ b/src/pages/Content/context/messaging/handlers.js@@ -702,7 +702,7 @@ export const setupHandlers = () => {registerMessage("cancel-recording", () => {const state = getState();- state.dismissRecording();+ state.dismissRecording("cancel-recording-cmd");});registerMessage("pause-recording", () => {@@ -768,10 +768,10 @@ export const setupHandlers = () => {chrome.i18n.getMessage("permissionsModalDismiss"),null,() => {- state.dismissRecording();+ state.dismissRecording("stream-error");},() => {- state.dismissRecording();+ state.dismissRecording("stream-error");},null,null,@@ -817,10 +817,10 @@ export const setupHandlers = () => {chrome.i18n.getMessage("permissionsModalDismiss"),null,() => {- state.dismissRecording();+ state.dismissRecording("backup-error");},() => {- state.dismissRecording();+ state.dismissRecording("backup-error");},null,null,diff --git a/src/pages/Content/popup/onboarding/proOnboarding.js b/src/pages/Content/popup/onboarding/proOnboarding.jsindex a60cfec..58929c5 100644--- a/src/pages/Content/popup/onboarding/proOnboarding.js+++ b/src/pages/Content/popup/onboarding/proOnboarding.js@@ -302,10 +302,22 @@ const ensureDriverStyles = () => {box-shadow: 0px 4px 30px rgba(30, 31, 37, 0.12) !important;padding: 20px !important;font-size: 14px !important;+ /* Popover renders in the host page's light DOM; pin inheritable+ text properties so host typography (e.g. a large html+ font-size) can't distort it. */+ line-height: normal !important;+ font-weight: 400 !important;+ font-style: normal !important;+ letter-spacing: normal !important;+ word-spacing: normal !important;+ text-transform: none !important;+ text-indent: 0 !important;+ text-align: left !important;+ text-shadow: none !important;}.driver-popover.ScreenityOnboardingPopover .driver-popover-title,.ScreenityOnboardingPopover .driver-popover-title {- font-size: 1rem !important;+ font-size: 16px !important;font-family: "Satoshi-Medium", sans-serif !important;font-weight: 500 !important;margin-bottom: 12px !important;diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex 27f97da..28eb5c3 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -255,13 +255,39 @@ const Recorder = () => {const START_GATE_TIMEOUT_MS = 12000;const streamingDataRetryTimer = useRef(null);- // Retry get-streaming-data: an initial sendMessage during SW wake-up can fail- // with "Receiving end does not exist" and silently drop. The SW also pushes- // streaming-data proactively, so the handler must remain idempotent.+ // Apply streaming-data once. Shared by the `get-streaming-data` pull+ // response and the `streaming-data` push message β whichever arrives+ // first wins; the rest is deduped via streamingDataReceivedAt.+ const applyStreamingData = (dataStr) => {+ if (streamingDataReceivedAt.current != null) {+ slLog("msg-streaming-data-duplicate");+ return;+ }+ slLog("msg-streaming-data");+ perfMark("Recorder streaming-data.received");+ streamingDataReceivedAt.current = Date.now();+ if (streamingDataTimeout.current) {+ clearTimeout(streamingDataTimeout.current);+ streamingDataTimeout.current = null;+ }+ try {+ startStreaming(JSON.parse(dataStr));+ } catch (e) {+ slLog("apply-streaming-data-error", {+ err: String(e?.message || e).slice(0, 120),+ });+ }+ };++ // Pull get-streaming-data from the SW. The SW answers the pull *directly*+ // with the payload (response.data), so delivery does not depend on the+ // tab's onMessage listener being registered yet, nor on the SW's+ // separate push landing in a timing window. An initial sendMessage+ // during SW wake-up can fail with "Receiving end does not exist"; retry.const requestStreamingDataWithRetry = (attempt = 0) => {if (streamingDataReceivedAt.current != null) return;- const maxAttempts = 5;- const backoffMs = [0, 250, 500, 1000, 2000];+ const maxAttempts = 6;+ const backoffMs = [0, 250, 500, 1000, 2000, 3000];const delay = backoffMs[Math.min(attempt, backoffMs.length - 1)];if (streamingDataRetryTimer.current) {clearTimeout(streamingDataRetryTimer.current);@@ -270,34 +296,41 @@ const Recorder = () => {streamingDataRetryTimer.current = null;if (streamingDataReceivedAt.current != null) return;slLog("get-streaming-data-send", { attempt });+ const retryIfNeeded = () => {+ if (+ streamingDataReceivedAt.current == null &&+ attempt + 1 < maxAttempts+ ) {+ requestStreamingDataWithRetry(attempt + 1);+ }+ };try {- chrome.runtime.sendMessage({ type: "get-streaming-data" }, () => {+ chrome.runtime.sendMessage({ type: "get-streaming-data" }, (response) => {const err = chrome.runtime.lastError;if (err) {slLog("get-streaming-data-send-error", {attempt,err: String(err.message || err).slice(0, 120),});+ retryIfNeeded();+ return;}- if (- err &&- streamingDataReceivedAt.current == null &&- attempt + 1 < maxAttempts- ) {- requestStreamingDataWithRetry(attempt + 1);+ // SW answered the pull directly with the payload β robust path.+ if (response && response.data) {+ slLog("get-streaming-data-response-applied", { attempt });+ applyStreamingData(response.data);+ return;}+ // No payload (e.g. older SW): fall back to the push; retry the+ // pull if it never lands.+ retryIfNeeded();});} catch (e) {slLog("get-streaming-data-throw", {attempt,err: String(e?.message || e).slice(0, 120),});- if (- streamingDataReceivedAt.current == null &&- attempt + 1 < maxAttempts- ) {- requestStreamingDataWithRetry(attempt + 1);- }+ retryIfNeeded();}}, delay);};@@ -356,6 +389,11 @@ const Recorder = () => {const pausedStateRef = useRef(false);const pausedAtRef = useRef(null);const stopSignalSent = useRef(false);+ // True once a stop/restart/dismiss was initiated locally (by this tab).+ // The abandonment listener uses it to tell a real stop apart from the+ // background tearing the session down without telling this tab.+ const localStopInitiated = useRef(false);+ const abandonHandled = useRef(false);const keepAliveAudioCtx = useRef(null);const keepAliveOscillator = useRef(null);@@ -657,6 +695,9 @@ const Recorder = () => {// At most one stop emission per recording session.const requestStop = (reason = "generic", extra = {}) => {+ // Any local stop intent suppresses the abandonment listener, even if+ // the guards below reject this particular call as redundant.+ localStopInitiated.current = true;if (stopSignalSent.current) {debugWarn("requestStop() ignored; already sent", { reason });return false;@@ -894,6 +935,103 @@ const Recorder = () => {} catch (err) {}}, []);+ // Grace before acting on a recording=false flag flip: a normal stop+ // flips storage a beat before its stop-recording-tab message reaches+ // this tab, so wait that window out before declaring abandonment.+ const ABANDON_GRACE_MS = 1500;++ // The session was torn down (recording flipped false) without this tab+ // being told to stop. Halt capture and discard quietly β the user has+ // already seen the failure, so resurrecting an editor would confuse.+ // Without this the MediaRecorder runs until the tab is closed by hand+ // (the ~8h orphan, support code SCR-AKJJ).+ const abortAbandonedRecording = (detail) => {+ if (abandonHandled.current) return;+ abandonHandled.current = true;+ localStopInitiated.current = true;+ isRecording.current = false;+ // Invalidate the run so any late ondataavailable is dropped.+ recordingGeneration.current += 1;+ lifecycle("Recorder", "self-stop-abandoned", {+ ...detail,+ savedCount: savedCount.current,+ recorderType: useWebCodecs.current ? "webcodecs" : "mediarecorder",+ });+ try {+ slLog("self-stop-abandoned", detail);+ } catch {}+ // Halt capture immediately; don't depend on window.close() timing.+ try {+ const r = recorder.current;+ if (r instanceof MediaRecorder) {+ r.ondataavailable = null;+ r.onstop = null;+ r.onerror = null;+ if (r.state !== "inactive") r.stop();+ } else if (r instanceof WebCodecsRecorder) {+ r.running = false;+ r.paused = false;+ Promise.resolve(r.cleanup?.()).catch(() => {});+ }+ } catch (err) {+ debugError("abortAbandonedRecording: recorder teardown failed", err);+ }+ [+ liveStream.current,+ helperVideoStream.current,+ helperAudioStream.current,+ ].forEach((s) => {+ try {+ s?.getTracks?.().forEach((t) => t.stop());+ } catch {}+ });+ // dismissRecording aborts the chunk writer, clears timing state and+ // closes the tab β the same quiet teardown path as a user dismiss.+ dismissRecording().catch(() => {});+ };++ // Abandonment watchdog: if `recording` flips trueβfalse in storage+ // while this tab is still capturing and nothing local asked for a+ // stop, the background tore the session down behind our back.+ useEffect(() => {+ const onStorageChanged = (changes, area) => {+ if (area !== "local") return;+ const rec = changes.recording;+ if (!rec || rec.oldValue !== true || rec.newValue !== false) return;+ if (+ abandonHandled.current ||+ !isRecording.current ||+ isFinishing.current ||+ isRestarting.current ||+ uiClosing.current ||+ localStopInitiated.current+ ) {+ return;+ }+ try {+ slLog("abandon-signal-detected", { savedCount: savedCount.current });+ } catch {}+ setTimeout(() => {+ if (+ abandonHandled.current ||+ !isRecording.current ||+ isFinishing.current ||+ isRestarting.current ||+ uiClosing.current ||+ localStopInitiated.current+ ) {+ try {+ slLog("abandon-signal-cleared");+ } catch {}+ return;+ }+ abortAbandonedRecording({ reason: "recording-flag-cleared" });+ }, ABANDON_GRACE_MS);+ };+ chrome.storage.onChanged.addListener(onStorageChanged);+ return () => chrome.storage.onChanged.removeListener(onStorageChanged);+ }, []);+function getStreamReadiness() {if (!helperVideoStream.current) return { ready: false, reason: "stream-ref-null" };const vt = helperVideoStream.current.getVideoTracks();@@ -1137,6 +1275,10 @@ const Recorder = () => {sentLast.current = false;isFinishing.current = false;stopSignalSent.current = false;+ // Fresh recording (incl. restart, which reuses this tab): clear the+ // abandonment signals so a later teardown is detected correctly.+ localStopInitiated.current = false;+ abandonHandled.current = false;const endCapsRead = perfSpan("Recorder.preflight storage+caps");const [@@ -2610,6 +2752,7 @@ const Recorder = () => {};async function stopRecording() {+ localStopInitiated.current = true;if (isFinishing.current) {debugWarn("stopRecording() called while already finishing");return;@@ -2724,6 +2867,7 @@ const Recorder = () => {const dismissRecording = async () => {debug("dismissRecording()");+ localStopInitiated.current = true;resetGateState();uiClosing.current = true;isRecording.current = false;@@ -2762,6 +2906,7 @@ const Recorder = () => {};const restartRecording = async () => {+ localStopInitiated.current = true;if (isRestarting.current) {debugWarn("restartRecording() called while already restarting");return false;@@ -3795,40 +3940,13 @@ const Recorder = () => {isTab.current = false;recordedTabId.current = null;}- requestStreamingDataWithRetry();- // If the SW never wakes to deliver streaming-data, the start-gate- // timeout never arms (it depends on startRequested, which depends- // on streaming-data). Surface an error after 15s.- if (streamingDataTimeout.current) {- clearTimeout(streamingDataTimeout.current);- }- streamingDataTimeout.current = setTimeout(() => {- if (streamingDataReceivedAt.current != null) return;- const diagInfo = {- tabIDError: tabIDError.current,- isTab: isTab.current,- msSinceLoaded: Date.now() - loadedAt.current,- };- slLog("streaming-data-watchdog-fire", diagInfo);- sendRecordingError(- "Recording not ready: streaming-data never arrived from background",- );- }, 15000);- loadedAt.current = Date.now();+ // streaming-data is pulled on mount (see the mount effect), not+ // here β `loaded` can be lost to the cold-start race and must not+ // be the sole trigger for the pull.} else if (request.type === "streaming-data") {- // Streaming-data may arrive twice (SW push + tab pull, or retries).- if (streamingDataReceivedAt.current != null) {- slLog("msg-streaming-data-duplicate");- return;- }- slLog("msg-streaming-data");- perfMark("Recorder streaming-data.received");- streamingDataReceivedAt.current = Date.now();- if (streamingDataTimeout.current) {- clearTimeout(streamingDataTimeout.current);- streamingDataTimeout.current = null;- }- startStreaming(JSON.parse(request.data));+ // Push path; the pull response usually wins. applyStreamingData+ // dedupes whichever arrives second.+ applyStreamingData(request.data);} else if (request.type === "start-recording-tab") {slLog("msg-start-recording-tab", {hasStream: !!helperVideoStream.current,@@ -4107,6 +4225,41 @@ const Recorder = () => {};}, []);+ // Pull streaming-data as soon as the recorder is mounted β do not wait+ // for the SW's `loaded` push, which is fire-and-forget at tab+ // status:complete and is routinely lost to the cold-start race (the+ // SWβtab handoff failure, support codes SCR-AKJJ / SCR-8LC2). The pull+ // is answered directly in its own sendMessage response, so it does not+ // depend on a push landing in a timing window. The 15s watchdog is+ // armed here too, independent of `loaded`, so a lost `loaded` can't+ // leave the recorder hanging without an error path.+ useEffect(() => {+ loadedAt.current = Date.now();+ requestStreamingDataWithRetry();+ if (streamingDataTimeout.current) {+ clearTimeout(streamingDataTimeout.current);+ }+ streamingDataTimeout.current = setTimeout(() => {+ if (streamingDataReceivedAt.current != null) return;+ slLog("streaming-data-watchdog-fire", {+ msSinceMount: Date.now() - loadedAt.current,+ });+ sendRecordingError(+ "Recording not ready: streaming-data never arrived from background",+ );+ }, 15000);+ return () => {+ if (streamingDataRetryTimer.current) {+ clearTimeout(streamingDataRetryTimer.current);+ streamingDataRetryTimer.current = null;+ }+ if (streamingDataTimeout.current) {+ clearTimeout(streamingDataTimeout.current);+ streamingDataTimeout.current = null;+ }+ };+ }, []);+return (<><RecorderUI started={started} isTab={isTab.current} />diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsxindex 957a9c1..00d5bc6 100644--- a/src/pages/Region/Recorder.jsx+++ b/src/pages/Region/Recorder.jsx@@ -150,18 +150,68 @@ const Recorder = () => {const lowStorageAbort = useRef(false);const savedCount = useRef(0);+ // True once streaming-data has been received (applied OR deferred) β+ // used to stop the pull retries.const streamingDataHandled = useRef(false);const streamingDataRetryTimer = useRef(null);+ // streaming-data can arrive before the `crop-target` message that sets+ // regionRef. startStreaming needs regionRef, so stash the payload here+ // and replay it via flushPendingStreamingData once regionRef flips true.+ const pendingStreamingData = useRef(null);const chunkWriter = useRef(null);const chunkBackendRef = useRef(null);- // Retry with backoff: SW mid-wakeup can drop the initial sendMessage- // silently. Combined with SW-side retry and handler idempotency, this- // covers slow Windows cold-starts.+ // Apply streaming-data once. Shared by the `get-streaming-data` pull+ // response and the `streaming-data` push message. Idempotent. If the+ // crop target hasn't landed yet (regionRef not set), the payload is+ // deferred β flushPendingStreamingData replays it.+ const applyStreamingData = (dataStr) => {+ if (streamingDataHandled.current) return;+ streamingDataHandled.current = true;+ if (regionRef.current) {+ pendingStreamingData.current = null;+ try {+ startStreaming(JSON.parse(dataStr));+ } catch (e) {+ persistRegionStartDebug({+ stage: "apply-streaming-data-error",+ err: String(e?.message || e).slice(0, 120),+ });+ }+ } else {+ // crop-target not here yet; replayed by flushPendingStreamingData.+ pendingStreamingData.current = dataStr;+ perfMark("Region.Recorder streaming-data.deferred");+ }+ };++ // Replay deferred streaming-data once regionRef is set (called from the+ // crop-target and start-recording-tab paths).+ const flushPendingStreamingData = () => {+ if (!regionRef.current) return;+ const dataStr = pendingStreamingData.current;+ if (dataStr == null) return;+ pendingStreamingData.current = null;+ perfMark("Region.Recorder streaming-data.flushed");+ try {+ startStreaming(JSON.parse(dataStr));+ } catch (e) {+ persistRegionStartDebug({+ stage: "flush-streaming-data-error",+ err: String(e?.message || e).slice(0, 120),+ });+ }+ };++ // Pull get-streaming-data from the SW. The SW answers the pull directly+ // with the payload (response.data), so delivery does not depend on the+ // `loaded` push landing β `loaded` is routinely lost to the cold-start+ // race (the SWβtab handoff failure). SW mid-wakeup can still drop the+ // initial sendMessage; retry with backoff.const requestStreamingDataWithRetry = (attempt = 0) => {if (streamingDataHandled.current) return;- const backoffMs = [0, 250, 500, 1000, 2000];+ const backoffMs = [0, 250, 500, 1000, 2000, 3000];const delay = backoffMs[Math.min(attempt, backoffMs.length - 1)];if (streamingDataRetryTimer.current) {clearTimeout(streamingDataRetryTimer.current);@@ -173,8 +223,13 @@ const Recorder = () => {stage: "get-streaming-data-send",attempt,});+ const retryIfNeeded = () => {+ if (!streamingDataHandled.current && attempt + 1 < backoffMs.length) {+ requestStreamingDataWithRetry(attempt + 1);+ }+ };try {- chrome.runtime.sendMessage({ type: "get-streaming-data" }, () => {+ chrome.runtime.sendMessage({ type: "get-streaming-data" }, (response) => {const err = chrome.runtime.lastError;if (err) {persistRegionStartDebug({@@ -182,14 +237,20 @@ const Recorder = () => {attempt,err: String(err.message || err).slice(0, 120),});+ retryIfNeeded();+ return;}- if (- err &&- !streamingDataHandled.current &&- attempt + 1 < backoffMs.length- ) {- requestStreamingDataWithRetry(attempt + 1);+ // SW answered the pull directly with the payload β robust path.+ if (response && response.data) {+ persistRegionStartDebug({+ stage: "get-streaming-data-response-applied",+ attempt,+ });+ applyStreamingData(response.data);+ return;}+ // No payload: fall back to the push; retry if it never lands.+ retryIfNeeded();});} catch (e) {persistRegionStartDebug({@@ -197,12 +258,7 @@ const Recorder = () => {attempt,err: String(e?.message || e).slice(0, 120),});- if (- !streamingDataHandled.current &&- attempt + 1 < backoffMs.length- ) {- requestStreamingDataWithRetry(attempt + 1);- }+ retryIfNeeded();}}, delay);};@@ -572,6 +628,9 @@ const Recorder = () => {if (event.data.type === "crop-target") {target.current = event.data.target;regionRef.current = true;+ // regionRef is now set β apply any streaming-data that arrived+ // before the crop target did.+ flushPendingStreamingData();} else if (event.data.type === "restart-recording") {restartRecording();}@@ -1794,6 +1853,7 @@ const Recorder = () => {// recorder tab) hits "Capture stream is not ready yet" at 5s.target.current = null;streamingDataHandled.current = false;+ pendingStreamingData.current = null;await updateFreeFinalizeStatus("stopping", 0);await setRecordingTimingState({recording: false,@@ -1900,6 +1960,7 @@ const Recorder = () => {regionRef.current = false;target.current = null;streamingDataHandled.current = false;+ pendingStreamingData.current = null;useWebCodecs.current = false;await setRecordingTimingState({recording: false,@@ -2351,9 +2412,9 @@ const Recorder = () => {isRegion: Boolean(request.region),});backupRef.current = request.backup;- if (request.region) {- requestStreamingDataWithRetry();- }+ // streaming-data is pulled on mount (see the mount effect), not+ // here β `loaded` can be lost to the cold-start race and must not+ // be the sole trigger for the pull.// Ack so BG's sendMessageRecord doesn't reject + trigger retries.try { sendResponse?.({ ok: true }); } catch {}return true;@@ -2364,12 +2425,9 @@ const Recorder = () => {regionMode: Boolean(regionRef.current),});const wasDuplicate = streamingDataHandled.current;- if (!wasDuplicate) {- streamingDataHandled.current = true;- if (regionRef.current) {- startStreaming(JSON.parse(request.data));- }- }+ // Push path; the pull response usually wins. applyStreamingData+ // dedupes, and defers if the crop target hasn't arrived yet.+ applyStreamingData(request.data);try { sendResponse?.({ ok: true, duplicate: wasDuplicate }); } catch {}return true;} else if (request.type === "start-recording-tab") {@@ -2379,6 +2437,9 @@ const Recorder = () => {});if (regionRef.current || target.current) {regionRef.current = true;+ // regionRef is set β apply any streaming-data that was deferred+ // because it arrived before the crop target.+ flushPendingStreamingData();setRegionRestartPhase("restart-started");startRecording();}@@ -2517,9 +2578,19 @@ const Recorder = () => {lifecycle("Region.Recorder", "iframe-mount", {href: typeof window !== "undefined" ? window.location?.href?.slice(0, 200) : null,});+ // Pull streaming-data as soon as the iframe is mounted β do not wait+ // for the SW's `loaded` push, which is routinely lost to the+ // cold-start race (the SWβtab handoff failure). The pull is answered+ // directly in its own response; if the crop target hasn't landed yet+ // the payload is deferred and replayed by flushPendingStreamingData.+ requestStreamingDataWithRetry();return () => {clearStartRetry();+ if (streamingDataRetryTimer.current) {+ clearTimeout(streamingDataRetryTimer.current);+ streamingDataRetryTimer.current = null;+ }chrome.runtime.onMessage.removeListener(onMessage);lifecycle("Region.Recorder", "iframe-unmount", {regionRef: regionRef.current,diff --git a/src/pages/Sandbox/Sandbox.jsx b/src/pages/Sandbox/Sandbox.jsxindex 21a9a58..c2bbb52 100644--- a/src/pages/Sandbox/Sandbox.jsx+++ b/src/pages/Sandbox/Sandbox.jsx@@ -19,7 +19,12 @@ const Sandbox = () => {const parentRef = useRef(null);const progress = useRef("");// ref so the stuck-timer closure (deps=[]) can read current state- const loadStateRef = useRef({ ready: false, hasBlob: false });+ const loadStateRef = useRef({+ ready: false,+ hasBlob: false,+ chunkIndex: 0,+ chunkCount: 0,+ });const getChromeVersion = () => {var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);@@ -102,7 +107,14 @@ const Sandbox = () => {useEffect(() => {loadStateRef.current.ready = Boolean(contentState.ready);loadStateRef.current.hasBlob = Boolean(contentState.blob);- }, [contentState.ready, contentState.blob]);+ loadStateRef.current.chunkIndex = contentState.chunkIndex || 0;+ loadStateRef.current.chunkCount = contentState.chunkCount || 0;+ }, [+ contentState.ready,+ contentState.blob,+ contentState.chunkIndex,+ contentState.chunkCount,+ ]);useEffect(() => {chrome.runtime.sendMessage({ type: "check-banner-support" }, (response) => {@@ -156,23 +168,27 @@ const Sandbox = () => {timers.push(setTimeout(() => tryRequest(i), ms));});- // Surface recovery modal if "Preparing recording..." sits 60s with no- // blob/ready/editorRecordingError; writing editorRecordingError reuses- // the ContentState consumer.- const STUCK_TIMEOUT_MS = 60_000;- const stuckTimer = setTimeout(() => {+ // Long IDB-backed recordings can take minutes to transfer from SW+ // to sandbox (chunks are base64-encoded and batched). A flat 60s+ // timeout would fire on healthy slow loads. Re-arm while chunks+ // keep arriving; only fire when nothing has progressed for 30s.+ const STUCK_FIRST_CHECK_MS = 60_000;+ const STUCK_RECHECK_MS = 15_000;+ const STUCK_NO_PROGRESS_MS = 30_000;+ const STUCK_MAX_TOTAL_MS = 10 * 60_000;+ const startAt = Date.now();+ let lastChunkIndex = 0;+ let lastProgressAt = startAt;+ const checkStuck = () => {try {if (cancelled) return;- // Skip the write if the editor finished. A bogus- // EDITOR_STUCK_TIMEOUT in diag zips makes the signal useless for- // telling real hangs from slow-but-fine.if (loadStateRef.current.ready || loadStateRef.current.hasBlob) {chrome.runtime.sendMessage({type: "diag-forward",event: "sandbox-stuck-timeout-suppressed",data: {- afterMs: STUCK_TIMEOUT_MS,+ afterMs: Date.now() - startAt,ready: loadStateRef.current.ready,hasBlob: loadStateRef.current.hasBlob,},@@ -180,11 +196,38 @@ const Sandbox = () => {.catch(() => {});return;}+ const now = Date.now();+ const idx = loadStateRef.current.chunkIndex || 0;+ const count = loadStateRef.current.chunkCount || 0;+ if (idx > lastChunkIndex) {+ lastChunkIndex = idx;+ lastProgressAt = now;+ }+ const sinceProgress = now - lastProgressAt;+ const totalWaited = now - startAt;+ const chunksFlowing =+ count > 0 && idx < count && sinceProgress < STUCK_NO_PROGRESS_MS;+ // After the last chunk lands the sandbox still has to assemble+ // the blob; give it longer before declaring stuck.+ const assemblingBlob =+ count > 0 && idx >= count && sinceProgress < 90_000;+ if (+ (chunksFlowing || assemblingBlob) &&+ totalWaited < STUCK_MAX_TOTAL_MS+ ) {+ timers.push(setTimeout(checkStuck, STUCK_RECHECK_MS));+ return;+ }chrome.runtime.sendMessage({type: "diag-forward",event: "sandbox-stuck-timeout",- data: { afterMs: STUCK_TIMEOUT_MS },+ data: {+ afterMs: totalWaited,+ chunkIndex: idx,+ chunkCount: count,+ sinceProgressMs: sinceProgress,+ },}).catch(() => {});chrome.storage.local.set({@@ -197,8 +240,8 @@ const Sandbox = () => {},});} catch {}- }, STUCK_TIMEOUT_MS);- timers.push(stuckTimer);+ };+ timers.push(setTimeout(checkStuck, STUCK_FIRST_CHECK_MS));return () => {cancelled = true;diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsxindex 08c4e3e..1db55e4 100644--- a/src/pages/Sandbox/context/ContentState.jsx+++ b/src/pages/Sandbox/context/ContentState.jsx@@ -3090,10 +3090,15 @@ const ContentState = (props) => {};const downloadGIF = async () => {- if (contentState.isFfmpegRunning || contentState.downloading) {+ // ref: rapid clicks fire before state propagates+ const latest = contentStateRef.current || contentState;+ // Don't gate on isFfmpegRunning β it leaks from background poll+ // handlers and would intermittently swallow the click. downloadingGIF+ // is the real lock (mirrors the `download` MP4 path).+ if (latest.downloadingGIF || latest.downloading) {return;}- if (contentState.duration > 30) {+ if (latest.duration > 30) {try {chrome.runtime.sendMessage({type: "show-toast",@@ -3112,7 +3117,7 @@ const ContentState = (props) => {sendMessage({type: "to-gif",- blob: contentState.blob,+ blob: latest.blob,});};diff --git a/src/pages/Sandbox/layout/player/RightPanel.js b/src/pages/Sandbox/layout/player/RightPanel.jsindex f383c67..0acd252 100644--- a/src/pages/Sandbox/layout/player/RightPanel.js+++ b/src/pages/Sandbox/layout/player/RightPanel.js@@ -916,8 +916,11 @@ const RightPanel = () => {className={styles.button}onClick={() => {// disabled on a div is meaningless; gate click manually.+ // Not gated on isFfmpegRunning: it leaks from background+ // poll handlers and would intermittently swallow the+ // click. downloadGIF self-locks via downloadingGIF.if (- contentState.isFfmpegRunning ||+ contentState.downloadingGIF ||contentState.duration > 30 ||!contentState.mp4ready ||contentState.noffmpeg@@ -927,7 +930,7 @@ const RightPanel = () => {contentState.downloadGIF();}}disabled={- contentState.isFfmpegRunning ||+ contentState.downloadingGIF ||contentState.duration > 30 ||!contentState.mp4ready ||contentState.noffmpeg