The free and privacy-friendly screen recorder with no limits 🎥
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Recording reliability, camera preview, and editor recovery
Alyssa Xd1b895d85995
diff --git a/package.json b/package.jsonindex 1b25d22..a462958 100755--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "screenity",- "version": "4.5.3",+ "version": "4.5.5","description": "The free and privacy-friendly screen recorder with no sign in needed.","scripts": {"build": "cross-env NODE_ENV=production node utils/build.js",diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.jsonindex 5df7d84..c625810 100644--- a/src/_locales/en/messages.json+++ b/src/_locales/en/messages.json@@ -1526,8 +1526,8 @@"description": "Shown when the screen capture stream is missing or can't be accessed (no streamId returned, getDisplayMedia threw, etc.)"},"tabStreamUnavailableError": {- "message": "Couldn't access this tab's video. Reload the tab and try again.",- "description": "Shown when Chrome won't return a tab capture stream for the chosen tab"+ "message": "Couldn't record this tab. Some pages like browser settings, the Web Store, or extension pages can't be captured. Try reloading the tab, switching to a different tab, or recording your screen instead.",+ "description": "Shown when Chrome won't return a tab capture stream for the chosen tab or region recording"},"streamingDataTimeoutError": {"message": "Recording didn't start in time. Please try again.",diff --git a/src/manifest.json b/src/manifest.jsonindex 3e5230e..bfcf6c1 100755--- a/src/manifest.json+++ b/src/manifest.json@@ -3,7 +3,7 @@"name": "__MSG_extName__","description": "__MSG_extDesc__","default_locale": "en",- "version": "4.5.3",+ "version": "4.5.5","background": {"service_worker": "background.bundle.js"},@@ -109,7 +109,8 @@"tabs","tabCapture","scripting",- "system.display"+ "system.display",+ "power"],"storage": {"managed_schema": "schema.json"diff --git a/src/media/fastRecorderGate.ts b/src/media/fastRecorderGate.tsindex 90b8bbc..08dc9f7 100644--- a/src/media/fastRecorderGate.ts+++ b/src/media/fastRecorderGate.ts@@ -170,6 +170,16 @@ export const isFastRecorderFailureTransient = () {return true;}+ // No frames off the capture track (starvation/track-ended/cancel) = capture+ // failed, not the encoder: don't sticky-disable. A real defect has framesFromMSTP > 0.+ if (+ reasonCode === "webcodecs-zero-frames" &&+ detail &&+ detail.framesEncoded === 0 &&+ detail.framesFromMSTP === 0+ ) {+ return true;+ }return false;};@@ -879,13 +889,15 @@ export const validateFastRecorderOutputBlob = async (details.canPlayType = safeCanPlayType(playMime);details.mediaSourceSupported = safeMseSupport(playMime);+ // blob-too-small is informational: a short clip is legitimately tiny (~15KB).+ // The empty-encoder case surfaces as demuxer-no-video-track, not size.+ const defectReasons = reasons.filter((r) => r !== "blob-too-small");const hardFail =- reasons.includes("no-blob") ||- reasons.includes("blob-too-small") ||- reasons.includes("unexpected-mime") ||- reasons.includes("demuxer-no-video-track");+ defectReasons.includes("no-blob") ||+ defectReasons.includes("unexpected-mime") ||+ defectReasons.includes("demuxer-no-video-track");- const ok = reasons.length === 0;+ const ok = defectReasons.length === 0;debugLog("validation result", { ok, hardFail, reasons, details });diff --git a/src/pages/Background/index.js b/src/pages/Background/index.jsindex 8cb857c..9799794 100644--- a/src/pages/Background/index.js+++ b/src/pages/Background/index.js@@ -6,6 +6,7 @@ import {} from "../../messaging/messageRouter";import { hydrateDiagnosticLog, diagEvent } from "../utils/diagnosticLog";import { initCountdownFallback } from "./recording/countdownFallback";+import { initKeepAwake } from "./recording/keepAwake";import { initLifecycleObserver } from "./lifecycleObserver";import {listSessionDirs,@@ -329,6 +330,7 @@ messageRouter();initializeListeners();setupHandlers();initCountdownFallback();+initKeepAwake();initLifecycleObserver();// Recovery must run AFTER clearStaleLocks: if the recorder tab dieddiff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.jsindex a55ab73..42eba38 100644--- a/src/pages/Background/messaging/handlers.js+++ b/src/pages/Background/messaging/handlers.js@@ -691,8 +691,17 @@ const clearRecordingSession = () => {const clearRecordingSessionSafe = async (reason = "unknown", details = {}) => {const prev = activeRecordingSession;clearRecordingSession();+ // Remove the stored session (not just the in-memory var) when done, so a 2nd+ // recording on the same tab doesn't route to a stale one. Kept on interruption.+ const recordingIsDone =+ reason === "video-ready" ||+ reason === "non-recording-session-conflict" ||+ reason === "stale-conflict-recovered";try {await chrome.storage.local.set({+ ...(recordingIsDone+ ? { recorderSession: null, pendingRecording: false }+ : {}),lastRecordingSessionClear: {ts: Date.now(),reason,diff --git a/src/pages/Background/recording/emitRecordingTelemetry.js b/src/pages/Background/recording/emitRecordingTelemetry.jsindex b1050b8..92388fd 100644--- a/src/pages/Background/recording/emitRecordingTelemetry.js+++ b/src/pages/Background/recording/emitRecordingTelemetry.js@@ -78,7 +78,7 @@ export const emitRecordingTelemetry = async (eventType, extra = {}) => {os: getOsName(),browser: getBrowserName(),browserMajor: getBrowserMajor(),- appVersion: null,+ appVersion: extVersion || null,},event: {type: eventType,diff --git a/src/pages/Background/recording/keepAwake.js b/src/pages/Background/recording/keepAwake.jsnew file mode 100644index 0000000..0c264bf--- /dev/null+++ b/src/pages/Background/recording/keepAwake.js@@ -0,0 +1,44 @@+// Keep the display awake while recording: a sleeping display drops or starves+// the screen-capture track (video freezes, audio continues). No-op without chrome.power.+import { diagEvent } from "../../utils/diagnosticLog";++const ENABLE_RECORDING_KEEP_AWAKE = true;++// Last applied state, so we don't request/release on every unrelated storage+// write. Resets on SW restart; init re-reads the recording flag to re-assert.+let currentlyHeld = null;++const applyKeepAwake = (isRecording) => {+ if (!ENABLE_RECORDING_KEEP_AWAKE) return;+ if (!chrome?.power?.requestKeepAwake || !chrome?.power?.releaseKeepAwake) {+ return;+ }+ const want = Boolean(isRecording);+ if (want === currentlyHeld) return;+ currentlyHeld = want;+ try {+ if (want) {+ // "display" not "system": screen capture needs the monitor to stay on.+ chrome.power.requestKeepAwake("display");+ } else {+ chrome.power.releaseKeepAwake();+ }+ diagEvent("recording-keep-awake", { held: want });+ } catch (err) {+ currentlyHeld = null;+ console.warn("[Screenity][BG] keep-awake apply failed", err);+ }+};++export const initKeepAwake = () => {+ chrome.storage.onChanged.addListener((changes, area) => {+ if (area !== "local" || !("recording" in changes)) return;+ applyKeepAwake(changes.recording.newValue);+ });+ // Re-assert on SW boot: a restart mid-recording re-acquires the lock; a+ // restart after a stop releases any lock left behind.+ chrome.storage.local+ .get(["recording"])+ .then(({ recording }) => applyKeepAwake(recording))+ .catch(() => {});+};diff --git a/src/pages/Background/recording/sendMessageRecord.js b/src/pages/Background/recording/sendMessageRecord.jsindex 516cf57..0dcf578 100644--- a/src/pages/Background/recording/sendMessageRecord.js+++ b/src/pages/Background/recording/sendMessageRecord.js@@ -1,4 +1,9 @@import { sendMessageTab } from "../tabManagement";+import { diagEvent } from "../../utils/diagnosticLog";++// Offscreen docs survive a SW restart. If the SW died mid-start and lost the+// `offscreen` flag, look for a live recorder offscreen doc before giving up.+const ENABLE_RESILIENT_HANDOFF = true;export const sendMessageRecord = (message, responseCallback = null) => {return new Promise((resolve, reject) => {@@ -34,30 +39,67 @@ export const sendMessageRecord = (message, responseCallback = null) => {reject(err);});} else {+ const sendViaOffscreen = () => {+ chrome.runtime.sendMessage(message, (response) => {+ if (chrome.runtime.lastError) {+ reject(chrome.runtime.lastError.message);+ } else {+ responseCallback ? responseCallback(response) : resolve(response);+ }+ });+ };// SW restart can lose recordingTab, fall back to recorderSession// but only if it's still live. completed/crashed/stopped sessions// point at a dead tab and would surface a misleading "No tab with// id" error instead of the real "no recorder tab" one.- chrome.storage.local.get(["recorderSession"], (sessionResult) => {- const session = sessionResult.recorderSession;- const recorderTabId =- session?.recorderTabId || session?.tabId || null;- const sessionLive =- session?.status === "recording" || session?.status === "starting";- if (sessionLive && recorderTabId) {- sendMessageTab(recorderTabId, message, responseCallback)- .then(resolve)- .catch(reject);- } else {- console.warn(- "sendMessageRecord: no recording tab available",- session- ? { sessionStatus: session.status, recorderTabId }- : { session: null }- );- reject(new Error("No recording tab available"));- }- });+ const tryRecorderSession = () => {+ chrome.storage.local.get(["recorderSession"], (sessionResult) => {+ const session = sessionResult.recorderSession;+ const recorderTabId =+ session?.recorderTabId || session?.tabId || null;+ const sessionLive =+ session?.status === "recording" ||+ session?.status === "starting";+ if (sessionLive && recorderTabId) {+ sendMessageTab(recorderTabId, message, responseCallback)+ .then(resolve)+ .catch(reject);+ } else {+ console.warn(+ "sendMessageRecord: no recording tab available",+ session+ ? { sessionStatus: session.status, recorderTabId }+ : { session: null }+ );+ reject(new Error("No recording tab available"));+ }+ });+ };+ // If a recorder offscreen is alive (the SW restart wiped the flag but+ // not the doc), resume the handoff to it instead of giving up.+ if (ENABLE_RESILIENT_HANDOFF && chrome.runtime.getContexts) {+ chrome.runtime+ .getContexts({})+ .then((contexts) => {+ const hasRecorderOffscreen = (contexts || []).some(+ (c) =>+ c.contextType === "OFFSCREEN_DOCUMENT" &&+ typeof c.documentUrl === "string" &&+ c.documentUrl.includes("offscreenrecorder.html")+ );+ if (hasRecorderOffscreen) {+ diagEvent("send-record-recovered-offscreen", {+ messageType: message?.type || null,+ });+ sendViaOffscreen();+ } else {+ tryRecorderSession();+ }+ })+ .catch(() => tryRecorderSession());+ } else {+ tryRecorderSession();+ }}});});diff --git a/src/pages/Camera/Camera.jsx b/src/pages/Camera/Camera.jsxindex 2669ace..0a28d01 100644--- a/src/pages/Camera/Camera.jsx+++ b/src/pages/Camera/Camera.jsx@@ -136,39 +136,24 @@ const Camera = () => {};useEffect(() => {- // Acquire the stream only when camera is enabled AND a recording is- // pending or active. Mounting alone must not trigger getUserMedia.- chrome.storage.local.get(- ["recording", "pendingRecording", "cameraActive"],- (result) => {- if (- result.cameraActive &&- (result.recording || result.pendingRecording)- ) {- acquireStream();- }- },- );+ // Acquire the preview whenever the camera is enabled, so the user sees+ // their camera before recording too, not only during a recording.+ chrome.storage.local.get(["cameraActive"], (result) => {+ if (result.cameraActive) {+ acquireStream();+ }+ });}, [videoRef.current]);- // Release the camera light when no recording is active. The iframe stays- // mounted to cache OS permissions, but holding getUserMedia keeps the- // camera indicator on with no visible UI.+ // Hold the camera while the bubble is on (cameraActive), release it when off.+ // This is what shows the preview before recording, not only during it.useEffect(() => {let inflightAcquire = false;const evaluate = async () => {- const { recording, pendingRecording, cameraActive } =- await chrome.storage.local.get([- "recording",- "pendingRecording",- "cameraActive",- ]);- // Hold the stream only when cameraActive AND a recording is- // active/pending. Without the gate, tab recordings without camera- // would re-acquire and surface camera-denied errors.- const wantStream = Boolean(- cameraActive && (recording || pendingRecording),- );+ const { cameraActive } = await chrome.storage.local.get(["cameraActive"]);+ // The camera iframe only mounts when cameraActive is true, so a tab+ // recording without camera never reaches here and can't re-acquire.+ const wantStream = Boolean(cameraActive);const hasStream = Boolean(streamRef.current?.active);if (!wantStream && hasStream) {stopCameraStream(streamRef, videoRef);@@ -187,11 +172,7 @@ const Camera = () => {};const listener = (changes, area) => {if (area !== "local") return;- if (- "recording" in changes ||- "pendingRecording" in changes ||- "cameraActive" in changes- ) {+ if ("cameraActive" in changes) {evaluate();}};diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex 3315223..548578d 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -656,7 +656,9 @@ const CloudRecorder = () => {os: getOsName(),browser: getBrowserName(),browserMajor,- appVersion: null,+ // Carry the version on env.appVersion so it's queryable. Was hardcoded+ // null, so per-version upload attribution only had the event/header.+ appVersion: eventPayload.extensionVersion || null,},event: {type: eventPayload.event,@@ -6977,6 +6979,8 @@ const CloudRecorder = () => {request.reason || "offscreen-shutdown");}+ // Don't stop capture tracks here: it raced a slow start (isInit not+ // yet flipped, tracks live) and killed the capture mid-start.const drainPromise = Promise.all([screenUploader.current?.waitForPendingUploads?.() ??Promise.resolve(),diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsxindex b149350..b1c7eac 100644--- a/src/pages/Content/context/ContentState.jsx+++ b/src/pages/Content/context/ContentState.jsx@@ -8,6 +8,7 @@ import React, {} from "react";import { updateFromStorage } from "./utils/updateFromStorage";+import { shouldResendCropTarget } from "./cropTargetGate";import { lifecycle } from "../../utils/lifecycleLog";import { perfMark, perfReset } from "../../utils/perfMarks";@@ -788,20 +789,25 @@ const ContentState = (props) => {tabRecordedID: null,});- if (- contentStateRef.current.recordingType === "region" &&- contentStateRef.current.cropTarget- ) {- contentStateRef.current.regionCaptureRef.contentWindow.postMessage(- {- type: "crop-target",- target: contentStateRef.current.cropTarget,- width: contentStateRef.current.regionWidth,- height: contentStateRef.current.regionHeight,- },- "*",- );- }+ // Sent only after the mic-muted modal is confirmed: this makes the recorder+ // call getDisplayMedia, so sending it earlier pops the picker behind the modal.+ const sendRegionCropTarget = () => {+ if (+ contentStateRef.current.recordingType === "region" &&+ contentStateRef.current.cropTarget &&+ contentStateRef.current.regionCaptureRef?.contentWindow+ ) {+ contentStateRef.current.regionCaptureRef.contentWindow.postMessage(+ {+ type: "crop-target",+ target: contentStateRef.current.cropTarget,+ width: contentStateRef.current.regionWidth,+ height: contentStateRef.current.regionHeight,+ },+ "*",+ );+ }+ };setContentState((prevContentState) => ({...prevContentState,@@ -818,6 +824,9 @@ const ContentState = (props) => {chrome.i18n.getMessage("micMutedModalAction"),chrome.i18n.getMessage("micMutedModalCancel"),() => {+ // Crop target first (after the user confirmed mic-off): this flushes+ // the recorder's deferred streaming-data and starts getDisplayMedia.+ sendRegionCropTarget();chrome.runtime.sendMessage({type: "desktop-capture",region:@@ -857,6 +866,9 @@ const ContentState = (props) => {},);} else {+ // Crop target first: flushes the recorder's deferred streaming-data and+ // starts getDisplayMedia (no mic modal to gate behind in this branch).+ sendRegionCropTarget();perfMark("Content desktop-capture.sent");// Sync recordingType to storage so the cloudrecorder tab reads// the current pick, not a stale value from a prior session.@@ -2198,6 +2210,51 @@ const ContentState = (props) => {}}, [contentState.hideUI]);+ // Recorder sets regionAwaitingCropTarget when its crop-target is missing; we+ // re-send it over storage (postMessage can drop). Gated to an active start.+ const cropTargetWantedRef = useRef(false);+ const sendCropTargetToRecorder = useCallback(() => {+ const s = contentStateRef.current;+ // Hard gate (see cropTargetGate): only answer the recorder during an actual+ // start, never on an idle region toggle/tweak.+ if (!shouldResendCropTarget(s)) return;+ const regionWin = s.regionCaptureRef?.contentWindow || null;+ if (!regionWin) return;+ regionWin.postMessage(+ {+ type: "crop-target",+ target: s.cropTarget,+ width: s.regionWidth,+ height: s.regionHeight,+ },+ "*",+ );+ }, []);++ useEffect(() => {+ const onChanged = (changes, area) => {+ if (area !== "local" || !changes.regionAwaitingCropTarget) return;+ // Mirror the recorder's "waiting" flag: reset on clear so the re-send+ // below can't fire on an idle region tweak and start outside a real one.+ if (!changes.regionAwaitingCropTarget.newValue) {+ cropTargetWantedRef.current = false;+ return;+ }+ cropTargetWantedRef.current = true;+ sendCropTargetToRecorder();+ };+ chrome.storage.onChanged.addListener(onChanged);+ return () => chrome.storage.onChanged.removeListener(onChanged);+ }, [sendCropTargetToRecorder]);++ // The recorder can ask before the async derivation resolves; send once it+ // does, but only while it is actually waiting (cropTargetWantedRef).+ useEffect(() => {+ if (!cropTargetWantedRef.current) return;+ if (!contentState.cropTarget) return;+ sendCropTargetToRecorder();+ }, [contentState.cropTarget, sendCropTargetToRecorder]);+useEffect(() => {updateFromStorage();}, []);diff --git a/src/pages/Content/context/cropTargetGate.js b/src/pages/Content/context/cropTargetGate.jsnew file mode 100644index 0000000..cbe9c3b--- /dev/null+++ b/src/pages/Content/context/cropTargetGate.js@@ -0,0 +1,10 @@+// Gate for the region crop-target re-send: only during an active start, never+// on an idle toggle (which once tripped a recording before Start was clicked).+export const shouldResendCropTarget = (state) => {+ if (!state) return false;+ if (state.recordingType !== "region") return false;+ if (!state.cropTarget) return false;+ return Boolean(+ state.pendingRecording || state.preparingRecording || state.recording+ );+};diff --git a/src/pages/Content/countdown/Countdown.jsx b/src/pages/Content/countdown/Countdown.jsxindex 669f745..9d69a32 100644--- a/src/pages/Content/countdown/Countdown.jsx+++ b/src/pages/Content/countdown/Countdown.jsx@@ -229,7 +229,7 @@ const Countdown = () => {finishTimeoutRef.current = null;}, END_HOLD_MS);}- }, [count, setContentState]);+ }, [count]);// Log every visible digit so UI ticks correlate with BG events.useEffect(() => {diff --git a/src/pages/Content/modal/Modal.jsx b/src/pages/Content/modal/Modal.jsxindex ca74841..c750df5 100644--- a/src/pages/Content/modal/Modal.jsx+++ b/src/pages/Content/modal/Modal.jsx@@ -10,15 +10,18 @@ const Modal = (props) => {const [description, setDescription] = useState("Description here");const [button1, setButton1] = useState("Submit");const [button2, setButton2] = useState("Cancel");- const [trigger, setTrigger] = useState(() => {});- const [trigger2, setTrigger2] = useState(() => {});+ // useState(() => fn) treats fn as a lazy initializer and stores its return,+ // so a callback default must return a function or it ends up undefined.+ const noop = () => {};+ const [trigger, setTrigger] = useState(() => noop);+ const [trigger2, setTrigger2] = useState(() => noop);const [showModal, setShowModal] = useState(false);const [image, setImage] = useState(null);const [learnmore, setLearnMore] = useState(null);- const [learnMoreLink, setLearnMoreLink] = useState(() => {});+ const [learnMoreLink, setLearnMoreLink] = useState(null);const [colorSafe, setColorSafe] = useState(false);const [sideButton, setSideButton] = useState(false);- const [sideButtonAction, setSideButtonAction] = useState(() => {});+ const [sideButtonAction, setSideButtonAction] = useState(() => noop);const openModal = useCallback((@@ -40,14 +43,16 @@ const Modal = (props) => {setButton1(button1);setButton2(button2);setShowModal(true);- setTrigger(() => action);- setTrigger2(() => action2);+ setTrigger(() => (typeof action === "function" ? action : noop));+ setTrigger2(() => (typeof action2 === "function" ? action2 : noop));setImage(image);setLearnMore(learnMore);- setLearnMoreLink(() => learnMoreLink);+ setLearnMoreLink(learnMoreLink);setColorSafe(colorSafe);setSideButton(sideButton);- setSideButtonAction(() => sideButtonAction);+ setSideButtonAction(() =>+ typeof sideButtonAction === "function" ? sideButtonAction : noop,+ );});diff --git a/src/pages/Content/popup/PopupContainer.jsx b/src/pages/Content/popup/PopupContainer.jsxindex 348ebdb..bf64400 100644--- a/src/pages/Content/popup/PopupContainer.jsx+++ b/src/pages/Content/popup/PopupContainer.jsx@@ -71,7 +71,7 @@ const PopupContainer = (props) => {showProSplash: nextShowProSplash,}));});- }, [setContentState]);+ }, []);useEffect(() => {if (contentState.isLoggedIn) {diff --git a/src/pages/Content/toolbar/components/RadialMenu.jsx b/src/pages/Content/toolbar/components/RadialMenu.jsxindex cf8fd0b..6260f36 100644--- a/src/pages/Content/toolbar/components/RadialMenu.jsx+++ b/src/pages/Content/toolbar/components/RadialMenu.jsx@@ -93,7 +93,11 @@ const RadialMenu = (props) => {</Popover.Trigger></TooltipWrap><Popover.Portal forceMount container={ref.current}>- <Popover.Content avoidCollisions={false} asChild onOpenAutoFocus>+ <Popover.Content+ avoidCollisions={false}+ asChild+ onOpenAutoFocus={(e) => e.preventDefault()}+ ><divclassName={fullwheel ? "radial-menu color-wheel" : "radial-menu"}ref={radialMenuRef}diff --git a/src/pages/Content/toolbar/components/Toast.jsx b/src/pages/Content/toolbar/components/Toast.jsxindex d7e8ebe..a234e6f 100644--- a/src/pages/Content/toolbar/components/Toast.jsx+++ b/src/pages/Content/toolbar/components/Toast.jsx@@ -15,7 +15,10 @@ const Toast = () => {const [contentState, setContentState] = useContext(contentStateContext);const [open, setOpen] = useState(false);const [title, setTitle] = useState("");- const [trigger, setTrigger] = useState(() => {});+ // useState(() => fn) treats fn as a lazy initializer and stores its return,+ // so the default must return a function or `trigger` ends up undefined.+ const noop = () => {};+ const [trigger, setTrigger] = useState(() => noop);const triggerRef = useRef(trigger);const openRef = useRef(open);const contentStateRef = useRef(contentState);@@ -29,7 +32,8 @@ const Toast = () => {if (contentStateRef.current.hideUI) return;setTitle(title);setOpen(true);- setTrigger(() => action);+ // Keep trigger callable even when a toast is opened without an action.+ setTrigger(() => (typeof action === "function" ? action : noop));setToastDuration(durationMs);});@@ -68,7 +72,7 @@ const Toast = () => {onEscapeKeyDown={(e) => {e.stopPropagation();e.preventDefault();- triggerRef.current();+ triggerRef.current?.();setOpen(false);}}>@@ -78,14 +82,14 @@ const Toast = () => {asChildaltText="Escape"onClick={() => {- trigger();+ trigger?.();}}><buttonclassName="Button"onClick={(e) => {e.stopPropagation();- trigger();+ trigger?.();}}>Escdiff --git a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx b/src/pages/Content/toolbar/layout/ToolbarWrap.jsxindex 76eef84..82e2e9d 100644--- a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx+++ b/src/pages/Content/toolbar/layout/ToolbarWrap.jsx@@ -73,7 +73,7 @@ const ToolbarWrap = () => {setToolbarMode: setMode,toolbarMode: mode,}));- }, [mode, setContentState]);+ }, [mode]);useEffect(() => {if (contentState.toolbarHover && contentState.hideUI) {diff --git a/src/pages/EditorApp/context/ContentState.jsx b/src/pages/EditorApp/context/ContentState.jsxindex 2f944e0..6f2506b 100644--- a/src/pages/EditorApp/context/ContentState.jsx+++ b/src/pages/EditorApp/context/ContentState.jsx@@ -25,6 +25,7 @@ import { diagForward } from "../../utils/diagForward";import { perfMark, perfSpan } from "../../utils/perfMarks";import { triggerSupportDownload } from "../../utils/triggerSupportDownload";import { chooseReader } from "../recorderStorage/chooseReader";+import { downloadResolvedRecording } from "../recorderStorage/resolveRecordingFile";import { runEditorOp } from "../editorOps";// mediabunny is ~630KB, only used by export/remux/conversion on user action.// Lazy-load to keep parse cost off editor mount. Cached promise.@@ -46,6 +47,10 @@ const ENABLE_EAGER_MP4_FINALIZE = true;// delivering the source file, so it's safe to leave on.const ENABLE_OFFSCREEN_WEBM = true;+// Fail an empty editor fast: a failed start can open an editor with no+// recording, so error at the first heartbeat instead of the ~3 min timeout.+const ENABLE_FAST_EMPTY_EDITOR_FAIL = true;+localforage.config({driver: localforage.INDEXEDDB,name: "screenity",@@ -119,6 +124,76 @@ const ContentState = (props) => {const MAX_HEARTBEATS = 6;const HEARTBEAT_MS = 30000;++ // isFfmpegRunning/processingProgress are set while waitForFinalizeReady+ // runs, so a slow finalize counts as activity and isn't read as empty.+ const hasLoadActivity = (s) =>+ Boolean(+ s?.ready ||+ s?.rawBlob ||+ s?.blob ||+ (s?.chunkCount ?? 0) > 0 ||+ s?.isFfmpegRunning ||+ s?.finalizingRecording ||+ (s?.processingProgress ?? 0) > 0,+ );++ // Show the same "couldn't load" error the load-failure paths use instead of+ // spinning forever.+ const showStuckError = (s, reason) => {+ if (+ s?.ready ||+ editorErrorShownRef.current ||+ typeof s?.openModal !== "function"+ ) {+ return;+ }+ editorErrorShownRef.current = true;+ diagForward("sandbox-stuck-timeout-error", { reason });+ s.openModal(+ chrome.i18n.getMessage("opfsLoadErrorTitle"),+ chrome.i18n.getMessage("opfsLoadErrorDescription"),+ // Primary action: recover the recording off disk. The editor couldn't+ // load it (usually an orphaned OPFS pointer) but the file is still there.+ chrome.i18n.getMessage("rawRecordingModalButton"),+ chrome.i18n.getMessage("permissionsModalDismiss"),+ () => {+ downloadResolvedRecording(+ contentStateRef.current?.title,+ (status) => {+ if (status === "started") return;+ chrome.runtime.sendMessage({+ type: "show-toast",+ message:+ chrome.i18n.getMessage("rawRecordingModalTitle") ++ (status === "active" ? "" : ": no data"),+ });+ },+ );+ },+ () => {},+ null,+ null,+ null,+ true,+ chrome.i18n.getMessage("getHelpButton"),+ () => {+ triggerSupportDownload({ source: "editor-stuck-timeout" });+ chrome.runtime.sendMessage({+ type: "report-error",+ source: "editor-stuck-timeout",+ errorCode: "EDITOR_STUCK_TIMEOUT",+ zipBundled: true,+ });+ },+ );+ setContentState((prev) => ({+ ...prev,+ ready: true,+ recordingFailed: true,+ }));+ };+const interval = setInterval(() => {const s = contentStateRef.current;if (s?.ready) {@@ -126,44 +201,9 @@ const ContentState = (props) => {return;}if (diagHeartbeatCountRef.current >= MAX_HEARTBEATS) {+ // Stuck with no data after ~3 min.clearInterval(interval);- // Stuck with no data after ~3 min. Show the same "couldn't load" error- // the load-failure paths use instead of spinning forever.- if (- !s?.ready &&- !editorErrorShownRef.current &&- typeof s?.openModal === "function"- ) {- editorErrorShownRef.current = true;- diagForward("sandbox-stuck-timeout-error", {});- s.openModal(- chrome.i18n.getMessage("opfsLoadErrorTitle"),- chrome.i18n.getMessage("opfsLoadErrorDescription"),- null,- chrome.i18n.getMessage("permissionsModalDismiss"),- () => {},- () => {},- null,- null,- null,- true,- chrome.i18n.getMessage("getHelpButton"),- () => {- triggerSupportDownload({ source: "editor-stuck-timeout" });- chrome.runtime.sendMessage({- type: "report-error",- source: "editor-stuck-timeout",- errorCode: "EDITOR_STUCK_TIMEOUT",- zipBundled: true,- });- },- );- setContentState((prev) => ({- ...prev,- ready: true,- recordingFailed: true,- }));- }+ showStuckError(s, "timeout");return;}diagHeartbeatCountRef.current += 1;@@ -176,6 +216,12 @@ const ContentState = (props) => {(Date.now() - (diagMountAtRef.current || Date.now())) / 1000,),});+ // Empty editor (failed-start orphan): nothing loading or finalizing, so+ // don't wait the full ~3 min.+ if (ENABLE_FAST_EMPTY_EDITOR_FAIL && !hasLoadActivity(s)) {+ clearInterval(interval);+ showStuckError(s, "no-load-activity");+ }}, HEARTBEAT_MS);return () => clearInterval(interval);diff --git a/src/pages/EditorApp/layout/player/RightPanel.js b/src/pages/EditorApp/layout/player/RightPanel.jsindex 4b7693a..c3f509b 100644--- a/src/pages/EditorApp/layout/player/RightPanel.js+++ b/src/pages/EditorApp/layout/player/RightPanel.js@@ -2,6 +2,7 @@ import React, { useContext, useEffect, useState, useRef } from "react";import styles from "../../styles/player/_RightPanel.module.scss";import { buildDiagnosticZip } from "../../../utils/buildDiagnosticZip";+import { downloadResolvedRecording } from "../../recorderStorage/resolveRecordingFile";import { ReactSVG } from "react-svg";@@ -246,10 +247,16 @@ const RightPanel = () => {const s = contentStateRef.current;const blob = s.rawBlob || s.blob;if (!blob) {- console.error("[Screenity] raw download: no rawBlob available");- chrome.runtime.sendMessage({- type: "show-toast",- message: chrome.i18n.getMessage("rawRecordingModalTitle") + ": no data",+ // In-memory blob never loaded (e.g. an orphaned OPFS pointer left+ // the editor unable to load). Recover straight from the OPFS file.+ await downloadResolvedRecording(s.title, (status) => {+ if (status === "started") return;+ chrome.runtime.sendMessage({+ type: "show-toast",+ message:+ chrome.i18n.getMessage("rawRecordingModalTitle") ++ (status === "active" ? "" : ": no data"),+ });});return;}diff --git a/src/pages/EditorApp/recorderStorage/resolveRecordingFile.js b/src/pages/EditorApp/recorderStorage/resolveRecordingFile.jsnew file mode 100644index 0000000..2399f25--- /dev/null+++ b/src/pages/EditorApp/recorderStorage/resolveRecordingFile.js@@ -0,0 +1,174 @@+// Recovery helper: resolve + download the current recording straight from its+// OPFS file, for when the editor's in-memory blob never loaded (orphaned pointer+// after an SW restart). READ-ONLY on OPFS (can't block a fresh recording or the+// 1-slot sweep), hands back the disk-backed File (O(1) memory), and won't return+// a file that's still being written.++const OPFS_RECORDING_PREFIX = "recording-";+const MIN_VALID_RECORDING_BYTES = 4096;+// Above this, the base64-via-background fallback would spike memory, so skip it.+// The disk-backed chrome.downloads path has no limit; the fallback is only for+// environments where blob-URL downloads are blocked (e.g. Brave).+const BASE64_FALLBACK_MAX_BYTES = 150_000_000;++const opfsAvailable = () =>+ typeof navigator !== "undefined" &&+ navigator.storage &&+ typeof navigator.storage.getDirectory === "function";++// Returns { name, handle, file } for the recording to recover, or null if+// none is recoverable, or { active: true } if a recording is currently being+// written (caller should not offer a raw download in that case).+export const resolveRecordingFile = async () => {+ if (!opfsAvailable()) return null;+ let dir;+ try {+ dir = await navigator.storage.getDirectory();+ } catch {+ return null;+ }++ let candidate = null;++ // 1) Fast path: the known pointer, if the file still exists and is valid.+ try {+ const { lastRecordingBackendRef } = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ const refName = lastRecordingBackendRef?.fileName;+ if (refName && refName.startsWith(OPFS_RECORDING_PREFIX)) {+ try {+ const handle = await dir.getFileHandle(refName);+ const file = await handle.getFile();+ if (file.size >= MIN_VALID_RECORDING_BYTES) {+ candidate = { name: refName, handle, file };+ }+ } catch {+ // NotFound / orphaned -> fall through to enumeration+ }+ }+ } catch {}++ // 2) Orphan fallback: newest valid recording-*.{mp4,webm}. With the 1-slot+ // model there is normally exactly one; we still pick the newest valid for+ // safety.+ if (!candidate) {+ const files = [];+ try {+ for await (const [name, handle] of dir.entries()) {+ if (!name.startsWith(OPFS_RECORDING_PREFIX)) continue;+ if (!name.endsWith(".mp4") && !name.endsWith(".webm")) continue;+ try {+ const file = await handle.getFile();+ if (file.size < MIN_VALID_RECORDING_BYTES) continue;+ files.push({ name, handle, file, lastModified: file.lastModified });+ } catch {}+ }+ } catch {+ return null;+ }+ if (!files.length) return null;+ files.sort((a, b) => b.lastModified - a.lastModified);+ candidate = files[0];+ }++ // Guard against handing back a file that's still being written (a fresh+ // recording in progress): a finished recording's size is stable.+ try {+ const size1 = candidate.file.size;+ await new Promise((r) => setTimeout(r, 600));+ const file2 = await candidate.handle.getFile();+ if (file2.size !== size1) {+ return { active: true };+ }+ candidate.file = file2;+ } catch {+ // file vanished mid-check (swept by a new recording) -> nothing to recover+ return null;+ }++ return candidate;+};++// Download a resolved recording File via chrome.downloads, streaming from disk.+// onResult(status) where status is "started" | "no-data" | "active" | "failed".+export const downloadResolvedRecording = async (titleBase, onResult) => {+ const resolved = await resolveRecordingFile();+ if (!resolved) {+ onResult?.("no-data");+ return;+ }+ if (resolved.active) {+ onResult?.("active");+ return;+ }+ const { file, name } = resolved;+ const ext = (file.type && file.type.includes("mp4")) || name.endsWith(".mp4")+ ? "mp4"+ : "webm";+ const safeBase =+ (titleBase || "screenity-recording")+ .replace(/[\\/:*?"<>|]/g, " ")+ .replace(/[\u0000-\u001F\u007F]/g, " ")+ .replace(/\s+/g, " ")+ .trim() || "screenity-recording";+ const filename = `${safeBase}.${ext}`;++ const fallbackViaBackground = async () => {+ // Only safe for small files: readAsDataURL materializes the whole file.+ if (file.size > BASE64_FALLBACK_MAX_BYTES) {+ onResult?.("failed");+ return;+ }+ try {+ const base64 = await new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onloadend = () => resolve(reader.result);+ reader.onerror = () => reject(reader.error);+ reader.readAsDataURL(file);+ });+ chrome.runtime.sendMessage({+ type: "request-download",+ base64,+ title: filename,+ });+ onResult?.("started");+ } catch {+ onResult?.("failed");+ }+ };++ let url = null;+ try {+ url = window.URL.createObjectURL(file);+ chrome.downloads.download({ url, filename }, (downloadId) => {+ if (chrome.runtime.lastError || !downloadId) {+ window.URL.revokeObjectURL(url);+ fallbackViaBackground();+ return;+ }+ onResult?.("started");+ const onChanged = (delta) => {+ if (delta.id !== downloadId || !delta.state) return;+ if (delta.state.current === "complete") {+ chrome.downloads.onChanged.removeListener(onChanged);+ window.URL.revokeObjectURL(url);+ } else if (delta.state.current === "interrupted") {+ chrome.downloads.onChanged.removeListener(onChanged);+ window.URL.revokeObjectURL(url);+ if (delta.error?.current !== "USER_CANCELED") fallbackViaBackground();+ }+ };+ chrome.downloads.onChanged.addListener(onChanged);+ });+ } catch {+ // download() threw synchronously (e.g. chrome.downloads unavailable) after+ // the URL was created; revoke it before falling back so it doesn't leak.+ if (url) {+ try {+ window.URL.revokeObjectURL(url);+ } catch {}+ }+ await fallbackViaBackground();+ }+};diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex 1aa8875..f7acf1e 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -3824,6 +3824,9 @@ const Recorder = () => {silentSamples += 1;if (silentSamples >= SAMPLES_BEFORE_ALERT && !alreadyReported) {alreadyReported = true;+ const hasMic = !!helperAudioStream.current?.getAudioTracks?.()+ ?.length;+ const hasSystemAudio = sysTracks.length > 0 && data.systemAudio;try {chrome.runtime.sendMessage({type: "diag-forward",@@ -3832,10 +3835,8 @@ const Recorder = () => {elapsedRecordingMs: recordingStartTime.current? Date.now() - recordingStartTime.current: null,- hasMic: !!helperAudioStream.current?.getAudioTracks?.()- ?.length,- hasSystemAudio:- sysTracks.length > 0 && data.systemAudio,+ hasMic,+ hasSystemAudio,audioContextState: aCtx.current?.state ?? null,docVisibility:typeof document !== "undefined"@@ -3844,14 +3845,8 @@ const Recorder = () => {},});} catch {}- // Surface but don't stop: silence may be intentional.- try {- chrome.runtime.sendMessage({- type: "show-toast",- message: chrome.i18n.getMessage("audioSilentToast"),- timeout: 8000,- }).catch(() => {});- } catch {}+ // No toast: silence is normal (nobody speaking, or no audio), so a+ // mid-recording warning just gets in the way. Diag above still logs it.}} else {silentSamples = 0;@@ -4502,7 +4497,11 @@ const Recorder = () => {const timeoutMs = Number(request.timeoutMs) || 20000;(async () => {try {- if (isRecording.current) stopRecording();+ if (isRecording.current) {+ stopRecording();+ }+ // Don't stop capture tracks here: it raced a slow start (isRecording+ // not yet flipped, tracks live) and killed the screen track mid-start.await new Promise((resolve) => setTimeout(resolve, 1000));} catch (err) {console.warn("[Recorder] offscreen-shutdown error", err);diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsxindex 653897a..801a5c6 100644--- a/src/pages/Region/Recorder.jsx+++ b/src/pages/Region/Recorder.jsx@@ -152,6 +152,11 @@ const Recorder = () => {// crop-target not here yet; replayed by flushPendingStreamingData.pendingStreamingData.current = dataStr;perfMark("Region.Recorder streaming-data.deferred");+ // Signal the content script to re-send the crop-target if the original+ // postMessage dropped (the region "stuck until restart" hang). No-op for tab.+ try {+ chrome.storage.local.set({ regionAwaitingCropTarget: Date.now() });+ } catch {}}};@@ -163,6 +168,10 @@ const Recorder = () => {if (dataStr == null) return;pendingStreamingData.current = null;perfMark("Region.Recorder streaming-data.flushed");+ // Crop-target arrived; stop the content script re-sending it.+ try {+ chrome.storage.local.set({ regionAwaitingCropTarget: null });+ } catch {}try {startStreaming(JSON.parse(dataStr));} catch (e) {diff --git a/src/pages/Region/regionStreamingGate.js b/src/pages/Region/regionStreamingGate.jsnew file mode 100644index 0000000..96c5ede--- /dev/null+++ b/src/pages/Region/regionStreamingGate.js@@ -0,0 +1,16 @@+// Gate for the region streaming-data dedup. `applyStreamingData` dedupes on a+// `streamingDataHandled` bool that can get stuck true after a start fails+// without routing through stop/dismiss/timeout, dropping the next recording's+// data. A real duplicate is always mid-session, so "handled" while fully idle is+// a stale leftover to reset, not a dupe.+export const isStaleStreamingHandled = (s) => {+ if (!s) return false;+ if (!s.streamingDataHandled) return false;+ return (+ !s.deferredTimerActive &&+ !s.regionMode &&+ !s.hasRecorder &&+ !s.recording &&+ !s.finishing+ );+};diff --git a/src/pages/utils/errorCodes.js b/src/pages/utils/errorCodes.jsindex 8ddf0f0..e883e7c 100644--- a/src/pages/utils/errorCodes.js+++ b/src/pages/utils/errorCodes.js@@ -151,6 +151,12 @@ export const classifyError = (errorStr = "", errorType = "") => {return REC_START_NOT_READY;}+ // Tab/region capture failures (often wrapped in a getUserMedia error). Match+ // before STREAM so the user gets the actionable tab message, not a generic one.+ if (lower.includes("tab capture") || lower.includes("this tab's video")) {+ return REC_START_TAB;+ }+if (STREAM_PATTERNS.some((p) => lower.includes(p))) {return REC_START_STREAM;}