Skip to content

The free and privacy-friendly screen recorder with no limits 🎥

Keep the previous recording while its editor is open, video issue on resize, + mediabunny upgrade

Alyssa X90a3a8b38ab8
diff --git a/package-lock.json b/package-lock.json
index b4cb500..dd35879 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,16 +1,16 @@
{
"name": "screenity",
- "version": "4.6.7",
+ "version": "4.6.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "screenity",
- "version": "4.6.7",
+ "version": "4.6.9",
"hasInstallScript": true,
"dependencies": {
"@babel/plugin-transform-react-jsx": "^7.27.1",
- "@mediabunny/aac-encoder": "^1.53.1",
+ "@mediabunny/aac-encoder": "^1.56.0",
"@mediapipe/tasks-vision": "0.10.32",
"@radix-ui/react-alert-dialog": "^1.0.4",
"@radix-ui/react-collapsible": "^1.0.2",
@@ -37,7 +37,7 @@
"gif.js": "^0.2.0",
"jszip": "^3.10.1",
"localforage": "^1.10.0",
- "mediabunny": "^1.53.0",
+ "mediabunny": "^1.56.0",
"patch-package": "^8.0.0",
"plyr": "3.7.8",
"plyr-react": "^5.3.0",
@@ -2159,9 +2159,9 @@
}
},
"node_modules/@mediabunny/aac-encoder": {
- "version": "1.53.1",
- "resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.53.1.tgz",
- "integrity": "sha512-rJ0LyqRltcfwpdILLJA8Pf0TZ9xAhGToNkRK37PtdMay4DHIWyYpgkUBYcKhX1DlMImZMaZhxtIiJwO2pldv2Q==",
+ "version": "1.56.0",
+ "resolved": "https://registry.npmjs.org/@mediabunny/aac-encoder/-/aac-encoder-1.56.0.tgz",
+ "integrity": "sha512-DY69WcgiCD/cQYLq6vAE/1lVdu4asY32l9WLx7r8b+PDC5qMF9Oe+n0DoqVXNN0TOf3PT4BwAz/Yf3MtHIwCyA==",
"license": "MPL-2.0",
"funding": {
"type": "individual",
@@ -9006,9 +9006,9 @@
}
},
"node_modules/mediabunny": {
- "version": "1.53.0",
- "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.53.0.tgz",
- "integrity": "sha512-RjWe9yJr9MPvb6kX4gSu54fZD2w1yf6RyCS0Jmgaml+fFSqEr7+XuASXoRxSqJxgc+wIe+7TujXWcyj3evJ3Bg==",
+ "version": "1.56.0",
+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.56.0.tgz",
+ "integrity": "sha512-VLVYEVXI4fA2PabQoZs3XOmxDsio4gpG1Npz0iVICRNCQ+XYI3fBOngnwHljafaEjHUbYzrIDoctZbxcVfQpgQ==",
"license": "MPL-2.0",
"workspaces": [
".",
diff --git a/package.json b/package.json
index 9a3c0f1..f4c969e 100755
--- a/package.json
+++ b/package.json
@@ -1,10 +1,10 @@
{
"name": "screenity",
- "version": "4.6.8",
+ "version": "4.6.9",
"description": "The free and privacy-friendly screen recorder with no sign in needed.",
"scripts": {
"build": "cross-env NODE_ENV=production node utils/build.js",
- "build:dev": "cross-env NODE_ENV=development node utils/build.js",
+ "build:dev": "cross-env NODE_ENV=development SCREENITY_DEV_MODE=true node utils/build.js",
"build:prod": "cross-env NODE_ENV=production node utils/build.js",
"build:local": "cross-env NODE_ENV=production SCREENITY_USE_LOCAL_ENV=1 node utils/build.js",
"build:release": "cross-env NODE_ENV=production SCREENITY_SKIP_ENV=true node utils/build.js",
@@ -38,7 +38,7 @@
},
"dependencies": {
"@babel/plugin-transform-react-jsx": "^7.27.1",
- "@mediabunny/aac-encoder": "^1.53.1",
+ "@mediabunny/aac-encoder": "^1.56.0",
"@mediapipe/tasks-vision": "0.10.32",
"@radix-ui/react-alert-dialog": "^1.0.4",
"@radix-ui/react-collapsible": "^1.0.2",
@@ -65,7 +65,7 @@
"gif.js": "^0.2.0",
"jszip": "^3.10.1",
"localforage": "^1.10.0",
- "mediabunny": "^1.53.0",
+ "mediabunny": "^1.56.0",
"patch-package": "^8.0.0",
"plyr": "3.7.8",
"plyr-react": "^5.3.0",
diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.json
index c4419c3..162d445 100644
--- a/src/_locales/ca/messages.json
+++ b/src/_locales/ca/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "No s'ha capturat cap vídeo. Torna a provar la gravació.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "El teu darrer enregistrament no està desat",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Encara és obert en una altra pestanya i es perdrà quan la tanquis. Baixa'l primer per conservar-lo.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Grava igualment",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Obre l'enregistrament",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "No ho tornis a mostrar",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.json
index 33b0b1b..ddb42cb 100644
--- a/src/_locales/de/messages.json
+++ b/src/_locales/de/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Es wurde kein Video aufgezeichnet. Bitte versuchen Sie die Aufnahme erneut.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Deine letzte Aufnahme ist nicht gespeichert",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Sie ist noch in einem anderen Tab geöffnet und geht verloren, sobald du diesen Tab schließt. Lade sie zuerst herunter, um sie zu behalten.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Trotzdem aufnehmen",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Aufnahme öffnen",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Nicht mehr anzeigen",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json
index d041b3f..edbd251 100644
--- a/src/_locales/en/messages.json
+++ b/src/_locales/en/messages.json
@@ -1800,5 +1800,25 @@
"emptyRecordingDescription": {
"message": "No video was captured. Please try recording again.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Your last recording isn't saved",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "It's still open in another tab, and will be lost once you close that tab. Download it first to keep it.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Record anyway",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Open recording",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Don't show again",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.json
index 18090a5..256d837 100644
--- a/src/_locales/es/messages.json
+++ b/src/_locales/es/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "No se capturó ningún vídeo. Vuelve a intentar la grabación.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Tu última grabación no está guardada",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Sigue abierta en otra pestaña y se perderá cuando la cierres. Descárgala primero para conservarla.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Grabar de todos modos",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Abrir grabación",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "No volver a mostrar",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.json
index e51fe1f..77e1f52 100644
--- a/src/_locales/fr/messages.json
+++ b/src/_locales/fr/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Aucune vidéo n'a été capturée. Veuillez réessayer l'enregistrement.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Votre dernier enregistrement n'est pas sauvegardé",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Il est encore ouvert dans un autre onglet et sera perdu dès que vous fermerez cet onglet. Téléchargez-le d'abord pour le conserver.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Démarrer quand même",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Ouvrir l'enregistrement",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Ne plus afficher",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.json
index b3e7641..e2b793d 100644
--- a/src/_locales/hi/messages.json
+++ b/src/_locales/hi/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "कोई वीडियो कैप्चर नहीं हुआ। कृपया दोबारा रिकॉर्ड करें।",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "आपकी पिछली रिकॉर्डिंग सहेजी नहीं गई है",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "यह अब भी दूसरे टैब में खुली है और उस टैब को बंद करते ही खो जाएगी। इसे रखने के लिए पहले डाउनलोड करें।",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "फिर भी रिकॉर्ड करें",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "रिकॉर्डिंग खोलें",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "दोबारा न दिखाएं",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.json
index 1680b36..6b6cc1e 100644
--- a/src/_locales/id/messages.json
+++ b/src/_locales/id/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Tidak ada video yang terekam. Silakan coba rekam lagi.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Rekaman terakhir Anda belum disimpan",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Rekaman masih terbuka di tab lain dan akan hilang setelah Anda menutup tab itu. Unduh dulu untuk menyimpannya.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Tetap rekam",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Buka rekaman",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Jangan tampilkan lagi",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.json
index 295238c..1ed4b4a 100644
--- a/src/_locales/it/messages.json
+++ b/src/_locales/it/messages.json
@@ -1777,5 +1777,25 @@
"emptyRecordingDescription": {
"message": "Nessun video è stato acquisito. Prova a registrare di nuovo.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "La tua ultima registrazione non è stata salvata",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "È ancora aperta in un'altra scheda e andrà persa quando la chiuderai. Scaricala prima per conservarla.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Registra comunque",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Apri registrazione",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Non mostrare più",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.json
index 3d3efc2..ccf7d8a 100644
--- a/src/_locales/ko/messages.json
+++ b/src/_locales/ko/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "영상이 녹화되지 않았어요. 다시 녹화해 주세요.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "마지막 녹화본이 저장되지 않았습니다",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "아직 다른 탭에 열려 있으며 그 탭을 닫으면 사라집니다. 보관하려면 먼저 다운로드하세요.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "그래도 녹화",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "녹화본 열기",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "다시 표시하지 않기",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.json
index 93be239..26da1a8 100644
--- a/src/_locales/pl/messages.json
+++ b/src/_locales/pl/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Nie zarejestrowano obrazu. Spróbuj nagrać ponownie.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Ostatnie nagranie nie zostało zapisane",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Jest nadal otwarte w innej karcie i przepadnie po jej zamknięciu. Pobierz je najpierw, aby je zachować.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Nagrywaj mimo to",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Otwórz nagranie",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Nie pokazuj ponownie",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.json
index 23c8bb8..fdf38ac 100644
--- a/src/_locales/pt_BR/messages.json
+++ b/src/_locales/pt_BR/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Nenhum vídeo foi capturado. Tente gravar novamente.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Sua última gravação não está salva",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Ela ainda está aberta em outra aba e será perdida quando você fechar essa aba. Baixe-a primeiro para mantê-la.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Gravar mesmo assim",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Abrir gravação",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Não mostrar novamente",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.json
index f50dbf3..7a1e8be 100644
--- a/src/_locales/pt_PT/messages.json
+++ b/src/_locales/pt_PT/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Não foi capturado nenhum vídeo. Tente gravar novamente.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "A sua última gravação não está guardada",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Ainda está aberta noutro separador e será perdida quando o fechar. Transfira-a primeiro para a manter.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Gravar mesmo assim",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Abrir gravação",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Não mostrar novamente",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.json
index 265f529..5e598ff 100644
--- a/src/_locales/ru/messages.json
+++ b/src/_locales/ru/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Видео не записано. Попробуйте записать снова.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Последняя запись не сохранена",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Она всё ещё открыта в другой вкладке и пропадёт, когда вы её закроете. Сначала скачайте её, чтобы сохранить.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Всё равно записать",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Открыть запись",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Больше не показывать",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.json
index 5810846..1c6bdcb 100644
--- a/src/_locales/ta/messages.json
+++ b/src/_locales/ta/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "எந்த வீடியோவும் பதிவாகவில்லை. மீண்டும் பதிவு செய்ய முயற்சிக்கவும்.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "உங்கள் கடைசி பதிவு சேமிக்கப்படவில்லை",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "அது இன்னும் மற்றொரு தாவலில் திறந்திருக்கிறது, அந்தத் தாவலை மூடியவுடன் இழக்கப்படும். வைத்திருக்க முதலில் பதிவிறக்குங்கள்.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "எப்படியும் பதிவுசெய்யுங்கள்",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "பதிவைத் திறங்கள்",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "மீண்டும் காட்ட வேண்டாம்",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.json
index 8a70b73..e44d04d 100644
--- a/src/_locales/tr/messages.json
+++ b/src/_locales/tr/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "Görüntü kaydedilmedi. Lütfen tekrar kaydetmeyi deneyin.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Son kaydınız kaydedilmedi",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Hâlâ başka bir sekmede açık ve o sekmeyi kapattığınızda kaybolacak. Saklamak için önce indirin.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Yine de kayda başla",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Kaydı aç",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Bir daha gösterme",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.json
index fd06894..1e9f0c3 100644
--- a/src/_locales/uk/messages.json
+++ b/src/_locales/uk/messages.json
@@ -1780,5 +1780,25 @@
"emptyRecordingDescription": {
"message": "Відео не записано. Спробуйте записати ще раз.",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "Останній запис не збережено",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "Він ще відкритий в іншій вкладці та зникне, щойно ви її закриєте. Спочатку завантажте його, щоб зберегти.",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "Усе одно записати",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "Відкрити запис",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "Більше не показувати",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json
index 8c5ecfe..ce8580f 100644
--- a/src/_locales/zh_CN/messages.json
+++ b/src/_locales/zh_CN/messages.json
@@ -1781,5 +1781,25 @@
"emptyRecordingDescription": {
"message": "未捕获到视频。请重新录制。",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "上一个录制内容尚未保存",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "它仍在另一个标签页中打开,关闭该标签页后就会丢失。请先下载以保留。",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "仍然录制",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "打开录制内容",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "不再显示",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json
index 92c7b9e..99b0a9c 100644
--- a/src/_locales/zh_TW/messages.json
+++ b/src/_locales/zh_TW/messages.json
@@ -1782,5 +1782,25 @@
"emptyRecordingDescription": {
"message": "未擷取到影片。請重新錄製。",
"description": "Modal description when the recording file contains no video"
+ },
+ "unsavedRecordingModalTitle": {
+ "message": "上一個錄製內容尚未儲存",
+ "description": "Title of the modal shown when starting a recording while the previous one is unsaved."
+ },
+ "unsavedRecordingModalDescription": {
+ "message": "它仍在另一個分頁中開啟,關閉該分頁後就會遺失。請先下載以保留。",
+ "description": "Body of the unsaved-previous-recording modal."
+ },
+ "unsavedRecordingModalAction": {
+ "message": "仍然錄製",
+ "description": "Confirm button: start the new recording anyway."
+ },
+ "unsavedRecordingModalCancel": {
+ "message": "開啟錄製內容",
+ "description": "Cancel button: bring the unsaved recording's tab forward instead."
+ },
+ "unsavedRecordingModalDismiss": {
+ "message": "不再顯示",
+ "description": "Side button: start the recording and stop prompting about unsaved recordings."
}
}
diff --git a/src/manifest.json b/src/manifest.json
index 3d07025..53e9af7 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.6.8",
+ "version": "4.6.9",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/pages/Background/alarms/handleAlarm.js b/src/pages/Background/alarms/handleAlarm.js
index adb0454..357e3ad 100644
--- a/src/pages/Background/alarms/handleAlarm.js
+++ b/src/pages/Background/alarms/handleAlarm.js
@@ -10,6 +10,15 @@ import { openExistingChunksStore } from "../../CloudRecorder/recorderStorage/cho
import { destroySessionDir } from "../../CloudRecorder/recorderStorage/opfsKvStore";
import { emitRecordingTelemetry } from "../recording/emitRecordingTelemetry";
import { markFastRecorderFailure } from "../../../media/fastRecorderGate";
+import {
+ runMicRecoveryScan,
+ hasAwaitSceneMarkers,
+ MIC_AWAIT_SCENE_ALARM,
+} from "../../CloudRecorder/micRecovery";
+import {
+ tryResumePendingUploads,
+ RESUME_RETRY_ALARM,
+} from "../recording/resumePendingUploads";
import {
CLOUD_LOCAL_PLAYBACK_KEY,
CLOUD_LOCAL_PLAYBACK_EVENT_KEY,
@@ -89,6 +98,17 @@ const handleTabMessaging = async (tab) => {
let _lastKeepaliveTickAt = 0;
export const handleAlarm = async (alarm) => {
+ if (alarm.name === RESUME_RETRY_ALARM) {
+ await tryResumePendingUploads({ trigger: "retry-alarm" });
+ return;
+ }
+ if (alarm.name === MIC_AWAIT_SCENE_ALARM) {
+ await runMicRecoveryScan().catch(() => {});
+ if (!(await hasAwaitSceneMarkers())) {
+ await chrome.alarms.clear(MIC_AWAIT_SCENE_ALARM).catch(() => {});
+ }
+ return;
+ }
if (alarm.name === RECORDER_KEEPALIVE_ALARM) {
const now = Date.now();
if (now - _lastKeepaliveTickAt < 30_000) {
diff --git a/src/pages/Background/drive/handleSaveToDrive.js b/src/pages/Background/drive/handleSaveToDrive.js
index ed13866..7741a76 100644
--- a/src/pages/Background/drive/handleSaveToDrive.js
+++ b/src/pages/Background/drive/handleSaveToDrive.js
@@ -1,6 +1,11 @@
import { base64ToUint8Array } from "../utils/base64ToUint8Array";
import { sendMessageTab } from "../tabManagement";
import { chunksStore } from "../recording/chunkHandler";
+import {
+ markRetainedSaved,
+ retainedEntryForTab,
+} from "../recording/recordingRetention";
+import { instanceForSlot } from "../../utils/chunkStores";
import signIn from "../modules/signIn";
import { diagEvent } from "../../utils/diagnosticLog";
@@ -379,7 +384,19 @@ const saveToDrive = async (videoBlob, fileName) => {
}
};
-const savedToDrive = async () => {
+const savedToDrive = async (tabId) => {
+ // A Drive save is a copy the user keeps, exactly like a download, so it
+ // releases retention and stops the unsaved-recording prompt.
+ try {
+ const { retainedRecordings } = await chrome.storage.local.get([
+ "retainedRecordings",
+ ]);
+ const list = Array.isArray(retainedRecordings) ? retainedRecordings : [];
+ // Only the saving tab's own entry. Guessing the newest unsaved one marked
+ // an unrelated recording saved and dropped its protection.
+ const mine = list.find((e) => e.tabId === tabId && !e.saved);
+ if (mine?.recordingId) await markRetainedSaved(mine.recordingId);
+ } catch {}
const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);
if (!sandboxTab) {
console.warn("[Drive] savedToDrive: sandboxTab not set, cannot notify UI");
@@ -433,7 +450,7 @@ const sweepStagedOpfsFiles = async (keepName = null) => {
} catch {}
};
-export const handleSaveToDrive = async (request, fallback = false) => {
+export const handleSaveToDrive = async (request, fallback = false, tabId = null) => {
try {
let response;
@@ -477,8 +494,22 @@ export const handleSaveToDrive = async (request, fallback = false) => {
response = await saveToDrive(blob, fileName);
} else {
// viewer/recovery mode: rebuild blob from IndexedDB chunks
+ // Read the asking tab's own slot: the live one holds the newer recording.
+ const entry = await retainedEntryForTab(tabId);
+ // An entry holding no slot keeps its bytes elsewhere (OPFS, or a slot
+ // already reclaimed). chunksStore follows the live take, so it would
+ // upload that one under this recording's name.
+ if (entry && !entry.slot) {
+ return {
+ status: "ew",
+ url: null,
+ error: "No recording data found",
+ errorCode: "drive-generic",
+ };
+ }
+ const store = entry?.slot ? instanceForSlot(entry.slot) : chunksStore;
const chunks = [];
- await chunksStore.iterate((value) => chunks.push(value));
+ await store.iterate((value) => chunks.push(value));
if (chunks.length === 0) {
console.error("[Drive] drive_upload_failed: no chunks in IndexedDB");
@@ -500,7 +531,7 @@ export const handleSaveToDrive = async (request, fallback = false) => {
}
if (response.status === "ok") {
- await savedToDrive();
+ await savedToDrive(tabId);
}
return response;
} catch (err) {
diff --git a/src/pages/Background/listeners/onActionButtonClickedListener.js b/src/pages/Background/listeners/onActionButtonClickedListener.js
index 798dcd6..bdb8658 100644
--- a/src/pages/Background/listeners/onActionButtonClickedListener.js
+++ b/src/pages/Background/listeners/onActionButtonClickedListener.js
@@ -7,6 +7,7 @@ import {
import { sendMessageRecord } from "../recording/sendMessageRecord.js";
import { loginWithWebsite } from "../auth/loginWithWebsite.js";
import { tryResumePendingUploads } from "../recording/resumePendingUploads";
+import { runMicRecoveryScan } from "../../CloudRecorder/micRecovery";
import { clearInMemoryEditorLock } from "../recording/stopRecording";
import { sendMessageEnsuringContentScript } from "../utils/executeScripts";
@@ -170,6 +171,8 @@ const isOffscreenAlive = async () => {
export const onActionButtonClickedListener = () => {
chrome.action.onClicked.addListener(async (tab) => {
tryResumePendingUploads({ trigger: "actionClick" }).catch(() => {});
+ // A recovered take's mic waits for its scene, which appears minutes after upload.
+ runMicRecoveryScan().catch(() => {});
try {
const snap = await chrome.storage.local.get([
"recording", "pendingRecording", "restarting", "recorderSession",
diff --git a/src/pages/Background/listeners/onTabRemovedListener.js b/src/pages/Background/listeners/onTabRemovedListener.js
index 4449ba7..dd09031 100644
--- a/src/pages/Background/listeners/onTabRemovedListener.js
+++ b/src/pages/Background/listeners/onTabRemovedListener.js
@@ -3,9 +3,13 @@ import { removeTab } from "../tabManagement/removeTab";
import { sendMessageRecord } from "../recording/sendMessageRecord";
import { isRecordingStartInFlight } from "../recording/startRecording";
import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";
+import { forgetRetained } from "../recording/recordingRetention";
export const onTabRemovedListener = () => {
chrome.tabs.onRemoved.addListener(async (tabId) => {
+ // Drops the protection only. The bytes stay until the next cleanup, so
+ // closing a tab never destroys a recording on its own.
+ forgetRetained(tabId).catch(() => {});
try {
const flags = await chrome.storage.local.get([
"recording",
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index 2479272..89ac2c4 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -70,6 +70,10 @@ import {
checkCapturePermissions,
} from "../recording/recordingHelpers";
import { clearAllRecordings } from "../recording/chunkHandler";
+import {
+ markRetainedSaved,
+ unsavedRetained,
+} from "../recording/recordingRetention";
import { setMicActiveTab } from "../tabManagement/tabHelpers";
import { handleSignOutDrive } from "../drive/handleSignOutDrive";
import { loginWithWebsite } from "../auth/loginWithWebsite";
@@ -1545,6 +1549,73 @@ export const setupHandlers = () => {
registerMessage("diag-editor-ready", (message) =>
diagEvent("editor-load-ready", { path: message?.path || null }),
);
+ // Which recording this editor owns. lastRecordingBackendRef always names the
+ // newest, so with several editors open none of them can use it.
+ registerMessage("resolve-editor-recording", async (_message, sender) => {
+ const tabId = sender?.tab?.id;
+ if (typeof tabId !== "number") return { ref: null };
+ try {
+ const { retainedRecordings } = await chrome.storage.local.get([
+ "retainedRecordings",
+ ]);
+ const list = Array.isArray(retainedRecordings) ? retainedRecordings : [];
+ const mine = list.find((e) => e.tabId === tabId);
+ if (!mine) return { ref: null };
+ // Its slot was reclaimed, so a ref would point this editor at whichever
+ // recording is live now.
+ if (mine.bytesGone) return { ref: null, gone: true };
+ // slot travels inside ref: the IDB reader takes it from there.
+ return {
+ ref: {
+ backend: mine.backend,
+ fileName: mine.fileName,
+ slot: mine.slot || null,
+ },
+ recordingId: mine.recordingId,
+ };
+ } catch {
+ return { ref: null };
+ }
+ });
+
+ // Asked before a recording starts. The popup blocks on the answer so the
+ // user acknowledges an unsaved previous recording before replacing it.
+ registerMessage("unsaved-retained-recording", async () => {
+ const entry = await unsavedRetained();
+ return entry
+ ? { hasUnsaved: true, tabId: entry.tabId, recordingId: entry.recordingId }
+ : { hasUnsaved: false };
+ });
+
+ // Bring the unsaved recording's editor forward so it can be downloaded.
+ registerMessage("focus-retained-recording", async (message) => {
+ const tabId = message?.tabId;
+ if (typeof tabId !== "number") return { ok: false };
+ try {
+ // Only a tab this registry knows, so the message is not a way to focus
+ // any tab in the browser.
+ const { retainedRecordings } = await chrome.storage.local.get([
+ "retainedRecordings",
+ ]);
+ const list = Array.isArray(retainedRecordings) ? retainedRecordings : [];
+ if (!list.some((e) => e.tabId === tabId)) return { ok: false };
+ const tab = await chrome.tabs.get(tabId);
+ await chrome.windows.update(tab.windowId, { focused: true });
+ await chrome.tabs.update(tabId, { active: true });
+ return { ok: true };
+ } catch {
+ return { ok: false };
+ }
+ });
+
+ // The editor reports a download or Drive save so retention can stop
+ // protecting a recording the user already has a copy of.
+ registerMessage("recording-saved", async (message, sender) => {
+ await markRetainedSaved(
+ message?.recordingId || null,
+ sender?.tab?.id ?? null,
+ );
+ });
// prefix allowlist so a compromised context can't spoof lifecycle events
registerMessage("diag-forward", (message) => {
const ev = typeof message?.event === "string" ? message.event : null;
@@ -1560,6 +1631,11 @@ export const setupHandlers = () => {
"editor-",
// AudioContext interrupt/resume from attachAudioContextWatchdog (page realm).
"audiocontext-",
+ // Mix-bus warm-up and the resume that keeps a suspended graph from
+ // muxing silence. Dropped before, so the bus was invisible in zips.
+ "audio-bus-",
+ // Mic separation decisions and fallbacks, dropped for the same reason.
+ "separated-",
];
if (!allowedPrefixes.some((p) => ev.startsWith(p))) return;
diagEvent(ev, message?.data ?? null);
@@ -1858,6 +1934,35 @@ export const setupHandlers = () => {
return true;
},
);
+ // Gated so DefinePlugin strips it from a release bundle. The DevHUD button
+ // behind the same flag is the only caller, and this revokes permissions.
+ if (process.env.SCREENITY_DEV_MODE === "true") {
+ // remove() needs no user gesture so the worker can do it, request() cannot.
+ registerMessage("reset-capture-permissions", async () => {
+ // One at a time: remove() is atomic, so a single unremovable entry fails
+ // the whole batch. lastError carries the reason and is otherwise swallowed.
+ const targets = [
+ "desktopCapture",
+ "alarms",
+ "offscreen",
+ "clipboardWrite",
+ ];
+ const results = {};
+ for (const permission of targets) {
+ results[permission] = await new Promise((resolve) => {
+ chrome.permissions.remove({ permissions: [permission] }, (ok) => {
+ const err = chrome.runtime.lastError;
+ resolve(err ? `error: ${err.message}` : ok ? "removed" : "refused");
+ });
+ });
+ }
+ const remaining = await new Promise((resolve) => {
+ chrome.permissions.getAll((p) => resolve(p?.permissions || []));
+ });
+ return { results, remaining };
+ });
+ }
+
registerMessage("is-pinned", async () => await isPinned());
// prevent Chrome from discarding the CloudRecorder tab while recording
@@ -1867,11 +1972,13 @@ export const setupHandlers = () => {
registerMessage(
"save-to-drive",
- async (message) => await handleSaveToDrive(message, false),
+ async (message, sender) =>
+ await handleSaveToDrive(message, false, sender?.tab?.id ?? null),
);
registerMessage(
"save-to-drive-fallback",
- async (message) => await handleSaveToDrive(message, true),
+ async (message, sender) =>
+ await handleSaveToDrive(message, true, sender?.tab?.id ?? null),
);
registerMessage("request-download", (message) =>
requestDownload(message.base64, message.title),
diff --git a/src/pages/Background/recording/chunkHandler.js b/src/pages/Background/recording/chunkHandler.js
index ab4b876..aa6681c 100644
--- a/src/pages/Background/recording/chunkHandler.js
+++ b/src/pages/Background/recording/chunkHandler.js
@@ -1,17 +1,13 @@
-import localforage from "localforage";
import { sendMessageTab } from "../tabManagement";
-
-localforage.config({
- driver: localforage.INDEXEDDB,
- name: "screenity",
- version: 1,
-});
+import { activeChunksStore } from "../../utils/chunkStores";
// in-memory promise chain. storage-based sendingChunks flag was racy:
// check-then-set via async chrome.storage let two concurrent triggers pass.
let _sendChain = Promise.resolve();
-export const chunksStore = localforage.createInstance({ name: "chunks" });
+// Resolves to whichever slot is live, see chunkStores.js. Same export name so
+// every existing caller still means "the current recording".
+export const chunksStore = activeChunksStore;
const DEBUG_POSTSTOP = false;
export const clearAllRecordings = async () => {
diff --git a/src/pages/Background/recording/openRecorderTab.js b/src/pages/Background/recording/openRecorderTab.js
index 49e8656..ac2cbc3 100644
--- a/src/pages/Background/recording/openRecorderTab.js
+++ b/src/pages/Background/recording/openRecorderTab.js
@@ -8,6 +8,7 @@ import { traceStep } from "../../utils/startFlowTrace.js";
import { handleGetStreamingData } from "./recordingHelpers.js";
import { perfMark, perfSpan } from "../../utils/perfMarks";
import { sweepRecorderTabs } from "./sweepRecorderTabs";
+import { applyRetentionPlan } from "./recordingRetention";
const openRecorderTab = async (
activeTab,
@@ -330,6 +331,13 @@ export const startRecorderSession = async (request, tabId = null) => {
camera: Boolean(request?.camera),
});
console.log("[Screenity][startRecorderSession] entered", { request, tabId });
+ // Before the recorder page exists. It clears the chunk store as it warms up,
+ // and that clear reads this plan to know which slot is free.
+ try {
+ await applyRetentionPlan();
+ } catch (err) {
+ console.warn("[Screenity][BG] retention plan failed", err);
+ }
const endTab = perfSpan("BG.startRecorderSession getCurrentTab");
let activeTab = await getCurrentTab();
endTab({ tabId: activeTab?.id || null });
diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.js
index 58733d1..2d8e3a0 100644
--- a/src/pages/Background/recording/recordingHelpers.js
+++ b/src/pages/Background/recording/recordingHelpers.js
@@ -44,9 +44,23 @@ export const checkCapturePermissions = async ({ isLoggedIn, isSubscribed }) => {
if (granted) {
addAlarmListener();
return { status: "ok" };
- } else {
- return { status: "error" };
}
+
+ // Falsy is ambiguous: real denial, or a rejected call from a lost gesture.
+ // contains() needs no gesture, so it settles which, without re-prompting an
+ // already-granted profile.
+ const has = await new Promise((resolve) => {
+ chrome.permissions.contains({ permissions }, (result) =>
+ resolve(Boolean(result))
+ );
+ });
+
+ if (has) {
+ addAlarmListener();
+ return { status: "ok" };
+ }
+
+ return { status: "error" };
};
export const handlePip = async (started = false) => {
diff --git a/src/pages/Background/recording/recordingRetention.js b/src/pages/Background/recording/recordingRetention.js
new file mode 100644
index 0000000..2c4f8ab
--- /dev/null
+++ b/src/pages/Background/recording/recordingRetention.js
@@ -0,0 +1,264 @@
+// Keeps a finished recording safe from the next recording's cleanup while its
+// editor tab is open. Closing the tab drops the protection, never the bytes.
+// Logged out only: a signed-in recording is already uploaded.
+import {
+ CHUNK_SLOT_A,
+ CHUNK_SLOT_B,
+ instanceForSlot,
+} from "../../utils/chunkStores";
+
+const KEY = "retainedRecordings";
+// Below this much free space retention yields. A recording nobody can write
+// beats a spare copy of an old one.
+const MIN_FREE_BYTES = 2 * 1024 * 1024 * 1024;
+
+const read = async () => {
+ try {
+ const got = await chrome.storage.local.get([KEY]);
+ return Array.isArray(got?.[KEY]) ? got[KEY] : [];
+ } catch {
+ return [];
+ }
+};
+
+const write = async (list) => {
+ try {
+ await chrome.storage.local.set({ [KEY]: list });
+ } catch {}
+};
+
+// chrome.tabs.get, never a ping. A discarded or suspended tab still exists and
+// will restore, but its page runs no script.
+const tabExists = async (tabId) => {
+ if (typeof tabId !== "number") return false;
+ try {
+ const tab = await chrome.tabs.get(tabId);
+ return Boolean(tab);
+ } catch {
+ return false;
+ }
+};
+
+const isLoggedIn = async () => {
+ try {
+ const got = await chrome.storage.local.get(["isLoggedIn"]);
+ return got?.isLoggedIn === true;
+ } catch {
+ return false;
+ }
+};
+
+const hasHeadroom = async () => {
+ try {
+ if (!navigator.storage?.estimate) return true;
+ const { quota, usage } = await navigator.storage.estimate();
+ if (!Number.isFinite(quota) || !Number.isFinite(usage)) return true;
+ return quota - usage > MIN_FREE_BYTES;
+ } catch {
+ // Matches the existing low-storage treatment. An estimate that throws
+ // counts as pressure rather than assumed healthy.
+ return false;
+ }
+};
+
+export const registerRetainable = async (entry) => {
+ if (!entry || typeof entry.tabId !== "number") return;
+ // An IDB recording has neither a recordingId nor a file name, so it takes
+ // its identity from the tab holding it.
+ const id =
+ entry.recordingId || entry.fileName || `tab:${entry.tabId}`;
+ if (await isLoggedIn()) return;
+ const list = await read();
+ const next = list.filter((e) => e.recordingId !== id && e.tabId !== entry.tabId);
+ next.push({
+ recordingId: id,
+ backend: entry.backend || null,
+ fileName: entry.fileName || null,
+ // IDB only. An OPFS entry carrying one makes callers read the live slot as
+ // busy and skip a recording that is free to recover.
+ slot: entry.backend === "opfs" ? null : entry.slot || null,
+ tabId: entry.tabId,
+ durationMs: Number(entry.durationMs) || 0,
+ saved: false,
+ at: Date.now(),
+ });
+ await write(next);
+};
+
+// A download or Drive save means the user has their own copy, so this stops
+// being protected and stops being warned about.
+export const markRetainedSaved = async (recordingId, tabId = null) => {
+ const list = await read();
+ // The stop-tab route has no recordingId, so fall back to the reporting tab,
+ // which registerRetainable stored. No newest-unsaved guess: it marked an
+ // unrelated recording saved and let the next take destroy it.
+ const target =
+ (recordingId && list.find((e) => e.recordingId === recordingId)) ||
+ (typeof tabId === "number" &&
+ list.find((e) => e.tabId === tabId && !e.saved)) ||
+ null;
+ if (!target || target.saved) return;
+ await write(
+ list.map((e) =>
+ e.recordingId === target.recordingId ? { ...e, saved: true } : e,
+ ),
+ );
+};
+
+
+// No length floor. A short recording can matter as much as a long one, and
+// still open and never saved is the whole condition.
+export const PROMPT_MIN_DURATION_MS = 0;
+
+// The dismissal expires. The button never said forever, and this is the only
+// warning before an unsaved recording is destroyed.
+const PROMPT_DISMISS_TTL_MS = 30 * 24 * 60 * 60 * 1000;
+
+export const unsavedRetained = async () => {
+ if (await isLoggedIn()) return null;
+ try {
+ const { unsavedRecordingPromptDismissed: dismissedAt } =
+ await chrome.storage.local.get(["unsavedRecordingPromptDismissed"]);
+ if (
+ typeof dismissedAt === "number" &&
+ Date.now() - dismissedAt < PROMPT_DISMISS_TTL_MS
+ ) {
+ return null;
+ }
+ } catch {}
+ const alive = await pruneRetained();
+ // Not gated on whether they played or scrubbed it. Still open and never saved
+ // is enough, better asked once too often than lost.
+ return alive.find((e) => !e.saved) || null;
+};
+
+// Drop entries whose editor tab is gone. Does not delete any bytes.
+export const pruneRetained = async () => {
+ const list = await read();
+ // In parallel. This sits on the record-start path, and a pile of open editors
+ // would otherwise cost one round trip each before recording.
+ const live = await Promise.all(list.map((e) => tabExists(e.tabId)));
+ const alive = list.filter((_, i) => live[i]);
+ if (alive.length !== list.length) await write(alive);
+ return alive;
+};
+
+// What the next recording may keep. `keepNames` are OPFS files to skip,
+// `retainSlot` is the IDB slot to leave alone so the new one takes the other.
+export const computeRetentionPlan = async () => {
+ const empty = { keepNames: [], retainSlot: null, activeSlot: CHUNK_SLOT_A };
+ // The common case, and this sits on the start path. One storage read before
+ // the estimate and the tab lookups.
+ if (!(await read()).length) return empty;
+ if (await isLoggedIn()) return empty;
+ if (!(await hasHeadroom())) return empty;
+
+ const alive = await pruneRetained();
+ if (!alive.length) return empty;
+
+ // Saved means they already have the file, so its editor closes and its bytes
+ // release exactly as before retention existed.
+ const unsaved = alive.filter((e) => !e.saved);
+ const opfs = unsaved.filter((e) => e.backend === "opfs" && e.fileName);
+ const keepNames = opfs.map((e) => e.fileName);
+
+ // Only one IDB recording survives: two slots, and the new recording needs
+ // one. Newest wins. A null backend predates the ref and can only be IDB.
+ const idb = unsaved
+ .filter((e) => (e.backend === "idb" || !e.backend) && e.slot)
+ .sort((a, b) => b.at - a.at)[0];
+ const retainSlot = idb ? idb.slot : null;
+ const activeSlot = !retainSlot
+ ? CHUNK_SLOT_A
+ : retainSlot === CHUNK_SLOT_A
+ ? CHUNK_SLOT_B
+ : CHUNK_SLOT_A;
+
+ return { keepNames, retainSlot, activeSlot };
+};
+
+// The chunk slot the editor in this tab owns, if it is a retained IDB one.
+export const slotForTab = async (tabId) => {
+ if (typeof tabId !== "number") return null;
+ const list = await read();
+ const mine = list.find((e) => e.tabId === tabId);
+ return mine?.slot || null;
+};
+
+// Separates "this tab owns no retained recording" from "it owns one holding no
+// IDB slot". The Drive fallback rebuilds from IDB and must tell them apart.
+export const retainedEntryForTab = async (tabId) => {
+ if (typeof tabId !== "number") return null;
+ const list = await read();
+ return list.find((e) => e.tabId === tabId) || null;
+};
+
+// Only drops the registry entry. Bytes stay until the next cleanup.
+export const forgetRetained = async (tabId) => {
+ const list = await read();
+ const next = list.filter((e) => e.tabId !== tabId);
+ if (next.length !== list.length) await write(next);
+};
+
+// Runs at session start, before the recorder page exists. It prewarms by
+// clearing the chunk store, and a later plan is read after that clear.
+export const applyRetentionPlan = async () => {
+ const plan = await computeRetentionPlan();
+ await chrome.storage.local.set({
+ retentionPlan: plan,
+ activeChunkSlot: plan.activeSlot,
+ });
+ reclaimIdleSlot(plan).catch(() => {});
+ return plan;
+};
+
+// Empty the slot that is neither written to nor retained. The recorder only
+// clears the slot it writes, so otherwise a whole recording sits there forever.
+export const reclaimIdleSlot = async (plan) => {
+ // Never while recording. A stale flag costs disk, clearing the slot a live
+ // recording writes to costs the recording.
+ try {
+ const { recording } = await chrome.storage.local.get(["recording"]);
+ if (recording === true) return;
+ } catch {
+ return;
+ }
+ const active = plan?.activeSlot || CHUNK_SLOT_A;
+ const retain = plan?.retainSlot || null;
+ const cleared = [];
+ for (const slot of [CHUNK_SLOT_A, CHUNK_SLOT_B]) {
+ if (slot === active || slot === retain) continue;
+ await instanceForSlot(slot).clear();
+ cleared.push(slot);
+ }
+ if (!cleared.length) return;
+ // The bytes are gone, so no entry may still name the slot. A ref would send
+ // that editor to whichever recording is live now.
+ const list = await read();
+ let changed = false;
+ const next = list.map((e) => {
+ if (!e.slot || !cleared.includes(e.slot)) return e;
+ changed = true;
+ return { ...e, slot: null, bytesGone: true };
+ });
+ if (changed) await write(next);
+};
+
+
+// Editor tabs the plan actually preserves. Derived from the plan, not the
+// registry, so a tab stays open only when the bytes behind it do.
+export const retainedTabIdsFor = async (plan) => {
+ const keep = new Set(plan?.keepNames || []);
+ const active = plan?.activeSlot || null;
+ const alive = await pruneRetained();
+ return new Set(
+ alive
+ .filter((e) => !e.saved && typeof e.tabId === "number")
+ .filter(
+ (e) =>
+ (e.backend === "opfs" && e.fileName && keep.has(e.fileName)) ||
+ (active && e.slot && e.slot !== active),
+ )
+ .map((e) => e.tabId),
+ );
+};
diff --git a/src/pages/Background/recording/restoreRecording.js b/src/pages/Background/recording/restoreRecording.js
index 73e8d7d..481e3e9 100644
--- a/src/pages/Background/recording/restoreRecording.js
+++ b/src/pages/Background/recording/restoreRecording.js
@@ -1,5 +1,10 @@
import { sendMessageTab, getCurrentTab } from "../tabManagement";
-import { chunksStore } from "./chunkHandler";
+import { pruneRetained, registerRetainable } from "./recordingRetention";
+import {
+ CHUNK_SLOT_A,
+ CHUNK_SLOT_B,
+ instanceForSlot,
+} from "../../utils/chunkStores";
// pass explicitTabId so toasts land on the original tab even after a switch
const notifyRestoreToast = async (message, explicitTabId = null) => {
@@ -61,20 +66,44 @@ const listOpfsRecordings = async () => {
}
};
+// A recording with its editor still open is not lost. Recovering it would mean
+// two tabs claiming one file.
+const openInAnEditor = async () => {
+ const alive = await pruneRetained().catch(() => []);
+ return {
+ fileNames: new Set(
+ alive.filter((e) => e.fileName).map((e) => e.fileName),
+ ),
+ slots: new Set(alive.filter((e) => e.slot).map((e) => e.slot)),
+ };
+};
+
+// Both slots. Retention leaves a finished recording in whichever slot the live
+// one is not using, so the live slot alone would miss it.
+const findIdbChunks = async (busySlots) => {
+ for (const slot of [CHUNK_SLOT_B, CHUNK_SLOT_A]) {
+ if (busySlots.has(slot)) continue;
+ const chunks = [];
+ try {
+ await instanceForSlot(slot).iterate((value) => {
+ chunks.push(value);
+ });
+ } catch (err) {
+ console.warn("[Screenity][BG] restoreRecording iterate failed", slot, err);
+ }
+ if (chunks.length) return { slot, chunks };
+ }
+ return { slot: null, chunks: [] };
+};
+
export const checkRestore = async () => {
- const [idbChunkCount, opfsFiles] = await Promise.all([
- (async () => {
- let count = 0;
- try {
- await chunksStore.iterate(() => {
- count += 1;
- });
- } catch {}
- return count;
- })(),
+ const busy = await openInAnEditor();
+ const [idb, opfsFiles] = await Promise.all([
+ findIdbChunks(busy.slots),
listOpfsRecordings(),
]);
- const restore = idbChunkCount > 0 || opfsFiles.length > 0;
+ const recoverable = opfsFiles.filter((f) => !busy.fileNames.has(f.name));
+ const restore = idb.chunks.length > 0 || recoverable.length > 0;
return { restore };
};
@@ -87,7 +116,10 @@ export const restoreRecording = async () => {
} catch {}
// WebCodecs (4.4.0+) writes here; prefer most recent
- const opfsFiles = await listOpfsRecordings();
+ const busy = await openInAnEditor();
+ const opfsFiles = (await listOpfsRecordings()).filter(
+ (f) => !busy.fileNames.has(f.name),
+ );
if (opfsFiles.length > 0) {
opfsFiles.sort((a, b) => b.lastModified - a.lastModified);
const latest = opfsFiles[0];
@@ -102,6 +134,15 @@ export const restoreRecording = async () => {
const editorUrl = "editor.html?mode=recover";
chrome.tabs.create({ url: editorUrl, active: true }, async (tab) => {
chrome.storage.local.set({ sandboxTab: tab.id });
+ // A recovered recording is the one most worth protecting, and it had none
+ // before. The next recording wiped it.
+ registerRetainable({
+ recordingId: null,
+ backend: "opfs",
+ fileName: latest.name,
+ slot: null,
+ tabId: tab.id,
+ }).catch(() => {});
await new Promise((resolve) => {
let settled = false;
const safetyId = setTimeout(() => {
@@ -169,26 +210,27 @@ export const restoreRecording = async () => {
messageType = "viewer-recording";
}
- const chunks = [];
- try {
- await chunksStore.iterate((value) => {
- chunks.push(value);
- });
- } catch (err) {
- console.warn("[Screenity][BG] restoreRecording chunksStore.iterate failed", err);
- }
+ const { slot: idbSlot, chunks } = await findIdbChunks(busy.slots);
if (chunks.length === 0) {
console.warn("[Screenity][BG] restoreRecording: no OPFS files and no IDB chunks");
await notifyRestoreEmpty(triggerTabId);
return;
}
- // force IDB reader regardless of stale backendRef
+ // force IDB reader regardless of stale backendRef, naming the slot the chunks
+ // were actually found in
await chrome.storage.local.set({
- lastRecordingBackendRef: { backend: "idb" },
+ lastRecordingBackendRef: { backend: "idb", slot: idbSlot },
});
chrome.tabs.create({ url: editorUrl, active: true }, async (tab) => {
chrome.storage.local.set({ sandboxTab: tab.id });
+ registerRetainable({
+ recordingId: null,
+ backend: "idb",
+ fileName: null,
+ slot: idbSlot,
+ tabId: tab.id,
+ }).catch(() => {});
await new Promise((resolve) => {
let settled = false;
const safetyId = setTimeout(() => {
diff --git a/src/pages/Background/recording/resumePendingUploads.js b/src/pages/Background/recording/resumePendingUploads.js
index 6083d39..fb516f6 100644
--- a/src/pages/Background/recording/resumePendingUploads.js
+++ b/src/pages/Background/recording/resumePendingUploads.js
@@ -1,6 +1,14 @@
const JOURNAL_KEY_PREFIX = "uploadJournal-";
+const SESSION_KEY_PREFIX = "cloudRecorderSession:";
+// The uploader rewrites the whole journal on every persist, so a counter kept
+// inside it resets on each attempt and the cap never trips.
+const ATTEMPTS_KEY = "uploadResumeAttempts";
const MAX_RESUME_ATTEMPTS = 5;
const RESUME_LOCK_TTL_MS = 10 * 60 * 1000;
+// Same name as MIC_AWAIT_SCENE_ALARM in micRecovery.js, kept literal so this
+// module stays dependency-free for its tests.
+const MIC_AWAIT_SCENE_ALARM = "mic-recovery-await-scene";
+export const RESUME_RETRY_ALARM = "resume-pending-uploads-retry";
// `recording` flips false before the host has drained and finalized. Resuming
// inside that window puts two writers on one Bunny video.
const ACTIVE_PIPELINE_STEPS = new Set([
@@ -14,6 +22,20 @@ const ACTIVE_PIPELINE_STEPS = new Set([
]);
// Bounded so a host that died mid-drain can't block resume for good.
const PIPELINE_ACTIVE_TTL_MS = 2 * 60 * 1000;
+// CloudRecorder beats every 15s while it holds a take. Past this it is gone.
+const HOST_BUSY_TTL_MS = 90 * 1000;
+// stale-cleared and crashed are what a toolbar click or a closed recorder tab
+// rewrites a crashed take to.
+const RECOVERABLE_SESSION_STATUSES = new Set([
+ "recording",
+ "hidden",
+ "unload",
+ "stopping",
+ "finalize-failed",
+ "upload-stalled",
+ "stale-cleared",
+ "crashed",
+]);
const getAllStorage = () =>
new Promise((resolve) => {
@@ -35,15 +57,29 @@ const isResumableJournal = (journal) => {
const pickResumeCandidates = (storage) => {
const pending = [];
const abandonedKeys = [];
+ const attempts = storage[ATTEMPTS_KEY] || {};
+ const discarded = new Set(
+ Array.isArray(storage.discardedRecordingSessionIds)
+ ? storage.discardedRecordingSessionIds
+ : []
+ );
for (const [key, value] of Object.entries(storage)) {
if (!key.startsWith(JOURNAL_KEY_PREFIX)) continue;
if (!value || typeof value !== "object") continue;
+ if (value.sessionId && discarded.has(value.sessionId)) {
+ abandonedKeys.push(key);
+ continue;
+ }
// Audio resumes too: it's the transcription source, and the track most
// often left stranded.
if (!isResumableJournal(value)) continue;
if (value.status === "completed") continue;
// status is source of truth; offset>=totalBytes still needs finalize()
- if ((value.resumeAttempts || 0) >= MAX_RESUME_ATTEMPTS) {
+ const tries = Math.max(
+ attempts[value.mediaId] || 0,
+ value.resumeAttempts || 0
+ );
+ if (tries >= MAX_RESUME_ATTEMPTS) {
abandonedKeys.push(key);
continue;
}
@@ -55,6 +91,39 @@ const pickResumeCandidates = (storage) => {
return pending;
};
+// Settles from each take's snapshot, so a settle cut short by a closed doc
+// finishes on the next pass.
+const pickUnsettledSessions = (storage) =>
+ Object.entries(storage)
+ .filter(
+ ([key, session]) =>
+ key.startsWith(SESSION_KEY_PREFIX) &&
+ session?.id &&
+ RECOVERABLE_SESSION_STATUSES.has(session.status)
+ )
+ .map(([, session]) => session.id);
+
+// A resume doc never acks a shutdown, so leaving it open makes the next start
+// wait out the whole flush timeout.
+const closeResumeDoc = async () => {
+ try {
+ const contexts = await chrome.runtime.getContexts({
+ contextTypes: ["OFFSCREEN_DOCUMENT"],
+ });
+ if (contexts?.[0]?.documentUrl?.includes("resume=1")) {
+ await chrome.offscreen.closeDocument();
+ }
+ } catch {}
+};
+
+// Startup and install fire once. A skipped pass retries on its own, since the
+// next click is usually a new recording.
+const scheduleRetry = (delayInMinutes = 2) => {
+ try {
+ chrome.alarms?.create?.(RESUME_RETRY_ALARM, { delayInMinutes })?.catch?.(() => {});
+ } catch {}
+};
+
export const tryResumePendingUploads = async ({
trigger = "unknown",
} = {}) => {
@@ -65,35 +134,61 @@ export const tryResumePendingUploads = async ({
"resumeInProgress",
"resumeLockAt",
"recorderPipelineState",
+ "cloudRecorderHostBusy",
+ "screenityToken",
]);
if (snap.recording || snap.pendingRecording) {
return { skipped: "recording-active" };
}
+ // Nothing survives a browser start or extension reload, so a leftover step or
+ // beat belongs to the host that died.
+ const hostsCanBeAlive = !/^on(Startup|Installed)/.test(String(trigger));
const pipeline = snap.recorderPipelineState;
if (
+ hostsCanBeAlive &&
pipeline &&
ACTIVE_PIPELINE_STEPS.has(pipeline.step) &&
Date.now() - (pipeline.ts || 0) < PIPELINE_ACTIVE_TTL_MS
) {
+ scheduleRetry();
return { skipped: `pipeline-active-${pipeline.step}` };
}
+ const hostBusy = snap.cloudRecorderHostBusy;
+ if (
+ hostsCanBeAlive &&
+ hostBusy &&
+ Date.now() - (hostBusy.at || 0) < HOST_BUSY_TTL_MS
+ ) {
+ scheduleRetry();
+ return { skipped: "host-busy" };
+ }
+ const all = await getAllStorage();
+ const candidates = pickResumeCandidates(all);
+ const sessions = pickUnsettledSessions(all);
+ if (!candidates.length && !sessions.length) {
+ return { skipped: "nothing-to-recover" };
+ }
+ // Can't reach the server, so retry later. Signed out waits for the click
+ // after signing in.
+ if (globalThis.navigator?.onLine === false) {
+ scheduleRetry();
+ return { skipped: "offline" };
+ }
+ if (!snap.screenityToken) return { skipped: "signed-out" };
if (snap.resumeInProgress) {
const lockAge = Date.now() - (snap.resumeLockAt || 0);
if (lockAge < RESUME_LOCK_TTL_MS) {
+ scheduleRetry();
return { skipped: "resume-in-progress" };
}
console.warn("[ResumeUploads] stale lock detected, clearing");
}
- const all = await getAllStorage();
- const candidates = pickResumeCandidates(all);
- if (!candidates.length) {
- return { skipped: "no-pending-journals" };
- }
-
console.log(
- "[ResumeUploads] candidates found:",
+ "[ResumeUploads] journals:",
candidates.length,
+ "unsettled sessions:",
+ sessions.length,
"trigger:",
trigger,
);
@@ -120,6 +215,7 @@ export const tryResumePendingUploads = async ({
.sendMessage({
type: "resume-pending-uploads",
journals: candidates,
+ sessions,
trigger,
})
.catch((err) => ({
@@ -128,6 +224,21 @@ export const tryResumePendingUploads = async ({
}));
console.log("[ResumeUploads] offscreen response:", response);
+ if (response?.recovered?.some((r) => r?.micHeld)) {
+ // The mic waits for a scene that appears minutes after the upload.
+ try {
+ chrome.alarms
+ ?.create?.(MIC_AWAIT_SCENE_ALARM, {
+ delayInMinutes: 5,
+ periodInMinutes: 5,
+ })
+ ?.catch?.(() => {});
+ } catch {}
+ }
+ // A sign-in still settling at browser start fails tus-auth. Nothing else
+ // retries that take before the next click.
+ if (response?.results?.some((r) => r?.transient)) scheduleRetry(10);
+ await closeResumeDoc();
return response || { ok: false };
} finally {
await chrome.storage.local.set({
diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.js
index bd26fd9..d1880b2 100644
--- a/src/pages/Background/recording/startRecording.js
+++ b/src/pages/Background/recording/startRecording.js
@@ -6,6 +6,7 @@ import { makeRecordingAttemptId } from "../../utils/errorCodes";
import { lifecycle } from "../../utils/lifecycleLog";
import { sweepRecorderTabs } from "./sweepRecorderTabs";
import { emitRecordingTelemetry } from "./emitRecordingTelemetry";
+import { retainedTabIdsFor } from "./recordingRetention";
// `recording` flag isn't set until the recorder iframe inits (seconds later),
// so countdown-finished + 8s fallback can both fire and open two recorder tabs
@@ -199,8 +200,22 @@ const _startRecordingInner = async (caller) => {
"recordingType",
]);
- // Close every prior editor tab by URL (sandboxTab only tracks the last).
- // OPFS wipes on new recording, so a stale editor would read missing data.
+ // Computed before the sweep below, because it decides which editor tabs are
+ // holding a recording that survives and therefore must stay open.
+ let retainedTabIds = new Set();
+ try {
+ // Read, not recomputed. startRecorderSession published this before the
+ // recorder acted on it, and a second answer here would disagree.
+ const stored = await chrome.storage.local.get(["retentionPlan"]);
+ retainedTabIds = await retainedTabIdsFor(stored?.retentionPlan);
+ } catch (err) {
+ // Retention is best-effort. A failure here must not stop a recording, and
+ // falling through means the old wipe-everything behaviour.
+ console.warn("[Screenity][BG] retention plan failed", err);
+ }
+
+ // sandboxTab only tracks the last tab, so match by URL instead. Skip tabs
+ // holding a kept recording: closing one drops its only copy.
try {
// editor.html covers viewer mode too (editor.html?view=1); startsWith match.
const editorUrls = [chrome.runtime.getURL("editor.html")];
@@ -208,6 +223,7 @@ const _startRecordingInner = async (caller) => {
const editorTabs = allTabs.filter(
(t) =>
t.id != null &&
+ !retainedTabIds.has(t.id) &&
t.url &&
editorUrls.some((prefix) => t.url.startsWith(prefix)),
);
@@ -320,7 +336,7 @@ const _startRecordingInner = async (caller) => {
}
});
} else {
- chrome.storage.local.remove(["recordingMeta"]);
+ chrome.storage.local.remove(["recordingMeta", "recordedTabDomain"]);
}
chrome.storage.local.set({ lastRecordingType: recordingType || "screen" });
diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.js
index 02b8535..9b69858 100644
--- a/src/pages/Background/recording/stopRecording.js
+++ b/src/pages/Background/recording/stopRecording.js
@@ -4,8 +4,46 @@ import { sendMessageRecord } from "./sendMessageRecord";
import { sendChunks } from "./sendChunks";
import { waitForContentScript } from "../utils/waitForContentScript";
import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";
+import { registerRetainable } from "./recordingRetention";
import { perfMark, perfSpan } from "../../utils/perfMarks";
+// As soon as the editor tab exists, not inside the tab-load callbacks. Those
+// await the content script, and a slow load left the recording unprotected.
+const registerEditorTabForRetention = (tabId, recordingId) => {
+ if (typeof tabId !== "number") return;
+ chrome.storage.local
+ .get(["lastRecordingBackendRef", "activeChunkSlot", "recordingDuration"])
+ .then(async (r) => {
+ const fileName = r?.lastRecordingBackendRef?.fileName || null;
+ await registerRetainable({
+ recordingId: recordingId || null,
+ backend: r?.lastRecordingBackendRef?.backend || null,
+ fileName,
+ slot: r?.activeChunkSlot || null,
+ durationMs: r?.recordingDuration || 0,
+ tabId,
+ });
+ const { retainedRecordings } = await chrome.storage.local.get([
+ "retainedRecordings",
+ ]);
+ diagEvent("recorder-retention-registered", {
+ tabId,
+ recordingId: recordingId || null,
+ fileName,
+ backend: r?.lastRecordingBackendRef?.backend || null,
+ count: Array.isArray(retainedRecordings) ? retainedRecordings.length : 0,
+ });
+ })
+ .catch((err) => {
+ try {
+ diagEvent("recorder-retention-register-failed", {
+ tabId,
+ why: String(err).slice(0, 120),
+ });
+ } catch {}
+ });
+};
+
// resolves via onReady, onTimeout (30s), or onClosed
const onTabLoaded = (tabId, onReady, onTimeout = null, onClosed = null) => {
let cleared = false;
@@ -249,6 +287,7 @@ export const stopRecording = async () => {
handleEditorOpenFailed(wcUrl, chrome.runtime.lastError?.message);
return;
}
+ registerEditorTabForRetention(tab.id, postStopRecordingId || null);
onTabLoaded(
tab.id,
async () => {
@@ -301,6 +340,7 @@ export const stopRecording = async () => {
handleEditorOpenFailed(viewerUrl, chrome.runtime.lastError?.message);
return;
}
+ registerEditorTabForRetention(tab.id, postStopRecordingId || null);
onTabLoaded(
tab.id,
async () => {
@@ -350,6 +390,7 @@ export const stopRecording = async () => {
handleEditorOpenFailed(editorUrl, chrome.runtime.lastError?.message);
return;
}
+ registerEditorTabForRetention(tab.id, postStopRecordingId || null);
onTabLoaded(
tab.id,
async () => {
@@ -565,6 +606,7 @@ export const handleStopRecordingTab = async (request) => {
handleEditorOpenFailed(fullUrl, errMsg);
return;
}
+ registerEditorTabForRetention(tab.id, recordingId);
let settled = false;
let onUpdatedListener = null;
// 45s tolerates slow OPFS/editor mounts (saw 24s in prod); on fire
@@ -646,6 +688,7 @@ export const handleStopRecordingTab = async (request) => {
return;
}
perfMark("BG.stopRecording editor-tab-create.done", { tabId: tab.id });
+ registerEditorTabForRetention(tab.id, null);
let settled = false;
let onUpdatedListener = null;
// See matching block above for rationale (45s + final-check).
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 05f264e..75c873b 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -26,6 +26,10 @@ import {
screenSurfaceSwitching,
} from "../utils/screenCaptureMode";
import { acquireDisplayMediaWithFocusRetry } from "../utils/acquireDisplayMedia";
+import {
+ resolveCaptureSurface,
+ setCapturedSurface,
+} from "../utils/captureSurface";
import { startPrewarm, stopPrewarm } from "../Recorder/streamWarmup";
import { preloadWebCodecsModules } from "../Recorder/webcodecs/WebCodecsRecorder";
import {
@@ -73,11 +77,23 @@ localforage.config({
import { shouldSeparateAudio } from "./shouldSeparateAudio";
import {
- uploadAndAttachMic,
+ shouldMuxBusAudio,
+ needsContextResume,
+ isBusSilentFault,
+} from "./audioBusPolicy";
+import {
setPendingMicRecovery,
clearPendingMicRecovery,
runMicRecoveryScan,
} from "./micRecovery";
+// Upload and attach separately, not through uploadAndAttachMic: the upload
+// starts before the scene POST and the attach is only needed when the id did
+// not make it into the payload.
+import {
+ collectMicChunks,
+ uploadMicToStorage,
+ attachSceneAudio,
+} from "./uploadMicToStorage";
const API_BASE = process.env.SCREENITY_API_BASE_URL;
// Big mic file on a slow uplink, but a wedged POST must not hold the recorder
@@ -86,6 +102,11 @@ const SEPARATED_MIC_UPLOAD_BUDGET_MS = 120000;
// Tighter: this one sits in front of the countdown, so the user watches it.
// Over budget only the IDB chunks go, the same loss as not trying.
const START_MIC_RECOVERY_BUDGET_MS = 15000;
+// Runs beside video finalize and the silence check, so it is usually done
+// by the scene POST: born with the mic beats gaining a voice after the
+// editor already loaded. Short because the editor waits on this POST;
+// over budget falls back to the attach path.
+const PRE_SCENE_MIC_UPLOAD_BUDGET_MS = 2500;
// Enable the start-flow logs unconditionally for dev builds so the
// startup timeline is visible in the cloudrecorder tab console without
// needing to set `window.SCREENITY_DEBUG_RECORDER = true` first. Prod
@@ -134,6 +155,8 @@ const resolveExtVersion = () => {
}
};
const SESSION_STATE_INDEX_KEY = "cloudRecorderSessionStateIndex";
+// stale-cleared and crashed are what a toolbar click or a closed recorder tab
+// rewrite a crashed take to.
const RECOVERABLE_SESSION_STATUSES = new Set([
"recording",
"hidden",
@@ -141,7 +164,10 @@ const RECOVERABLE_SESSION_STATUSES = new Set([
"stopping",
"finalize-failed",
"upload-stalled",
+ "stale-cleared",
+ "crashed",
]);
+const HOST_BUSY_BEAT_MS = 15000;
// `let` (not `const`) so ensureChunkStoreReady() can swap each instance
// from the IDB default to an OPFS-backed adapter at session start. All
@@ -213,6 +239,14 @@ const IS_IFRAME_CONTEXT =
const CloudRecorder = () => {
const screenTimer = useRef({ start: null, total: 0, paused: false });
const cameraTimer = useRef({ start: null, total: 0, paused: false });
+ // The mic records on its own recorder, started after the video ones and able
+ // to die without them, so its length is measured rather than inherited.
+ const audioTimer = useRef({
+ start: null,
+ total: 0,
+ paused: false,
+ everStarted: false,
+ });
const [started, setStarted] = useState(false);
const [initProject, setInitProject] = useState(false);
const [finalizeFailure, setFinalizeFailure] = useState(null);
@@ -388,6 +422,8 @@ const CloudRecorder = () => {
const fatalErrorRef = useRef(false);
const idbReadyRef = useRef(false);
const recoveryAttempted = useRef(false);
+ const purgeMarksRef = useRef({});
+ const purgeMarkChainRef = useRef(Promise.resolve());
const recoveryExportedRef = useRef(false);
const screenTrackLostRef = useRef(false);
const screenTrackMonitor = useRef(null);
@@ -462,6 +498,18 @@ const CloudRecorder = () => {
// Live AudioContext interruption stats from attachAudioContextWatchdog,
// folded into the audio diag snapshot at finalize for upload telemetry.
const audioHealthRef = useRef(null);
+ // What is actually wired into the bus, not what the user asked for.
+ // The mux decision reads this so an empty bus is never encoded.
+ const busSources = useRef({ mic: false, system: false });
+ // Bus health at recording start, folded into the audio diag snapshot.
+ const busWarmupRef = useRef({
+ ran: false,
+ rms: null,
+ silentFault: false,
+ ctxResumedAtStart: false,
+ ctxStateAtStart: null,
+ });
+ const busTap = useRef(null);
const destination = useRef(null);
const keepAliveInterval = useRef(null);
@@ -1922,13 +1970,23 @@ const CloudRecorder = () => {
// chunk_0 stays: it's the init segment the crash-recovery and Download
// paths need. Unconfirmed chunks stay too, see selectPrefixChunksToDrop.
- const dropRetainedPrefix = async (store, keyPrefix, uploader, rangesRef) => {
+ const dropRetainedPrefix = async (
+ store,
+ keyPrefix,
+ uploader,
+ rangesRef,
+ confirmedOffset = null,
+ markIndex = Infinity
+ ) => {
const prefix = screenRetainedPrefixRef.current;
- const { drop, keptUnconfirmed } = selectPrefixChunksToDrop({
+ const selected = selectPrefixChunksToDrop({
prefix,
- lastServerOffset: Number(uploader?.lastServerOffset) || 0,
+ lastServerOffset:
+ confirmedOffset ?? (Number(uploader?.lastServerOffset) || 0),
safetyWindowBytes: CHUNK_PURGE_SAFETY_WINDOW_BYTES,
});
+ const keptUnconfirmed = selected.keptUnconfirmed;
+ const drop = selected.drop.filter((i) => i <= markIndex);
// Stop offering local playback either way: the opening is about to be
// partly gone, so an offer built from it would not decode.
screenRetainedPrefixRef.current = {
@@ -1983,6 +2041,40 @@ const CloudRecorder = () => {
}
};
+ // Where a track's chunks on disk pick up after the purged gap. Resume can't
+ // place the bytes that follow a gap without it.
+ const persistPurgeMark = (track, entry) => {
+ // Screen and camera share one key, so writes run one at a time or one
+ // track can put back the other's older mark after its chunks are gone.
+ const run = purgeMarkChainRef.current.then(() =>
+ writePurgeMark(track, entry)
+ );
+ purgeMarkChainRef.current = run.catch(() => false);
+ return run;
+ };
+
+ const writePurgeMark = async (track, entry) => {
+ const sessionId = recorderSession.current?.id;
+ if (!sessionId) return false;
+ if ((purgeMarksRef.current[track]?.index ?? -1) >= entry.index) return true;
+ const key = `chunkPurgeMarks:${sessionId}`;
+ const next = {
+ ...purgeMarksRef.current,
+ [track]: { index: entry.index, endByte: entry.endByte },
+ };
+ try {
+ await chrome.storage.local.set({ [key]: next });
+ // The offscreen storage proxy swallows a failed write, so only a read
+ // back proves the mark exists before anything is deleted.
+ const { [key]: stored } = await chrome.storage.local.get([key]);
+ if (stored?.[track]?.index !== entry.index) return false;
+ } catch {
+ return false;
+ }
+ purgeMarksRef.current = next;
+ return true;
+ };
+
// Purge IDB chunks Bunny has confirmed. chunk_0 (webm init segment) is preserved.
const purgeConfirmedChunks = async (
store,
@@ -2019,13 +2111,36 @@ const CloudRecorder = () => {
mode
) => {
const isScreen = trackLabel === "screen";
+ // One reading per pass. A PATCH landing mid-pass would otherwise widen the
+ // deletes past the mark just saved.
+ const confirmedOffset = Number(uploader.lastServerOffset) || 0;
+ const { untrack: confirmed } = selectChunksToPurge({
+ ranges: rangesRef.current,
+ lastServerOffset: confirmedOffset,
+ safetyWindowBytes: CHUNK_PURGE_SAFETY_WINDOW_BYTES,
+ prefixChunks: 0,
+ });
+ // Written before anything leaves disk, so a crash can't leave a gap
+ // resume has no position for.
+ const lastConfirmed = confirmed[confirmed.length - 1];
+ if (lastConfirmed && !(await persistPurgeMark(trackLabel, lastConfirmed))) {
+ return;
+ }
+ const markIndex = purgeMarksRef.current[trackLabel]?.index ?? -1;
if (isScreen && mode === "all") {
- await dropRetainedPrefix(store, keyPrefix, uploader, rangesRef);
+ await dropRetainedPrefix(
+ store,
+ keyPrefix,
+ uploader,
+ rangesRef,
+ confirmedOffset,
+ markIndex
+ );
}
const ranges = rangesRef.current;
const { untrack, purge } = selectChunksToPurge({
ranges,
- lastServerOffset: Number(uploader.lastServerOffset) || 0,
+ lastServerOffset: confirmedOffset,
safetyWindowBytes: CHUNK_PURGE_SAFETY_WINDOW_BYTES,
prefixChunks: isScreen ? screenRetainedPrefixRef.current.chunks : 0,
});
@@ -2033,6 +2148,7 @@ const CloudRecorder = () => {
let purgedCount = 0;
let purgedBytes = 0;
for (const entry of purge) {
+ if (entry.index > markIndex) break;
try {
// eslint-disable-next-line no-await-in-loop
await store.removeItem(`${keyPrefix}${entry.index}`);
@@ -2383,6 +2499,8 @@ const CloudRecorder = () => {
trackContainers: { ...trackContainers },
trackCodecs: { ...trackCodecs },
encoderHwSlots,
+ // Resume holds a separated mic's chunks on this. The container can't tell.
+ separatedAudio: separatedAudio.current,
updatedAt: Date.now(),
...overrides,
};
@@ -2442,6 +2560,7 @@ const CloudRecorder = () => {
trackContainers: { ...trackContainers },
trackCodecs: { ...trackCodecs },
encoderHwSlots,
+ separatedAudio: separatedAudio.current,
diag: captureSessionDiag(),
...meta,
};
@@ -2491,6 +2610,62 @@ const CloudRecorder = () => {
return true;
};
+ // Read the mixed bus for a moment after start. A silent bus with a live
+ // mic is the signature that costs the user their voice for the whole take.
+ const measureBusWarmup = async () => {
+ const analyser = busTap.current;
+ if (!analyser || busWarmupRef.current.ran) return;
+ busWarmupRef.current.ran = true;
+ const buf = new Float32Array(analyser.fftSize);
+ let peak = 0;
+ for (let i = 0; i < 6; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ if (isFinishing.current) return;
+ try {
+ analyser.getFloatTimeDomainData(buf);
+ } catch {
+ return;
+ }
+ let sum = 0;
+ for (let j = 0; j < buf.length; j++) sum += buf[j] * buf[j];
+ peak = Math.max(peak, Math.sqrt(sum / buf.length));
+ }
+ busWarmupRef.current.rms = peak;
+ const micTrack = rawMicStream.current?.getAudioTracks?.()[0] || null;
+ const fault = isBusSilentFault({
+ rms: peak,
+ micIntended: busSources.current.mic,
+ hasLiveMicTrack: Boolean(micTrack && micTrack.readyState === "live"),
+ });
+ busWarmupRef.current.silentFault = fault;
+ if (!fault) return;
+ // Backstop for anything that suspends the graph after start. Safe while
+ // unpaused, and never touches the gain the user muted deliberately.
+ if (
+ aCtx.current &&
+ needsContextResume({
+ state: aCtx.current.state,
+ paused: pausedStateRef.current,
+ })
+ ) {
+ try {
+ await aCtx.current.resume();
+ } catch {}
+ }
+ diagForward("audio-bus-silent-at-start", {
+ rms: peak,
+ ctxState: aCtx.current?.state ?? null,
+ ctxStateAtStart: busWarmupRef.current.ctxStateAtStart,
+ ctxResumedAtStart: busWarmupRef.current.ctxResumedAtStart,
+ busHasMic: busSources.current.mic,
+ busHasSystem: busSources.current.system,
+ micGain: audioInputGain.current?.gain?.value ?? null,
+ trackMuted: micTrack ? Boolean(micTrack.muted) : null,
+ trackEnabled: micTrack ? Boolean(micTrack.enabled) : null,
+ });
+ };
+
// MediaRecorder has no getDiagSnapshot(), so assemble the equivalent from
// sessionTrackState plus the live mic track. Null only when the mic wasn't
// part of the recording; zero bytes still returns a snapshot.
@@ -2539,6 +2714,19 @@ const CloudRecorder = () => {
typeof document !== "undefined" ? document.hidden : null,
visibilityState:
typeof document !== "undefined" ? document.visibilityState : null,
+ // What the mux actually got. micChosen true with busHasMic false is
+ // the separated take, and both false with a silent bus is the fault.
+ busHasMic: Boolean(busSources.current.mic),
+ busHasSystem: Boolean(busSources.current.system),
+ // Warm-up level on the mixed bus. Zero here with a live mic track is
+ // the full length silent AAC signature, readable without the file.
+ busRmsAtStart:
+ typeof busWarmupRef.current.rms === "number"
+ ? busWarmupRef.current.rms
+ : null,
+ busSilentAtStart: Boolean(busWarmupRef.current.silentFault),
+ ctxStateAtStart: busWarmupRef.current.ctxStateAtStart,
+ ctxResumedAtStart: Boolean(busWarmupRef.current.ctxResumedAtStart),
// AudioContext interruption cause-signal: an OS "interrupted" state
// feeds the destination silence, so chunksOut===0 here with
// sawInterrupted distinguishes a silent gap from a dead mic track.
@@ -2655,6 +2843,12 @@ const CloudRecorder = () => {
.catch(() => {});
throw err;
} finally {
+ if (!RECOVERABLE_SESSION_STATUSES.has(status)) {
+ chrome.storage.local
+ .remove([`chunkPurgeMarks:${sessionId}`, "cloudRecorderHostBusy"])
+ .catch(() => {});
+ }
+ purgeMarksRef.current = {};
recorderSession.current = null;
recordingSessionId.current = null;
sessionStateIndexedRef.current = false;
@@ -3183,85 +3377,8 @@ const CloudRecorder = () => {
}
};
- // Removes stale TUS journals, lookup keys, and Bunny video-map entries that
- // survive a process crash. Without this, the next session can resume the old
- // partial Bunny upload and append fresh chunks, producing a garbled video.
- // Also resets sceneId so the next session gets a fresh scene.
- const clearStaleUploadJournals = async (storedSession) => {
- const keysToRemove = [];
- const tracks = storedSession?.tracks || {};
-
- for (const trackData of Object.values(tracks)) {
- const upl = trackData?.uploader;
- if (!upl) continue;
-
- if (upl.journalKey) keysToRemove.push(upl.journalKey);
- if (upl.journalLookupKey) keysToRemove.push(upl.journalLookupKey);
-
- const pid = upl.projectId || storedSession?.projectId || null;
- const sid = upl.sceneId || null;
- const t = upl.type || upl.trackType || null;
- if (pid && t) {
- keysToRemove.push(
- `bunnyVideoMap-${pid}-${sid || "none"}-${t || "none"}`
- );
- }
- }
-
- // Reset sceneId so getOrCreateSceneId doesn't reuse a scene tied to cleared journals.
- keysToRemove.push("sceneId", "sceneIdStatus");
-
- const uniqKeys = [...new Set(keysToRemove)];
-
- const screenUpl = tracks.screen?.uploader || null;
- const cameraUpl = tracks.camera?.uploader || null;
-
- console.info(
- "[CloudRecorder] clearStaleUploadJournals: removing stale journal + sceneId keys",
- {
- sessionId: storedSession?.id || null,
- keyCount: uniqKeys.length,
- screen: {
- journalKey: screenUpl?.journalKey || null,
- mediaId: screenUpl?.mediaId || null,
- journalOffset: screenUpl?.offset || 0,
- journalTotalBytes: screenUpl?.totalBytes || 0,
- journalStatus: screenUpl?.status || null,
- },
- camera: {
- journalKey: cameraUpl?.journalKey || null,
- mediaId: cameraUpl?.mediaId || null,
- journalOffset: cameraUpl?.offset || 0,
- },
- }
- );
-
- void emitUploadTelemetry("upload_recovery_journals_cleared", {
- reason: "post-crash-recovery",
- sessionId: storedSession?.id || null,
- projectId: storedSession?.projectId || null,
- clearedKeyCount: uniqKeys.length,
- screenJournalKey: screenUpl?.journalKey || null,
- screenMediaId: screenUpl?.mediaId || null,
- screenJournalOffset: screenUpl?.offset || 0,
- screenJournalTotalBytes: screenUpl?.totalBytes || 0,
- screenJournalStatus: screenUpl?.status || null,
- cameraJournalKey: cameraUpl?.journalKey || null,
- cameraMediaId: cameraUpl?.mediaId || null,
- cameraJournalOffset: cameraUpl?.offset || 0,
- });
-
- if (!uniqKeys.length) return;
- try {
- await chrome.storage.local.remove(uniqKeys);
- } catch (err) {
- console.warn(
- "[CloudRecorder] clearStaleUploadJournals: failed to remove keys",
- { keys: uniqKeys, error: err?.message || String(err) }
- );
- }
- };
-
+ // Background resume owns a crashed take (resumeJournal.js), cleanup included.
+ // This host only has to stop the crashed take's scene id being reused.
const tryRecoverPreviousSession = useCallback(async () => {
if (recoveryAttempted.current) return;
recoveryAttempted.current = true;
@@ -3269,164 +3386,18 @@ const CloudRecorder = () => {
const { recorderSession: storedSession } = await chrome.storage.local.get(
["recorderSession"]
);
-
- // Recovery reads from whatever backend the previous session wrote to.
- // Sessions before the OPFS migration have no storageBackends field; fall
- // back to IDB across the board, matching pre-migration behaviour.
- const prevBackends = storedSession?.storageBackends || {
- screen: "idb",
- audio: "idb",
- camera: "idb",
- };
- const prevOpfsSessionId =
- storedSession?.opfsSessionId || storedSession?.id || null;
- const recoveryScreenStore = openExistingChunksStore({
- sessionId: prevOpfsSessionId,
- track: "screen",
- backend: prevBackends.screen || "idb",
- }).store;
- const recoveryCameraStore = openExistingChunksStore({
- sessionId: prevOpfsSessionId,
- track: "camera",
- backend: prevBackends.camera || "idb",
- }).store;
- const recoveryAudioStore = openExistingChunksStore({
- sessionId: prevOpfsSessionId,
- track: "audio",
- backend: prevBackends.audio || "idb",
- }).store;
-
- const [chunkCount, cameraChunkCount, audioChunkCount] = await Promise.all(
- [
- recoveryScreenStore.length().catch(() => 0),
- recoveryCameraStore.length().catch(() => 0),
- recoveryAudioStore.length().catch(() => 0),
- ]
- );
- const isRecoverable = RECOVERABLE_SESSION_STATUSES.has(
- storedSession?.status
- );
- const hasDurableChunks =
- chunkCount > 0 || cameraChunkCount > 0 || audioChunkCount > 0;
- if (storedSession && isRecoverable && hasDurableChunks) {
- void emitUploadTelemetry("upload_recovery_available", {
- reason: "durable-chunks",
- recoveredChunkCount: chunkCount,
- recoveredCameraChunkCount: cameraChunkCount,
- recoveredAudioChunkCount: audioChunkCount,
- recordingSessionId: storedSession?.id || null,
- projectId: storedSession?.projectId || null,
- screenStorageBackend: prevBackends.screen || "idb",
- cameraStorageBackend: prevBackends.camera || "idb",
- audioStorageBackend: prevBackends.audio || "idb",
- });
- const ts = new Date().toISOString();
-
- if (chunkCount > 0) {
- const recovered = [];
- await recoveryScreenStore.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-${ts}.webm`,
- saveAs: false,
- });
- } finally {
- // download() resolves before the blob fetch; delay revoke.
- setTimeout(() => {
- try {
- URL.revokeObjectURL(objectUrl);
- } catch {}
- }, 2000);
- }
- }
- }
-
- if (cameraChunkCount > 0) {
- const cameraRecovered = [];
- await recoveryCameraStore.iterate((value) => {
- cameraRecovered.push(value);
- });
- cameraRecovered.sort((a, b) => (a.index || 0) - (b.index || 0));
- const cameraBlob = createBlobFromChunks(
- cameraRecovered.map((c) => c.chunk),
- "video/webm"
- );
- if (cameraBlob) {
- const cameraObjectUrl = URL.createObjectURL(cameraBlob);
- try {
- await chrome.downloads.download({
- url: cameraObjectUrl,
- filename: `Screenity-Recovered-Camera-${ts}.webm`,
- saveAs: false,
- });
- } finally {
- setTimeout(() => {
- try {
- URL.revokeObjectURL(cameraObjectUrl);
- } catch {}
- }, 2000);
- }
- }
- }
-
- chrome.runtime.sendMessage({
- type: "show-toast",
- message: chrome.i18n.getMessage("toastRecoveredSession"),
- });
-
- await recoveryScreenStore.clear().catch(() => {});
- await recoveryAudioStore.clear().catch(() => {});
- await recoveryCameraStore.clear().catch(() => {});
- // If the previous session wrote anything to OPFS, drop the whole
- // session directory so the parent doesn't accumulate empty subdirs.
- const prevUsedOpfs = Object.values(prevBackends).some(
- (b) => b === "opfs"
- );
- if (prevUsedOpfs && prevOpfsSessionId) {
- destroySessionDir(prevOpfsSessionId).catch(() => {});
- }
- await clearStaleUploadJournals(storedSession);
- await chrome.storage.local.set({
- recorderSession: {
- ...storedSession,
- status: "recovered",
- recoveredAt: Date.now(),
- recoveredChunkCount: chunkCount,
- recoveredCameraChunkCount: cameraChunkCount,
- },
- });
- } else if (storedSession && isRecoverable) {
- void emitUploadTelemetry("upload_recovery_available", {
- reason: "metadata-only",
- recoveredChunkCount: 0,
- recordingSessionId: storedSession?.id || null,
- projectId: storedSession?.projectId || null,
- });
- // Even without durable chunks, video-map/lookup keys alone can cause a garbled resume.
- await clearStaleUploadJournals(storedSession);
- await chrome.storage.local.set({
- recorderSession: {
- ...storedSession,
- status: "recovery-metadata-only",
- recoveredAt: Date.now(),
- recoveredChunkCount: 0,
- },
- });
- } else {
- void emitUploadTelemetry("upload_recovery_unavailable", {
- reason: "no-recoverable-session",
- });
+ if (
+ !storedSession ||
+ !RECOVERABLE_SESSION_STATUSES.has(storedSession.status)
+ ) {
+ return;
}
+ await chrome.storage.local.remove(["sceneId", "sceneIdStatus"]);
+ void emitUploadTelemetry("upload_recovery_available", {
+ reason: "handed-to-resume",
+ recordingSessionId: storedSession.id,
+ projectId: storedSession.projectId || null,
+ });
} catch (err) {
console.warn("Recovery check failed:", err);
}
@@ -3710,6 +3681,8 @@ const CloudRecorder = () => {
micSource
.connect(audioInputGain.current)
.connect(destination.current);
+ if (busTap.current) audioInputGain.current.connect(busTap.current);
+ busSources.current.mic = true;
}
// Set either way, matching the eager path: later consumers read
// micStream as the audio bus.
@@ -3863,8 +3836,27 @@ const CloudRecorder = () => {
sendRecordingErrorBase(why, cancel);
};
+ // Written before the uploaders abort, so a browser dying mid-discard or
+ // mid-cancel can't have the take resumed back into the user's library.
+ const markSessionDiscarded = async () => {
+ try {
+ const discardedId = recorderSession.current?.id;
+ if (!discardedId) return;
+ const { discardedRecordingSessionIds: prev } =
+ await chrome.storage.local.get(["discardedRecordingSessionIds"]);
+ const list = Array.isArray(prev) ? prev : [];
+ await chrome.storage.local.set({
+ discardedRecordingSessionIds: [
+ ...list.filter((id) => id !== discardedId),
+ discardedId,
+ ].slice(-10),
+ });
+ } catch {}
+ };
+
const dismissRecording = async (restarting = false, reason = "dismiss") => {
clearPendingStart();
+ await markSessionDiscarded();
setInitProject(false);
await cleanupIfEmptyUploads(restarting ? "restart" : "dismiss");
@@ -5038,18 +5030,35 @@ const CloudRecorder = () => {
hasCamera: Boolean(cameraStream.current),
hasMic: Boolean(micStream.current),
});
+ // Pause suspends the graph and restart clears pausedStateRef without
+ // resuming, so the next take muxed silence for its whole length.
+ const ctxStateAtStart = aCtx.current?.state ?? null;
+ busWarmupRef.current.ctxStateAtStart = ctxStateAtStart;
+ busWarmupRef.current.ctxResumedAtStart = false;
+ busWarmupRef.current.ran = false;
+ busWarmupRef.current.rms = null;
+ busWarmupRef.current.silentFault = false;
+ if (
+ aCtx.current &&
+ needsContextResume({
+ state: ctxStateAtStart,
+ paused: pausedStateRef.current,
+ })
+ ) {
+ try {
+ await aCtx.current.resume();
+ busWarmupRef.current.ctxResumedAtStart = true;
+ } catch {}
+ diagForward("audio-bus-context-resumed", {
+ stateBefore: ctxStateAtStart,
+ stateAfter: aCtx.current?.state ?? null,
+ });
+ }
if (screenStream.current) {
setupTrack = "screen";
- // Stream-track presence isn't reliable: micStream is always
- // attached when a mic exists (the mix point for system audio)
- // and gain-muted when micActive=false. audioIntent reads from
- // BG before contentState's fresh-state auto-default can race.
- const { micActive, systemAudio } = audioIntent.current;
- // On a separated take the mic is not on the bus, so micActive says
- // nothing about whether the bus carries sound; attaching muxes silence.
- const screenHasAudio = separatedAudio.current
- ? systemAudio === true
- : micActive === true || systemAudio === true;
+ // What is wired into the bus, not what was asked for. Intent said
+ // "system audio on" with nothing connected, muxing full length silence.
+ const screenHasAudio = shouldMuxBusAudio(busSources.current);
const stream = screenHasAudio
? attachMicToStream(screenStream.current, micStream.current)
: // Strip incidental audio tracks (e.g. residual tab-capture
@@ -5175,11 +5184,8 @@ const CloudRecorder = () => {
notePausedDrop("screen", blob);
return;
}
- if (screenUploader.current.queuedBytes > 15 * 1024 * 1024) {
- await screenUploader.current
- .waitForPendingUploads?.()
- .catch(() => {});
- }
+ // No pre-write backpressure gate here: parking before write()
+ // lets the next chunk overtake this one into the byte stream.
await screenUploader.current.write(blob);
consecutiveScreenFailures.current = 0;
const endByte = Number(screenUploader.current?.totalBytes) || 0;
@@ -5254,6 +5260,8 @@ const CloudRecorder = () => {
});
screenRecorder.current.start(2000);
+ // Fire and forget: the samples take 1.5s and start latency is budgeted.
+ void measureBusWarmup();
// First-chunk watchdog (8s, chrome.alarms-backed).
chrome.runtime
@@ -5372,6 +5380,13 @@ const CloudRecorder = () => {
type: "show-toast",
message: chrome.i18n.getMessage("toastAudioCaptureDegraded"),
});
+ // The mic file stops here, so freeze its clock or it claims the
+ // whole session's length.
+ if (!audioTimer.current.paused && audioTimer.current.start) {
+ audioTimer.current.total +=
+ Date.now() - audioTimer.current.start;
+ audioTimer.current.paused = true;
+ }
try {
if (audioRecorder.current?.state === "recording") {
audioRecorder.current.stop();
@@ -5440,18 +5455,22 @@ const CloudRecorder = () => {
});
audioRecorder.current.start(2000);
+ // Same tick as start(), so the clock covers exactly what the file does.
+ audioTimer.current.start = Date.now();
+ audioTimer.current.total = 0;
+ audioTimer.current.paused = false;
+ audioTimer.current.everStarted = true;
}
if (cameraStream.current) {
setupTrack = "camera";
let streamToRecord = cameraStream.current;
- // Camera-only carries the mic in-stream; screen+camera routes audio
- // through the audio uploader so the camera track stays video-only.
- // audioIntent is the BG snapshot (see screen branch above for why).
+ // Camera-only carries the mic in-stream. Screen+camera routes audio through the
+ // audio uploader so the camera track stays video-only, same bus rule as screen.
if (
recordingType.current === "camera" &&
- audioIntent.current.micActive &&
+ shouldMuxBusAudio(busSources.current) &&
micStream.current
) {
streamToRecord = attachMicToStream(
@@ -5621,6 +5640,8 @@ const CloudRecorder = () => {
});
cameraRecorder.current.start(2000);
+ // Camera-only muxes the mic too, and the screen call site never runs.
+ void measureBusWarmup();
scheduleCameraSilenceCheck();
}
@@ -5663,6 +5684,16 @@ const CloudRecorder = () => {
cameraTimer.current.paused = false;
cameraTimer.current.total = 0;
}
+ // A restart that loses the mic would otherwise report the previous take's
+ // measured length.
+ if (!audioRecorder.current) {
+ audioTimer.current = {
+ start: null,
+ total: 0,
+ paused: false,
+ everStarted: false,
+ };
+ }
lastUploadProgress.current = {
screen: screenUploader.current?.offset || 0,
@@ -5695,6 +5726,12 @@ const CloudRecorder = () => {
}
cameraTimer.current.start = null;
cameraTimer.current.paused = false;
+ if (!audioTimer.current.paused && audioTimer.current.start) {
+ audioTimer.current.total =
+ (audioTimer.current.total || 0) + (now - audioTimer.current.start);
+ }
+ audioTimer.current.start = null;
+ audioTimer.current.paused = false;
}
const stopAllRecorders = async ({ stopStreams = true } = {}) => {
@@ -5732,6 +5769,13 @@ const CloudRecorder = () => {
}
};
+ // Freeze the mic clock here, not at cleanupTimers: the drain below waits on
+ // onstop and pending writes, and none of that time is in the file.
+ if (!audioTimer.current.paused && audioTimer.current.start) {
+ audioTimer.current.total += Date.now() - audioTimer.current.start;
+ audioTimer.current.paused = true;
+ }
+
await Promise.all([
stopRecorder(screenRecorder),
stopRecorder(cameraRecorder),
@@ -5756,6 +5800,10 @@ const CloudRecorder = () => {
destination.current = null;
audioInputGain.current = null;
audioOutputGain.current = null;
+ // The tap belongs to the closed context, and nothing is on the bus
+ // any more. Both are rebuilt with the next graph.
+ busTap.current = null;
+ busSources.current = { mic: false, system: false };
}
};
@@ -5783,13 +5831,17 @@ const CloudRecorder = () => {
const screen = getDuration(screenTimer.current);
const camera = getDuration(cameraTimer.current);
+ // Bunny can't measure an audio-only track (reports 1), so this number is
+ // the only duration the mic media ever gets. Muxed shapes have no mic
+ // recorder and keep the video timer.
+ const audio = audioTimer.current.everStarted
+ ? getDuration(audioTimer.current)
+ : Math.max(screen, camera);
return {
screen,
camera,
- // The mic starts, pauses and stops with the session, so the live video
- // timer is its length. Bunny can't measure an audio-only track, reports 1.
- audio: Math.max(screen, camera),
+ audio,
fallbackMs:
firstChunkTime.current && lastTimecode.current
? Math.max(0, lastTimecode.current - firstChunkTime.current)
@@ -6067,6 +6119,30 @@ const CloudRecorder = () => {
};
}, []);
+ // Tells background resume this host still holds a take, including a post-stop
+ // drain or open retry modal no pipeline step covers.
+ useEffect(() => {
+ const beat = () => {
+ if (
+ !recorderSession.current &&
+ !finalizeFailureRef.current &&
+ !isInit.current
+ ) {
+ return;
+ }
+ chrome.storage.local
+ .set({
+ cloudRecorderHostBusy: {
+ at: Date.now(),
+ sessionId: recorderSession.current?.id || null,
+ },
+ })
+ .catch(() => {});
+ };
+ const id = setInterval(beat, HOST_BUSY_BEAT_MS);
+ return () => clearInterval(id);
+ }, []);
+
useEffect(() => {
tryRecoverPreviousSession();
}, [tryRecoverPreviousSession]);
@@ -6232,12 +6308,13 @@ const CloudRecorder = () => {
const createSceneOrHandleMultiMode = async (
uploadMeta,
durations,
- isSilent
+ isSilent,
+ separatedMic = null
) => {
const {
projectId,
clickEvents = [],
- surface,
+ capturedSurface = null,
multiMode,
multiSceneCount = 0,
multiLastSceneId = null,
@@ -6248,7 +6325,7 @@ const CloudRecorder = () => {
} = await chrome.storage.local.get([
"projectId",
"clickEvents",
- "surface",
+ "capturedSurface",
"multiMode",
"multiSceneCount",
"multiLastSceneId",
@@ -6346,16 +6423,18 @@ const CloudRecorder = () => {
audioMediaId: separatedAudio.current
? null
: uploadMeta.audio?.mediaId || null,
- // Null on a separated take: the mic uploads after this POST so the
- // editor isn't held behind it; attach-scene-audio fills it in.
- audioSourceMediaId: null,
- // No audioLayout: the server derives it from the mic's media doc, which
- // does not exist yet. attach-scene-audio marks the scene later.
+ // The mic id, when its upload beat this POST: the scene is born with
+ // its voice instead of gaining one after the editor already read it.
+ // Null means the upload lost the race; attach-scene-audio fills it in
+ // after, as before.
+ audioSourceMediaId: separatedMic?.mediaId || null,
+ // No audioLayout: the server reads it off the mic's media doc, which
+ // /api/bunny/upload stamped 'separated' when the file went up.
recordingSessionId: recorderSession.current?.id || null,
durations,
captionSource: uploadMeta.screen ? "screen" : "camera",
transcriptionSourceMediaId: !isSilent
- ? uploadMeta.audio?.mediaId || null
+ ? uploadMeta.audio?.mediaId || separatedMic?.mediaId || null
: null,
thumbnail: uploadMeta.screen?.thumbnail || null,
dimensions: {
@@ -6369,7 +6448,9 @@ const CloudRecorder = () => {
: null,
},
clickEvents: scaledClickEvents,
- surface,
+ // Omitted when unknown: the app defaults to monitor, and a
+ // guess would be worse than that default.
+ ...(capturedSurface ? { surface: capturedSurface } : {}),
instantMode: instantMode.current,
newProject: !recordingToScene && (!multiMode || multiSceneCount === 0),
insertAfterSceneId,
@@ -6435,6 +6516,8 @@ const CloudRecorder = () => {
sceneId,
screenMediaId: uploadMeta.screen?.mediaId || null,
cameraMediaId: uploadMeta.camera?.mediaId || null,
+ // Not the mic: a recovered scene carries no micIncluded, so the
+ // attach path gives it its voice instead of naming it twice.
audioMediaId: uploadMeta.audio?.mediaId || null,
// Pass the duration + capture dims so the server can stamp
// them onto the media docs (and therefore the scene) right
@@ -6518,7 +6601,13 @@ const CloudRecorder = () => {
]).then(() => {
logDebugEvent("scene-create-complete", { projectId, sceneId });
});
- return { created: true };
+ // micIncluded is claimed only here, by the POST that carried the id.
+ // A reused scene's earlier POST sent none; a recovered one never sent
+ // this payload at all. Both still need the attach.
+ return {
+ created: true,
+ micIncluded: Boolean(separatedMic?.mediaId),
+ };
}
}
@@ -6997,6 +7086,75 @@ const CloudRecorder = () => {
}
const audioBlob = await buildAudioBlobFromDurableStore();
+
+ // Starts ahead of the scene POST: the POST releases the editor and
+ // nothing refetches the scene after, so a mic attached later only shows
+ // up if the user reloads. Sending the media id in the payload avoids that.
+ //
+ // Not at the drain (chunks are complete by then): the no-upload check
+ // above can still abandon the take, and nothing sweeps an unreferenced
+ // Bunny Storage upload, so starting earlier would strand a file for a
+ // recording that was never saved.
+ //
+ // Ahead of the silence check on purpose: isAudioSilent decodes the whole
+ // track on this thread, so overlapping it with the in-flight POST is
+ // free; the other order adds the decode to the wait.
+ const willUploadMic = Boolean(
+ separatedAudio.current && audioRecorder.current
+ );
+ let micUploadPromise = null;
+ if (willUploadMic) {
+ // Claimed before the scene POST: createSceneOrHandleMultiMode sends
+ // editor-ready, and the BG starts discarding this document on arrival,
+ // so a flag set afterwards is never seen.
+ await chrome.storage.local.set({
+ micUploadInFlight: { at: Date.now(), sceneId: uploadMeta.sceneId },
+ });
+ // Marker first, cleared on success, so a tab dying mid-upload leaves the
+ // launch scan something to find. Gated on the recorder, not the store:
+ // the store exists on every take, so a mic-off one overwrote real markers.
+ await setPendingMicRecovery({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ duration: usedDurations.audio || null,
+ mimeType: trackContainers.audio || "audio/webm",
+ // Audio goes to OPFS where supported, so the scan needs both to
+ // reopen the same store rather than an empty one.
+ sessionId: storageOpfsSessionId,
+ backend: storageBackends.audio || "idb",
+ // So a recovered mic still queues captions against the right video
+ // track, which the scene POST could not name.
+ targetMediaId:
+ uploadMeta.screen?.mediaId || uploadMeta.camera?.mediaId || null,
+ });
+ micRecoveryPending.current = true;
+ micUploadPromise = (async () => {
+ const { screenityToken } = await chrome.storage.local.get([
+ "screenityToken",
+ ]);
+ // The blob above already holds every chunk and uploadMicToStorage
+ // re-wraps whatever it's handed, so pass it instead of reading the
+ // store again. Empty means the store gave nothing back; fall back to
+ // its own read for a memory-only take.
+ const chunks =
+ audioBlob && audioBlob.size > 0
+ ? [audioBlob]
+ : await collectMicChunks(audioChunksStore);
+ if (!chunks.length) return { ok: false, reason: "no-chunks" };
+ return uploadMicToStorage({
+ chunks,
+ mimeType: trackContainers.audio || "audio/webm",
+ sceneId: uploadMeta.sceneId,
+ projectId,
+ duration: usedDurations.audio || null,
+ token: screenityToken,
+ });
+ })().catch((err) => ({
+ ok: false,
+ reason: err?.message || String(err),
+ }));
+ }
+
const silent = audioBlob ? await isAudioSilent(audioBlob) : true;
await upsertPendingScene(uploadMeta.sceneId, {
@@ -7049,12 +7207,6 @@ const CloudRecorder = () => {
);
}
- // Claimed before the scene POST: createSceneOrHandleMultiMode sends
- // editor-ready, and the BG starts discarding this document on arrival,
- // so a flag set afterwards is never seen.
- const willUploadMic = Boolean(
- separatedAudio.current && audioRecorder.current
- );
diagForward("mic-upload-decision", {
willUploadMic,
separated: separatedAudio.current,
@@ -7063,16 +7215,38 @@ const CloudRecorder = () => {
rawMicTracks: rawMicStream.current?.getAudioTracks?.().length || 0,
audioStoreReady: audioChunkStoreReadyRef.current,
});
- if (willUploadMic) {
- await chrome.storage.local.set({
- micUploadInFlight: { at: Date.now(), sceneId: uploadMeta.sceneId },
+ // Gives the upload started before the silence check a short window to
+ // land, so the scene can be created holding its own voice. Short
+ // because the editor waits on this POST; over budget, the scene goes
+ // out without the mic and the attach below fills it in, same as
+ // before this change.
+ let separatedMic = null;
+ if (micUploadPromise) {
+ const raced = await Promise.race([
+ micUploadPromise,
+ new Promise((r) =>
+ setTimeout(
+ () => r({ ok: false, reason: "pre-scene-budget" }),
+ PRE_SCENE_MIC_UPLOAD_BUDGET_MS
+ )
+ ),
+ ]);
+ if (raced?.ok && raced.mediaId) {
+ separatedMic = { mediaId: raced.mediaId, url: raced.url || null };
+ }
+ diagForward("separated-mic-pre-scene", {
+ won: Boolean(separatedMic),
+ reason: raced?.reason || null,
});
}
- await createSceneOrHandleMultiMode(uploadMeta, usedDurations, silent);
+ const sceneResult = await createSceneOrHandleMultiMode(
+ uploadMeta,
+ usedDurations,
+ silent,
+ separatedMic
+ );
- // Before the mic upload, not after: that POST is the whole mic file and
- // awaiting it held the editor shut for its duration.
if (!willUploadMic) {
await chrome.storage.local
.remove(["micUploadInFlight"])
@@ -7081,25 +7255,35 @@ const CloudRecorder = () => {
chrome.runtime.sendMessage({ type: "video-ready", uploadMeta });
- // Marker first, cleared on success, so a tab dying mid-upload leaves the
- // launch scan something to find. Gated on the recorder, not the store:
- // the store exists on every take, so a mic-off one overwrote real markers.
- if (willUploadMic) {
- await setPendingMicRecovery({
- projectId,
- sceneId: uploadMeta.sceneId,
- duration: usedDurations.audio || null,
- mimeType: trackContainers.audio || "audio/webm",
- // Audio goes to OPFS where supported, so the scan needs both to
- // reopen the same store rather than an empty one.
- sessionId: storageOpfsSessionId,
- backend: storageBackends.audio || "idb",
- // So a recovered mic still queues captions against the right video
- // track, which the scene POST could not name.
- targetMediaId:
- uploadMeta.screen?.mediaId || uploadMeta.camera?.mediaId || null,
+ // The marker and the upload were both claimed before the POST, so there
+ // are only two cases left: the scene already names the mic, or it does
+ // not and still needs the attach.
+ if (willUploadMic && sceneResult?.micIncluded && separatedMic) {
+ micRecoveryPending.current = false;
+ await clearPendingMicRecovery(uploadMeta.sceneId);
+ await chrome.storage.local
+ .remove(["micUploadInFlight"])
+ .catch(() => {});
+ diagForward("separated-mic-in-scene", {
+ mediaId: String(separatedMic.mediaId).slice(0, 40),
});
- micRecoveryPending.current = true;
+ // The POST named the mic as its transcription source, but
+ // uploadMeta.audio is still empty on a separated take and
+ // handleTranscription reads it.
+ if (!silent) {
+ uploadMeta.audio = {
+ ...(uploadMeta.audio || {}),
+ mediaId: separatedMic.mediaId,
+ separated: true,
+ };
+ handleTranscription(uploadMeta, projectId).catch((err) =>
+ console.warn(
+ "[CloudRecorder] separated handleTranscription failed:",
+ err
+ )
+ );
+ }
+ } else if (willUploadMic) {
try {
const { screenityToken } = await chrome.storage.local.get([
"screenityToken",
@@ -7107,15 +7291,11 @@ const CloudRecorder = () => {
// Budgeted: this sits ahead of pipeline-completed, finalize and
// window.close, so a stalled several-hundred-MB POST would hold the
// tab and its capture binding open. Timing out leaves the marker.
- const result = await Promise.race([
- uploadAndAttachMic({
- store: audioChunksStore,
- projectId,
- sceneId: uploadMeta.sceneId,
- duration: usedDurations.audio || null,
- mimeType: trackContainers.audio || "audio/webm",
- token: screenityToken,
- }),
+ // Waits on the upload already in flight rather than starting a
+ // second one.
+ const uploaded = await Promise.race([
+ micUploadPromise ||
+ Promise.resolve({ ok: false, reason: "no-upload-started" }),
new Promise((r) =>
setTimeout(
() => r({ ok: false, reason: "inline-upload-timeout" }),
@@ -7123,6 +7303,31 @@ const CloudRecorder = () => {
)
),
]);
+ // A reused or recovered scene reaches here too, and that is the
+ // point: the POST behind it carried no mic id, so this attach is
+ // what gives it a voice.
+ const result = !uploaded?.ok
+ ? { ok: false, reason: `upload-${uploaded?.reason || "unknown"}` }
+ : await (async () => {
+ const attached = await attachSceneAudio({
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ audioMediaId: uploaded.mediaId,
+ duration: usedDurations.audio || null,
+ token: screenityToken,
+ });
+ return attached.ok
+ ? {
+ ok: true,
+ mediaId: uploaded.mediaId,
+ attached: attached.attached,
+ }
+ : {
+ ok: false,
+ reason: `attach-${attached.reason}`,
+ mediaId: uploaded.mediaId,
+ };
+ })();
if (result.ok) {
micRecoveryPending.current = false;
await clearPendingMicRecovery(uploadMeta.sceneId);
@@ -7390,6 +7595,9 @@ const CloudRecorder = () => {
// Only the screen branch supersamples; clear it so a later take can't
// inherit a previous recording's value.
captureCapRef.current = null;
+ // Same for the reported surface: unknown until this attempt's
+ // stream is up, and a camera take never sets one.
+ await setCapturedSurface(null);
const prewarmedStream = streamOpts.prewarmedStream || null;
const { width = 1920, height = 1080 } = getResolutionForQuality() || {};
@@ -7481,6 +7689,16 @@ const CloudRecorder = () => {
src.connect(ctx.destination);
}
+ // Report what was cropped, not the crop. preferCurrentTab
+ // makes this browser unless the user switched panes.
+ await setCapturedSurface(
+ resolveCaptureSurface(
+ screenStream.current.getVideoTracks()[0].getSettings()
+ .displaySurface,
+ { isTab: isTab.current }
+ )
+ );
+
bindScreenTrack(screenStream.current.getVideoTracks()[0]);
} catch (err) {
if (isUserCaptureCancel(err)) {
@@ -7847,7 +8065,17 @@ const CloudRecorder = () => {
});
}
- traceStep("streamAcquired", { surface: surface || null });
+ // tabCapture streams carry no displaySurface, so fall back to
+ // isTab. Unknown stays unset and the scene payload omits it.
+ const capturedSurface = resolveCaptureSurface(surface, {
+ isTab: isTab.current,
+ });
+ await setCapturedSurface(capturedSurface);
+
+ traceStep("streamAcquired", {
+ surface: surface || null,
+ capturedSurface,
+ });
setTimeout(() => {
traceStep("preparingSent");
@@ -7894,6 +8122,11 @@ const CloudRecorder = () => {
let boundSurface = surface;
track.addEventListener("configurationchange", () => {
const next = track.getSettings();
+ void setCapturedSurface(
+ resolveCaptureSurface(next.displaySurface, {
+ isTab: isTab.current,
+ })
+ );
chrome.storage.local.set({
surface: next.displaySurface,
recordedStreamDimensions: {
@@ -7987,6 +8220,13 @@ const CloudRecorder = () => {
console.log(
"[CloudRecorder] getDisplayMedia fallback OK after streamId rejection"
);
+ await setCapturedSurface(
+ resolveCaptureSurface(
+ screenStream.current.getVideoTracks()[0].getSettings()
+ .displaySurface,
+ { isTab: isTab.current }
+ )
+ );
bindScreenTrack(screenStream.current.getVideoTracks()[0]);
} catch (fallbackErr) {
// Stop the pre-acquired camera so the LED doesn't stay on.
@@ -8157,6 +8397,13 @@ const CloudRecorder = () => {
const rawTrack = rawMicStream.current?.getAudioTracks?.()[0];
if (rawTrack) {
rawTrack.addEventListener("ended", () => {
+ // The take carries on for system audio, but the mic file stops
+ // here, so freeze its clock or it claims the session's length.
+ if (!audioTimer.current.paused && audioTimer.current.start) {
+ audioTimer.current.total +=
+ Date.now() - audioTimer.current.start;
+ audioTimer.current.paused = true;
+ }
const startMs = screenTimer.current?.start || null;
const dur = startMs ? Date.now() - startMs : null;
const SALVAGE_THRESHOLD_MS = 30000;
@@ -8211,6 +8458,15 @@ const CloudRecorder = () => {
"CloudRecorder"
);
destination.current = aCtx.current.createMediaStreamDestination();
+ // Parallel tap so the warm-up check can read the mixed bus. A
+ // MediaStreamDestination is a sink and cannot be analysed directly.
+ busSources.current = { mic: false, system: false };
+ try {
+ busTap.current = aCtx.current.createAnalyser();
+ busTap.current.fftSize = 2048;
+ } catch {
+ busTap.current = null;
+ }
// A stereo destination duplicates a mono mic, wasting half the AAC bitrate.
// System audio only joins at start, so the lazy setMic path stays stereo.
audioBusChannels.current = null;
@@ -8248,6 +8504,8 @@ const CloudRecorder = () => {
micSource
.connect(audioInputGain.current)
.connect(destination.current);
+ if (busTap.current) audioInputGain.current.connect(busTap.current);
+ busSources.current.mic = true;
micStream.current = destination.current.stream;
const { micActive } = await chrome.storage.local.get(["micActive"]);
@@ -8265,6 +8523,8 @@ const CloudRecorder = () => {
screenSource
.connect(audioOutputGain.current)
.connect(destination.current);
+ if (busTap.current) audioOutputGain.current.connect(busTap.current);
+ busSources.current.system = true;
// Diagnostic only: system/tab audio can die mid-recording (tab closed,
// OS mute, BT disconnect). Log it, don't stop; video/mic continue.
@@ -8821,6 +9081,8 @@ const CloudRecorder = () => {
const timeoutMs = Number(request.timeoutMs) || 20000;
(async () => {
try {
+ // Only cancel and discard send shouldFinalize:false.
+ if (request.shouldFinalize === false) await markSessionDiscarded();
if (isInit.current) {
await stopRecording(
request.shouldFinalize !== false,
@@ -8899,6 +9161,16 @@ const CloudRecorder = () => {
cameraTimer.current.total += now - cameraTimer.current.start;
cameraTimer.current.paused = true;
}
+ // Gated on the recorder: a pause landing during mic setup is skipped for
+ // the mic alone, and the clock has to track the file, not the session.
+ if (
+ audioRecorder.current?.state === "paused" &&
+ !audioTimer.current.paused &&
+ audioTimer.current.start
+ ) {
+ audioTimer.current.total += now - audioTimer.current.start;
+ audioTimer.current.paused = true;
+ }
pausedStateRef.current = true;
void setRecordingTimingState({
paused: true,
@@ -8935,6 +9207,13 @@ const CloudRecorder = () => {
cameraTimer.current.start = now;
cameraTimer.current.paused = false;
}
+ if (
+ audioTimer.current.paused &&
+ audioRecorder.current?.state === "recording"
+ ) {
+ audioTimer.current.start = now;
+ audioTimer.current.paused = false;
+ }
pausedStateRef.current = false;
void (async () => {
try {
diff --git a/src/pages/CloudRecorder/audioBusPolicy.js b/src/pages/CloudRecorder/audioBusPolicy.js
new file mode 100644
index 0000000..afb3de3
--- /dev/null
+++ b/src/pages/CloudRecorder/audioBusPolicy.js
@@ -0,0 +1,30 @@
+// What the screen/camera mux should do with the shared audio bus.
+// An empty or frozen bus encodes as full length silent AAC, unrecoverable.
+
+// Attach only when something is actually connected. A separated take keeps
+// the mic off the bus, and system audio can be requested but never granted.
+export const shouldMuxBusAudio = ({
+ busHasMic = false,
+ busHasSystem = false,
+} = {}) => Boolean(busHasMic || busHasSystem);
+
+// A suspended AudioContext feeds its MediaStreamDestination digital silence.
+// Pause suspends it on purpose, so only resume when we are not paused.
+export const needsContextResume = ({ state, paused = false } = {}) =>
+ state === "suspended" && !paused;
+
+// Below this the bus is digital silence rather than a quiet room. Measured
+// against float samples, so it sits far under any real noise floor.
+export const BUS_SILENCE_RMS = 1e-5;
+
+// Silent bus while the user asked for a mic and a live mic track exists.
+// That combination is always a fault, never a quiet speaker.
+export const isBusSilentFault = ({
+ rms = null,
+ micIntended = false,
+ hasLiveMicTrack = false,
+} = {}) =>
+ typeof rms === "number" &&
+ rms < BUS_SILENCE_RMS &&
+ micIntended &&
+ hasLiveMicTrack;
diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.js
index 1fb19a2..5bac0b2 100644
--- a/src/pages/CloudRecorder/bunnyTusUploader.js
+++ b/src/pages/CloudRecorder/bunnyTusUploader.js
@@ -437,6 +437,38 @@ export default class BunnyTusUploader {
}
}
+ // Tombstone rather than delete. Settle reads an absent journal as "nothing
+ // left to save" and reaps the local bytes, so a resume that never concluded
+ // has to leave one behind.
+ async invalidateUploadJournal(journal = null) {
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return;
+ const mediaId = journal?.mediaId || this.mediaId || null;
+ const journalKey = journal?.key || this.getJournalKey(mediaId);
+ const lookupKey = journal?.lookupKey || this.journalLookupKey;
+ try {
+ const stored = journalKey
+ ? (await chrome.storage.local.get([journalKey]))[journalKey]
+ : null;
+ const base = stored || journal || null;
+ if (journalKey && base) {
+ await chrome.storage.local.set({
+ [journalKey]: {
+ ...base,
+ status: "invalidated",
+ uploadUrl: null,
+ invalidatedAt: Date.now(),
+ },
+ });
+ }
+ if (lookupKey) await chrome.storage.local.remove([lookupKey]);
+ this.notifyStateChange("journal-invalidated");
+ } catch (err) {
+ this.debugLog("Failed to invalidate upload journal", {
+ error: err?.message || err,
+ });
+ }
+ }
+
async persistUploadJournal({ force = false } = {}) {
if (
typeof chrome === "undefined" ||
@@ -660,7 +692,8 @@ export default class BunnyTusUploader {
sceneId,
type,
});
- await this.clearUploadJournal({
+ await this.invalidateUploadJournal({
+ ...(candidate.journal || {}),
key: candidate.key,
lookupKey: candidate.lookupKey,
mediaId: candidate.journal?.mediaId || null,
@@ -872,6 +905,9 @@ export default class BunnyTusUploader {
}
this.videoId = reuse.videoId;
this.mediaId = reuse.mediaId;
+ // Crash recovery hands over the journal's upload so the HEAD below
+ // continues at the server's offset instead of a new upload at byte 0.
+ if (reuse.uploadUrl) this.uploadUrl = reuse.uploadUrl;
} else if (resumeJournal?.videoId && resumeJournal?.mediaId) {
this.initializedFromResume = true;
this.videoId = resumeJournal.videoId;
@@ -1049,7 +1085,7 @@ export default class BunnyTusUploader {
videoId: String(this.videoId || ""),
});
try {
- await this.clearUploadJournal();
+ await this.invalidateUploadJournal();
} catch {}
try {
const mapKey = this.getVideoMapKey(
@@ -1278,13 +1314,13 @@ export default class BunnyTusUploader {
throw new Error(`Uploader in error state: ${this.error}`);
}
- await this.checkAuthExpiration();
this.status = "uploading";
if (!this.hasEmittedClientStarted) {
this.hasEmittedClientStarted = true;
this.emitTelemetry("upload_client_started");
}
+ // Enqueue before any await, so concurrent write() calls keep call order.
for (let i = 0; i < chunk.size; i += this.CHUNK_SIZE) {
const subChunk = chunk.slice(i, i + this.CHUNK_SIZE);
this.chunkQueue.push(subChunk);
@@ -1292,6 +1328,7 @@ export default class BunnyTusUploader {
this.totalBytes += subChunk.size;
}
this.lastChunkQueuedAt = Date.now();
+ await this.checkAuthExpiration();
this.scheduleJournalPersist();
if (!this.isProcessingQueue) {
diff --git a/src/pages/CloudRecorder/micRecovery.js b/src/pages/CloudRecorder/micRecovery.js
index ec89465..0074c4a 100644
--- a/src/pages/CloudRecorder/micRecovery.js
+++ b/src/pages/CloudRecorder/micRecovery.js
@@ -11,6 +11,10 @@ import {
const API_BASE = process.env.SCREENITY_API_BASE_URL;
const MARKER_KEY = "pendingMicRecovery";
+export const MIC_AWAIT_SCENE_ALARM = "mic-recovery-await-scene";
+// Longer than the stop path's 120s inline budget plus margin, so a flag left
+// behind by a closed tab can't block the scan forever.
+const INLINE_UPLOAD_FRESH_MS = 5 * 60 * 1000;
// Past a week the Bunny signature is useless and the marker is likelier a
// stale profile than a real debt.
const MAX_MARKER_AGE_MS = 7 * 24 * 60 * 60 * 1000;
@@ -81,6 +85,9 @@ export const listPendingMicRecovery = async () => {
return Object.values(map).sort((a, b) => (a.at || 0) - (b.at || 0));
};
+export const hasAwaitSceneMarkers = async () =>
+ (await listPendingMicRecovery()).some((m) => m.awaitScene);
+
export const readPendingMicRecovery = async () => {
try {
const all = await listPendingMicRecovery();
@@ -180,6 +187,22 @@ const bumpAttempts = async (marker) => {
} catch {}
};
+const fetchScene = async ({ projectId, sceneId }, token) => {
+ if (!API_BASE || !token || !projectId || !sceneId) return null;
+ try {
+ // Uncached, or a "not yet" answer sticks for a minute.
+ const res = await fetch(`${API_BASE}/videos/${projectId}/?refresh=true`, {
+ headers: { Authorization: `Bearer ${token}` },
+ credentials: "include",
+ });
+ if (!res.ok) return null;
+ const body = await res.json().catch(() => null);
+ return body?.video?.data?.scenes?.[sceneId] || null;
+ } catch {
+ return null;
+ }
+};
+
// Keyed on the marker, not a bare "ever": a worker outlives several recordings
// and a new debt deserves a fresh attempt.
const _attempted = new Set();
@@ -217,6 +240,23 @@ const recoverOne = async (marker, { logger, token, ignoreLiveRecording }) => {
return { ran: false, reason: "store-open-failed" };
}
+ // Crash recovery writes this marker before the scene exists, and attaching to
+ // a missing scene reads as settled and clears the voice.
+ if (marker.awaitScene) {
+ const scene = await fetchScene(marker, token);
+ if (!scene) return { ran: false, reason: "scene-not-ready" };
+ // The stop path attached it and was only cut off before cleaning up.
+ // Sending it again would orphan a second copy on Storage.
+ if (scene.audioSourceMediaId) {
+ await clearPendingMicRecovery(marker.sceneId);
+ const live = await chrome.storage.local.get(["recording", "pendingRecording"]);
+ if (!live.recording && !live.pendingRecording) {
+ await store.clear().catch(() => {});
+ }
+ return { ran: false, reason: "already-attached" };
+ }
+ }
+
_attempted.add(key);
// Counted before the attempt, so a crash mid-upload still burns one.
await bumpAttempts(marker);
@@ -283,9 +323,19 @@ export const runMicRecoveryScan = async ({
// durable backup with it. Only a pass that reaches the chunks burns the
// one-shot, so the early returns below must not block a later wake.
const all = await listPendingMicRecovery();
- const markers = backend
- ? all.filter((m) => (m.backend || "idb") === backend)
- : all;
+ // The stop path writes its marker before its own inline upload, so scanning
+ // that marker then would send the same mic twice.
+ const { micUploadInFlight } = await chrome.storage.local.get([
+ "micUploadInFlight",
+ ]);
+ const inFlightScene =
+ micUploadInFlight &&
+ Date.now() - (micUploadInFlight.at || 0) < INLINE_UPLOAD_FRESH_MS
+ ? micUploadInFlight.sceneId
+ : null;
+ const markers = (
+ backend ? all.filter((m) => (m.backend || "idb") === backend) : all
+ ).filter((m) => !inFlightScene || m.sceneId !== inFlightScene);
if (!markers.length) return { ran: false, reason: "no-marker" };
if (!ignoreLiveRecording) {
diff --git a/src/pages/Content/DevHUD.jsx b/src/pages/Content/DevHUD.jsx
index bd7d58b..2c2f016 100644
--- a/src/pages/Content/DevHUD.jsx
+++ b/src/pages/Content/DevHUD.jsx
@@ -103,6 +103,42 @@ const DevHUD = ({ contentStateRef, setContentState }) => {
label: "Editor recovery",
fn: () => toast(chrome.i18n.getMessage("editorRecoveryToast"), 12000),
},
+ {
+ label: "Unsaved recording modal",
+ fn: () => {
+ const s = contentStateRef.current;
+ s?.openModal?.(
+ chrome.i18n.getMessage("unsavedRecordingModalTitle"),
+ chrome.i18n.getMessage("unsavedRecordingModalDescription"),
+ chrome.i18n.getMessage("unsavedRecordingModalAction"),
+ chrome.i18n.getMessage("unsavedRecordingModalCancel"),
+ () => {},
+ () => {},
+ null,
+ null,
+ null,
+ false,
+ chrome.i18n.getMessage("unsavedRecordingModalDismiss"),
+ () => {},
+ );
+ },
+ },
+ {
+ label: "Recovered session (live)",
+ fn: () => toast(chrome.i18n.getMessage("toastRecoveredSession"), 10000),
+ },
+ {
+ // Candidate copy, not in the locales. The live string names the event but
+ // not the outcome, and the file is already in Downloads by then.
+ label: "Recovered (alt A)",
+ fn: () =>
+ toast("Unsaved recording recovered. It's in your downloads.", 10000),
+ },
+ {
+ label: "Recovered (alt B)",
+ fn: () =>
+ toast("Recovered an unsaved recording. Saved to your downloads.", 10000),
+ },
{
label: "Memory limit modal",
fn: () => {
@@ -127,6 +163,35 @@ const DevHUD = ({ contentStateRef, setContentState }) => {
}));
},
},
+ {
+ // Puts the profile back to never-granted so the first-run permission
+ // path can be tested. Granting again only works from an extension page.
+ label: "Wipe capture perms",
+ fn: async () => {
+ try {
+ const res = await chrome.runtime.sendMessage({
+ type: "reset-capture-permissions",
+ });
+ console.log("[DevHUD] wipe capture perms", res);
+ const left = (res?.remaining || []).filter((p) =>
+ ["desktopCapture", "offscreen", "alarms", "clipboardWrite"].includes(
+ p,
+ ),
+ );
+ const detail = Object.entries(res?.results || {})
+ .map(([k, v]) => `${k}: ${v}`)
+ .join(" | ");
+ toast(
+ left.length
+ ? `Still granted: ${left.join(", ")} (${detail})`
+ : "Capture perms wiped. Reload the page, then record.",
+ 15000,
+ );
+ } catch (err) {
+ toast(`Wipe failed: ${String(err?.message || err).slice(0, 80)}`);
+ }
+ },
+ },
];
if (!portalEl) return null;
diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsx
index 6144cfe..d1d7bec 100644
--- a/src/pages/Content/context/ContentState.jsx
+++ b/src/pages/Content/context/ContentState.jsx
@@ -608,19 +608,10 @@ const ContentState = (props) => {
}, []);
const startStreaming = useCallback(async () => {
- // Double-click guard: a previous start may still be in flight.
- const snap = await chrome.storage.local.get([
- "pendingRecording",
- "recording",
- "restarting",
- ]);
- if (snap.pendingRecording || snap.recording || snap.restarting) {
- return;
- }
-
// Region capture runs getDisplayMedia in our in-page iframe, so a host page
// that won't delegate display-capture (e.g. facebook.com) rejects it before any
// picker. The popup disables this, but the shortcut path doesn't, so backstop it.
+ // Synchronous, and ahead of the permission call so a blocked site never prompts.
if (
contentStateRef.current?.recordingType === "region" &&
contentStateRef.current?.siteDisplayCaptureBlocked
@@ -632,14 +623,23 @@ const ContentState = (props) => {
return;
}
- // Kick off synchronously: later awaits (initStartFlowTrace, Pro storage
- // quota) would consume the click's user-gesture before it reaches
- // chrome.permissions.request in the SW.
+ // Must fire before any await, including the storage read below: one spends
+ // the click's activation, so the SW's request() fails and reads as a denial.
const isExtensionPage = window.location.href.includes("chrome-extension://");
const permissionPromise = isExtensionPage
? null
: checkChromeCapturePermissionsSW();
+ // Double-click guard: a previous start may still be in flight.
+ const snap = await chrome.storage.local.get([
+ "pendingRecording",
+ "recording",
+ "restarting",
+ ]);
+ if (snap.pendingRecording || snap.recording || snap.restarting) {
+ return;
+ }
+
const attemptId = `ra-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
await initStartFlowTrace(attemptId, {
recordingType: contentStateRef.current.recordingType,
diff --git a/src/pages/Content/modal/Modal.jsx b/src/pages/Content/modal/Modal.jsx
index 3558f84..f3eb9d1 100644
--- a/src/pages/Content/modal/Modal.jsx
+++ b/src/pages/Content/modal/Modal.jsx
@@ -106,8 +106,8 @@ const Modal = (props) => {
<AlertDialog.Description className="AlertDialogDescription">
{description.split("\n").map((line, idx) => (
<React.Fragment key={idx}>
+ {idx > 0 && <br />}
{line}
- <br />
</React.Fragment>
))}
{learnmore && (
diff --git a/src/pages/Content/popup/layout/RecordingType.jsx b/src/pages/Content/popup/layout/RecordingType.jsx
index f08172e..c94e91e 100644
--- a/src/pages/Content/popup/layout/RecordingType.jsx
+++ b/src/pages/Content/popup/layout/RecordingType.jsx
@@ -83,8 +83,51 @@ const RecordingType = (props) => {
setTime(minutes + ":" + seconds);
}, [contentState.alarmTime]);
- // Start recording
- const startStreaming = () => {
+ // An unsaved recording is still in an editor tab and a new one destroys it,
+ // so the user acknowledges it first.
+ const startStreaming = async () => {
+ let unsaved = null;
+ try {
+ unsaved = await chrome.runtime.sendMessage({
+ type: "unsaved-retained-recording",
+ });
+ } catch {}
+ if (
+ unsaved?.hasUnsaved &&
+ typeof contentState.openModal === "function"
+ ) {
+ contentState.openModal(
+ chrome.i18n.getMessage("unsavedRecordingModalTitle"),
+ chrome.i18n.getMessage("unsavedRecordingModalDescription"),
+ chrome.i18n.getMessage("unsavedRecordingModalAction"),
+ chrome.i18n.getMessage("unsavedRecordingModalCancel"),
+ () => {
+ contentState.startStreaming();
+ },
+ () => {
+ chrome.runtime
+ .sendMessage({
+ type: "focus-retained-recording",
+ tabId: unsaved.tabId,
+ })
+ .catch(() => {});
+ },
+ null,
+ null,
+ null,
+ false,
+ chrome.i18n.getMessage("unsavedRecordingModalDismiss"),
+ () => {
+ // Stops the prompt for good and still starts the recording, so the
+ // side button is not a dead end.
+ chrome.storage.local
+ .set({ unsavedRecordingPromptDismissed: Date.now() })
+ .catch(() => {});
+ contentState.startStreaming();
+ },
+ );
+ return;
+ }
contentState.startStreaming();
};
diff --git a/src/pages/Download/Download.jsx b/src/pages/Download/Download.jsx
index 0342dfd..39465bc 100644
--- a/src/pages/Download/Download.jsx
+++ b/src/pages/Download/Download.jsx
@@ -1,6 +1,7 @@
import React, { useState, useCallback, useEffect } from "react";
import localforage from "localforage";
+import { activeChunksStore } from "../utils/chunkStores";
import { openExistingChunksStore } from "../CloudRecorder/recorderStorage/chooseChunksStore";
import { destroySessionDir } from "../CloudRecorder/recorderStorage/opfsKvStore";
import {
@@ -15,9 +16,9 @@ localforage.config({
version: 1,
});
-// Default IDB instances for the legacy recover-indexed-db-mp4 path that
-// doesn't go through CloudRecorder's per-session backend choice.
-const chunksStore = localforage.createInstance({ name: "chunks" });
+// Legacy recover-indexed-db-mp4 path, outside CloudRecorder's per-session
+// backend choice. Always the newest recording, so it follows the live slot.
+const chunksStore = activeChunksStore;
const cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });
const audioChunksStore = localforage.createInstance({ name: "audioChunks" });
@@ -207,8 +208,7 @@ const Download = () => {
]);
// Remove stale TUS journal + scene keys so the next recording can't
- // resume the crashed upload or reuse the old scene. Mirrors
- // clearStaleUploadJournals() in CloudRecorder.jsx.
+ // resume the crashed upload or reuse the old scene.
const journalKeysToRemove = ["sceneId", "sceneIdStatus"];
const tracks = recorderSession?.tracks || {};
for (const trackData of Object.values(tracks)) {
diff --git a/src/pages/Editor/mediabunny/lib/videoTrimmer.ts b/src/pages/Editor/mediabunny/lib/videoTrimmer.ts
index 61d7a0e..7dd155a 100644
--- a/src/pages/Editor/mediabunny/lib/videoTrimmer.ts
+++ b/src/pages/Editor/mediabunny/lib/videoTrimmer.ts
@@ -64,9 +64,12 @@ export class VideoTrimmer {
if (!videoTrack) throw new Error("Trimming failed - no video track");
const audioTrack = await input.getPrimaryAudioTrack().catch(() => null);
- // Stream-copy needs a keyframe at the cut; output is rebased to 0.
+ // Stream-copy needs a keyframe at the cut, output rebased to 0. Containers can
+ // mislabel a delta packet as key, so verifyKeyPackets falls back to a real one.
const videoSink = new EncodedPacketSink(videoTrack);
- const startKey = await videoSink.getKeyPacket(startTime);
+ const startKey = await videoSink.getKeyPacket(startTime, {
+ verifyKeyPackets: true,
+ });
if (!startKey) throw new Error("Trimming failed - no key packet at start");
const baseTime = startKey.timestamp;
const endVideoPacket = Number.isFinite(endTime)
diff --git a/src/pages/EditorApp/context/ContentState.jsx b/src/pages/EditorApp/context/ContentState.jsx
index 33e6512..90acb5f 100644
--- a/src/pages/EditorApp/context/ContentState.jsx
+++ b/src/pages/EditorApp/context/ContentState.jsx
@@ -637,10 +637,44 @@ const ContentState = (props) => {
}));
}, [contentState.chunkIndex, contentState.chunkCount]);
- const buildBlobFromChunks = async () => {
+ // lastRecordingBackendRef is one slot the next recording overwrites, so a tab
+ // re-reading it later loads a different recording. Resolve once and pin it.
+ const pinnedBackendRef = useRef(null);
+ const resolveOwnBackendRef = async () => {
+ if (pinnedBackendRef.current) return pinnedBackendRef.current;
+ // Ask what this tab owns before falling back to the shared pointer, which
+ // only ever names the newest recording.
+ try {
+ const owned = await chrome.runtime.sendMessage({
+ type: "resolve-editor-recording",
+ });
+ if (owned?.ref?.backend) {
+ pinnedBackendRef.current = owned.ref;
+ return owned.ref;
+ }
+ } catch {}
const { lastRecordingBackendRef } = await chrome.storage.local.get([
"lastRecordingBackendRef",
]);
+ const mine = launchRecordingIdRef.current;
+ if (
+ mine &&
+ lastRecordingBackendRef?.fileName &&
+ !String(lastRecordingBackendRef.fileName).includes(mine)
+ ) {
+ // The pointer has moved on. Ours may still be on disk, but it is not
+ // what this key names any more, so reading it would be the wrong file.
+ return null;
+ }
+ pinnedBackendRef.current = lastRecordingBackendRef || null;
+ return pinnedBackendRef.current;
+ };
+
+ const buildBlobFromChunks = async () => {
+ const lastRecordingBackendRef = await resolveOwnBackendRef();
+ if (!lastRecordingBackendRef) {
+ throw new Error("recording-no-longer-available");
+ }
const reader = chooseReader(lastRecordingBackendRef);
await reader.open(lastRecordingBackendRef);
let readResult;
@@ -3007,6 +3041,18 @@ const ContentState = (props) => {
delta.state.current === "complete" ||
delta.state.current === "interrupted"
) {
+ if (delta.state.current === "complete") {
+ // The user now has their own copy, so retention can stop
+ // protecting this recording and stop warning about it.
+ try {
+ chrome.runtime
+ .sendMessage({
+ type: "recording-saved",
+ recordingId: launchRecordingIdRef.current || null,
+ })
+ .catch(() => {});
+ } catch {}
+ }
done();
}
};
diff --git a/src/pages/EditorApp/recorderStorage/idbChunkReader.js b/src/pages/EditorApp/recorderStorage/idbChunkReader.js
index a959971..e0bbefb 100644
--- a/src/pages/EditorApp/recorderStorage/idbChunkReader.js
+++ b/src/pages/EditorApp/recorderStorage/idbChunkReader.js
@@ -1,5 +1,5 @@
-// IDB ChunkReader. Iterates chunksStore, sorts by (timestamp, index).
import localforage from "localforage";
+import { instanceForSlot, loadActiveSlot } from "../../utils/chunkStores";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -7,17 +7,18 @@ localforage.config({
version: 1,
});
-const chunksStore = localforage.createInstance({
- name: "chunks",
-});
-
export class IdbChunkReader {
constructor() {
this._opened = false;
+ this._store = null;
}
- async open(_backendRef) {
- await chunksStore.ready();
+ // backendRef.slot names this editor's own recording. Without it a second
+ // editor reads whichever slot is live, which is the newer recording.
+ async open(backendRef) {
+ const slot = backendRef?.slot || (await loadActiveSlot());
+ this._store = instanceForSlot(slot);
+ await this._store.ready();
this._opened = true;
}
@@ -26,7 +27,7 @@ export class IdbChunkReader {
throw new Error("idb-chunk-reader-not-opened");
}
const items = [];
- await chunksStore.iterate((value) => {
+ await this._store.iterate((value) => {
items.push(value);
return undefined;
});
@@ -58,5 +59,3 @@ export class IdbChunkReader {
this._opened = false;
}
}
-
-export { chunksStore as idbChunksStore };
diff --git a/src/pages/OffscreenRecorder/index.jsx b/src/pages/OffscreenRecorder/index.jsx
index 51f63b7..9b0b19f 100644
--- a/src/pages/OffscreenRecorder/index.jsx
+++ b/src/pages/OffscreenRecorder/index.jsx
@@ -35,13 +35,27 @@ const swKeepaliveTimer = setInterval(() => {
}, SW_KEEPALIVE_MS);
window.addEventListener("pagehide", () => clearInterval(swKeepaliveTimer));
+const IS_RESUME_DOC =
+ new URLSearchParams(window.location.search).get("resume") === "1";
+
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
+ // Resume can stop anywhere: the next pass re-reads the server offset and
+ // settles from the snapshot. Waiting only stalls the next recording's start.
+ if (msg?.type === "offscreen-shutdown" && IS_RESUME_DOC) {
+ chrome.runtime
+ .sendMessage({ type: "offscreen-shutdown-complete" })
+ .catch(() => {});
+ return false;
+ }
if (msg?.type === "resume-pending-uploads" && Array.isArray(msg.journals)) {
(async () => {
try {
const { resumeAllJournals } = await import("./resumeJournal");
- const results = await resumeAllJournals(msg.journals);
- sendResponse({ ok: true, results });
+ const { results, recovered } = await resumeAllJournals(
+ msg.journals,
+ Array.isArray(msg.sessions) ? msg.sessions : [],
+ );
+ sendResponse({ ok: true, results, recovered });
} catch (err) {
console.error("[OffscreenRecorder] resume failed:", err);
sendResponse({ ok: false, error: err?.message || String(err) });
diff --git a/src/pages/OffscreenRecorder/resumeJournal.js b/src/pages/OffscreenRecorder/resumeJournal.js
index 448ebd2..821d105 100644
--- a/src/pages/OffscreenRecorder/resumeJournal.js
+++ b/src/pages/OffscreenRecorder/resumeJournal.js
@@ -3,6 +3,8 @@ import BunnyTusUploader from "../CloudRecorder/bunnyTusUploader";
import { getClientSessionId } from "../CloudRecorder/clientSessionId";
import { TRACK_KEY_PREFIX } from "../CloudRecorder/recorderStorage/chooseChunksStore";
import { openExistingChunksStore } from "../CloudRecorder/recorderStorage/chooseChunksStore";
+import { destroySessionDir } from "../CloudRecorder/recorderStorage/opfsKvStore";
+import { setPendingMicRecovery } from "../CloudRecorder/micRecovery";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -10,7 +12,34 @@ localforage.config({
version: 1,
});
+const API_BASE = process.env.SCREENITY_API_BASE_URL;
const JOURNAL_KEY_PREFIX = "uploadJournal-";
+const SESSION_KEY_PREFIX = "cloudRecorderSession:";
+const PURGE_MARKS_PREFIX = "chunkPurgeMarks:";
+const ATTEMPTS_KEY = "uploadResumeAttempts";
+const MIC_MARKER_KEY = "pendingMicRecovery";
+const LOCAL_PLAYBACK_OFFER_KEY = "cloudLocalScreenPlaybackOffer";
+// No bytes landing for this long means a wedged uploader. Its drain loop never
+// returns on an error the heartbeat missed.
+const STALL_LIMIT_MS = 5 * 60 * 1000;
+const STALL_CHECK_MS = 10 * 1000;
+const LOCK_REFRESH_MS = 60 * 1000;
+// Offset errors that mean the upload itself is broken, not the connection.
+const BROKEN_UPLOAD_CODES = new Set([
+ "invalid-server-offset",
+ "server-offset-not-advancing",
+ "server-offset-regressed",
+]);
+const RECOVERABLE_SESSION_STATUSES = new Set([
+ "recording",
+ "hidden",
+ "unload",
+ "stopping",
+ "finalize-failed",
+ "upload-stalled",
+ "stale-cleared",
+ "crashed",
+]);
// Audio must map to its own store. Flattening it to "screen" would resume a
// mic journal out of the screen chunks and upload the wrong track's bytes.
@@ -27,7 +56,7 @@ const resolveBackendForJournal = async (journal) => {
// Try the per-session snapshot first (it survives even after a newer
// session has overwritten the latest `recorderSession`).
if (sessionId) {
- const sessionStateKey = `cloudRecorderSession:${sessionId}`;
+ const sessionStateKey = `${SESSION_KEY_PREFIX}${sessionId}`;
try {
const snap = await chrome.storage.local.get([sessionStateKey]);
const session = snap?.[sessionStateKey];
@@ -56,6 +85,21 @@ const resolveBackendForJournal = async (journal) => {
}
} catch {}
+ // Defaulting to IDB would find no chunks (recordings prefer OPFS wherever it
+ // works) and drop the journal as if there were none to resume.
+ if (sessionId) {
+ try {
+ const { store } = openExistingChunksStore({
+ sessionId,
+ track: trackKey,
+ backend: "opfs",
+ });
+ if ((await store.length()) > 0) {
+ return { backend: "opfs", opfsSessionId: sessionId };
+ }
+ } catch {}
+ }
+
return { backend: "idb", opfsSessionId: sessionId };
};
@@ -80,6 +124,17 @@ const loadChunksSorted = async (store, prefix = "chunk_") => {
return items;
};
+// Chunks at or below the purge mark were confirmed and deleted mid-recording,
+// so what is left must run unbroken from just past it, starting at its byte.
+const planLocalBytes = (chunks, mark) => {
+ const base = mark ? Number(mark.endByte) || 0 : 0;
+ const firstIndex = mark ? mark.index + 1 : 0;
+ const tail = chunks.filter((c) => c.index >= firstIndex);
+ const unbroken = tail.every((c, i) => c.index === firstIndex + i);
+ const tailBytes = tail.reduce((n, c) => n + (c.chunk?.size || 0), 0);
+ return { base, tail, unbroken, end: base + tailBytes };
+};
+
// Tus PATCH writes at the offset header without content validation, so
// re-sending chunks already received corrupts the file silently.
const skipAlreadyUploadedChunks = (chunks, alreadyUploadedBytes) => {
@@ -106,21 +161,137 @@ const skipAlreadyUploadedChunks = (chunks, alreadyUploadedBytes) => {
return [];
};
-const bumpResumeAttempts = async (journal) => {
+// Offline, signed out or a struggling server says nothing about the take, so
+// none of it counts toward the attempt cap.
+const isTransient = (err) => {
+ if (err?.transient === true) return true;
+ if (globalThis.navigator?.onLine === false) return true;
+ const status = Number(err?.status) || 0;
+ if ([401, 403, 408, 429].includes(status) || status >= 500) return true;
+ if (err?.name === "TypeError") return true;
+ return /failed to fetch|network|not authenticated|missing user token|verify server offset/i.test(
+ String(err?.message || err || "")
+ );
+};
+
+const bumpAttempts = async (mediaId) => {
+ if (!mediaId) return;
+ try {
+ const { [ATTEMPTS_KEY]: map } = await chrome.storage.local.get([ATTEMPTS_KEY]);
+ const next = { ...(map || {}), [mediaId]: ((map || {})[mediaId] || 0) + 1 };
+ await chrome.storage.local.set({ [ATTEMPTS_KEY]: next });
+ } catch {}
+};
+
+const clearAttempts = async (mediaId) => {
+ try {
+ const { [ATTEMPTS_KEY]: map } = await chrome.storage.local.get([ATTEMPTS_KEY]);
+ if (!map || !(mediaId in map)) return;
+ const next = { ...map };
+ delete next[mediaId];
+ await chrome.storage.local.set({ [ATTEMPTS_KEY]: next });
+ } catch {}
+};
+
+// initialize() only prunes a journal once it's stale past 24h. Restoring it
+// here keeps a failed attempt from leaving nothing for settle to find, which
+// would delete a take that can still land.
+const restoreJournal = async (journal) => {
const key = `${JOURNAL_KEY_PREFIX}${journal.mediaId}`;
try {
- const existing = await chrome.storage.local.get([key]);
- const current = existing?.[key] || journal;
- const updated = {
- ...current,
- resumeAttempts: (current.resumeAttempts || 0) + 1,
- lastResumeAttemptAt: Date.now(),
+ const { [key]: current } = await chrome.storage.local.get([key]);
+ if (!current) await chrome.storage.local.set({ [key]: journal });
+ } catch {}
+};
+
+const removeJournal = async (mediaId) => {
+ try {
+ await chrome.storage.local.remove([`${JOURNAL_KEY_PREFIX}${mediaId}`]);
+ } catch {}
+};
+
+// Settle reads the take's media ids from here. A replaced video has a new id
+// the snapshot never saw.
+const noteRecoveredMedia = async (sessionId, track, mediaId) => {
+ if (!sessionId || !mediaId) return;
+ const key = `${SESSION_KEY_PREFIX}${sessionId}`;
+ try {
+ const { [key]: session } = await chrome.storage.local.get([key]);
+ if (!session) return;
+ await chrome.storage.local.set({
+ [key]: {
+ ...session,
+ recoveredMediaIds: { ...(session.recoveredMediaIds || {}), [track]: mediaId },
+ },
+ });
+ } catch {}
+};
+
+const watchForStall = (uploader) => {
+ let lastOffset = uploader.offset;
+ let lastProgressAt = Date.now();
+ let timer = null;
+ const stalled = new Promise((resolve) => {
+ timer = setInterval(() => {
+ if (uploader.offset !== lastOffset) {
+ lastOffset = uploader.offset;
+ lastProgressAt = Date.now();
+ } else if (Date.now() - lastProgressAt > STALL_LIMIT_MS) {
+ resolve("stalled");
+ }
+ }, STALL_CHECK_MS);
+ });
+ return { stalled, stop: () => clearInterval(timer) };
+};
+
+// No recorder to forward through here, so this posts directly; env is left
+// out since the server fills it in from the request headers.
+const postTelemetry = async (type, fields = {}) => {
+ if (!API_BASE) return;
+ try {
+ const { screenityToken } = await chrome.storage.local.get([
+ "screenityToken",
+ ]);
+ const version = chrome?.runtime?.getManifest?.()?.version || null;
+ const mediaId = fields.mediaId || null;
+ const body = {
+ recordingId: mediaId || fields.recordingSessionId || null,
+ recordingSessionId: fields.recordingSessionId || null,
+ projectId: fields.projectId || null,
+ sceneId: fields.sceneId || null,
+ mediaId,
+ bunnyVideoId: fields.bunnyVideoId || null,
+ source: "extension",
+ extVersion: version,
+ event: {
+ type,
+ t: Date.now(),
+ trackType: fields.trackType || null,
+ offsetBytes: typeof fields.offset === "number" ? fields.offset : null,
+ fileSize:
+ typeof fields.totalBytes === "number"
+ ? fields.totalBytes
+ : typeof fields.finalizedBytes === "number"
+ ? fields.finalizedBytes
+ : null,
+ errMsg: fields.errMsg || null,
+ },
};
- await chrome.storage.local.set({ [key]: updated });
+ await fetch(`${API_BASE}/log/upload-event`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-screenity-source": "extension",
+ ...(version ? { "x-screenity-ext-version": version } : {}),
+ ...(screenityToken ? { Authorization: `Bearer ${screenityToken}` } : {}),
+ },
+ credentials: "include",
+ body: JSON.stringify(body),
+ });
} catch {}
};
-const emit = (type, payload) => {
+const emit = (type, payload = {}) => {
try {
chrome.runtime
.sendMessage({
@@ -130,160 +301,424 @@ const emit = (type, payload) => {
})
.catch(() => {});
} catch {}
+ const errMsg =
+ payload.errMsg ||
+ [payload.phase, payload.error].filter(Boolean).join(": ") ||
+ null;
+ void postTelemetry(type, { ...payload, errMsg });
};
-export const resumeOneJournal = async (journal) => {
+const makeUploader = (trackType) =>
+ new BunnyTusUploader({
+ trackType,
+ clientSessionId: getClientSessionId(),
+ onTelemetry: (event, body) => {
+ if (event !== "upload_progress") void postTelemetry(event, body);
+ },
+ });
+
+export const resumeOneJournal = async (journal, { latestSessionId = null } = {}) => {
const trackType = journal.trackType || journal.type || "screen";
+ const track = trackName(trackType);
const mediaId = journal.mediaId;
const projectId = journal.projectId;
const sceneId = journal.sceneId;
+ const ctx = {
+ mediaId,
+ projectId,
+ sceneId,
+ trackType,
+ recordingSessionId: journal.sessionId || null,
+ };
if (!mediaId || !projectId) {
return { ok: false, error: "journal-missing-ids" };
}
+ const drop = async (reason) => {
+ emit("upload_resume_dropped", { ...ctx, errMsg: reason });
+ await removeJournal(mediaId);
+ await clearAttempts(mediaId);
+ return { ok: false, dropped: true, error: reason };
+ };
+
emit("upload_resume_started", {
- mediaId,
- projectId,
- sceneId,
- trackType,
+ ...ctx,
offset: journal.offset,
totalBytes: journal.totalBytes,
- resumeAttempts: journal.resumeAttempts || 0,
});
const { backend, opfsSessionId } = await resolveBackendForJournal(journal);
+ // IDB is one store for every take. Once a newer take has written to it, the
+ // chunks there are not this journal's.
+ if (
+ backend !== "opfs" &&
+ journal.sessionId &&
+ journal.sessionId !== latestSessionId
+ ) {
+ return drop("idb-not-latest");
+ }
+
const { store } = openExistingChunksStore({
sessionId: opfsSessionId,
- track: trackName(trackType),
+ track,
backend,
});
- const chunks = await loadChunksSorted(
- store,
- chunkKeyPrefixForTrack(trackType),
- );
+ const chunks = await loadChunksSorted(store, chunkKeyPrefixForTrack(trackType));
+ const marksKey = journal.sessionId
+ ? `${PURGE_MARKS_PREFIX}${journal.sessionId}`
+ : null;
+ const marks = marksKey
+ ? (await chrome.storage.local.get([marksKey]))?.[marksKey]
+ : null;
+ const plan = planLocalBytes(chunks, marks?.[track] || null);
+ // A host whose finalize failed clears its chunks, while Bunny may still hold
+ // every byte. Only the server can say whether that take can still close.
+ const noLocalBytes = !plan.tail.length && plan.base === 0;
- if (!chunks.length) {
- // Orphan journal: chunks cleared or never written. GC.
- emit("upload_resume_chunks_missing", { mediaId, trackType });
- try {
- await chrome.storage.local.remove([
- `${JOURNAL_KEY_PREFIX}${mediaId}`,
- ]);
- } catch {}
- return { ok: false, error: "chunks-missing" };
- }
+ // With no mark to place a gap, the bytes after it would land at the wrong
+ // offset, which Bunny accepts and plays back as garbage.
+ if (!plan.unbroken) return drop("gap-without-mark");
- const uploader = new BunnyTusUploader({
- trackType,
- clientSessionId: getClientSessionId(),
- });
+ const initOpts = {
+ title: journal.title || `Recording ${mediaId}`,
+ type: trackType,
+ width: journal.width || null,
+ height: journal.height || null,
+ sceneId: sceneId || null,
+ sessionId: journal.sessionId || null,
+ };
+
+ let uploader = makeUploader(trackType);
+ let freshMedia = false;
+
+ const fail = async (phase, err) => {
+ console.warn(`[resumeJournal] ${phase} failed:`, err);
+ // The fresh media carries its own journal, so the replaced one must not
+ // come back and mint a third.
+ if (freshMedia) await removeJournal(mediaId);
+ else await restoreJournal(journal);
+ const transient = isTransient(err);
+ if (!transient) await bumpAttempts(uploader.mediaId || mediaId);
+ emit("upload_resume_failed", {
+ ...ctx,
+ mediaId: uploader.mediaId || mediaId,
+ phase,
+ error: `${transient ? "transient " : ""}${err?.message || String(err)}`,
+ });
+ return { ok: false, transient, error: `${phase}: ${err?.message || err}` };
+ };
try {
await uploader.initialize(projectId, {
- title: journal.title || `Recording ${mediaId}`,
- type: trackType,
- width: journal.width || null,
- height: journal.height || null,
- sceneId: sceneId || null,
- sessionId: journal.sessionId || null,
- reuse: { videoId: journal.videoId, mediaId },
+ ...initOpts,
+ reuse: {
+ videoId: journal.videoId,
+ mediaId,
+ uploadUrl: journal.uploadUrl || null,
+ },
});
} catch (err) {
- console.warn("[resumeJournal] initialize failed:", err);
- await bumpResumeAttempts(journal);
- emit("upload_resume_failed", {
- mediaId,
- phase: "initialize",
- error: err?.message || String(err),
+ if (err?.status !== 404) return fail("initialize", err);
+ // Purged bytes were confirmed and the server keeps any video holding bytes,
+ // so a 404 here means those bytes are gone.
+ if (plan.base > 0 || noLocalBytes) return drop("reaped-without-local-bytes");
+ // tus-auth 404 with nothing purged: the server removed a video none of the
+ // bytes reached, so the whole file goes up as new media in the same scene.
+ uploader = makeUploader(trackType);
+ try {
+ await uploader.initialize(projectId, initOpts);
+ } catch (freshErr) {
+ return fail("initialize-fresh", freshErr);
+ }
+ freshMedia = true;
+ await noteRecoveredMedia(journal.sessionId, track, uploader.mediaId);
+ emit("upload_resume_fresh_media", {
+ ...ctx,
+ mediaId: uploader.mediaId,
+ errMsg: `replaces ${mediaId}`,
});
- return { ok: false, error: `initialize: ${err?.message || err}` };
}
- // uploader.offset = bytes Bunny has. Finalize-only if full, else replay
- // the gap (bail on sparse local chunks).
const serverOffset = uploader.offset || 0;
- const journalTotalBytes = journal.totalBytes || 0;
- const serverHasEverything =
- journalTotalBytes > 0 && serverOffset >= journalTotalBytes;
-
- let remainingChunks = [];
- if (serverHasEverything) {
- emit("upload_resume_finalize_only", {
- mediaId,
- trackType,
- serverOffset,
- journalTotalBytes,
- });
- } else {
- const isContiguous = chunks.every((c, i) => c.index === i);
- if (!isContiguous) {
- emit("upload_resume_sparse_chunks", {
- mediaId,
- trackType,
- firstIndex: chunks[0]?.index,
- lastIndex: chunks[chunks.length - 1]?.index,
- count: chunks.length,
- serverOffset,
- journalTotalBytes,
- });
- try {
- await chrome.storage.local.remove([
- `${JOURNAL_KEY_PREFIX}${mediaId}`,
- ]);
- } catch {}
- return { ok: false, error: "sparse-chunks" };
+ if (noLocalBytes) {
+ const serverComplete =
+ journal.totalBytes > 0 && serverOffset >= journal.totalBytes;
+ if (!serverComplete) return drop("chunks-missing");
+ }
+ if (serverOffset < plan.base) {
+ // A HEAD with its offset header stripped reads as 0, which proves nothing.
+ if (serverOffset === 0) {
+ return fail("initialize", new Error("server offset read as 0 below purge mark"));
}
+ // Everything below the mark was on the server before it left disk.
+ return drop("server-behind-purge");
+ }
+ const remaining = skipAlreadyUploadedChunks(plan.tail, serverOffset - plan.base);
+ const expectedEnd = Math.max(plan.end, serverOffset);
- remainingChunks = skipAlreadyUploadedChunks(chunks, serverOffset);
- emit("upload_resume_chunks_skipped", {
- mediaId,
- serverOffset,
- totalChunks: chunks.length,
- remainingChunks: remainingChunks.length,
- });
+ const watch = watchForStall(uploader);
+ let outcome;
+ try {
+ outcome = await Promise.race([
+ (async () => {
+ for (const { chunk } of remaining) {
+ await uploader.write(chunk);
+ }
+ // write() only queues chunks and surfaces failures later, so the
+ // server's own offset is checked instead of trusting it resolved.
+ await uploader.waitForPendingUploads();
+ const landed = await uploader.getServerOffset();
+ if (landed === null || landed < expectedEnd) {
+ return new Error(`server has ${landed} of ${expectedEnd}`);
+ }
+ return "landed";
+ })(),
+ watch.stalled,
+ ]);
+ } catch (err) {
+ outcome = err;
+ } finally {
+ watch.stop();
+ }
+ if (outcome === "stalled") {
+ const stall = new Error("no bytes landed for 5 minutes");
+ // The uploader retries dropped connections forever, so a stall is usually
+ // a dead link. Only its offset errors say the upload itself is broken.
+ stall.transient = !BROKEN_UPLOAD_CODES.has(uploader.lastErrorCode);
+ return fail("upload", stall);
+ }
+ if (outcome !== "landed") {
+ // Finalizing now would declare a short file Bunny can't take back.
+ return fail("upload", outcome);
}
try {
- for (const { chunk } of remainingChunks) {
- if (uploader.status === "aborted" || uploader.status === "error") break;
- await uploader.write(chunk);
- }
await uploader.finalize();
- emit("upload_resume_completed", {
- mediaId,
+ } catch (err) {
+ return fail("finalize", err);
+ }
+
+ await clearAttempts(mediaId);
+ emit("upload_resume_completed", {
+ ...ctx,
+ mediaId: uploader.mediaId,
+ finalizedBytes: expectedEnd,
+ });
+ return { ok: true, mediaId: uploader.mediaId, freshMedia };
+};
+
+// How long an invalidated journal keeps holding the local bytes. Matches the
+// uploader's own 24h journal staleness window.
+const INVALIDATED_HOLD_MS = 24 * 60 * 60 * 1000;
+
+// Every journal of the take has landed or been dropped, so the local copy goes.
+// A separated mic is the exception: it was never on TUS and still has to attach.
+const settleSession = async (sessionId, all) => {
+ const snapKey = `${SESSION_KEY_PREFIX}${sessionId}`;
+ const session = all[snapKey];
+ if (!session || !RECOVERABLE_SESSION_STATUSES.has(session.status)) return null;
+ // An invalidated journal is a tombstone: the resume never concluded, so the
+ // local bytes stay. Past 24h it stops holding them, matching journal staleness.
+ const pending = Object.entries(all).some(([key, journal]) => {
+ if (!key.startsWith(JOURNAL_KEY_PREFIX)) return false;
+ if (journal?.sessionId !== sessionId) return false;
+ if (journal.status === "completed") return false;
+ if (
+ journal.status === "invalidated" &&
+ Number(journal.invalidatedAt || 0) > 0 &&
+ Date.now() - Number(journal.invalidatedAt) > INVALIDATED_HOLD_MS
+ ) {
+ return false;
+ }
+ return true;
+ });
+ if (pending) return null;
+
+ const tracks = session.tracks || {};
+ const uploaderMeta = tracks.screen?.uploader || tracks.camera?.uploader || null;
+ const projectId = uploaderMeta?.projectId || session.projectId || null;
+ const sceneId = uploaderMeta?.sceneId || null;
+ const mediaFor = (t) =>
+ session.recoveredMediaIds?.[t] || tracks[t]?.uploader?.mediaId || null;
+ const discarded = (all.discardedRecordingSessionIds || []).includes(sessionId);
+ const backends = session.storageBackends || {
+ screen: "idb",
+ camera: "idb",
+ audio: "idb",
+ };
+ const opfsSessionId = session.opfsSessionId || sessionId;
+ const storeFor = (t) =>
+ openExistingChunksStore({
+ sessionId: opfsSessionId,
+ track: t,
+ backend: backends[t] || "idb",
+ }).store;
+ // IDB is one store for every take, so it is only this take's to clear while
+ // nothing newer has written to it.
+ const isLatestSession = all.recorderSession?.id === sessionId;
+ const liveRecording = Boolean(all.recording || all.pendingRecording);
+ const mayClear = (t) =>
+ (backends[t] || "idb") === "opfs" || (isLatestSession && !liveRecording);
+ // IDB is shared with whatever records next, and several awaits sit between
+ // the snapshot above and the clear, so re-read right next to the write.
+ const mayClearNow = async (t) => {
+ if (!mayClear(t)) return false;
+ if ((backends[t] || "idb") === "opfs") return true;
+ const now = await chrome.storage.local.get([
+ "recorderSession",
+ "recording",
+ "pendingRecording",
+ ]);
+ return (
+ now.recorderSession?.id === sessionId &&
+ !now.recording &&
+ !now.pendingRecording
+ );
+ };
+
+ const localCounts = {};
+ for (const t of ["screen", "camera", "audio"]) {
+ localCounts[t] = mayClear(t) ? await storeFor(t).length().catch(() => 0) : 0;
+ }
+ const hadLocalBytes = Object.values(localCounts).some((n) => n > 0);
+
+ const debts = Object.values(all[MIC_MARKER_KEY] || {});
+ let micHeld = debts.some((d) => d?.sessionId === opfsSessionId);
+ if (
+ !micHeld &&
+ !discarded &&
+ session.separatedAudio === true &&
+ backends.audio === "opfs" &&
+ localCounts.audio > 0 &&
+ projectId &&
+ sceneId
+ ) {
+ // The scan checks the scene first, so a mic the stop path already attached
+ // before being cut off is cleared there rather than sent twice.
+ await setPendingMicRecovery({
projectId,
sceneId,
- trackType,
- finalizedBytes: uploader.totalBytes,
+ duration: null,
+ mimeType: session.trackContainers?.audio || "audio/webm",
+ sessionId: opfsSessionId,
+ backend: "opfs",
+ targetMediaId: mediaFor("screen") || mediaFor("camera"),
+ awaitScene: true,
});
- return { ok: true };
- } catch (err) {
- console.warn("[resumeJournal] upload/finalize failed:", err);
- await bumpResumeAttempts(journal);
- emit("upload_resume_failed", {
- mediaId,
- phase: "upload",
- error: err?.message || String(err),
- resumeAttempts: (journal.resumeAttempts || 0) + 1,
+ micHeld = true;
+ }
+
+ // An open editor may still be playing this take from disk. Read fresh: one
+ // may have opened while the passes above were running.
+ const freshOffer = await chrome.storage.local.get([LOCAL_PLAYBACK_OFFER_KEY]);
+ const offer = freshOffer[LOCAL_PLAYBACK_OFFER_KEY];
+ const offerHolds =
+ offer?.recordingSessionId === sessionId &&
+ Number(offer.expiresAt || 0) > Date.now();
+
+ for (const t of ["screen", "camera", "audio"]) {
+ if (t === "audio" && micHeld) continue;
+ if (t === "screen" && offerHolds) continue;
+ if (!(await mayClearNow(t))) continue;
+ await storeFor(t).clear().catch(() => {});
+ }
+ if (!micHeld && !offerHolds) {
+ await destroySessionDir(opfsSessionId).catch(() => {});
+ }
+
+ const outcome =
+ discarded ||
+ !(mediaFor("screen") || mediaFor("camera") || mediaFor("audio"))
+ ? "recovery-discarded"
+ : "recovered";
+ const now = Date.now();
+ // Re-read: a take may have started while the stores were being cleared.
+ const fresh = await chrome.storage.local.get([
+ "recorderSession",
+ "recording",
+ "pendingRecording",
+ "sceneId",
+ ]);
+ const updates = {
+ [snapKey]: { ...session, status: outcome, recoveredAt: now },
+ };
+ if (
+ fresh.recorderSession?.id === sessionId &&
+ !fresh.recording &&
+ !fresh.pendingRecording
+ ) {
+ updates.recorderSession = {
+ ...fresh.recorderSession,
+ status: outcome,
+ recoveredAt: now,
+ };
+ }
+ if (sceneId && fresh.sceneId === sceneId) updates.sceneIdStatus = "completed";
+ await chrome.storage.local.set(updates);
+ await chrome.storage.local
+ .remove([`${PURGE_MARKS_PREFIX}${sessionId}`])
+ .catch(() => {});
+
+ // Older builds left snapshots with nothing on disk. Settling them is cleanup,
+ // not a recovery, so it isn't reported.
+ if (hadLocalBytes) {
+ emit("upload_recovery_completed", {
+ mediaId: mediaFor("screen") || mediaFor("camera") || mediaFor("audio"),
+ projectId,
+ sceneId,
+ recordingSessionId: sessionId,
+ errMsg: [outcome, micHeld ? "mic-pending" : null].filter(Boolean).join(" "),
});
- return { ok: false, error: `upload: ${err?.message || err}` };
}
+ return { sessionId, projectId, sceneId, micHeld, outcome };
};
-export const resumeAllJournals = async (journals) => {
- const results = [];
- for (const journal of journals) {
- try {
- const r = await resumeOneJournal(journal);
- results.push({ mediaId: journal.mediaId, ...r });
- } catch (err) {
- results.push({
+export const resumeAllJournals = async (journals, sessionIds = []) => {
+ const { recorderSession } = await chrome.storage.local.get(["recorderSession"]);
+ const latestSessionId = recorderSession?.id || null;
+ // A long upload outlives the lock TTL, and an expired lock lets the next
+ // trigger start a second pass.
+ const lockTimer = setInterval(() => {
+ chrome.storage.local.set({ resumeLockAt: Date.now() }).catch(() => {});
+ }, LOCK_REFRESH_MS);
+
+ try {
+ const results = [];
+ for (const journal of journals) {
+ const base = {
mediaId: journal.mediaId,
- ok: false,
- error: err?.message || String(err),
- });
+ sessionId: journal.sessionId || null,
+ trackType: journal.trackType || journal.type || "screen",
+ };
+ try {
+ const r = await resumeOneJournal(journal, { latestSessionId });
+ results.push({ ...base, ...r });
+ } catch (err) {
+ results.push({
+ ...base,
+ ok: false,
+ error: err?.message || String(err),
+ });
+ }
+ }
+
+ const all = (await chrome.storage.local.get(null)) || {};
+ const ids = new Set([
+ ...sessionIds,
+ ...journals.map((j) => j.sessionId).filter(Boolean),
+ ]);
+ const recovered = [];
+ for (const sessionId of ids) {
+ try {
+ const settled = await settleSession(sessionId, all);
+ if (settled) recovered.push(settled);
+ } catch (err) {
+ console.warn("[resumeJournal] settling session failed:", err);
+ }
}
+ return { results, recovered };
+ } finally {
+ clearInterval(lockTimer);
}
- return results;
};
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index 67e0b4b..979d242 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -15,6 +15,11 @@ import {
constrainTrackDown,
enforceOversampleRatio,
} from "../utils/captureResolution";
+import {
+ createDimensionLockedStream,
+ isDimensionLockDisabled,
+} from "./dimensionLock";
+import { activeChunksStore, loadActiveSlot } from "../utils/chunkStores";
import {
getBitrates,
getResolutionForQuality,
@@ -72,9 +77,9 @@ localforage.config({
version: 1,
});
-const chunksStore = localforage.createInstance({
- name: "chunks",
-});
+// The retained recording sits in the other slot, so a hardcoded instance here
+// would have cleared it. Resolves the live slot on every call.
+const chunksStore = activeChunksStore;
document.body.style.willChange = "contents";
@@ -302,6 +307,25 @@ const Recorder = () => {
const pendingMicIntent = useRef(null);
const recorder = useRef(null);
+
+ // Recordings whose editor tab is still open, computed by the background at
+ // record start. Awaiting the slot pointer keeps writes on the free slot.
+ const readRetentionPlan = async () => {
+ try {
+ await loadActiveSlot();
+ const { retentionPlan } = await chrome.storage.local.get([
+ "retentionPlan",
+ ]);
+ const names = retentionPlan?.keepNames;
+ return Array.isArray(names) ? names : [];
+ } catch {
+ return [];
+ }
+ };
+
+ // Fixed-size relay for the MediaRecorder path, see dimensionLock.js.
+
+ const dimensionLock = useRef(null);
const useWebCodecs = useRef(false);
// null on MediaRecorder path.
const chunkWriter = useRef(null);
@@ -1470,6 +1494,7 @@ const Recorder = () => {
if (!openResult) {
openResult = await selection.writer.open(recordingId, {
extension: recordingExtension,
+ keepNames: await readRetentionPlan(),
});
}
endOpen({ backend: selection.backend, prewarmed: prewarmedMatches });
@@ -1489,6 +1514,7 @@ const Recorder = () => {
selection = await chooseWriter({ preferOpfs: false });
openResult = await selection.writer.open(recordingId, {
extension: recordingExtension,
+ keepNames: await readRetentionPlan(),
});
} else {
throw openErr;
@@ -2278,6 +2304,8 @@ const Recorder = () => {
);
(async () => {
const prev = recorder.current;
+ dimensionLock.current?.stop().catch(() => {});
+ dimensionLock.current = null;
recorder.current = null;
useWebCodecs.current = false;
try {
@@ -2369,6 +2397,8 @@ const Recorder = () => {
type: "show-toast",
message: chrome.i18n.getMessage("webcodecsFailedOffToast"),
});
+ dimensionLock.current?.stop().catch(() => {});
+ dimensionLock.current = null;
recorder.current = null;
// Abort the OPFS writer opened for the WebCodecs path. The recursive
// startRecording() picks IDB because forceMediaRecorder short-circuits
@@ -2432,7 +2462,48 @@ const Recorder = () => {
// slot rather than leaving it to the unclaimed-prewarm timeout.
closeActiveEncoderPrewarm().catch(() => {});
try {
- recorder.current = createMediaRecorder(liveStream.current, {
+ // A surface resize mid-recording corrupts the rest of the file.
+ // Record a dimension-locked relay, not the raw track.
+ let recordStream = liveStream.current;
+ let lock = null;
+ if (!(await isDimensionLockDisabled())) {
+ lock = createDimensionLockedStream(liveStream.current, {
+ width,
+ height,
+ fps,
+ onError: (info) => {
+ chrome.runtime
+ .sendMessage({
+ type: "diag-forward",
+ event: "recorder-dimension-lock-error",
+ data: {
+ error: info.error,
+ framesIn: info.framesIn,
+ framesOut: info.framesOut,
+ sourceSizeChanges: info.sourceSizeChanges,
+ },
+ })
+ .catch(() => {});
+ requestStop("dimension-lock-pump-error");
+ },
+ });
+ if (lock) {
+ dimensionLock.current = lock;
+ recordStream = lock.stream;
+ }
+ chrome.runtime
+ .sendMessage({
+ type: "diag-forward",
+ event: "recorder-dimension-lock",
+ data: {
+ engaged: Boolean(lock),
+ width: lock ? lock.width : null,
+ height: lock ? lock.height : null,
+ },
+ })
+ .catch(() => {});
+ }
+ recorder.current = createMediaRecorder(recordStream, {
audioBitsPerSecond,
videoBitsPerSecond: videoBitsPerSecond,
});
@@ -2536,6 +2607,8 @@ const Recorder = () => {
} catch (err) {
debugError("Failed to start MediaRecorder", err);
sendRecordingError("Failed to start recording: " + String(err));
+ dimensionLock.current?.stop().catch(() => {});
+ dimensionLock.current = null;
recorder.current = null;
isStarting.current = false;
stopTabKeepAlive();
@@ -3034,6 +3107,7 @@ const Recorder = () => {
} catch {}
const openResult = await selection.writer.open(recordingId, {
extension: prewarmExt,
+ keepNames: await readRetentionPlan(),
});
return { selection, openResult, recordingId, extension: prewarmExt };
} catch {
@@ -3210,6 +3284,8 @@ const Recorder = () => {
if (!useWebCodecs.current) {
await updateFreeFinalizeStatus("chunks_ready", 100);
}
+ dimensionLock.current?.stop().catch(() => {});
+ dimensionLock.current = null;
recorder.current = null;
stopTabKeepAlive();
@@ -3278,6 +3354,9 @@ const Recorder = () => {
} catch {}
}
+ dimensionLock.current?.stop().catch(() => {});
+ dimensionLock.current = null;
+
if (chunkWriter.current) {
try {
await chunkWriter.current.abort();
@@ -3365,6 +3444,10 @@ const Recorder = () => {
return false;
}
+ dimensionLock.current?.stop().catch(() => {});
+
+ dimensionLock.current = null;
+
recorder.current = null;
pending.current = [];
@@ -4782,6 +4865,10 @@ const Recorder = () => {
} catch (err) {
debugWarn("offscreen-shutdown discard teardown failed", err);
}
+ // Stops the relay pump. It never stops the capture tracks, so the
+ // slow-start race noted below does not apply.
+ dimensionLock.current?.stop().catch(() => {});
+ dimensionLock.current = null;
if (chunkWriter.current) {
try {
await chunkWriter.current.abort();
diff --git a/src/pages/Recorder/dimensionLock.js b/src/pages/Recorder/dimensionLock.js
new file mode 100644
index 0000000..973ac8e
--- /dev/null
+++ b/src/pages/Recorder/dimensionLock.js
@@ -0,0 +1,176 @@
+// MediaRecorder bakes the frame size into the header, so a surface resized
+// across a 16px macroblock boundary corrupts the rest of the file.
+// Fixed-size canvas relay, same letterbox transform as WebCodecs (immune).
+// rAF doesn't fire in an offscreen document, so track processor reads drive frames.
+import { computeLetterboxRect } from "./webcodecs/letterbox";
+
+export const isDimensionLockDisabled = async () => {
+ try {
+ if (typeof chrome === "undefined" || !chrome.storage?.local) return false;
+ const { disableDimensionLock } = await chrome.storage.local.get([
+ "disableDimensionLock",
+ ]);
+ return disableDimensionLock === true;
+ } catch {
+ return false;
+ }
+};
+
+export const canLockDimensions = () =>
+ typeof MediaStreamTrackProcessor !== "undefined" &&
+ typeof MediaStreamTrackGenerator !== "undefined" &&
+ typeof VideoFrame !== "undefined";
+
+// Holds one video size for the whole recording, audio passes through. Returns
+// null when locking isn't possible, so the caller records the source directly.
+export function createDimensionLockedStream(
+ sourceStream,
+ { width, height, fps, onError }
+) {
+ if (!sourceStream || !canLockDimensions()) return null;
+ const sourceTrack = sourceStream.getVideoTracks?.()[0];
+ if (!sourceTrack) return null;
+
+ const tw = Math.max(2, Math.round(width / 2) * 2);
+ const th = Math.max(2, Math.round(height / 2) * 2);
+ const frameRate = fps > 0 ? fps : 30;
+ const frameDurationUs = Math.round(1_000_000 / frameRate);
+
+ let canvas;
+ let ctx;
+ let generator;
+ let writer;
+ let reader;
+ try {
+ canvas = document.createElement("canvas");
+ canvas.width = tw;
+ canvas.height = th;
+ ctx = canvas.getContext("2d", { alpha: false });
+ if (!ctx) return null;
+ generator = new MediaStreamTrackGenerator({ kind: "video" });
+ writer = generator.writable.getWriter();
+ reader = new MediaStreamTrackProcessor({
+ track: sourceTrack,
+ }).readable.getReader();
+ } catch {
+ return null;
+ }
+
+ const stats = {
+ framesIn: 0,
+ framesOut: 0,
+ sourceSizeChanges: 0,
+ lastSourceSize: null,
+ error: null,
+ };
+ let stopped = false;
+ // Source timestamps, rebased to zero. The frame counter they replace assumed
+ // the source delivers fps frames a second, which static capture never does.
+ let baseTs = null;
+ let lastOutTs = null;
+
+ const pump = (async () => {
+ while (!stopped) {
+ let frame;
+ try {
+ const { value, done } = await reader.read();
+ if (done || !value) break;
+ frame = value;
+ } catch (err) {
+ stats.error = String(err);
+ break;
+ }
+ stats.framesIn += 1;
+ const frameTs = Number.isFinite(frame.timestamp) ? frame.timestamp : null;
+ const sw = frame.codedWidth;
+ const sh = frame.codedHeight;
+ if (
+ !stats.lastSourceSize ||
+ stats.lastSourceSize.width !== sw ||
+ stats.lastSourceSize.height !== sh
+ ) {
+ if (stats.lastSourceSize) stats.sourceSizeChanges += 1;
+ stats.lastSourceSize = { width: sw, height: sh };
+ }
+
+ const rect = computeLetterboxRect({ sw, sh, tw, th });
+ try {
+ // A fitted draw misses pixels. Without the clear the previous surface
+ // stays frozen in the bars around the new one.
+ if (!rect.fills) {
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, tw, th);
+ }
+ ctx.drawImage(frame, rect.x, rect.y, rect.w, rect.h);
+ } catch (err) {
+ stats.error = String(err);
+ frame.close();
+ break;
+ }
+ frame.close();
+
+ let out;
+ try {
+ // Carry the source clock rather than a frame counter. Measured: this
+ // Chromium stamps generator frames on arrival, so it is defensive only.
+ let tsUs;
+ if (frameTs === null) {
+ tsUs = lastOutTs === null ? 0 : lastOutTs + frameDurationUs;
+ } else {
+ if (baseTs === null) baseTs = frameTs;
+ tsUs = frameTs - baseTs;
+ }
+ // A repeat or a step back across a surface switch is the one input
+ // MediaRecorder has no defined answer for.
+ if (lastOutTs !== null && tsUs <= lastOutTs) tsUs = lastOutTs + 1;
+ lastOutTs = tsUs;
+ out = new VideoFrame(canvas, { timestamp: tsUs });
+ } catch (err) {
+ stats.error = String(err);
+ break;
+ }
+ try {
+ await writer.write(out);
+ stats.framesOut += 1;
+ } catch (err) {
+ // Writer closed under us (recording stopped, track ended).
+ try {
+ out.close();
+ } catch {}
+ stats.error = String(err);
+ break;
+ }
+ }
+ // A break leaves the generator live, so MediaRecorder keeps finalizing a
+ // file that stopped receiving frames. Never fires for our own stop.
+ if (!stopped && stats.error) {
+ try {
+ onError?.({ ...stats });
+ } catch {}
+ }
+ })();
+
+ const stream = new MediaStream([generator]);
+ for (const track of sourceStream.getAudioTracks?.() || []) {
+ stream.addTrack(track);
+ }
+
+ const stop = async () => {
+ if (stopped) return;
+ stopped = true;
+ try {
+ await reader.cancel();
+ } catch {}
+ try {
+ await writer.close();
+ } catch {}
+ try {
+ await pump;
+ } catch {}
+ try {
+ generator.stop();
+ } catch {}
+ };
+
+ return { stream, stop, stats, width: tw, height: th };
+}
diff --git a/src/pages/Recorder/recorderStorage/idbChunkWriter.js b/src/pages/Recorder/recorderStorage/idbChunkWriter.js
index bd8f49c..3ffaa7d 100644
--- a/src/pages/Recorder/recorderStorage/idbChunkWriter.js
+++ b/src/pages/Recorder/recorderStorage/idbChunkWriter.js
@@ -1,15 +1,7 @@
// IDB-backed ChunkWriter. Fallback when OPFS unavailable.
-import localforage from "localforage";
+import { activeChunksStore } from "../../utils/chunkStores";
-localforage.config({
- driver: localforage.INDEXEDDB,
- name: "screenity",
- version: 1,
-});
-
-const chunksStore = localforage.createInstance({
- name: "chunks",
-});
+const chunksStore = activeChunksStore;
export class IdbChunkWriter {
constructor() {
diff --git a/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js b/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js
index d94942e..cd86ce1 100644
--- a/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js
+++ b/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js
@@ -123,8 +123,10 @@ export class OpfsChunkWriter {
throw new Error("opfs-chunk-writer-reused");
}
const extension = opts.extension === "webm" ? "webm" : "mp4";
+ // Recordings whose editor tab is still open. The worker skips deleting them.
+ const keepNames = Array.isArray(opts.keepNames) ? opts.keepNames : [];
const resp = await this._request(
- { type: "open", recordingId, extension },
+ { type: "open", recordingId, extension, keepNames },
OPEN_TIMEOUT_MS,
);
if (this._aborted || this._closed) {
diff --git a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js b/src/pages/Recorder/recorderStorage/opfs/writerWorker.js
index 15b8cc3..62f766c 100644
--- a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js
+++ b/src/pages/Recorder/recorderStorage/opfs/writerWorker.js
@@ -18,14 +18,16 @@ let offset = 0;
let chunkCount = 0;
let closed = false;
-// Keep exactly one recoverable recording (matches chunksStore.clear()
-// on the IDB path); old recording stays until a new one actually starts.
-const clearPreviousRecordings = async (exceptName = null) => {
+// One recoverable recording, like chunksStore.clear() on IDB, kept until a new
+// one starts. keepNames (open editors) comes from the caller, never forces a delete.
+const clearPreviousRecordings = async (exceptName = null, keepNames = []) => {
try {
+ const keep = new Set(Array.isArray(keepNames) ? keepNames : []);
const dir = await navigator.storage.getDirectory();
for await (const [name] of dir.entries()) {
if (!name.startsWith(FILE_PREFIX)) continue;
if (exceptName && name === exceptName) continue;
+ if (keep.has(name)) continue;
await dir.removeEntry(name).catch(() => {});
}
} catch {}
@@ -54,7 +56,7 @@ const openSyncAccessHandleWithRetry = async (handle) => {
throw lastErr;
};
-const openFile = async (recordingId, extension) => {
+const openFile = async (recordingId, extension, keepNames = []) => {
// Create NEW before deleting old: if creation fails, the previous
// recording remains intact for recovery, and a recovery editor
// already loading the old file doesn't lose it mid-load.
@@ -69,7 +71,7 @@ const openFile = async (recordingId, extension) => {
offset = 0;
chunkCount = 0;
closed = false;
- await clearPreviousRecordings(name);
+ await clearPreviousRecordings(name, keepNames);
devLog("open", { fileName: name });
return { fileName: name };
};
@@ -163,7 +165,11 @@ self.onmessage = (e) => {
if (msg.type === "open") {
enqueue(async () => {
try {
- const { fileName: fn } = await openFile(msg.recordingId, msg.extension);
+ const { fileName: fn } = await openFile(
+ msg.recordingId,
+ msg.extension,
+ msg.keepNames,
+ );
post({ type: "ready", requestId: msg.requestId, ok: true, fileName: fn });
} catch (err) {
post({
diff --git a/src/pages/Recorder/webcodecs/MkvMuxerWrapper.ts b/src/pages/Recorder/webcodecs/MkvMuxerWrapper.ts
index 1df8217..4e00b29 100644
--- a/src/pages/Recorder/webcodecs/MkvMuxerWrapper.ts
+++ b/src/pages/Recorder/webcodecs/MkvMuxerWrapper.ts
@@ -22,6 +22,7 @@ interface MkvMuxerWrapperOptions {
videoCodec?: string;
audioCodec?: string;
onChunk: (chunk: Uint8Array, timestampUs: number | null) => void | Promise<void>;
+ onMuxError?: (err: any, kind: "video" | "audio") => void;
debug?: boolean;
}
@@ -45,6 +46,8 @@ export class MkvMuxerWrapper {
private lastAudioTimestampUs = 0;
private _lastDecoderConfig: any = null;
+ private _audioClosed = false;
+ private _muxErrorReported = false;
private _writeBuffer: Uint8Array[] = [];
private _writeBufferBytes = 0;
@@ -137,6 +140,33 @@ export class MkvMuxerWrapper {
}
}
+ // Packet buffering: the Output waits for audio at every timestamp, so a dead
+ // audio track stops all fragment writes and buffers video in memory.
+ closeAudio() {
+ if (!this.audioSource || this._audioClosed) return;
+ this._audioClosed = true;
+ this.log("[MKV-MUXER] closeAudio");
+ try {
+ this.audioSource.close();
+ } catch (err) {
+ this.warn("[MKV-MUXER] closeAudio threw", err);
+ }
+ }
+
+ // finalize() still resolves after a rejected add(), so dropped packets ship
+ // as a valid but empty recording. Report the first one.
+ private trackAdd(p: any, kind: "video" | "audio") {
+ if (!(p instanceof Promise)) return p;
+ return p.catch((err) => {
+ if (this._muxErrorReported) return;
+ this._muxErrorReported = true;
+ this.err(`[MKV-MUXER] ${kind} add failed`, err);
+ try {
+ this.options.onMuxError?.(err, kind);
+ } catch {}
+ });
+ }
+
addVideoChunk(chunk: EncodedVideoChunk, meta: any) {
if (meta?.decoderConfig) {
this._lastDecoderConfig = meta.decoderConfig;
@@ -148,14 +178,14 @@ export class MkvMuxerWrapper {
: meta;
const packet = this.buildPacket(chunk, effectiveMeta, "video");
- return this.videoSource.add(packet, effectiveMeta);
+ return this.trackAdd(this.videoSource.add(packet, effectiveMeta), "video");
}
addAudioChunk(chunk: EncodedAudioChunk, meta: any) {
- if (!this.audioSource) return;
+ if (!this.audioSource || this._audioClosed) return;
const packet = this.buildPacket(chunk, meta, "audio");
- return this.audioSource.add(packet, meta);
+ return this.trackAdd(this.audioSource.add(packet, meta), "audio");
}
async start() {
diff --git a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
index 770aa41..92632cd 100644
--- a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
+++ b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
@@ -22,6 +22,7 @@ interface Mp4MuxerWrapperOptions {
videoCodec?: string;
audioCodec?: string;
onChunk: (chunk: Uint8Array, timestampUs: number | null) => void | Promise<void>;
+ onMuxError?: (err: any, kind: "video" | "audio") => void;
debug?: boolean;
}
@@ -48,6 +49,8 @@ export class Mp4MuxerWrapper {
private lastAudioTimestampUs = 0;
private _lastDecoderConfig: any = null;
+ private _audioClosed = false;
+ private _muxErrorReported = false;
// Coalesces small StreamTarget writes (per-fragment headers, sample data,
// trailing bytes) into fewer larger IDB puts.
@@ -154,6 +157,33 @@ export class Mp4MuxerWrapper {
}
}
+ // Packet buffering: the Output waits for audio at every timestamp, so a dead
+ // audio track stops all fragment writes and buffers video in memory.
+ closeAudio() {
+ if (!this.audioSource || this._audioClosed) return;
+ this._audioClosed = true;
+ this.log("[MUXER] closeAudio");
+ try {
+ this.audioSource.close();
+ } catch (err) {
+ this.warn("[MUXER] closeAudio threw", err);
+ }
+ }
+
+ // finalize() still resolves after a rejected add(), so dropped packets ship
+ // as a valid but empty recording. Report the first one.
+ private trackAdd(p: any, kind: "video" | "audio") {
+ if (!(p instanceof Promise)) return p;
+ return p.catch((err) => {
+ if (this._muxErrorReported) return;
+ this._muxErrorReported = true;
+ this.err(`[MUXER] ${kind} add failed`, err);
+ try {
+ this.options.onMuxError?.(err, kind);
+ } catch {}
+ });
+ }
+
addVideoChunk(chunk: EncodedVideoChunk, meta: any) {
if (meta?.decoderConfig) {
this._lastDecoderConfig = meta.decoderConfig;
@@ -166,14 +196,14 @@ export class Mp4MuxerWrapper {
: meta;
const packet = this.buildPacket(chunk, effectiveMeta, "video");
- return this.videoSource.add(packet, effectiveMeta);
+ return this.trackAdd(this.videoSource.add(packet, effectiveMeta), "video");
}
addAudioChunk(chunk: EncodedAudioChunk, meta: any) {
- if (!this.audioSource) return;
+ if (!this.audioSource || this._audioClosed) return;
const packet = this.buildPacket(chunk, meta, "audio");
- return this.audioSource.add(packet, meta);
+ return this.trackAdd(this.audioSource.add(packet, meta), "audio");
}
async start() {
diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
index fa7db11..384207e 100644
--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
@@ -177,6 +177,8 @@ export class WebCodecsRecorder {
// Mid-stream watchdog: encoder goes silent after producing chunks
// (HW reclaim, hang). Triggers graceful finalize on the partial.
this._lastChunkAt = null;
+ this._muxerAudioClosed = false;
+ this._muxErrorReported = false;
this._midStreamWatchdog = null;
this._midStreamWatchdogMs = Number.isFinite(options.midStreamWatchdogMs)
? options.midStreamWatchdogMs
@@ -445,6 +447,9 @@ export class WebCodecsRecorder {
this._swRetryReason = null;
this._hiddenRearmCount = 0;
this._lastChunkAt = null;
+ // A reused instance gets a fresh muxer, so neither latch may carry over.
+ this._muxerAudioClosed = false;
+ this._muxErrorReported = false;
this._lastFailureCode = null;
this._forceNextKeyframe = false;
this._startupWindowClosed = false;
@@ -712,6 +717,7 @@ export class WebCodecsRecorder {
videoCodec: videoConfig.containerCodec,
audioCodec: muxerAudioCodec,
onChunk: this.options.onChunk,
+ onMuxError: (err, kind) => this._handleMuxError(err, kind),
});
} else {
const endLoadMuxer = perfSpan("WCR.loadMp4MuxerWrapper");
@@ -726,6 +732,7 @@ export class WebCodecsRecorder {
videoCodec: videoConfig.containerCodec,
audioCodec: muxerAudioCodec,
onChunk: this.options.onChunk,
+ onMuxError: (err, kind) => this._handleMuxError(err, kind),
});
}
@@ -2376,6 +2383,31 @@ export class WebCodecsRecorder {
return new Uint8Array([byte0, byte1]);
}
+ // A track never returns from "ended", so latching this is safe.
+ _closeMuxerAudio(reason) {
+ if (this._muxerAudioClosed) return;
+ this._muxerAudioClosed = true;
+ this.log("[WCR] closing muxer audio", reason);
+ try {
+ this.muxer?.closeAudio?.();
+ } catch (err) {
+ this.warn("[WCR] closeAudio threw", err);
+ }
+ }
+
+ // Dropped packets otherwise finalize as a valid but empty recording.
+ _handleMuxError(err, kind) {
+ if (this._muxErrorReported) return;
+ this._muxErrorReported = true;
+ this.warn("[WCR] muxer add failed", kind, err);
+ const wrapped = new Error(
+ `muxer ${kind} add failed: ${String(err?.message || err).slice(0, 200)}`,
+ );
+ wrapped.code = "webcodecs-mux-add-failed";
+ wrapped.detail = { kind };
+ this.options.onError?.(wrapped);
+ }
+
// Handle VideoEncoder.error: rebuild on HW reclaim (capped by
// _maxEncoderReclaims), or one HW→SW rebuild for pre-first-chunk
// async errors. Otherwise surface to onError.
@@ -3567,6 +3599,7 @@ export class WebCodecsRecorder {
if (readResult.timedOut) {
const trackEnded =
!this.audioTrack || this.audioTrack.readyState === "ended";
+ if (trackEnded) this._closeMuxerAudio("track-ended");
if (
!this._audioReady ||
this.paused ||
@@ -3634,6 +3667,7 @@ export class WebCodecsRecorder {
}
if (!this.audioTrack || this.audioTrack.readyState === "ended") {
this.warn("[WCR] audio lost");
+ this._closeMuxerAudio("audio-lost");
this.options.onError?.({ type: "audio-lost" });
break;
}
diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsx
index ddd3e2d..f1a5afc 100644
--- a/src/pages/Region/Recorder.jsx
+++ b/src/pages/Region/Recorder.jsx
@@ -44,6 +44,7 @@ import { perfMark, perfSpan } from "../utils/perfMarks";
import { markStartProgress } from "../utils/startProgress";
import localforage from "localforage";
+import { activeChunksStore } from "../utils/chunkStores";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -51,9 +52,9 @@ localforage.config({
version: 1,
});
-const chunksStore = localforage.createInstance({
- name: "chunks",
-});
+// Region always writes to IDB. Goes through the slot resolver so it writes to
+// and clears the free slot, leaving a retained recording alone.
+const chunksStore = activeChunksStore;
const DEBUG_RECORDER =
typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;
diff --git a/src/pages/utils/captureSurface.js b/src/pages/utils/captureSurface.js
new file mode 100644
index 0000000..a7eeb1c
--- /dev/null
+++ b/src/pages/utils/captureSurface.js
@@ -0,0 +1,29 @@
+// What kind of surface a recording actually captured, in the shape the
+// app expects (monitor, browser, window). Anything else maps to window.
+export const normalizeCaptureSurface = (displaySurface) => {
+ if (typeof displaySurface !== "string" || !displaySurface) return null;
+ if (displaySurface === "monitor" || displaySurface === "browser") {
+ return displaySurface;
+ }
+ return "window";
+};
+
+// Chrome only fills displaySurface on getDisplayMedia streams. A
+// tabCapture stream has none but is a tab either way.
+export const resolveCaptureSurface = (displaySurface, { isTab } = {}) => {
+ const normalized = normalizeCaptureSurface(displaySurface);
+ if (normalized) return normalized;
+ return isTab ? "browser" : null;
+};
+
+// null means unknown, and the key is left cleared so the scene payload
+// omits surface rather than guessing.
+export const setCapturedSurface = async (surface) => {
+ try {
+ if (surface) {
+ await chrome.storage.local.set({ capturedSurface: surface });
+ } else {
+ await chrome.storage.local.remove(["capturedSurface"]);
+ }
+ } catch {}
+};
diff --git a/src/pages/utils/chunkStores.js b/src/pages/utils/chunkStores.js
new file mode 100644
index 0000000..4b6a3cb
--- /dev/null
+++ b/src/pages/utils/chunkStores.js
@@ -0,0 +1,90 @@
+// Two IDB chunk slots, so a finished recording survives the next one: the new
+// recording writes to the free slot.
+// Slot A keeps the historic "chunks" name. An update mid-recording must still
+// find its bytes there, so it never changes.
+import localforage from "localforage";
+
+localforage.config({
+ driver: localforage.INDEXEDDB,
+ name: "screenity",
+ version: 1,
+});
+
+export const CHUNK_SLOT_A = "chunks";
+export const CHUNK_SLOT_B = "chunks_b";
+export const CHUNK_SLOTS = [CHUNK_SLOT_A, CHUNK_SLOT_B];
+const ACTIVE_SLOT_KEY = "activeChunkSlot";
+
+const instances = new Map();
+export const instanceForSlot = (slot) => {
+ const name = slot === CHUNK_SLOT_B ? CHUNK_SLOT_B : CHUNK_SLOT_A;
+ if (!instances.has(name)) {
+ instances.set(name, localforage.createInstance({ name }));
+ }
+ return instances.get(name);
+};
+
+// Defaults to A, so any read that lands before the pointer loads hits the
+// store every prior version wrote to.
+let activeSlot = CHUNK_SLOT_A;
+
+export const getActiveSlot = () => activeSlot;
+
+export const otherSlot = (slot = activeSlot) =>
+ slot === CHUNK_SLOT_A ? CHUNK_SLOT_B : CHUNK_SLOT_A;
+
+export const loadActiveSlot = async () => {
+ try {
+ const stored = await chrome.storage.local.get([ACTIVE_SLOT_KEY]);
+ const slot = stored?.[ACTIVE_SLOT_KEY];
+ if (slot === CHUNK_SLOT_A || slot === CHUNK_SLOT_B) activeSlot = slot;
+ } catch {}
+ return activeSlot;
+};
+
+export const setActiveSlot = async (slot) => {
+ const next = slot === CHUNK_SLOT_B ? CHUNK_SLOT_B : CHUNK_SLOT_A;
+ activeSlot = next;
+ try {
+ await chrome.storage.local.set({ [ACTIVE_SLOT_KEY]: next });
+ } catch {}
+ return next;
+};
+
+// Every context runs its own copy of this module, so follow the pointer
+// rather than each one caching a stale answer.
+try {
+ if (typeof chrome !== "undefined" && chrome.storage?.onChanged) {
+ chrome.storage.onChanged.addListener((changes, area) => {
+ if (area !== "local" || !changes[ACTIVE_SLOT_KEY]) return;
+ const next = changes[ACTIVE_SLOT_KEY].newValue;
+ if (next === CHUNK_SLOT_A || next === CHUNK_SLOT_B) activeSlot = next;
+ });
+ }
+} catch {}
+
+// Every method resolves the pointer first, so a call landing before it loads
+// cannot hit the wrong store. clear and removeItem re-read it every time.
+const ALWAYS_REFRESH = new Set(["clear", "removeItem"]);
+
+let slotReady = null;
+const ensureSlot = (prop) => {
+ if (ALWAYS_REFRESH.has(prop)) return loadActiveSlot();
+ if (!slotReady) slotReady = loadActiveSlot();
+ return slotReady;
+};
+
+export const activeChunksStore = new Proxy(
+ {},
+ {
+ get(_target, prop) {
+ const probe = instanceForSlot(activeSlot)[prop];
+ if (typeof probe !== "function") return probe;
+ // activeSlot is read after the await, never captured before it.
+ return (...args) =>
+ ensureSlot(prop).then(() =>
+ instanceForSlot(activeSlot)[prop](...args),
+ );
+ },
+ },
+);
diff --git a/src/pages/utils/diagnosticLog.js b/src/pages/utils/diagnosticLog.js
index b0e9019..658b21f 100644
--- a/src/pages/utils/diagnosticLog.js
+++ b/src/pages/utils/diagnosticLog.js
@@ -258,6 +258,12 @@ export const getStorageFlags = async () => {
"lastRestartFlow",
"restartFlowHistory",
"lastFirstChunkWatchdog",
+ // Unsaved-recording retention: which recordings are protected, the plan
+ // handed to the writer, and the IDB slot in use.
+ "retainedRecordings",
+ "retentionPlan",
+ "activeChunkSlot",
+ "unsavedRecordingPromptDismissed",
// Cloud recorder lifecycle (Pro flow). Surfaces the recorder session
// state machine + the message-flow flags needed to debug double-prompt
// / silent-close scenarios.