The free and privacy-friendly screen recorder with no limits 🎥
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Improved recording stability
Alyssa X9d1871d4a63c
diff --git a/src/manifest.json b/src/manifest.jsonindex 9127fd4..d8fe9a9 100755--- a/src/manifest.json+++ b/src/manifest.json@@ -3,7 +3,7 @@"name": "__MSG_extName__","description": "__MSG_extDesc__","default_locale": "en",- "version": "4.2.0",+ "version": "4.2.2","background": {"service_worker": "background.bundle.js"},diff --git a/src/pages/Background/listeners/onTabActivatedListener.js b/src/pages/Background/listeners/onTabActivatedListener.jsindex 3eb328d..3d7fba4 100644--- a/src/pages/Background/listeners/onTabActivatedListener.js+++ b/src/pages/Background/listeners/onTabActivatedListener.js@@ -2,25 +2,37 @@ import { sendMessageTab } from "../tabManagement";export const handleTabActivation = async (activeInfo) => {try {- const { recordingStartTime } = await chrome.storage.local.get([+ const {+ recordingStartTime,+ recording,+ restarting,+ pendingRecording,+ recorderSession,+ } = await chrome.storage.local.get(["recordingStartTime",+ "recording",+ "restarting",+ "pendingRecording",+ "recorderSession",]);// Get the activated tabconst tab = await chrome.tabs.get(activeInfo.tabId);- // Check if currently recording or restarting- const { recording } = await chrome.storage.local.get(["recording"]);- const { restarting } = await chrome.storage.local.get(["restarting"]);- const { pendingRecording } = await chrome.storage.local.get([- "pendingRecording",- ]);+ // Check both recording flag AND recorderSession to avoid race conditions+ // recorderSession persists even if the SW restarts+ const isActivelyRecording =+ recording || (recorderSession && recorderSession.status === "recording");- if (recording) {+ if (isActivelyRecording) {// Check if region recording and if the current tab is the recording tab- const { tabRecordedID } = await chrome.storage.local.get([- "tabRecordedID",- ]);+ const { tabRecordedID, region, customRegion, recordingType } =+ await chrome.storage.local.get([+ "tabRecordedID",+ "region",+ "customRegion",+ "recordingType",+ ]);if (tabRecordedID && tabRecordedID !== activeInfo.tabId) {sendMessageTab(activeInfo.tabId, { type: "hide-popup-recording" });} else if (@@ -34,18 +46,13 @@ export const handleTabActivation = async (activeInfo) => {}// Check if it's region or customRegion recording- const { region } = await chrome.storage.local.get(["region"]);- const { customRegion } = await chrome.storage.local.get(["customRegion"]);- const { recordingType } = await chrome.storage.local.get([- "recordingType",- ]);if (!region && !customRegion && recordingType !== "region") {sendMessageTab(activeInfo.tabId, {type: "recording-check",recordingStartTime,});}- } else if (!recording && !restarting && !pendingRecording) {+ } else if (!isActivelyRecording && !restarting && !pendingRecording) {sendMessageTab(activeInfo.tabId, { type: "recording-ended" });}diff --git a/src/pages/Background/listeners/onTabRemovedListener.js b/src/pages/Background/listeners/onTabRemovedListener.jsindex d6a2cab..45f927d 100644--- a/src/pages/Background/listeners/onTabRemovedListener.js+++ b/src/pages/Background/listeners/onTabRemovedListener.js@@ -1,4 +1,5 @@import { sendMessageTab, focusTab } from "../tabManagement";+import { sendMessageRecord } from "../recording/sendMessageRecord";/*** Listener for when a tab is removed.@@ -14,6 +15,7 @@ export const onTabRemovedListener = () => {restarting,recordingTab,tabRecordedID,+ recorderSession,} = await chrome.storage.local.get(["region","customRegion",@@ -21,28 +23,53 @@ export const onTabRemovedListener = () => {"restarting","recordingTab","tabRecordedID",+ "recorderSession",]);const isRegionMode = region || customRegion;const recordedTabId = tabRecordedID || recordingTab;- if (!recording || restarting) return;+ // Check both recording flag AND recorderSession+ const isActivelyRecording =+ recording ||+ (recorderSession && recorderSession.status === "recording");- // If the removed tab is the one being recorded+ if (!isActivelyRecording || restarting) return;++ // If the removed tab is the one being recorded (for tab capture)if (tabId === recordedTabId) {// Clear reference to the removed tabchrome.storage.local.set({ recordingTab: null, tabRecordedID: null });- const { activeTab } = await chrome.storage.local.get(["activeTab"]);-+ // Send stop directly to the recorder, not through content script+ // This is more reliable as the content script tab may not existtry {- if (activeTab) {- await sendMessageTab(activeTab, { type: "stop-recording-tab" });- }+ await sendMessageRecord({+ type: "stop-recording-tab",+ reason: "recorded-tab-closed",+ });} catch (err) {- console.warn("Could not message active tab to stop recording:", err);+ console.warn("Could not message recorder to stop:", err);}+ // Also try to notify the active tab for UI cleanup+ const { activeTab } = await chrome.storage.local.get(["activeTab"]);+ if (activeTab && activeTab !== tabId) {+ sendMessageTab(activeTab, { type: "stop-pending" }).catch(() => {});+ }++ chrome.action.setIcon({ path: "assets/icon-34.png" });+ }++ // If the CloudRecorder tab itself was closed, that's a critical failure+ if (tabId === recordingTab && recordingTab !== recordedTabId) {+ console.error("CloudRecorder tab was closed during recording!");+ chrome.storage.local.set({+ recording: false,+ recorderSession: recorderSession+ ? { ...recorderSession, status: "crashed", crashedAt: Date.now() }+ : null,+ });chrome.action.setIcon({ path: "assets/icon-34.png" });}} catch (error) {diff --git a/src/pages/Background/listeners/onTabUpdatedListener.js b/src/pages/Background/listeners/onTabUpdatedListener.jsindex c1a5eae..4304851 100644--- a/src/pages/Background/listeners/onTabUpdatedListener.js+++ b/src/pages/Background/listeners/onTabUpdatedListener.js@@ -3,21 +3,32 @@ import { sendMessageTab } from "../tabManagement";export const handleTabUpdate = async (tabId, changeInfo, tab) => {try {if (changeInfo.status === "complete") {- const { recording } = await chrome.storage.local.get(["recording"]);- const { restarting } = await chrome.storage.local.get(["restarting"]);- const { tabRecordedID } = await chrome.storage.local.get([+ const {+ recording,+ restarting,+ tabRecordedID,+ pendingRecording,+ recordingStartTime,+ recorderSession,+ } = await chrome.storage.local.get([+ "recording",+ "restarting","tabRecordedID",- ]);- const { pendingRecording } = await chrome.storage.local.get(["pendingRecording",- ]);- const { recordingStartTime } = await chrome.storage.local.get(["recordingStartTime",+ "recorderSession",]);- if (!recording && !restarting && !pendingRecording) {+ // Check both recording flag AND recorderSession to avoid race conditions+ // recorderSession persists even if the SW restarts+ const isActivelyRecording =+ recording ||+ (recorderSession && recorderSession.status === "recording");+ const isPendingOrRestarting = restarting || pendingRecording;++ if (!isActivelyRecording && !isPendingOrRestarting) {sendMessageTab(tabId, { type: "recording-ended" });- } else if (recording) {+ } else if (isActivelyRecording) {if (tabRecordedID && tabRecordedID === tabId) {sendMessageTab(tabId, {type: "recording-check",diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.jsindex 38e7e18..13f4212 100644--- a/src/pages/Background/messaging/handlers.js+++ b/src/pages/Background/messaging/handlers.js@@ -57,6 +57,32 @@ const API_BASE = process.env.SCREENITY_API_BASE_URL;const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";+let activeRecordingSession = null;+let recordingTabListener = null;++const clearRecordingSession = () => {+ activeRecordingSession = null;+ if (recordingTabListener) {+ chrome.tabs.onRemoved.removeListener(recordingTabListener);+ recordingTabListener = null;+ }+};++const registerRecordingTabListener = (tabId) => {+ if (!tabId || recordingTabListener) return;+ recordingTabListener = (closedTabId) => {+ if (closedTabId === tabId) {+ chrome.runtime.sendMessage({+ type: "stop-recording-tab",+ reason: "recording-tab-closed",+ tabId: closedTabId,+ });+ clearRecordingSession();+ }+ };+ chrome.tabs.onRemoved.addListener(recordingTabListener);+};+export const copyToClipboard = (text) => {if (!text) return;chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {@@ -104,7 +130,29 @@ export const setupHandlers = () => {async (message, sender) => await handleGetStreamingData(message, sender));registerMessage("cancel-recording", (message) => cancelRecording(message));- registerMessage("stop-recording-tab", (message, sendResponse) => {+ registerMessage("stop-recording-tab", (message, sender, sendResponse) => {+ try {+ const reason = message?.reason || "unknown";+ const senderTabId = message?.tabId || sender?.tab?.id || null;+ const senderUrl = sender?.url || null;+ const stack = new Error().stack;+ console.warn("[Screenity][BG] stop-recording-tab received", {+ reason,+ senderTabId,+ senderUrl,+ });+ chrome.storage.local.set({+ lastStopRecordingEvent: {+ reason,+ senderTabId,+ senderUrl,+ stack,+ ts: Date.now(),+ },+ });+ } catch (err) {+ console.warn("[Screenity][BG] stop-recording-tab logging failed", err);+ }handleStopRecordingTab(message);sendResponse({ ok: true });return true;@@ -236,6 +284,21 @@ export const setupHandlers = () => {});registerMessage("is-pinned", async () => await isPinned());++ // Prevent Chrome from discarding the CloudRecorder tab during recording+ registerMessage("set-tab-auto-discardable", async ({ payload }, sender) => {+ try {+ const tabId = sender?.tab?.id;+ if (tabId) {+ await chrome.tabs.update(tabId, {+ autoDiscardable: payload.discardable,+ });+ }+ } catch (err) {+ console.warn("Failed to set tab autoDiscardable:", err);+ }+ });+registerMessage("save-to-drive",async (message) => await handleSaveToDrive(message, false)@@ -911,4 +974,49 @@ export const setupHandlers = () => {});return true;});+ registerMessage(+ "register-recording-session",+ (message, sender, sendResponse) => {+ const incoming = message.session || {};+ if (+ activeRecordingSession &&+ activeRecordingSession.id &&+ incoming.id &&+ activeRecordingSession.id !== incoming.id+ ) {+ sendResponse({+ ok: false,+ error: "Another recording session is already active",+ activeRecordingSession,+ });+ return true;+ }++ const tabId = incoming.tabId || sender?.tab?.id || null;+ activeRecordingSession = { ...incoming, tabId };+ registerRecordingTabListener(tabId);+ sendResponse({ ok: true, session: activeRecordingSession });+ return true;+ }+ );++ registerMessage(+ "clear-recording-session",+ (message, sender, sendResponse) => {+ clearRecordingSession();+ sendResponse({ ok: true });+ return true;+ }+ );++ registerMessage(+ "restore-recording-session",+ async (message, sender, sendResponse) => {+ const { recorderSession } = await chrome.storage.local.get([+ "recorderSession",+ ]);+ sendResponse({ recorderSession: recorderSession || null });+ return true;+ }+ );};diff --git a/src/pages/Background/offscreen/offscreenDocument.js b/src/pages/Background/offscreen/offscreenDocument.jsindex c5a2db7..0cb035e 100644--- a/src/pages/Background/offscreen/offscreenDocument.js+++ b/src/pages/Background/offscreen/offscreenDocument.js@@ -38,6 +38,9 @@ const openRecorderTab = async (active: switchTab,}).then((tab) => {+ // Prevent Chrome from discarding this tab during recording+ chrome.tabs.update(tab.id, { autoDiscardable: false }).catch(() => {});+chrome.storage.local.set({recordingTab: tab.id,offscreen: false,diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.jsindex 03170ab..34af7d3 100644--- a/src/pages/Background/recording/recordingHelpers.js+++ b/src/pages/Background/recording/recordingHelpers.js@@ -79,8 +79,19 @@ export const handleRecordingComplete = async () => {};export const handleRecordingError = async (request) => {+ console.log("handleRecordingError called with request:", request);const { activeTab } = await chrome.storage.local.get(["activeTab"]);+ // For stream-ended, we just notify the user but DON'T stop the recording+ // The user can decide whether to continue or stop+ if (request.error === "stream-ended") {+ sendMessageTab(activeTab, {+ type: "stream-ended-warning",+ message: request.why || "Screen sharing stopped unexpectedly.",+ }).catch(() => {});+ return; // Don't continue with the normal error handling+ }+sendMessageRecord({ type: "recording-error" }).then(() => {sendMessageTab(activeTab, { type: "stop-pending" });focusTab(activeTab);diff --git a/src/pages/Background/recording/restoreRecording.js b/src/pages/Background/recording/restoreRecording.jsindex a6bd337..e097af9 100644--- a/src/pages/Background/recording/restoreRecording.js+++ b/src/pages/Background/recording/restoreRecording.js@@ -15,7 +15,8 @@ export const checkRestore = async () => {};export const restoreRecording = async () => {- const hasWebCodecs = supportsWebCodecs();+ //const hasWebCodecs = supportsWebCodecs();+ const hasWebCodecs = false; // FLAG: Force old FFMPEG for nowlet editorUrl, messageType;diff --git a/src/pages/Background/recording/sendMessageRecord.js b/src/pages/Background/recording/sendMessageRecord.jsindex b578bdd..f12858c 100644--- a/src/pages/Background/recording/sendMessageRecord.js+++ b/src/pages/Background/recording/sendMessageRecord.js@@ -4,6 +4,10 @@ export const sendMessageRecord = (message, responseCallback = null) => {return new Promise((resolve, reject) => {chrome.storage.local.get(["recordingTab", "offscreen"], (result) => {if (chrome.runtime.lastError) {+ console.warn(+ "sendMessageRecord: storage error",+ chrome.runtime.lastError.message+ );return reject(chrome.runtime.lastError.message);}@@ -15,10 +19,40 @@ export const sendMessageRecord = (message, responseCallback = null) => {responseCallback ? responseCallback(response) : resolve(response);}});- } else {+ } else if (result.recordingTab) {sendMessageTab(result.recordingTab, message, responseCallback).then(resolve)- .catch(reject);+ .catch((err) => {+ console.warn(+ "sendMessageRecord: failed to message recordingTab",+ result.recordingTab,+ err+ );+ reject(err);+ });+ } else {+ // No recordingTab set - check if there's an active recorderSession+ // This can happen if the service worker restarted and lost in-memory state+ chrome.storage.local.get(["recorderSession"], (sessionResult) => {+ if (+ sessionResult.recorderSession &&+ sessionResult.recorderSession.tabId+ ) {+ // Try the tab from the persisted session+ sendMessageTab(+ sessionResult.recorderSession.tabId,+ message,+ responseCallback+ )+ .then(resolve)+ .catch(reject);+ } else {+ console.warn(+ "sendMessageRecord: no recordingTab or recorderSession available"+ );+ reject(new Error("No recording tab available"));+ }+ });}});});diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.jsindex 1939146..4c1e796 100644--- a/src/pages/Background/recording/stopRecording.js+++ b/src/pages/Background/recording/stopRecording.js@@ -29,7 +29,9 @@ export const stopRecording = async () => {chrome.storage.local.set({ recordingStartTime: 0 });// Check if browser supports WebCodecs for Mediabunny- const hasWebCodecs = supportsWebCodecs();+ //const hasWebCodecs = supportsWebCodecs();+ // FLAG: Force old FFMPEG for now+ const hasWebCodecs = false;if (isSubscribed) {chrome.alarms.clear("recording-alarm");diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex 448e4e5..589764f 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -31,6 +31,7 @@ const CloudRecorder = () => {const isTab = useRef(false);const tabID = useRef(null);+ const recordingTabId = useRef(null);const tabPreferred = useRef(false);const screenStream = useRef(null);@@ -74,6 +75,23 @@ const CloudRecorder = () => {const consecutiveScreenFailures = useRef(0);const consecutiveCameraFailures = useRef(0);+ const firstChunkTime = useRef(null);++ const recorderSession = useRef(null);+ const sessionHeartbeat = useRef(null);+ const chunkStallTimer = useRef(null);+ const uploadHeartbeatTimer = useRef(null);+ const lastUploadProgress = useRef({+ screen: 0,+ camera: 0,+ ts: 0,+ });+ const stallNotified = useRef(false);+ const fatalErrorRef = useRef(false);+ const idbReadyRef = useRef(false);+ const recoveryAttempted = useRef(false);+ const screenTrackLostRef = useRef(false);+ const screenTrackMonitor = useRef(null);// This checks if the recording was previously initializedconst isInit = useRef(false);@@ -82,24 +100,425 @@ const CloudRecorder = () => {const destination = useRef(null);const keepAliveInterval = useRef(null);+ const keepAliveAudioCtx = useRef(null);+ const keepAliveOscillator = useRef(null);++ // Note: We no longer try to "keep alive" the service worker with pings.+ // Instead, we persist recording state to chrome.storage.local so the SW can+ // recover context when it restarts. The CloudRecorder tab is the source of truth.+ // However, we DO need to keep the tab itself alive using silent audio to prevent+ // Chrome from freezing/discarding this background tab.++ /**+ * Start silent audio playback to prevent Chrome from freezing this tab.+ * Chrome throttles/freezes background tabs after ~5 minutes of inactivity,+ * which would stop our recording. Playing silent audio keeps the tab active.+ */+ const startTabKeepAlive = () => {+ try {+ if (keepAliveAudioCtx.current) return; // Already running- const startKeepAlive = () => {- if (keepAliveInterval.current) clearInterval(keepAliveInterval.current);+ const ctx = new (window.AudioContext || window.webkitAudioContext)();+ keepAliveAudioCtx.current = ctx;- keepAliveInterval.current = setInterval(async () => {- try {- const auth = await chrome.runtime.sendMessage({ type: "refresh-auth" });+ // Create a silent oscillator (inaudible frequency at zero gain)+ const oscillator = ctx.createOscillator();+ const gainNode = ctx.createGain();++ oscillator.frequency.value = 0; // DC signal (no audible tone)+ gainNode.gain.value = 0; // Completely silent++ oscillator.connect(gainNode);+ gainNode.connect(ctx.destination);+ oscillator.start();++ keepAliveOscillator.current = oscillator;++ // Also request that Chrome not discard this tab+ chrome.runtime.sendMessage({+ type: "set-tab-auto-discardable",+ discardable: false,+ });++ console.log("[CloudRecorder] Tab keep-alive started");+ } catch (err) {+ console.warn("[CloudRecorder] Failed to start tab keep-alive:", err);+ }+ };++ /**+ * Stop the silent audio playback when recording ends.+ */+ const stopTabKeepAlive = () => {+ try {+ if (keepAliveOscillator.current) {+ keepAliveOscillator.current.stop();+ keepAliveOscillator.current.disconnect();+ keepAliveOscillator.current = null;+ }+ if (keepAliveAudioCtx.current) {+ keepAliveAudioCtx.current.close();+ keepAliveAudioCtx.current = null;+ }- if (!auth?.authenticated) {- console.warn("Auth expired or refresh failed");- chrome.runtime.sendMessage({ type: "auth-expired" });+ // Allow Chrome to discard this tab again if needed+ chrome.runtime.sendMessage({+ type: "set-tab-auto-discardable",+ discardable: true,+ });++ console.log("[CloudRecorder] Tab keep-alive stopped");+ } catch (err) {+ console.warn("[CloudRecorder] Failed to stop tab keep-alive:", err);+ }+ };++ const logScreenTrackEvent = async (event, track) => {+ try {+ const settings = track?.getSettings?.() || {};+ const now = Date.now();+ const data = {+ event,+ ts: now,+ label: track?.label || null,+ readyState: track?.readyState || null,+ muted: track?.muted || false,+ settings,+ };+ const { screenTrackLog = [] } = await chrome.storage.local.get([+ "screenTrackLog",+ ]);+ const next = [...screenTrackLog, data].slice(-50);+ chrome.storage.local.set({ screenTrackLog: next });+ } catch (err) {+ console.warn("Failed to log screen track event", err);+ }+ };++ const bindScreenTrack = (track) => {+ if (!track) return;+ screenTrackLostRef.current = false;+ logScreenTrackEvent("track-start", track);++ track.onended = () => {+ screenTrackLostRef.current = true;+ logScreenTrackEvent("track-ended", track);+ const label = track?.label || null;++ // Collect diagnostic info to understand WHY the track ended+ const diagnosticInfo = {+ reason: "screen-track-ended",+ tabId: recordingTabId.current || null,+ label,+ readyState: track?.readyState || null,+ ts: Date.now(),+ isTab: isTab.current,+ recordingType: recordingType.current,+ isIframe: IS_IFRAME_CONTEXT,+ documentHidden: document.hidden,+ documentVisibility: document.visibilityState,+ recorderState: screenRecorder.current?.state || null,+ hasChunks: hasChunks.current,+ chunkCount: index.current,+ lastChunkTime: lastTimecode.current,+ timeSinceLastChunk: lastTimecode.current+ ? Date.now() - lastTimecode.current+ : null,+ };++ console.error("🔴 Screen track ended unexpectedly!", diagnosticInfo);++ chrome.storage.local.set({+ screenTrackLost: true,+ lastTrackEndedEvent: diagnosticInfo,+ lastTrackEnded: diagnosticInfo,+ });++ // When screen track ends, we MUST stop the recording+ // Otherwise we'd be recording black/frozen video with no way for user to know+ if (!isFinishing.current && !sentLast.current) {+ console.warn("⚠️ Screen track ended - stopping recording");+ stopRecording(true, "screen-track-ended");+ }+ };++ track.onmute = () => {+ screenTrackLostRef.current = true;+ logScreenTrackEvent("track-muted", track);+ };+ track.onunmute = () => {+ screenTrackLostRef.current = false;+ logScreenTrackEvent("track-unmuted", track);+ };++ startScreenTrackMonitor();+ };++ const startScreenTrackMonitor = () => {+ if (screenTrackMonitor.current) clearInterval(screenTrackMonitor.current);+ screenTrackMonitor.current = setInterval(() => {+ const track = screenStream.current?.getVideoTracks?.()[0] || null;+ if (!track) return;+ if (track.readyState === "ended" && !screenTrackLostRef.current) {+ screenTrackLostRef.current = true;+ logScreenTrackEvent("monitor-ended", track);++ // Stop the recording when track dies+ if (!isFinishing.current && !sentLast.current) {+ console.warn(+ "⚠️ Screen track monitor detected ended track - stopping recording"+ );+ stopRecording(true, "screen-track-monitor-ended");}- } catch (err) {- console.error("❌ Failed to check auth via background", err);}- }, 1000 * 60 * 5); // every 5 minutes+ }, 5000);+ };++ const ensureChunkStoreReady = async () => {+ if (idbReadyRef.current) return true;+ try {+ await chunksStore.setItem("__probe", { ts: Date.now() });+ await chunksStore.removeItem("__probe");+ idbReadyRef.current = true;+ return true;+ } catch (err) {+ fatalErrorRef.current = true;+ sendRecordingError(+ "Local storage is blocked (IndexedDB unavailable). Recording cannot start."+ );+ return false;+ }};+ const persistSessionState = async (overrides = {}) => {+ if (!recorderSession.current) return;+ const nextState = {+ ...recorderSession.current,+ lastChunkIndex: index.current - 1,+ lastChunkTime: lastTimecode.current || null,+ lastUploadOffset: {+ screen: screenUploader.current?.offset || 0,+ camera: cameraUploader.current?.offset || 0,+ },+ updatedAt: Date.now(),+ ...overrides,+ };+ recorderSession.current = nextState;+ try {+ await chrome.storage.local.set({ recorderSession: nextState });+ } catch (err) {+ console.warn("Failed to persist recorder session state:", err);+ }+ };++ const startRecorderSession = async (meta = {}) => {+ const session = {+ id: crypto.randomUUID(),+ startedAt: Date.now(),+ tabId: recordingTabId.current || null,+ tabCaptureId: tabID.current || null,+ isTab: isTab.current,+ region: Boolean(regionRef.current),+ status: "recording",+ ...meta,+ };+ recorderSession.current = session;+ await chrome.storage.local.set({ recorderSession: session });+ try {+ const result = await chrome.runtime.sendMessage({+ type: "register-recording-session",+ session,+ });+ if (result?.ok === false) {+ fatalErrorRef.current = true;+ recorderSession.current = null;+ chrome.storage.local.remove("recorderSession");+ sendRecordingError(+ result?.error ||+ "Another Screenity recorder is already running. Please close it and try again."+ );+ return false;+ }+ } catch (err) {+ console.warn(+ "Failed to register recording session with background:",+ err+ );+ }+ return true;+ };++ const finalizeRecorderSession = async (status = "completed") => {+ if (!recorderSession.current) return;+ await chrome.storage.local.set({+ recorderSession: {+ ...recorderSession.current,+ status,+ finishedAt: Date.now(),+ },+ });+ chrome.runtime.sendMessage({ type: "clear-recording-session" });+ recorderSession.current = null;+ };++ const startChunkWatchdog = () => {+ if (chunkStallTimer.current) clearInterval(chunkStallTimer.current);+ chunkStallTimer.current = setInterval(() => {+ if (!hasChunks.current || fatalErrorRef.current) return;+ const last = lastTimecode.current || 0;+ if (!last) return;+ if (Date.now() - last > 15000) {+ if (!stallNotified.current) {+ stallNotified.current = true;+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "stream-warning",+ why: "No video data received for 15 seconds. Recording may be stalled.",+ });+ }+ }+ }, 5000);+ };++ const startUploadHeartbeat = () => {+ if (uploadHeartbeatTimer.current)+ clearInterval(uploadHeartbeatTimer.current);+ uploadHeartbeatTimer.current = setInterval(() => {+ const now = Date.now();+ const screenOffset = screenUploader.current?.offset || 0;+ const cameraOffset = cameraUploader.current?.offset || 0;+ const { screen, camera, ts } = lastUploadProgress.current;++ if (screenOffset !== screen || cameraOffset !== camera) {+ lastUploadProgress.current = {+ screen: screenOffset,+ camera: cameraOffset,+ ts: now,+ };+ stallNotified.current = false;+ persistSessionState();+ return;+ }++ if (+ hasChunks.current &&+ ts &&+ now - ts > 30000 &&+ !stallNotified.current+ ) {+ stallNotified.current = true;+ chrome.runtime.sendMessage({+ type: "upload-stalled",+ offset: { screen: screenOffset, camera: cameraOffset },+ });+ } else if (+ hasChunks.current &&+ stallNotified.current &&+ ts &&+ now - ts > 45000+ ) {+ exportLocalRecovery("upload-stalled");+ }+ }, 5000);+ };++ const stopAllIntervals = () => {+ if (sessionHeartbeat.current) clearInterval(sessionHeartbeat.current);+ if (chunkStallTimer.current) clearInterval(chunkStallTimer.current);+ if (uploadHeartbeatTimer.current)+ clearInterval(uploadHeartbeatTimer.current);+ if (screenTrackMonitor.current) clearInterval(screenTrackMonitor.current);+ sessionHeartbeat.current = null;+ chunkStallTimer.current = null;+ uploadHeartbeatTimer.current = null;+ screenTrackMonitor.current = null;+ };++ const exportLocalRecovery = async (reason = "upload failed") => {+ try {+ let blob =+ createBlobFromChunks(screenChunks.current, "video/webm") ||+ createBlobFromChunks(cameraChunks.current, "video/webm");+ if (!blob) {+ const recovered = [];+ await chunksStore.iterate((value) => {+ recovered.push(value);+ });+ recovered.sort((a, b) => a.index - b.index);+ blob = createBlobFromChunks(+ recovered.map((c) => c.chunk),+ "video/webm"+ );+ }+ if (!blob) return;+ const objectUrl = URL.createObjectURL(blob);+ try {+ await chrome.downloads.download({+ url: objectUrl,+ filename: `Screenity-Recovery-${new Date().toISOString()}-${reason}.webm`,+ saveAs: false,+ });+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: "Upload stalled. A recovery file was saved locally.",+ });+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+ } catch (err) {+ console.warn("Failed to export local recovery:", err);+ }+ };++ const tryRecoverPreviousSession = useCallback(async () => {+ if (recoveryAttempted.current) return;+ recoveryAttempted.current = true;+ try {+ const { recorderSession: storedSession } = await chrome.storage.local.get(+ ["recorderSession"]+ );++ const chunkCount = await chunksStore.length().catch(() => 0);+ if (+ storedSession &&+ storedSession.status === "recording" &&+ chunkCount > 0+ ) {+ const recovered = [];+ await chunksStore.iterate((value) => {+ recovered.push(value);+ });+ recovered.sort((a, b) => a.index - b.index);+ const blob = createBlobFromChunks(+ recovered.map((c) => c.chunk),+ "video/webm"+ );+ if (blob) {+ const objectUrl = URL.createObjectURL(blob);+ try {+ await chrome.downloads.download({+ url: objectUrl,+ filename: `Screenity-Recovered-${new Date().toISOString()}.webm`,+ saveAs: false,+ });+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: "Recovered unsaved recording from the previous session.",+ });+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+ }+ await chunksStore.clear();+ await chrome.storage.local.set({+ recorderSession: { ...storedSession, status: "recovered" },+ });+ }+ } catch (err) {+ console.warn("Recovery check failed:", err);+ }+ }, []);+const attachMicToStream = (videoStream, micStream) => {if (!videoStream || !micStream) return videoStream;return new MediaStream([@@ -113,7 +532,7 @@ const CloudRecorder = () => {const minMemory = 26214400;if (data.quota < minMemory) {chrome.storage.local.set({ memoryError: true });- sendStopRecording();+ sendStopRecording("low-storage-quota");}});};@@ -206,6 +625,9 @@ const CloudRecorder = () => {const dismissRecording = async (restarting = false) => {setInitProject(false);+ // Stop the silent audio keep-alive+ stopTabKeepAlive();+const { projectId, multiMode, multiSceneCount, recordingToScene } =await chrome.storage.local.get(["projectId",@@ -238,6 +660,7 @@ const CloudRecorder = () => {}cleanupTimers();+ stopAllIntervals();isRestarting.current = true;@@ -275,7 +698,8 @@ const CloudRecorder = () => {uploadMetaRef.current = null;- window.close();+ // FLAG: decide whether to close or not+ //window.close();return;}@@ -301,7 +725,9 @@ const CloudRecorder = () => {}uploadMetaRef.current = null;isInit.current = false;- window.close();++ // FLAG: decide whether to close or not+ //window.close();};const restartRecording = async () => {@@ -340,8 +766,29 @@ const CloudRecorder = () => {throw new Error("Missing projectId");}+ const onStall = (payload) => {+ stallNotified.current = true;+ chrome.runtime.sendMessage({+ type: "upload-stalled",+ offset: {+ screen: payload?.offset || screenUploader.current?.offset || 0,+ camera: cameraUploader.current?.offset || 0,+ },+ });+ };+if (screenStream.current) {- screenUploader.current = new BunnyTusUploader();+ screenUploader.current = new BunnyTusUploader({+ onProgress: ({ offset }) => {+ lastUploadProgress.current = {+ ...lastUploadProgress.current,+ screen: offset,+ ts: Date.now(),+ };+ persistSessionState();+ },+ onStall,+ });const track = screenStream.current.getVideoTracks()[0];let width, height;if (regionRef.current && target.current) {@@ -362,7 +809,17 @@ const CloudRecorder = () => {}if (cameraStream.current) {- cameraUploader.current = new BunnyTusUploader();+ cameraUploader.current = new BunnyTusUploader({+ onProgress: ({ offset }) => {+ lastUploadProgress.current = {+ ...lastUploadProgress.current,+ camera: offset,+ ts: Date.now(),+ };+ persistSessionState();+ },+ onStall,+ });const track = cameraStream.current.getVideoTracks()[0];if (track?.readyState === "ended") {throw new Error("Camera track has ended");@@ -410,7 +867,21 @@ const CloudRecorder = () => {const startRecording = async () => {setInitProject(false);- startKeepAlive();+ // Start silent audio to prevent Chrome from freezing this background tab+ startTabKeepAlive();++ const storageReady = await ensureChunkStoreReady();+ if (!storageReady) return;++ const pinned = await chrome.runtime+ .sendMessage({ type: "is-pinned" })+ .catch(() => true);+ if (pinned === false) {+ sendRecordingError(+ "Screenity must stay pinned to record. Pin the extension and try again."+ );+ return;+ }if (!uploadersInitialized.current) {sendRecordingError(@@ -431,12 +902,38 @@ const CloudRecorder = () => {return;}+ if (isTab.current && recordingTabId.current) {+ const tabAlive = await chrome.tabs+ .get(recordingTabId.current)+ .then(() => true)+ .catch(() => false);+ if (!tabAlive) {+ sendRecordingError(+ "The tab you selected for recording was closed. Please start again."+ );+ return;+ }+ }++ if (!recorderSession.current) {+ const registered = await startRecorderSession({ projectId });+ if (!registered) return;+ }+if (!screenUploader.current && !cameraUploader.current) {sendRecordingError("Uploaders not ready. Please restart recording.");return;}- await chunksStore.clear();+ try {+ await chunksStore.clear();+ } catch (err) {+ fatalErrorRef.current = true;+ sendRecordingError(+ "Unable to initialize local buffer (IndexedDB issue)."+ );+ return;+ }lastTimecode.current = 0;hasChunks.current = false;index.current = 0;@@ -476,7 +973,7 @@ const CloudRecorder = () => {sendRecordingError("Recording failed - no video data being captured. Please try again.");- sendStopRecording();+ sendStopRecording("empty-screen-chunk");}return;}@@ -489,17 +986,29 @@ const CloudRecorder = () => {if (!hasChunks.current) {hasChunks.current = true;lastTimecode.current = timestamp;+ firstChunkTime.current = timestamp;} else if (timestamp < lastTimecode.current) {return; // Skip duplicate} else {lastTimecode.current = timestamp;}- await chunksStore.setItem(`chunk_${index.current}`, {- index: index.current,- chunk: blob,- timestamp,- });+ await chunksStore+ .setItem(`chunk_${index.current}`, {+ index: index.current,+ chunk: blob,+ timestamp,+ })+ .catch((err) => {+ fatalErrorRef.current = true;+ sendRecordingError(+ "Could not buffer recording data locally (IndexedDB blocked)."+ );+ sendStopRecording();+ throw err;+ });++ persistSessionState({ lastChunkIndex: index.current });if (uploadersInitialized.current && screenUploader.current) {try {@@ -515,10 +1024,11 @@ const CloudRecorder = () => {console.error("Failed to upload chunk to Bunny:", uploadErr);consecutiveScreenFailures.current++;if (consecutiveScreenFailures.current > 3) {+ stallNotified.current = true;sendRecordingError(- "Screen upload failed repeatedly. Stopping recording."+ "Screen upload failed repeatedly. Continuing locally; upload will retry on finalize.");- sendStopRecording();+ screenUploader.current?.pause?.();}}}@@ -537,14 +1047,7 @@ const CloudRecorder = () => {// Start recording with 2-second time slicesscreenRecorder.current.start(2000);- screenStream.current.getVideoTracks()[0].onended = () => {- chrome.storage.local.set({- recording: false,- restarting: false,- });- cleanupTimers();- sendStopRecording();- };+ bindScreenTrack(screenStream.current.getVideoTracks()[0]);}// Audio recorder setup (for transcription)@@ -616,8 +1119,10 @@ const CloudRecorder = () => {);consecutiveCameraFailures.current++;if (consecutiveCameraFailures.current > 3) {- console.error("Camera upload failing repeatedly");- // Don't stop recording, just log - camera is secondary+ console.error(+ "Camera upload failing repeatedly; pausing camera uploader"+ );+ cameraUploader.current?.pause?.();}}}@@ -660,7 +1165,7 @@ const CloudRecorder = () => {chrome.runtime.sendMessage({type: "time-stopped",});- sendStopRecording();+ sendStopRecording("max-duration");}}, 1000);@@ -669,6 +1174,7 @@ const CloudRecorder = () => {screenTimer.current.warned = warned;chrome.storage.local.set({ recording: true });+ persistSessionState({ status: "recording" });setStarted(true);} catch (err) {sendRecordingError("Recording failed: " + err.message);@@ -685,6 +1191,14 @@ const CloudRecorder = () => {cameraTimer.current.paused = false;cameraTimer.current.total = 0;}++ lastUploadProgress.current = {+ screen: screenUploader.current?.offset || 0,+ camera: cameraUploader.current?.offset || 0,+ ts: Date.now(),+ };+ startChunkWatchdog();+ startUploadHeartbeat();};function cleanupTimers() {@@ -773,6 +1287,10 @@ const CloudRecorder = () => {return {screen: getDuration(screenTimer.current),camera: getDuration(cameraTimer.current),+ fallbackMs:+ firstChunkTime.current && lastTimecode.current+ ? Math.max(0, lastTimecode.current - firstChunkTime.current)+ : null,};};@@ -820,16 +1338,26 @@ const CloudRecorder = () => {};useEffect(() => {- const onHide = () => {+ const onHide = (event) => {+ // Only finalize if the page is actually being unloaded (persisted = false)+ // Don't finalize just because the tab went to background+ // event.persisted indicates if the page might be restored from bfcache+ const isActualUnload = !event.persisted;+// Only finalize if an active recording really existsconst hasActiveRecorder =screenRecorder.current?.state === "recording" ||cameraRecorder.current?.state === "recording" ||audioRecorder.current?.state === "recording";- if (hasActiveRecorder && !sentLast.current) {- console.warn("⚠️ Recorder page hiding — finalizing");- stopRecording(true);+ if (hasActiveRecorder && !sentLast.current && isActualUnload) {+ console.warn("⚠️ Recorder page unloading — finalizing");+ // Use sendBeacon or sync storage write for reliability+ navigator.sendBeacon?.(+ `${API_BASE}/log/recorder-unload`,+ JSON.stringify({ reason: "pagehide", ts: Date.now() })+ );+ stopRecording(true, "pagehide-unload");}};@@ -837,6 +1365,45 @@ const CloudRecorder = () => {return () => window.removeEventListener("pagehide", onHide);}, []);+ useEffect(() => {+ const onVisibilityChange = () => {+ if (document.visibilityState === "hidden") {+ persistSessionState({ status: "hidden" });+ }+ };++ const onBeforeUnload = () => {+ if (hasChunks.current) {+ persistSessionState({ status: "unload" });+ }+ };++ document.addEventListener("visibilitychange", onVisibilityChange);+ window.addEventListener("beforeunload", onBeforeUnload);++ return () => {+ document.removeEventListener("visibilitychange", onVisibilityChange);+ window.removeEventListener("beforeunload", onBeforeUnload);+ };+ }, []);++ useEffect(() => {+ tryRecoverPreviousSession();+ }, [tryRecoverPreviousSession]);++ useEffect(() => {+ return () => {+ stopAllIntervals();+ stopTabKeepAlive(); // Clean up keep-alive on unmount+ };+ }, []);++ useEffect(() => {+ return () => {+ stopAllIntervals();+ };+ }, []);+const createSceneOrHandleMultiMode = async (uploadMeta,durations,@@ -987,14 +1554,37 @@ const CloudRecorder = () => {return avg < silenceThreshold; // true if basically silent};- const stopRecording = async (shouldFinalize = true) => {+ const stopRecording = async (shouldFinalize = true, reason = "unknown") => {if (isFinishing.current || sentLast.current) return;+ console.debug("[Screenity] stopRecording invoked", {+ reason,+ shouldFinalize,+ screenState: screenRecorder.current?.state,+ cameraState: cameraRecorder.current?.state,+ audioState: audioRecorder.current?.state,+ screenOffset: screenUploader.current?.offset || 0,+ cameraOffset: cameraUploader.current?.offset || 0,+ chunkCount: screenChunks.current.length + cameraChunks.current.length,+ });+ chrome.storage.local.set({+ lastStopRecordingEvent: {+ reason,+ screenOffset: screenUploader.current?.offset || 0,+ cameraOffset: cameraUploader.current?.offset || 0,+ chunkCount: screenChunks.current.length + cameraChunks.current.length,+ ts: Date.now(),+ },+ });+if (keepAliveInterval.current) {clearInterval(keepAliveInterval.current);keepAliveInterval.current = null;}+ // Stop the silent audio keep-alive since we're done recording+ stopTabKeepAlive();+const { projectId, recordingToScene, multiMode } =await chrome.storage.local.get(["projectId",@@ -1002,6 +1592,8 @@ const CloudRecorder = () => {"multiMode",]);+ await persistSessionState({ status: "stopping" });+if (shouldFinalize) {if (recordingToScene) {chrome.runtime.sendMessage({@@ -1021,6 +1613,7 @@ const CloudRecorder = () => {}isFinishing.current = true;chrome.storage.local.set({ recording: false });+ stopAllIntervals();await stopAllRecorders();@@ -1028,10 +1621,16 @@ const CloudRecorder = () => {await flushPendingChunks();- await Promise.allSettled([- screenUploader.current?.finalize?.(),- cameraUploader.current?.finalize?.(),- ]);+ let finalizeError = null;+ try {+ await Promise.allSettled([+ screenUploader.current?.finalize?.(),+ cameraUploader.current?.finalize?.(),+ ]);+ } catch (err) {+ finalizeError = err;+ console.warn("Finalize threw an error:", err);+ }const { sceneId } = await chrome.storage.local.get(["sceneId"]);@@ -1051,27 +1650,57 @@ const CloudRecorder = () => {cleanupTimers();- if (!shouldFinalize) return;+ if (!shouldFinalize) {+ await finalizeRecorderSession("cancelled");+ return;+ }++ if (finalizeError) {+ await exportLocalRecovery("finalize-error");+ await finalizeRecorderSession("failed");+ sendRecordingError(+ "Upload failed to finalize. A recovery copy was downloaded."+ );+ return;+ }// Validate that at least one media source was successfully uploaded+ const hasAnyScreenData = (uploadMeta.screen?.offset || 0) > 0;+ const hasAnyCameraData = (uploadMeta.camera?.offset || 0) > 0;const hasValidScreen =- uploadMeta.screen?.status === "completed" &&+ hasAnyScreenData &&uploadMeta.screen?.mediaId &&uploadMeta.screen?.videoId;const hasValidCamera =- uploadMeta.camera?.status === "completed" &&+ hasAnyCameraData &&uploadMeta.camera?.mediaId &&uploadMeta.camera?.videoId;// Warn if upload size seems suspiciously small for recording durationconst screenDuration = durations.screen || 0;const cameraDuration = durations.camera || 0;- if (hasValidScreen && screenDuration > 5) {+ const fallbackSeconds = durations.fallbackMs+ ? durations.fallbackMs / 1000+ : 0;+ const effectiveScreenDuration =+ screenDuration < MIN_DURATION_SECONDS && fallbackSeconds > 0+ ? fallbackSeconds+ : screenDuration;+ const effectiveCameraDuration =+ cameraDuration < MIN_DURATION_SECONDS && fallbackSeconds > 0+ ? fallbackSeconds+ : cameraDuration;++ const usedDurations = {+ screen: effectiveScreenDuration || screenDuration,+ camera: effectiveCameraDuration || cameraDuration,+ };+ if (hasValidScreen && effectiveScreenDuration > 5) {const screenOffset = uploadMeta.screen?.offset || 0;- const minExpectedSize = screenDuration * 50000; // ~50KB/sec minimum+ const minExpectedSize = effectiveScreenDuration * 50000; // ~50KB/sec minimumif (screenOffset < minExpectedSize) {console.warn(- `⚠️ Screen upload size (${screenOffset} bytes) seems small for ${screenDuration}s recording. Expected at least ${minExpectedSize} bytes.`+ `⚠️ Screen upload size (${screenOffset} bytes) seems small for ${effectiveScreenDuration}s recording. Expected at least ${minExpectedSize} bytes.`);}}@@ -1083,9 +1712,20 @@ const CloudRecorder = () => {const cameraOffset = uploadMeta.camera?.offset || 0;const screenError = uploadMeta.screen?.error || "none";const cameraError = uploadMeta.camera?.error || "none";- throw new Error(- `No media was successfully uploaded. Screen: ${screenStatus} (${screenOffset} bytes, error: ${screenError}), Camera: ${cameraStatus} (${cameraOffset} bytes, error: ${cameraError})`- );+ // If we see bytes on Bunny (offset > 0) but status is not completed, treat as success with a warning.+ if (hasAnyScreenData || hasAnyCameraData) {+ console.warn(+ "Uploads have data but were not marked completed. Proceeding with scene creation.",+ { screenStatus, cameraStatus, screenOffset, cameraOffset }+ );+ } else {+ await exportLocalRecovery("no-upload");+ await finalizeRecorderSession("failed");+ sendRecordingError(+ `No media was successfully uploaded. Screen: ${screenStatus} (${screenOffset} bytes, error: ${screenError}), Camera: ${cameraStatus} (${cameraOffset} bytes, error: ${cameraError})`+ );+ return;+ }}// Create final audio blob from chunks@@ -1102,19 +1742,22 @@ const CloudRecorder = () => {sentLast.current = true;const silent = audioBlob ? await isAudioSilent(audioBlob) : true;try {- await createSceneOrHandleMultiMode(uploadMeta, durations, silent);+ await createSceneOrHandleMultiMode(uploadMeta, usedDurations, silent);if (!silent && audioBlob) {await handleTranscription(uploadMeta, projectId);}chrome.runtime.sendMessage({ type: "video-ready", uploadMeta });+ await chunksStore.clear().catch(() => {});if (!IS_IFRAME_CONTEXT) {- window.close();+ // FLAG: decide whether to close or not+ //window.close();} else {window.location.reload();}+ await finalizeRecorderSession("completed");} catch (err) {console.error("❌ Failed to create scene:", err);@@ -1148,11 +1791,14 @@ const CloudRecorder = () => {// Give user time to see the error messagesetTimeout(() => {if (!IS_IFRAME_CONTEXT) {- window.close();+ // FLAG: decide whether to close or not+ //window.close();} else {window.location.reload();}}, 3000);+ await exportLocalRecovery("scene-error");+ await finalizeRecorderSession("failed");}}};@@ -1250,13 +1896,7 @@ const CloudRecorder = () => {src.connect(ctx.destination);}- screenStream.current.getVideoTracks()[0].onended = () => {- chrome.storage.local.set({- recording: false,- restarting: false,- });- sendStopRecording();- };+ bindScreenTrack(screenStream.current.getVideoTracks()[0]);} catch (err) {sendRecordingError("Failed to access region stream: " + err.message);return;@@ -1395,13 +2035,7 @@ const CloudRecorder = () => {src.connect(ctx.destination);}- screenStream.current.getVideoTracks()[0].onended = () => {- chrome.storage.local.set({- recording: false,- restarting: false,- });- sendStopRecording();- };+ bindScreenTrack(screenStream.current.getVideoTracks()[0]);} catch (err) {sendRecordingError("Failed to access screen stream: " + err.message);return;@@ -1642,6 +2276,7 @@ const CloudRecorder = () => {} else if (!request.region) {if (!tabPreferred.current) {isTab.current = request.isTab;+ recordingTabId.current = request.tabID || null;if (request.isTab) getStreamID(request.tabID);} else {isTab.current = false;@@ -1673,7 +2308,7 @@ const CloudRecorder = () => {}} else if (request.type === "stop-recording-tab") {if (!isInit.current) return;- stopRecording();+ stopRecording(true, request.reason || "message-stop");} else if (request.type === "set-mic-active-tab") {if (!isInit.current) return;setMic(request);diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.jsindex 8fae54b..6286a10 100644--- a/src/pages/CloudRecorder/bunnyTusUploader.js+++ b/src/pages/CloudRecorder/bunnyTusUploader.js@@ -59,8 +59,13 @@ export default class BunnyTusUploader {this.CHUNK_SIZE = options.chunkSize || 512 * 1024; // 512KB defaultthis.MAX_RETRIES = options.maxRetries || 5;this.RETRY_DELAY = options.retryDelay || 1000;+ this.UPLOAD_TIMEOUT_MS = options.uploadTimeoutMs || 20000;+ this.HEARTBEAT_INTERVAL_MS = options.heartbeatIntervalMs || 10000;+ this.HEARTBEAT_LAG_MS = options.heartbeatLagMs || 30000;this.TOKEN_REFRESH_THRESHOLD = options.tokenRefreshThreshold || 300;this.MAX_QUEUE_SIZE = options.maxQueueSize || 100;+ this.onProgress = options.onProgress || null;+ this.onStall = options.onStall || null;this.uploadUrl = null;this.offset = 0;@@ -77,11 +82,15 @@ export default class BunnyTusUploader {this.metadata = {};this.pendingUploads = [];this.userToken = null;+ this.heartbeatTimer = null;+ this.lastProgressAt = Date.now();+ this.stalled = false;this.chunkQueue = [];this.isProcessingQueue = false;this.queueProcessingPromise = null;this.queuedBytes = 0;+ this._hasExtractedMeta = true; // Skip in-flight thumbnail extraction to avoid timeouts/noise}async initialize(@@ -160,6 +169,7 @@ export default class BunnyTusUploader {await this.refreshTusAuth();await this.initTusUpload();+ this.startHeartbeat();this.status = "ready";return { videoId: this.videoId, mediaId: this.mediaId };} catch (err) {@@ -246,29 +256,8 @@ export default class BunnyTusUploader {await this.waitForPendingUploads();}- if (!this._hasExtractedMeta && chunk.size > 128 * 1024) {- try {- const blob = new Blob([chunk], { type: "video/webm" });-- if (this.metadata.type === "screen") {- const thumbPromise = getThumbnailFromBlob(blob);-- // Add timeout safety- const safeThumbnail = await Promise.race([- thumbPromise,- new Promise((_, reject) =>- setTimeout(() => reject("thumbnail-timeout"), 1500)- ),- ]);-- this.metaThumbnail = safeThumbnail;- }-- this._hasExtractedMeta = true;- } catch (err) {- console.warn("⚠️ Failed to extract metadata from chunk:", err);- }- }+ // Thumbnail extraction disabled in-flight to reduce timeouts/noise.+ this._hasExtractedMeta = true;}async checkAuthExpiration() {@@ -292,6 +281,12 @@ export default class BunnyTusUploader {const currentOffset = this.offset;this.offset += data.length;+ const controller = new AbortController();+ const timeout = setTimeout(+ () => controller.abort("upload-timeout"),+ this.UPLOAD_TIMEOUT_MS+ );+const res = await fetch(this.uploadUrl, {method: "PATCH",headers: {@@ -304,7 +299,9 @@ export default class BunnyTusUploader {VideoId: this.videoId,},body: data,+ signal: controller.signal,});+ clearTimeout(timeout);if (res.ok || res.status === 204) {// Verify server offset matches our expectation@@ -325,10 +322,28 @@ export default class BunnyTusUploader {this.offset = expectedOffset;}+ this.recordProgress(data.length);return;} else {const errorText = await res.text();+ // If the TUS session was invalidated (404), flag as fatal so callers can fall back.+ if (res.status === 404) {+ this.status = "error";+ this.error = "tus-session-missing";+ this.stalled = true;+ if (typeof this.onStall === "function") {+ this.onStall({+ mediaId: this.mediaId,+ videoId: this.videoId,+ offset: this.offset,+ diff: Date.now() - this.lastProgressAt,+ reason: "tus-404",+ });+ }+ throw new Error("TUS session missing (404).");+ }+// Handle offset mismatch errors (409 Conflict)if (res.status === 409 ||@@ -369,6 +384,9 @@ export default class BunnyTusUploader {throw new Error(`Upload failed (${res.status}): ${errorText}`);}} catch (err) {+ if (err?.name === "AbortError") {+ console.warn("⚠️ Upload chunk timed out");+ }if (attempt === this.MAX_RETRIES) {console.error(`❌ Failed to upload chunk after ${this.MAX_RETRIES} retries:`,@@ -382,8 +400,9 @@ export default class BunnyTusUploader {} failed, retrying...`,err.message);+ const jitter = Math.random() * 300;await new Promise((r) =>- setTimeout(r, this.RETRY_DELAY * Math.pow(2, attempt))+ setTimeout(r, this.RETRY_DELAY * Math.pow(2, attempt) + jitter));}}@@ -434,6 +453,12 @@ export default class BunnyTusUploader {this.isProcessingQueue ||this.pendingUploads.length > 0) {+ if (this.stalled && this.lastProgressAt) {+ const diff = Date.now() - this.lastProgressAt;+ if (diff > this.HEARTBEAT_LAG_MS * 2) {+ break;+ }+ }if (this.chunkQueue.length && !this.isProcessingQueue) {await this.processQueue();}@@ -468,6 +493,34 @@ export default class BunnyTusUploader {);}+ // Re-validate offset with server to avoid partial finalization+ try {+ const headRes = await fetch(this.uploadUrl, {+ method: "HEAD",+ headers: {+ "Tus-Resumable": "1.0.0",+ AuthorizationSignature: this.signature,+ AuthorizationExpire: String(this.expires),+ LibraryId: String(this.libraryId),+ VideoId: this.videoId,+ },+ });++ if (headRes.ok) {+ const serverOffset = parseInt(+ headRes.headers.get("Upload-Offset") || "0"+ );+ if (serverOffset !== this.offset) {+ console.warn(+ `⚠️ Finalize correcting offset from ${this.offset} to ${serverOffset}`+ );+ this.offset = serverOffset;+ }+ }+ } catch (err) {+ console.warn("⚠️ Failed to verify offset before finalize:", err);+ }+const res = await fetch(this.uploadUrl, {method: "PATCH",headers: {@@ -484,6 +537,7 @@ export default class BunnyTusUploader {if (!res.ok && res.status !== 204) throw new Error("Finalization failed");this.status = "completed";+ this.stopHeartbeat();}getMeta() {@@ -503,6 +557,8 @@ export default class BunnyTusUploader {height: this.metaHeight || null,thumbnail: this.metaThumbnail || null,sceneId: this.sceneId || null,+ lastProgressAt: this.lastProgressAt,+ stalled: this.stalled,};}@@ -526,6 +582,65 @@ export default class BunnyTusUploader {this.chunkQueue = [];this.queuedBytes = 0;this.pendingUploads = [];+ this.stopHeartbeat();+ }++ startHeartbeat() {+ this.stopHeartbeat();+ this.lastProgressAt = Date.now();+ this.stalled = false;+ this.heartbeatTimer = setInterval(() => {+ const now = Date.now();+ const diff = now - this.lastProgressAt;+ if (diff > this.HEARTBEAT_LAG_MS) {+ this.stalled = true;+ if (typeof this.onStall === "function") {+ this.onStall({+ mediaId: this.mediaId,+ videoId: this.videoId,+ offset: this.offset,+ diff,+ });+ }+ }+ }, this.HEARTBEAT_INTERVAL_MS);+ }++ stopHeartbeat() {+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);+ this.heartbeatTimer = null;+ }++ recordProgress(bytes) {+ this.lastProgressAt = Date.now();+ this.stalled = false;+ if (typeof this.onProgress === "function") {+ try {+ this.onProgress({+ bytes,+ offset: this.offset,+ videoId: this.videoId,+ mediaId: this.mediaId,+ at: this.lastProgressAt,+ });+ } catch (err) {+ console.warn("Progress callback failed:", err);+ }+ }++ // Journal offsets locally to aid recovery+ if (typeof chrome !== "undefined" && chrome.storage?.local) {+ const key = `uploadJournal-${this.mediaId}`;+ chrome.storage.local.set({+ [key]: {+ offset: this.offset,+ updatedAt: this.lastProgressAt,+ videoId: this.videoId,+ mediaId: this.mediaId,+ stalled: this.stalled,+ },+ });+ }}}diff --git a/src/pages/CloudRecorder/messaging.js b/src/pages/CloudRecorder/messaging.jsindex ea6bd76..8c5ca01 100644--- a/src/pages/CloudRecorder/messaging.js+++ b/src/pages/CloudRecorder/messaging.js@@ -19,8 +19,13 @@ export function sendRecordingError(why, cancel = false) {}export function sendStopRecording(reason = "generic") {+ const payload =+ typeof reason === "string"+ ? { reason }+ : { ...(reason || {}), reason: reason?.reason || "generic" };+chrome.runtime.sendMessage({type: "stop-recording-tab",- reason,+ ...payload,});}diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.jsindex e26170b..0b60d9d 100644--- a/src/pages/Content/context/messaging/handlers.js+++ b/src/pages/Content/context/messaging/handlers.js@@ -82,13 +82,31 @@ export const setupHandlers = () => {}));});- registerMessage("recording-ended", () => {+ registerMessage("recording-ended", async () => {const state = getState();- if (- !state.showPopup- // &&- // !state.pendingRecording- ) {++ // Double-check with storage before resetting UI+ // This prevents false positives when service worker restarts with stale state+ const { recording, recorderSession, pendingRecording } =+ await chrome.storage.local.get([+ "recording",+ "recorderSession",+ "pendingRecording",+ ]);++ const isActuallyRecording =+ recording || (recorderSession && recorderSession.status === "recording");++ // Only reset if we're truly not recording+ if (isActuallyRecording || pendingRecording) {+ // Recording is actually still active - ignore this stale message+ console.warn(+ "Ignoring stale recording-ended message - recording still active"+ );+ return;+ }++ if (!state.showPopup) {setContentState((prev) => ({...prev,showExtension: false,@@ -221,6 +239,20 @@ export const setupHandlers = () => {);});+ registerMessage("stream-ended-warning", (message) => {+ const state = getState();+ // Show a toast warning but don't stop the recording+ // The user can decide whether to continue or stop manually+ if (state.openToast) {+ state.openToast(+ message.message ||+ "Screen sharing stopped. Stop recording to save your video.",+ () => {},+ 10000 // Show for 10 seconds+ );+ }+ });+registerMessage("backup-error", () => {const state = getState();state.openModal(diff --git a/src/pages/Editor/Sandbox.jsx b/src/pages/Editor/Sandbox.jsxindex 61ab577..928f3f0 100644--- a/src/pages/Editor/Sandbox.jsx+++ b/src/pages/Editor/Sandbox.jsx@@ -11,6 +11,7 @@ import hasAudio from "./utils/hasAudio";import muteVideo from "./utils/muteVideo";import reencodeVideo from "./utils/reencodeVideo";import toGIF from "./utils/toGIF";+import toWebM from "./utils/toWebM";const Sandbox = () => {const iframeRef = useRef(null);@@ -108,7 +109,12 @@ const Sandbox = () => {try {const blob = await base64ToBlob(ffmpegInstance.current, message.base64);const base64 = await toBase64(blob);- sendMessage({ type: "updated-blob", base64: base64, topLevel: true });+ sendMessage({+ type: "updated-blob",+ base64: base64,+ topLevel: true,+ edited: false,+ });} catch (error) {sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });}@@ -212,6 +218,26 @@ const Sandbox = () => {} catch (error) {sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });}+ } else if (message.type === "to-webm") {+ try {+ const blob = await toWebM(+ ffmpegInstance.current,+ message.blob,+ message.duration+ );+ const base64 = await toBase64(blob);++ sendMessage({+ type: "download-webm",+ base64,+ topLevel: true,+ });+ } catch (error) {+ sendMessage({+ type: "ffmpeg-error",+ error: JSON.stringify(error),+ });+ }}};diff --git a/src/pages/Editor/utils/toWebM.js b/src/pages/Editor/utils/toWebM.jsnew file mode 100644index 0000000..b349e31--- /dev/null+++ b/src/pages/Editor/utils/toWebM.js@@ -0,0 +1,27 @@+async function toWebM(ffmpeg, blob) {+ const inputData = new Uint8Array(await blob.arrayBuffer());+ ffmpeg.FS("writeFile", "input.mp4", inputData);++ const output = "output.webm";++ await ffmpeg.run(+ "-i",+ "input.mp4",+ "-c:v",+ "libvpx", // VP8 (much faster)+ "-b:v",+ "2M", // higher bitrate = fewer CPU cycles+ "-crf",+ "10", // low compression work+ "-speed",+ "8", // EXTREMELY important for WASM+ "-threads",+ "0",+ "-auto-alt-ref",+ "0", // turn off slow filtering+ output+ );++ const data = ffmpeg.FS("readFile", output);+ return new Blob([data.buffer], { type: "video/webm" });+}diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex bd47f03..ede8416 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -91,6 +91,14 @@ const Recorder = () => {const isRecording = useRef(false);+ // Keep-alive mechanism to prevent Chrome from freezing this background tab+ const keepAliveAudioCtx = useRef(null);+ const keepAliveOscillator = useRef(null);++ // Session state for recovery and diagnostics+ const recordingStartTime = useRef(null);+ const sessionHeartbeat = useRef(null);+debug("Recorder component mounted");async function canFitChunk(byteLength) {@@ -120,6 +128,109 @@ const Recorder = () => {}}+ /**+ * Start silent audio playback to prevent Chrome from freezing this tab.+ * Chrome throttles/freezes background tabs after ~5 minutes of inactivity,+ * which would stop our recording. Playing silent audio keeps the tab active.+ */+ const startTabKeepAlive = () => {+ try {+ if (keepAliveAudioCtx.current) return; // Already running++ const ctx = new (window.AudioContext || window.webkitAudioContext)();+ keepAliveAudioCtx.current = ctx;++ // Create a silent oscillator (inaudible frequency at zero gain)+ const oscillator = ctx.createOscillator();+ const gainNode = ctx.createGain();++ oscillator.frequency.value = 0; // DC signal (no audible tone)+ gainNode.gain.value = 0; // Completely silent++ oscillator.connect(gainNode);+ gainNode.connect(ctx.destination);+ oscillator.start();++ keepAliveOscillator.current = oscillator;++ // Request Chrome not to discard this tab+ chrome.runtime+ .sendMessage({ type: "set-tab-auto-discardable", discardable: false })+ .catch(() => {});++ debug("Tab keep-alive started");+ } catch (err) {+ debugWarn("Failed to start tab keep-alive:", err);+ }+ };++ /**+ * Stop the silent audio playback when recording ends.+ */+ const stopTabKeepAlive = () => {+ try {+ if (keepAliveOscillator.current) {+ keepAliveOscillator.current.stop();+ keepAliveOscillator.current.disconnect();+ keepAliveOscillator.current = null;+ }+ if (keepAliveAudioCtx.current) {+ keepAliveAudioCtx.current.close();+ keepAliveAudioCtx.current = null;+ }++ // Allow Chrome to discard this tab again if needed+ chrome.runtime+ .sendMessage({ type: "set-tab-auto-discardable", discardable: true })+ .catch(() => {});++ debug("Tab keep-alive stopped");+ } catch (err) {+ debugWarn("Failed to stop tab keep-alive:", err);+ }+ };++ /**+ * Persist recording session state for recovery and diagnostics.+ */+ const persistSessionState = async (status = "recording") => {+ try {+ await chrome.storage.local.set({+ freeRecorderSession: {+ status,+ chunkCount: savedCount.current,+ lastChunkTime: lastTimecode.current,+ startedAt: recordingStartTime.current,+ updatedAt: Date.now(),+ },+ });+ } catch (err) {+ debugWarn("Failed to persist session state:", err);+ }+ };++ /**+ * Start a heartbeat to periodically persist session state.+ */+ const startSessionHeartbeat = () => {+ if (sessionHeartbeat.current) clearInterval(sessionHeartbeat.current);+ sessionHeartbeat.current = setInterval(() => {+ if (isRecording.current) {+ persistSessionState("recording");+ }+ }, 10000); // Every 10 seconds+ };++ /**+ * Stop the session heartbeat.+ */+ const stopSessionHeartbeat = () => {+ if (sessionHeartbeat.current) {+ clearInterval(sessionHeartbeat.current);+ sessionHeartbeat.current = null;+ }+ };+async function saveChunk(e, i) {const ts = e.timecode ?? 0;@@ -251,6 +362,12 @@ const Recorder = () => {debug("startRecording()");+ // Start silent audio to prevent Chrome from freezing this background tab+ startTabKeepAlive();++ // Record the start time for session tracking+ recordingStartTime.current = Date.now();+navigator.storage.persist();if (!helperVideoStream.current ||@@ -258,6 +375,7 @@ const Recorder = () => {) {debugError("No video tracks available in helperVideoStream");sendRecordingError("No video tracks available");+ stopTabKeepAlive();return;}@@ -286,7 +404,7 @@ const Recorder = () => {});// FLAG: Force old MediaRecorder for testing- const FORCE_MEDIARECORDER = false;+ const FORCE_MEDIARECORDER = true;const canUseWebCodecs =!FORCE_MEDIARECORDER &&@@ -320,6 +438,10 @@ const Recorder = () => {isRestarting.current = false;index.current = 0;+ // Start session heartbeat for recovery tracking+ startSessionHeartbeat();+ persistSessionState("recording");+const handleChunk = async (data, timestampMs) => {if (useWebCodecs.current) {const blob =@@ -562,31 +684,77 @@ const Recorder = () => {const track = helperAudioStream.current.getAudioTracks()[0];if (track) {track.onended = () => {- debugWarn("helperAudioStream audio track ended");- chrome.storage.local.set({ recording: false });- sendStopRecording();+ // Log detailed diagnostics for debugging+ const diagnosticInfo = {+ reason: "audio-track-ended",+ savedChunks: savedCount.current,+ lastTimecode: lastTimecode.current,+ recordingDuration: recordingStartTime.current+ ? Date.now() - recordingStartTime.current+ : null,+ trackLabel: track?.label || null,+ trackReadyState: track?.readyState || null,+ };+ console.warn(+ "[Recorder] Audio track ended unexpectedly",+ diagnosticInfo+ );+ chrome.storage.local.set({+ recording: false,+ lastTrackEndEvent: diagnosticInfo,+ });+ sendStopRecording("audio-track-ended");};}}liveStream.current.getVideoTracks()[0].onended = () => {- debugWarn("liveStream video track ended");+ const track = liveStream.current?.getVideoTracks()[0];+ // Log detailed diagnostics for debugging+ const diagnosticInfo = {+ reason: "liveStream-video-track-ended",+ savedChunks: savedCount.current,+ lastTimecode: lastTimecode.current,+ recordingDuration: recordingStartTime.current+ ? Date.now() - recordingStartTime.current+ : null,+ trackLabel: track?.label || null,+ trackReadyState: track?.readyState || null,+ };+ console.warn("[Recorder] liveStream video track ended", diagnosticInfo);chrome.storage.local.set({recording: false,restarting: false,tabRecordedID: null,+ lastTrackEndEvent: diagnosticInfo,});- sendStopRecording();+ sendStopRecording("video-track-ended");};helperVideoStream.current.getVideoTracks()[0].onended = () => {- debugWarn("helperVideoStream video track ended");+ const track = helperVideoStream.current?.getVideoTracks()[0];+ // Log detailed diagnostics for debugging+ const diagnosticInfo = {+ reason: "helperVideoStream-video-track-ended",+ savedChunks: savedCount.current,+ lastTimecode: lastTimecode.current,+ recordingDuration: recordingStartTime.current+ ? Date.now() - recordingStartTime.current+ : null,+ trackLabel: track?.label || null,+ trackReadyState: track?.readyState || null,+ };+ console.warn(+ "[Recorder] helperVideoStream video track ended",+ diagnosticInfo+ );chrome.storage.local.set({recording: false,restarting: false,tabRecordedID: null,+ lastTrackEndEvent: diagnosticInfo,});- sendStopRecording();+ sendStopRecording("video-track-ended");};}@@ -654,6 +822,10 @@ const Recorder = () => {isFinishing.current = true;isRecording.current = false;+ // Stop the session heartbeat and persist final state+ stopSessionHeartbeat();+ persistSessionState("stopping");+try {if (useWebCodecs.current &&@@ -677,6 +849,12 @@ const Recorder = () => {await waitForDrain();recorder.current = null;+ // Stop the silent audio keep-alive+ stopTabKeepAlive();++ // Clear session state after successful stop+ persistSessionState("completed");+if (!isRestarting.current) {debug("Stopping tracks and clearing streams");liveStream.current?.getTracks().forEach((t) => t.stop());@@ -693,6 +871,12 @@ const Recorder = () => {debug("dismissRecording()");uiClosing.current = true;isRecording.current = false;++ // Clean up keep-alive and session tracking+ stopTabKeepAlive();+ stopSessionHeartbeat();+ persistSessionState("dismissed");+window.close();};@@ -1090,6 +1274,15 @@ const Recorder = () => {tabID.current = streamId;};+ // Cleanup on component unmount+ useEffect(() => {+ return () => {+ debug("Component unmounting - cleaning up");+ stopTabKeepAlive();+ stopSessionHeartbeat();+ };+ }, []);+useEffect(() => {const handleClose = (e) => {debug("beforeunload event", {@@ -1098,6 +1291,8 @@ const Recorder = () => {});if (uiClosing.current || !isRecording.current) return;+ // Stop recording - note: beforeunload can't reliably wait for async+ // The keep-alive and session state will help with recovery if neededstopRecording();e.preventDefault();diff --git a/src/pages/RecorderOffscreen/RecorderOffscreen.jsx b/src/pages/RecorderOffscreen/RecorderOffscreen.jsxindex b1d3731..486e822 100644--- a/src/pages/RecorderOffscreen/RecorderOffscreen.jsx+++ b/src/pages/RecorderOffscreen/RecorderOffscreen.jsx@@ -336,21 +336,55 @@ const RecorderOffscreen = () => {};liveStream.current.getVideoTracks()[0].onended = () => {+ const track = liveStream.current?.getVideoTracks()[0];+ // Log detailed diagnostics for debugging+ const diagnosticInfo = {+ reason: "liveStream-video-track-ended-offscreen",+ savedChunks: savedCount.current,+ lastTimecode: lastTimecode.current,+ trackLabel: track?.label || null,+ trackReadyState: track?.readyState || null,+ };+ console.warn(+ "[RecorderOffscreen] liveStream video track ended",+ diagnosticInfo+ );chrome.storage.local.set({recording: false,restarting: false,tabRecordedID: null,+ lastTrackEndEvent: diagnosticInfo,+ });+ chrome.runtime.sendMessage({+ type: "stop-recording-tab",+ reason: "video-track-ended",});- chrome.runtime.sendMessage({ type: "stop-recording-tab" });};helperVideoStream.current.getVideoTracks()[0].onended = () => {+ const track = helperVideoStream.current?.getVideoTracks()[0];+ // Log detailed diagnostics for debugging+ const diagnosticInfo = {+ reason: "helperVideoStream-video-track-ended-offscreen",+ savedChunks: savedCount.current,+ lastTimecode: lastTimecode.current,+ trackLabel: track?.label || null,+ trackReadyState: track?.readyState || null,+ };+ console.warn(+ "[RecorderOffscreen] helperVideoStream video track ended",+ diagnosticInfo+ );chrome.storage.local.set({recording: false,restarting: false,tabRecordedID: null,+ lastTrackEndEvent: diagnosticInfo,+ });+ chrome.runtime.sendMessage({+ type: "stop-recording-tab",+ reason: "video-track-ended",});- chrome.runtime.sendMessage({ type: "stop-recording-tab" });};}diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsxindex 7f99b53..025cccf 100644--- a/src/pages/Sandbox/context/ContentState.jsx+++ b/src/pages/Sandbox/context/ContentState.jsx@@ -702,7 +702,7 @@ const ContentState = (props) => {...prev,blob: blob,mp4ready: true,- hasBeenEdited: true,+ hasBeenEdited: event.data.edited === false ? prev.hasBeenEdited : true,isFfmpegRunning: false,reencoding: false,trimming: false,@@ -1199,6 +1199,20 @@ const ContentState = (props) => {return;}+ // ➜ ADD THIS: If untouched + already webm → skip FFmpeg entirely+ if (!contentState.hasBeenEdited && contentState.webm) {+ const url = URL.createObjectURL(contentState.webm);+ await requestDownload(url, ".webm");++ setContentState((prev) => ({+ ...prev,+ downloadingWEBM: false,+ isFfmpegRunning: false,+ saved: true,+ }));+ return;+ }+setContentState((prevState) => ({...prevState,downloadingWEBM: true,