The free and privacy-friendly screen recorder with no limits 🎥
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Upload byte loss under retries, Linux MP4 audio, pip behavior, + clearer connection errors
Alyssa Xe10e375fafa1
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex f711938..b620116 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -36,9 +36,10 @@ _SPDX `Apache-2.0`, 2 packages_- **localforage** @ 1.10.0, Copyright (c) 2013-2017 Mozilla### Mozilla Public License 2.0-_SPDX `MPL-2.0`, 1 package_+_SPDX `MPL-2.0`, 2 packages_-- **mediabunny** @ 1.46.0, Copyright (c) Vanilagy and contributors+- **mediabunny** @ 1.53.0, Copyright (c) Vanilagy and contributors+- **@mediabunny/aac-encoder** @ 1.53.1, Copyright (c) Vanilagy and contributors### MIT License_SPDX `MIT`, 144 packages_@@ -429,7 +430,7 @@ Apache License## Mozilla Public License 2.0-Applies to **mediabunny**, bundled unmodified from npm (`[email protected]`). Source is available upstream.+Applies to **mediabunny** and **@mediabunny/aac-encoder**, bundled unmodified from npm (`[email protected]`, `@mediabunny/[email protected]`). Source is available upstream.```Mozilla Public License Version 2.0diff --git a/package-lock.json b/package-lock.jsonindex 4cde4ae..c934a24 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,15 +1,16 @@{"name": "screenity",- "version": "4.6.4",+ "version": "4.6.6","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "screenity",- "version": "4.6.4",+ "version": "4.6.6","hasInstallScript": true,"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",+ "@mediabunny/aac-encoder": "^1.53.1","@mediapipe/tasks-vision": "0.10.32","@radix-ui/react-alert-dialog": "^1.0.4","@radix-ui/react-collapsible": "^1.0.2",@@ -36,7 +37,7 @@"gif.js": "^0.2.0","jszip": "^3.10.1","localforage": "^1.10.0",- "mediabunny": "^1.51.0",+ "mediabunny": "^1.53.0","patch-package": "^8.0.0","plyr": "3.7.8","plyr-react": "^5.3.0",@@ -2157,6 +2158,19 @@"node": ">=10"}},+ "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==",+ "license": "MPL-2.0",+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ },+ "peerDependencies": {+ "mediabunny": "^1.0.0"+ }+ },"node_modules/@mediapipe/tasks-vision": {"version": "0.10.32","resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.32.tgz",@@ -8992,9 +9006,9 @@}},"node_modules/mediabunny": {- "version": "1.51.0",- "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.51.0.tgz",- "integrity": "sha512-u327374xU8Ho0gCaMII7fUK8t0PnqkabCox1k8uUwvgvGb9o6YQGZEG2Qr4DTe7nTMpzfL7ukgnHDvDROySZ+Q==",+ "version": "1.53.0",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.53.0.tgz",+ "integrity": "sha512-RjWe9yJr9MPvb6kX4gSu54fZD2w1yf6RyCS0Jmgaml+fFSqEr7+XuASXoRxSqJxgc+wIe+7TujXWcyj3evJ3Bg==","license": "MPL-2.0","workspaces": [".",diff --git a/package.json b/package.jsonindex 45efc1f..0232e39 100755--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "screenity",- "version": "4.6.5",+ "version": "4.6.6","description": "The free and privacy-friendly screen recorder with no sign in needed.","scripts": {"build": "cross-env NODE_ENV=production node utils/build.js",@@ -38,6 +38,7 @@},"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",+ "@mediabunny/aac-encoder": "^1.53.1","@mediapipe/tasks-vision": "0.10.32","@radix-ui/react-alert-dialog": "^1.0.4","@radix-ui/react-collapsible": "^1.0.2",@@ -64,7 +65,7 @@"gif.js": "^0.2.0","jszip": "^3.10.1","localforage": "^1.10.0",- "mediabunny": "^1.51.0",+ "mediabunny": "^1.53.0","patch-package": "^8.0.0","plyr": "3.7.8","plyr-react": "^5.3.0",diff --git a/scripts/release.mjs b/scripts/release.mjsindex d5aaf6f..d03e633 100755--- a/scripts/release.mjs+++ b/scripts/release.mjs@@ -15,6 +15,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = join(__dirname, "..");const MANIFEST_PATH = join(ROOT, "src", "manifest.json");const PACKAGE_PATH = join(ROOT, "package.json");+const LOCK_PATH = join(ROOT, "package-lock.json");const BUILD_DIR = join(ROOT, "build");const ZIP_PATH = join(ROOT, "build.zip");@@ -90,7 +91,24 @@ manifest.version = nextVersion;pkg.version = nextVersion;writeFileSync(MANIFEST_PATH, JSON.stringify(manifest, null, 2) + "\n");writeFileSync(PACKAGE_PATH, JSON.stringify(pkg, null, 2) + "\n");-console.log("Wrote manifest.json + package.json.\n");++// Patch the lockfile's two version fields in place. `npm install+// --package-lock-only` would re-resolve deps inside their ranges too.+let lockNote = "";+try {+ const lock = JSON.parse(readFileSync(LOCK_PATH, "utf8"));+ lock.version = nextVersion;+ if (lock.packages && lock.packages[""]) {+ lock.packages[""].version = nextVersion;+ }+ writeFileSync(LOCK_PATH, JSON.stringify(lock, null, 2) + "\n");+ lockNote = " + package-lock.json";+} catch (err) {+ console.warn(+ `Warning: could not update package-lock.json version (${err?.message || err}).`,+ );+}+console.log(`Wrote manifest.json + package.json${lockNote}.\n`);console.log("Running source hygiene check...");try {diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.jsonindex 7b1d1ee..c4419c3 100644--- a/src/_locales/ca/messages.json+++ b/src/_locales/ca/messages.json@@ -551,6 +551,22 @@"message": "Torna-ho a provar","description": "Botó de tornar-ho a provar de l'etiqueta sense connexió"},+ "serverIssueTitle": {+ "message": "Screenity no està disponible",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "L'enregistrament al núvol no està disponible ara mateix. Torna-ho a provar d'aquí a poc.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "No es pot connectar amb Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Comprova la connexió o torna-ho a provar d'aquí a un moment.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Cal actualitzar Chrome","description": "Etiqueta d'actualització de Chrome"diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.jsonindex ac5a5db..33b0b1b 100644--- a/src/_locales/de/messages.json+++ b/src/_locales/de/messages.json@@ -551,6 +551,22 @@"message": "Erneut versuchen","description": "Schaltfläche 'Erneut versuchen' des Offline-Schriftzugs"},+ "serverIssueTitle": {+ "message": "Screenity ist nicht verfügbar",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Cloud-Aufnahmen sind gerade nicht verfügbar. Versuche es in Kürze erneut.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Screenity ist nicht erreichbar",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Prüfe deine Verbindung oder versuche es gleich noch einmal.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome muss aktualisiert werden","description": "Aktualisieren Sie den Chrome-Schriftzug"diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.jsonindex 0e0cbf2..d041b3f 100644--- a/src/_locales/en/messages.json+++ b/src/_locales/en/messages.json@@ -539,6 +539,22 @@"message": "Try again","description": "Offline label try again button"},+ "serverIssueTitle": {+ "message": "Screenity is unavailable",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Cloud recording isn't available right now. Please try again shortly.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Can't reach Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Please check your connection or try again in a moment.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome needs to be updated","description": "Update Chrome label"diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.jsonindex 7f63736..18090a5 100644--- a/src/_locales/es/messages.json+++ b/src/_locales/es/messages.json@@ -551,6 +551,22 @@"message": "Intenta de nuevo","description": "Botón de intentar de nuevo de la etiqueta de sin conexión"},+ "serverIssueTitle": {+ "message": "Screenity no está disponible",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "La grabación en la nube no está disponible ahora mismo. Vuelve a intentarlo en unos momentos.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "No se puede conectar con Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Comprueba tu conexión o vuelve a intentarlo en un momento.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome necesita actualizarse","description": "Etiqueta de actualizar Chrome"diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.jsonindex 9d03fa5..e51fe1f 100644--- a/src/_locales/fr/messages.json+++ b/src/_locales/fr/messages.json@@ -551,6 +551,22 @@"message": "Réessayer","description": "Bouton de réessai de l'étiquette hors ligne"},+ "serverIssueTitle": {+ "message": "Screenity est indisponible",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "L'enregistrement dans le cloud est indisponible pour le moment. Réessayez dans quelques instants.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Impossible de joindre Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Vérifiez votre connexion ou réessayez dans un instant.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome a besoin d'une mise à jour","description": "Étiquette de mise à jour de Chrome"diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.jsonindex bf364d2..b3e7641 100644--- a/src/_locales/hi/messages.json+++ b/src/_locales/hi/messages.json@@ -551,6 +551,22 @@"message": "फिर से प्रयास करें","description": "ऑफ़लाइन लेबल पुनः प्रयास करें बटन"},+ "serverIssueTitle": {+ "message": "Screenity उपलब्ध नहीं है",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "क्लाउड रिकॉर्डिंग अभी उपलब्ध नहीं है। कुछ देर बाद फिर प्रयास करें।",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Screenity से कनेक्ट नहीं हो पा रहा",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "अपना कनेक्शन जांचें या कुछ देर बाद फिर प्रयास करें।",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "क्रोम को अपडेट करने की आवश्यकता है","description": "क्रोम अपडेट लेबल"diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.jsonindex 5bba2d2..1680b36 100644--- a/src/_locales/id/messages.json+++ b/src/_locales/id/messages.json@@ -551,6 +551,22 @@"message": "Coba lagi","description": "Tombol Coba lagi label Offline"},+ "serverIssueTitle": {+ "message": "Screenity tidak tersedia",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Perekaman cloud tidak tersedia saat ini. Coba lagi sebentar lagi.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Tidak dapat terhubung ke Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Periksa koneksi Anda atau coba lagi sebentar lagi.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome perlu diperbarui","description": "Label Perbarui Chrome"diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.jsonindex 6860425..295238c 100644--- a/src/_locales/it/messages.json+++ b/src/_locales/it/messages.json@@ -551,6 +551,22 @@"message": "Riprova","description": "Pulsante per riprovare dell'etichetta offline"},+ "serverIssueTitle": {+ "message": "Screenity non è disponibile",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "La registrazione nel cloud non è disponibile al momento. Riprova tra poco.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Impossibile raggiungere Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Controlla la connessione o riprova tra poco.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome deve essere aggiornato","description": "Etichetta per aggiornare Chrome"diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.jsonindex 0c274f1..3d3efc2 100644--- a/src/_locales/ko/messages.json+++ b/src/_locales/ko/messages.json@@ -551,6 +551,22 @@"message": "다시 시도","description": "Offline label try again button"},+ "serverIssueTitle": {+ "message": "Screenity를 사용할 수 없습니다",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "지금은 클라우드 녹화를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Screenity에 연결할 수 없습니다",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "연결 상태를 확인하거나 잠시 후 다시 시도해 주세요.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome을 업데이트해야 합니다","description": "Update Chrome label"diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.jsonindex 6d57b76..93be239 100644--- a/src/_locales/pl/messages.json+++ b/src/_locales/pl/messages.json@@ -551,6 +551,22 @@"message": "Spróbuj ponownie","description": "Przycisk etykiety offline Spróbuj ponownie"},+ "serverIssueTitle": {+ "message": "Screenity jest niedostępne",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Nagrywanie w chmurze jest chwilowo niedostępne. Spróbuj ponownie za chwilę.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Nie można połączyć się ze Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Sprawdź połączenie lub spróbuj ponownie za chwilę.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Konieczna aktualizacja Chrome'a","description": "Etykieta aktualizacji Chrome'a"diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.jsonindex 95f4fb4..23c8bb8 100644--- a/src/_locales/pt_BR/messages.json+++ b/src/_locales/pt_BR/messages.json@@ -551,6 +551,22 @@"message": "Tentar novamente","description": "Botão de tentar novamente do rótulo de offline"},+ "serverIssueTitle": {+ "message": "O Screenity está indisponível",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "A gravação na nuvem está indisponível no momento. Tente novamente em instantes.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Não foi possível conectar ao Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Verifique sua conexão ou tente novamente em instantes.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "O Chrome precisa ser atualizado","description": "Rótulo de atualizar o Chrome"diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.jsonindex 4fcaf71..f50dbf3 100644--- a/src/_locales/pt_PT/messages.json+++ b/src/_locales/pt_PT/messages.json@@ -551,6 +551,22 @@"message": "Tentar novamente","description": "Botão de tentar novamente do rótulo de offline"},+ "serverIssueTitle": {+ "message": "O Screenity está indisponível",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "A gravação na nuvem está indisponível de momento. Tenta novamente dentro de momentos.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Não foi possível contactar o Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Verifica a tua ligação ou tenta novamente dentro de momentos.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "O Chrome precisa de ser atualizado","description": "Rótulo de atualizar o Chrome"diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.jsonindex 73da6d5..265f529 100644--- a/src/_locales/ru/messages.json+++ b/src/_locales/ru/messages.json@@ -551,6 +551,22 @@"message": "Попробуйте снова","description": "Кнопка повторной попытки при офлайне"},+ "serverIssueTitle": {+ "message": "Screenity недоступен",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Запись в облако сейчас недоступна. Попробуйте снова через несколько секунд.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Не удаётся связаться со Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Проверьте подключение или повторите попытку через несколько секунд.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Требуется обновление Chrome","description": "Метка обновления Chrome"diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.jsonindex 6134998..5810846 100644--- a/src/_locales/ta/messages.json+++ b/src/_locales/ta/messages.json@@ -551,6 +551,22 @@"message": "மீண்டும் முயற்சி செய்","description": "ஆஃப்லைன் லேபிள் மீண்டும் முயற்சி செய் பொத்தான்"},+ "serverIssueTitle": {+ "message": "Screenity கிடைக்கவில்லை",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "கிளவுட் பதிவு தற்போது கிடைக்கவில்லை. சிறிது நேரம் கழித்து மீண்டும் முயற்சிக்கவும்.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Screenity ஐ அணுக முடியவில்லை",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "உங்கள் இணைப்பைச் சரிபார்க்கவும் அல்லது சிறிது நேரம் கழித்து மீண்டும் முயற்சிக்கவும்.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "கூகுள் புதுப்பிக்க வேண்டும்","description": "கைப்பு கூகுள் புதுப்பிப்பு லேபிள்"diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.jsonindex 89747fe..8a70b73 100644--- a/src/_locales/tr/messages.json+++ b/src/_locales/tr/messages.json@@ -551,6 +551,22 @@"message": "Yeniden Deneyin","description": "Çevrimdışı etiketi tekrar deneme düğmesi"},+ "serverIssueTitle": {+ "message": "Screenity kullanılamıyor",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Bulut kaydı şu anda kullanılamıyor. Lütfen birazdan tekrar deneyin.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Screenity'ye ulaşılamıyor",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Lütfen bağlantınızı kontrol edin veya birazdan tekrar deneyin.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome güncellenmesi gerekiyor","description": "Chrome güncelleme etiketi"diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.jsonindex 6e95d2f..fd06894 100644--- a/src/_locales/uk/messages.json+++ b/src/_locales/uk/messages.json@@ -551,6 +551,22 @@"message": "Спробуйте знову","description": "Offline label try again button"},+ "serverIssueTitle": {+ "message": "Screenity недоступний",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "Запис у хмару зараз недоступний. Спробуйте ще раз за кілька секунд.",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "Не вдається зв'язатися зі Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "Перевірте з'єднання або спробуйте ще раз за кілька секунд.",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Необхідне оновлення Chrome","description": "Update Chrome label"diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.jsonindex ec499b8..8c5ecfe 100644--- a/src/_locales/zh_CN/messages.json+++ b/src/_locales/zh_CN/messages.json@@ -551,6 +551,22 @@"message": "重试","description": "Offline label try again button"},+ "serverIssueTitle": {+ "message": "Screenity 暂时不可用",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "云端录制暂时不可用,请稍后重试。",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "无法连接到 Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "请检查网络连接,或稍后重试。",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome 需要更新","description": "Update Chrome label"diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.jsonindex 3549caa..92c7b9e 100644--- a/src/_locales/zh_TW/messages.json+++ b/src/_locales/zh_TW/messages.json@@ -551,6 +551,22 @@"message": "再試一次","description": "Offline label try again button"},+ "serverIssueTitle": {+ "message": "Screenity 暫時無法使用",+ "description": "Title shown when the Screenity API is returning server errors"+ },+ "serverIssueDescription": {+ "message": "雲端錄影暫時無法使用,請稍後再試。",+ "description": "Description shown when the Screenity API is returning server errors"+ },+ "serverUnreachableTitle": {+ "message": "無法連線至 Screenity",+ "description": "Title shown when the Screenity API cannot be reached"+ },+ "serverUnreachableDescription": {+ "message": "請檢查網路連線,或稍後再試。",+ "description": "Description shown when the Screenity API cannot be reached"+ },"updateChromeLabelTitle": {"message": "Chrome 需要更新","description": "Update Chrome label"diff --git a/src/manifest.json b/src/manifest.jsonindex cc08fc4..5abb446 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.5",+ "version": "4.6.6","background": {"service_worker": "background.bundle.js"},diff --git a/src/pages/Background/index.js b/src/pages/Background/index.jsindex f17291f..a4460f7 100644--- a/src/pages/Background/index.js+++ b/src/pages/Background/index.js@@ -13,6 +13,7 @@ import {destroySessionDir,} from "../CloudRecorder/recorderStorage/opfsKvStore";import { handleGetStreamingData } from "./recording/recordingHelpers";+import { initUninstallSurvey } from "./utils/uninstallSurvey";// Don't tear down an in-flight start on SW restart: a fresh start is// mid-setup (recorder tab not loaded yet), not dead. Mirrors the alarm@@ -332,6 +333,7 @@ setupHandlers();initCountdownFallback();initKeepAwake();initLifecycleObserver();+initUninstallSurvey();// Recovery must run AFTER clearStaleLocks: if the recorder tab died// with the SW, clearStaleLocks clears pendingRecording and recoverydiff --git a/src/pages/Background/listeners/onActionButtonClickedListener.js b/src/pages/Background/listeners/onActionButtonClickedListener.jsindex 71b3dc7..798dcd6 100644--- a/src/pages/Background/listeners/onActionButtonClickedListener.js+++ b/src/pages/Background/listeners/onActionButtonClickedListener.js@@ -8,6 +8,7 @@ import { sendMessageRecord } from "../recording/sendMessageRecord.js";import { loginWithWebsite } from "../auth/loginWithWebsite.js";import { tryResumePendingUploads } from "../recording/resumePendingUploads";import { clearInMemoryEditorLock } from "../recording/stopRecording";+import { sendMessageEnsuringContentScript } from "../utils/executeScripts";const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";@@ -124,7 +125,7 @@ const openPlaygroundOrPopup = async (tab) => {// never gate on navigator.onLine; that caused duplicate playground tabsif (!isForbidden || isPlaygroundOrSetup) {- sendMessageTab(tab.id, { type: "toggle-popup" })+ sendMessageEnsuringContentScript(tab.id, { type: "toggle-popup" }).then(() => console.log("[Screenity][ActionClick] toggle-popup delivered to tab", tab.id)).catch((err) => console.error("[Screenity][ActionClick] toggle-popup FAILED to tab", tab.id, String(err).slice(0, 120)));chrome.storage.local.set({ activeTab: tab.id });diff --git a/src/pages/Background/listeners/onCommandListener.js b/src/pages/Background/listeners/onCommandListener.jsindex 85aed3c..113f22a 100644--- a/src/pages/Background/listeners/onCommandListener.js+++ b/src/pages/Background/listeners/onCommandListener.js@@ -1,5 +1,6 @@import { sendMessageTab, getCurrentTab } from "../tabManagement";import { sendMessageRecord } from "../recording/sendMessageRecord.js";+import { sendMessageEnsuringContentScript } from "../utils/executeScripts";export const onCommandListener = () => {let lastToggleDrawingAt = 0;@@ -34,7 +35,9 @@ export const onCommandListener = () => {!tabUrl.includes("chrome.google.com/webstore") &&!tabUrl.includes("chromewebstore.google.com")) {- sendMessageTab(activeTab.id, { type: "start-stream" });+ sendMessageEnsuringContentScript(activeTab.id, {+ type: "start-stream",+ }).catch(() => {});} else {chrome.tabs.create({diff --git a/src/pages/Background/listeners/onInstalledListener.js b/src/pages/Background/listeners/onInstalledListener.jsindex cb28a8f..9f85ad1 100644--- a/src/pages/Background/listeners/onInstalledListener.js+++ b/src/pages/Background/listeners/onInstalledListener.js@@ -1,5 +1,4 @@import { executeScripts } from "../utils/executeScripts";-import { supportContextQuery } from "../../utils/buildSupportContext";import { tryResumePendingUploads } from "../recording/resumePendingUploads";const cloudFeaturesEnabled =@@ -12,10 +11,6 @@ export const onInstalledListener = () => {if (details.reason === "install") {chrome.storage.local.clear();- const installQs = await supportContextQuery({ source: "uninstall" });- const installUrl = `https://tally.so/r/w8Zro5?${installQs}`;- chrome.runtime.setUninstallURL(installUrl);-chrome.storage.local.set({firstTime: true,onboarding: cloudFeaturesEnabled,@@ -61,10 +56,6 @@ export const onInstalledListener = () => {if (typeof extensionInstalledAt !== "number") {chrome.storage.local.set({ extensionInstalledAt: 0 });}-- const updateQs = await supportContextQuery({ source: "uninstall" });- const updateUrl = `https://tally.so/r/3Ex6kX?${updateQs}`;- chrome.runtime.setUninstallURL(updateUrl);}if (details.reason === "install") {diff --git a/src/pages/Background/listeners/onTabActivatedListener.js b/src/pages/Background/listeners/onTabActivatedListener.jsindex 32531d2..3137996 100644--- a/src/pages/Background/listeners/onTabActivatedListener.js+++ b/src/pages/Background/listeners/onTabActivatedListener.js@@ -1,4 +1,5 @@import { sendMessageTab } from "../tabManagement";+import { sendMessageEnsuringContentScript } from "../utils/executeScripts";export const handleTabActivation = async (activeInfo) => {try {@@ -48,10 +49,12 @@ export const handleTabActivation = async (activeInfo) => {// Check if it's region or customRegion recordingif (!region && !customRegion && recordingType !== "region") {- sendMessageTab(activeInfo.tabId, {+ // The backfill may not have reached this tab yet, and it needs the+ // script before it can show the toolbar.+ sendMessageEnsuringContentScript(activeInfo.tabId, {type: "recording-check",recordingStartTime,- });+ }).catch(() => {});}} else if (!isActivelyRecording && !restarting && !pendingRecording) {sendMessageTab(activeInfo.tabId, { type: "recording-ended" });diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.jsindex ec9cc88..2479272 100644--- a/src/pages/Background/messaging/handlers.js+++ b/src/pages/Background/messaging/handlers.js@@ -1,6 +1,7 @@import JSZip from "jszip";import { registerMessage } from "../../../messaging/messageRouter";import { appendUploadTelemetryEventSerialized } from "../utils/serializedTelemetryStore";+import { noteApiError, noteApiResponse } from "../utils/apiReachability";import { perfMark, perfSpan } from "../../utils/perfMarks";import {focusTab,@@ -572,17 +573,66 @@ const handleReopenPopupMulti = async () => {}};-const handleCheckStorageQuota = async (retried = false) => {+// This check blocks the whole start flow, so a dropped connection or a cold+// server can't become a modal on the first try.+const QUOTA_TIMEOUT_MS = 8000;+const QUOTA_NETWORK_RETRY_DELAYS_MS = [400, 1200];++const isNetworkError = (err) =>+ err instanceof TypeError ||+ err?.name === "AbortError" ||+ err?.name === "TimeoutError";++const fetchStorageQuota = async (token) => {+ let lastErr = null;+ for (let i = 0; i <= QUOTA_NETWORK_RETRY_DELAYS_MS.length; i += 1) {+ if (i > 0) {+ await new Promise((resolve) =>+ setTimeout(resolve, QUOTA_NETWORK_RETRY_DELAYS_MS[i - 1]),+ );+ }+ try {+ return await fetch(`${API_BASE}/storage/quota`, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${token}`,+ },+ credentials: "include",+ signal: AbortSignal.timeout(QUOTA_TIMEOUT_MS),+ });+ } catch (err) {+ lastErr = err;+ if (!isNetworkError(err)) break;+ }+ }+ throw lastErr;+};++// Single attempt, no retry ladder: the banner checks whether the API is back+// and the full ladder reads as stuck. 8s matches the start path.+const probeApiReachability = async () => {try {const { screenityToken } = await chrome.storage.local.get("screenityToken");-const res = await fetch(`${API_BASE}/storage/quota`, {method: "GET",headers: {Authorization: `Bearer ${screenityToken}`,},credentials: "include",+ signal: AbortSignal.timeout(QUOTA_TIMEOUT_MS),});+ return await noteApiResponse(res);+ } catch (err) {+ return await noteApiError(err);+ }+};++const handleCheckStorageQuota = async (retried = false) => {+ try {+ const { screenityToken } = await chrome.storage.local.get("screenityToken");++ const res = await fetchStorageQuota(screenityToken);+ await noteApiResponse(res);// 401: invalidate auth cache so loginWithWebsite refreshes the tokenif (res.status === 401 && !retried) {@@ -594,19 +644,32 @@ const handleCheckStorageQuota = async (retried = false) => {return { success: false, error: "Not authenticated" };}- const result = await res.json();+ // Gateway errors answer with HTML. An uncaught parse throw would+ // masquerade as a network failure.+ let result = null;+ try {+ result = await res.json();+ } catch {}if (!res.ok) {return {success: false,- error: result?.error || "Fetch failed",+ error: result?.error || `Request failed (${res.status})`,+ reachability: res.status >= 500 ? "server" : "ok",};}return { success: true, ...result };} catch (err) {console.error("❌ Error checking storage quota:", err);- return { success: false, error: err.message };+ const state = await noteApiError(err);+ return {+ success: false,+ error: isNetworkError(err)+ ? "Network unavailable"+ : err.message || "Fetch failed",+ reachability: state,+ };}};@@ -2207,6 +2270,18 @@ export const setupHandlers = () => {return true;},);+ registerMessage(+ "recheck-api-reachability",+ async (message, sender, sendResponse) => {+ if (!CLOUD_FEATURES_ENABLED) {+ sendResponse({ state: "ok" });+ return true;+ }+ const state = await probeApiReachability();+ sendResponse({ state });+ return true;+ },+ );registerMessage("time-warning", async (message) => {const tab = await getCurrentTab();if (tab?.id) {diff --git a/src/pages/Background/recording/countdownFallback.js b/src/pages/Background/recording/countdownFallback.jsindex 11e784a..1f6b2ca 100644--- a/src/pages/Background/recording/countdownFallback.js+++ b/src/pages/Background/recording/countdownFallback.js@@ -5,6 +5,9 @@ import { startAfterCountdown } from "./startRecording";// 3s countdown + 1s END_HOLD_MS + POST_HIDE_START_DELAY_MS + slackconst FALLBACK_AFTER_COUNTDOWN_STARTED_MS = 8000;+// countdownStartedAt is never cleared, so on startup it can be days old. Past+// this it's a phantom start, not recovery: a real SW restart lands in seconds.+const FALLBACK_RECOVERY_CEILING_MS = 60000;let fallbackTimerId = null;@@ -63,18 +66,43 @@ export const noteCountdownStarted = () => {// fallback dispatch synchronously if the deadline already passed.export const recoverPendingCountdownOnStartup = async () => {try {- const { pendingRecording, recording, restarting, countdownStartedAt } =- await chrome.storage.local.get([- "pendingRecording",- "recording",- "restarting",- "countdownStartedAt",- ]);+ const {+ pendingRecording,+ recording,+ restarting,+ countdownStartedAt,+ recordingStoppedAt,+ } = await chrome.storage.local.get([+ "pendingRecording",+ "recording",+ "restarting",+ "countdownStartedAt",+ "recordingStoppedAt",+ ]);if (!pendingRecording || recording || restarting) return;const startedAt = Number(countdownStartedAt) || 0;if (!startedAt) return;+ // A countdown that predates the last stop belongs to a finished recording.+ // pendingRecording can be true from a start whose countdown hasn't ticked.+ if (+ typeof recordingStoppedAt === "number" &&+ startedAt <= recordingStoppedAt+ ) {+ console.info(+ "[Screenity][BG] recoverPendingCountdownOnStartup: countdown predates last stop, skipping",+ { startedAt, recordingStoppedAt },+ );+ return;+ }const elapsed = Date.now() - startedAt;if (elapsed < FALLBACK_AFTER_COUNTDOWN_STARTED_MS) return;+ if (elapsed > FALLBACK_RECOVERY_CEILING_MS) {+ console.info(+ "[Screenity][BG] recoverPendingCountdownOnStartup: stale countdown, skipping",+ { elapsedMs: elapsed },+ );+ return;+ }console.info("[Screenity][BG] recoverPendingCountdownOnStartup: SW restarted past countdown deadline, dispatching",{ elapsedMs: elapsed },diff --git a/src/pages/Background/recording/resumePendingUploads.js b/src/pages/Background/recording/resumePendingUploads.jsindex 73b0259..6083d39 100644--- a/src/pages/Background/recording/resumePendingUploads.js+++ b/src/pages/Background/recording/resumePendingUploads.js@@ -1,6 +1,19 @@const JOURNAL_KEY_PREFIX = "uploadJournal-";const MAX_RESUME_ATTEMPTS = 5;const RESUME_LOCK_TTL_MS = 10 * 60 * 1000;+// `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([+ "recording-starting",+ "uploaders-initializing",+ "uploaders-ready",+ "recording",+ "finalizing",+ "scene-creating",+ "scene-recovering",+]);+// Bounded so a host that died mid-drain can't block resume for good.+const PIPELINE_ACTIVE_TTL_MS = 2 * 60 * 1000;const getAllStorage = () =>new Promise((resolve) => {@@ -11,13 +24,23 @@ const getAllStorage = () =>}});+// resumeOneJournal dereferences these without a fallback, so a journal missing+// any of them can't be resumed safely.+const isResumableJournal = (journal) => {+ if (!journal.mediaId || !journal.projectId || !journal.videoId) return false;+ const track = journal.trackType || journal.type;+ return track === "screen" || track === "camera" || track === "audio";+};+const pickResumeCandidates = (storage) => {const pending = [];const abandonedKeys = [];for (const [key, value] of Object.entries(storage)) {if (!key.startsWith(JOURNAL_KEY_PREFIX)) continue;if (!value || typeof value !== "object") continue;- if (value.trackType === "audio") continue; // audio is diagnostic, never uploaded+ // 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) {@@ -41,10 +64,19 @@ export const tryResumePendingUploads = async ({"pendingRecording","resumeInProgress","resumeLockAt",+ "recorderPipelineState",]);if (snap.recording || snap.pendingRecording) {return { skipped: "recording-active" };}+ const pipeline = snap.recorderPipelineState;+ if (+ pipeline &&+ ACTIVE_PIPELINE_STEPS.has(pipeline.step) &&+ Date.now() - (pipeline.ts || 0) < PIPELINE_ACTIVE_TTL_MS+ ) {+ return { skipped: `pipeline-active-${pipeline.step}` };+ }if (snap.resumeInProgress) {const lockAge = Date.now() - (snap.resumeLockAt || 0);if (lockAge < RESUME_LOCK_TTL_MS) {diff --git a/src/pages/Background/recording/sendMessageRecord.js b/src/pages/Background/recording/sendMessageRecord.jsindex 0dcf578..b4e789e 100644--- a/src/pages/Background/recording/sendMessageRecord.js+++ b/src/pages/Background/recording/sendMessageRecord.js@@ -5,6 +5,10 @@ import { diagEvent } from "../../utils/diagnosticLog";// `offscreen` flag, look for a live recorder offscreen doc before giving up.const ENABLE_RESILIENT_HANDOFF = true;+// Always false: "message port closed" can come from any context that got the+// broadcast and didn't reply (camera page). Only sendResponse confirms delivery.+const isDeliveredWithoutReply = () => false;+export const sendMessageRecord = (message, responseCallback = null) => {return new Promise((resolve, reject) => {chrome.storage.local.get(["recordingTab", "offscreen"], (result) => {@@ -18,8 +22,11 @@ export const sendMessageRecord = (message, responseCallback = null) => {if (result.offscreen) {chrome.runtime.sendMessage(message, (response) => {- if (chrome.runtime.lastError) {- reject(chrome.runtime.lastError.message);+ const err = chrome.runtime.lastError?.message;+ if (err && !isDeliveredWithoutReply(err)) {+ reject(err);+ } else if (err) {+ resolve(undefined);} else {responseCallback ? responseCallback(response) : resolve(response);}@@ -41,8 +48,11 @@ export const sendMessageRecord = (message, responseCallback = null) => {} else {const sendViaOffscreen = () => {chrome.runtime.sendMessage(message, (response) => {- if (chrome.runtime.lastError) {- reject(chrome.runtime.lastError.message);+ const err = chrome.runtime.lastError?.message;+ if (err && !isDeliveredWithoutReply(err)) {+ reject(err);+ } else if (err) {+ resolve(undefined);} else {responseCallback ? responseCallback(response) : resolve(response);}diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.jsindex 7a47729..74e5ce4 100644--- a/src/pages/Background/recording/startRecording.js+++ b/src/pages/Background/recording/startRecording.js@@ -11,6 +11,13 @@ import { emitRecordingTelemetry } from "./emitRecordingTelemetry";// so countdown-finished + 8s fallback can both fire and open two recorder tabslet _startRecordingInFlight = false;const STARTRECORDING_GUARD_TIMEOUT_MS = 30000;+// Start-fail re-check keeps polling while the recorder reports stage progress,+// so a slow-but-live start isn't torn down. The caps bound a wedged start.+const RECHECK_INTERVAL_MS = 2500;+// Generous: the encoder probe stage can legitimately run several seconds on a+// flaky encoder, and killing a live start is the worse bug.+const PROGRESS_STALE_MS = 10000;+const START_PROGRESS_CAP_MS = 25000;let _startRecordingGuardTimer = null;const releaseStartRecordingGuard = () => {_startRecordingInFlight = false;@@ -247,6 +254,9 @@ const _startRecordingInner = async (caller) => {// editor into reading the new in-flight recordinglastRecordingFinalizedFileName: null,lastRecordingError: null,+ // Stale counters make a genuine start failure read as "recorder was alive"+ // in the stuck report.+ recorderLiveProgress: null,lastChunkSendFailure: null,lastRecordingSalvaged: null,lastStartRecordingCaller: { caller, stack, ts: Date.now() },@@ -315,11 +325,21 @@ const _startRecordingInner = async (caller) => {chrome.storage.local.set({ lastRecordingType: recordingType || "screen" });- const { quality, systemAudio, audioInput, offscreen, alarm, alarmTime, countdown } =+ const {+ quality,+ systemAudio,+ micActive,+ defaultAudioInput,+ offscreen,+ alarm,+ alarmTime,+ countdown,+ } =await chrome.storage.local.get(["quality","systemAudio",- "audioInput",+ "micActive",+ "defaultAudioInput","offscreen","alarm","alarmTime",@@ -338,7 +358,8 @@ const _startRecordingInner = async (caller) => {quality: quality || null,region: Boolean(customRegion),systemAudio: Boolean(systemAudio),- audioInput: Boolean(audioInput),+ // Was "audioInput", a key nothing ever wrote, so this always logged false.+ audioInput: Boolean(micActive) && defaultAudioInput !== "none",offscreen: Boolean(offscreen),alarm: Boolean(alarm),alarmTime: alarm ? (alarmTime || null) : null,@@ -414,6 +435,8 @@ const _startRecordingInner = async (caller) => {? { type: "start-recording-tab", region: true }: { type: "start-recording-tab" };+ const startDispatchedAt = Date.now();+sendMessageRecord(startMsg).catch((err) => {const errStr = String(err).slice(0, 120);const isStaleTab =@@ -421,16 +444,49 @@ const _startRecordingInner = async (caller) => {errStr.includes("No tab with id") ||errStr.includes("No recording tab available");// sendMessage can reject "message port closed" even on a healthy start; re-check- setTimeout(async () => {+ const recheck = async () => {let isReallyRecording = false;+ let trackEnd = null;+ let progress = null;try {const snap = await chrome.storage.local.get(["recording","pendingRecording",+ "lastTrackEndEvent",+ "recorderStartProgress",]);isReallyRecording = Boolean(snap.recording);+ trackEnd = snap.lastTrackEndEvent || null;+ progress = snap.recorderStartProgress || null;} catch {}if (isReallyRecording) return;+ // Still moving mid-start: a slow encoder probe outlasts one window, and+ // discarding the offscreen doc here is what killed the recording.+ const isThisStart = progress?.ts && progress.ts >= startDispatchedAt;+ const isFresh = isThisStart && Date.now() - progress.ts < PROGRESS_STALE_MS;+ const withinCap = Date.now() - startDispatchedAt < START_PROGRESS_CAP_MS;+ if (isFresh && withinCap) {+ setTimeout(recheck, RECHECK_INTERVAL_MS);+ return;+ }+ if (isThisStart) {+ diagEvent("warning", {+ note: "start-fail after progress stalled",+ stage: String(progress.stage || "").slice(0, 40),+ stalledMs: Date.now() - progress.ts,+ });+ }+ // Stream came up then died (native Stop sharing, source window gone).+ // That handler already stopped it, so don't overwrite the real reason.+ if (trackEnd?.ts && trackEnd.ts >= startDispatchedAt) {+ diagEvent("warning", {+ note: "start-fail suppressed, stream ended after start",+ reason: String(trackEnd.reason || "").slice(0, 60),+ afterMs: trackEnd.ts - startDispatchedAt,+ });+ releaseStartRecordingGuard();+ return;+ }diagEvent("start-fail", {region: Boolean(customRegion),error: errStr,@@ -460,7 +516,8 @@ const _startRecordingInner = async (caller) => {// sweep it so it can't keep capturing unattendedsweepRecorderTabs().catch(() => {});chrome.action.setIcon({ path: "assets/icon-34.png" });- }, 2500);+ };+ setTimeout(recheck, RECHECK_INTERVAL_MS);});chrome.action.setIcon({ path: "assets/recording-logo.png" });// chrome.alarms 30s minimum in prod; sub-30s silently bumps or never firesdiff --git a/src/pages/Background/tabManagement/setSurface.js b/src/pages/Background/tabManagement/setSurface.jsindex c400a3d..73ccd7c 100644--- a/src/pages/Background/tabManagement/setSurface.js+++ b/src/pages/Background/tabManagement/setSurface.js@@ -4,13 +4,29 @@ import { loginWithWebsite } from "../auth/loginWithWebsite";export const setSurface = async (request) => {await chrome.storage.local.set({ surface: request.surface });- const result = await loginWithWebsite({ force: true });- const { activeTab } = await chrome.storage.local.get(["activeTab"]);+ // A throw here took the whole message down, leaving the camera bubble up over+ // the recording. Logout is exactly when it fails, so fall back to the cache.+ let result = null;+ try {+ result = await loginWithWebsite({ force: true });+ } catch (err) {+ console.warn("[Screenity][BG] setSurface auth refresh failed:", err);+ }+ const { activeTab, isSubscribed, instantMode, recordingType } =+ await chrome.storage.local.get([+ "activeTab",+ "isSubscribed",+ "instantMode",+ "recordingType",+ ]);sendMessageTab(activeTab, {type: "set-surface",surface: request.surface,- subscribed: result?.subscribed || false,- instantMode: result?.instantMode || false,+ // A region/tab capture still reports displaySurface "monitor". Without this+ // the camera treats it as a full-screen recording and opens PiP.+ recordingType: recordingType || null,+ subscribed: result ? Boolean(result.subscribed) : Boolean(isSubscribed),+ instantMode: result ? Boolean(result.instantMode) : Boolean(instantMode),});};diff --git a/src/pages/Background/utils/apiReachability.js b/src/pages/Background/utils/apiReachability.jsnew file mode 100644index 0000000..9bceb9a--- /dev/null+++ b/src/pages/Background/utils/apiReachability.js@@ -0,0 +1,35 @@+// Lets the popup say what's actually wrong instead of blaming the connection.+// ok = reachable, offline = browser says no network, server = 5xx (our end),+// unreachable = nothing came back, cause unknown from here.++export const API_REACHABILITY_KEY = "apiReachability";++export const setApiReachability = async (state) => {+ try {+ // Written even when unchanged: `at` is the popup's freshness clock, so+ // skipping the repeat let the banner go stale and hide mid-outage.+ await chrome.storage.local.set({+ [API_REACHABILITY_KEY]: { state, at: Date.now() },+ });+ } catch (err) {+ console.warn("Failed to record API reachability:", err);+ }+ return state;+};++// 4xx means the server is up and talking to us. Only 5xx is our end down.+export const noteApiResponse = (res) =>+ setApiReachability(res && res.status >= 500 ? "server" : "ok");++export const noteApiError = (err) => {+ const offline =+ typeof navigator !== "undefined" && navigator.onLine === false;+ if (offline) return setApiReachability("offline");+ // fetch TypeError, abort and timeout are indistinguishable from here:+ // nothing came back and we can't tell whose end broke.+ const networkish =+ err instanceof TypeError ||+ err?.name === "AbortError" ||+ err?.name === "TimeoutError";+ return setApiReachability(networkish ? "unreachable" : "server");+};diff --git a/src/pages/Background/utils/executeScripts.js b/src/pages/Background/utils/executeScripts.jsindex b1f4c94..4101d2d 100644--- a/src/pages/Background/utils/executeScripts.js+++ b/src/pages/Background/utils/executeScripts.js@@ -7,6 +7,11 @@// simultaneously. With a couple of dozen tabs that saturates the CPU and the// whole browser goes sluggish, tab switching included.const INJECT_CONCURRENCY = 3;+// Long tail: one at a time with a gap, so a few hundred stale tabs cost+// background time instead of a pinned CPU.+const BACKFILL_CONCURRENCY = 1;+const BACKFILL_GAP_MS = 250;+// executeScript resolves as a promise only when no callback is passed. The// callback form returns undefined, so awaiting these used to wait on nothing.@@ -31,6 +36,81 @@ const runPool = async (jobs, limit) => {await Promise.all(workers);};+// A reload orphans every tab's content script, and the clicked tab shouldn't+// wait behind the backfill queue.+export const injectContentScriptIntoTab = async (tabId) => {+ if (typeof tabId !== "number") return false;+ const contentScripts = chrome.runtime.getManifest().content_scripts || [];+ const files = contentScripts.flatMap((cs) => cs.js || []);+ if (files.length === 0) return false;+ try {+ await chrome.scripting.executeScript({ target: { tabId }, files });+ return true;+ } catch {+ return false;+ }+};++// The backfill is no longer guaranteed to have reached the tab, so callers+// can't assume a content script is there.+export const sendMessageEnsuringContentScript = async (tabId, message) => {+ const { sendMessageTab } = await import("../tabManagement");+ try {+ return await sendMessageTab(tabId, message);+ } catch (err) {+ if (!String(err).includes("Receiving end does not exist")) throw err;+ }+ if (!(await injectContentScriptIntoTab(tabId))) {+ throw new Error(`content script injection failed for tab ${tabId}`);+ }+ return sendMessageTab(tabId, message);+};++// Recently-used first. Sinks collapsed-group tabs without needing the+// tabGroups permission to identify them.+const injectionPriority = (tab, focusedWindowId) => {+ if (tab.active) return 0;+ if (focusedWindowId != null && tab.windowId === focusedWindowId) return 1;+ return 2;+};++// Skips the ~1MB re-parse when the script is already there. Only absence+// reads "Receiving end does not exist", so any other reply means it is.+const hasContentScript = async (tabId) => {+ const { sendMessageTab } = await import("../tabManagement");+ try {+ await sendMessageTab(tabId, { type: "screenity-ping" });+ return true;+ } catch (err) {+ return !String(err).includes("Receiving end does not exist");+ }+};++// Recording start is latency-critical and runs on this same worker. Backfilling+// hundreds of tabs alongside it is what the user feels.+const recordingInFlight = async () => {+ try {+ const s = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "restarting",+ ]);+ return Boolean(s.recording || s.pendingRecording || s.restarting);+ } catch {+ return false;+ }+};++const injectIfMissing = async (tabId, files, gapMs = 0) => {+ // gapMs > 0 marks the background tier, which waits out a live recording.+ while (gapMs > 0 && (await recordingInFlight())) {+ await new Promise((r) => setTimeout(r, 2000));+ }+ if (await hasContentScript(tabId)) return;+ await injectInto(tabId, files);+ if (gapMs > 0) await new Promise((r) => setTimeout(r, gapMs));+};+export const executeScripts = async () => {const contentScripts = chrome.runtime.getManifest().content_scripts;const tabQueries = contentScripts.map((cs) =>@@ -38,7 +118,13 @@ export const executeScripts = async () => {);const tabResults = await Promise.all(tabQueries);- const jobs = [];+ let focusedWindowId = null;+ try {+ focusedWindowId = (await chrome.windows.getLastFocused()).id;+ } catch {}++ const urgent = [];+ const background = [];for (let i = 0; i < tabResults.length; i++) {const cs = contentScripts[i];// Discarded and unloaded tabs have no renderer to inject into, and the@@ -48,13 +134,24 @@ export const executeScripts = async () => {(tab) =>typeof tab.id === "number" && !tab.discarded && tab.status !== "unloaded",);- // Visible tabs first: those are the ones where a missing content script is- // immediately noticeable, and they finish before the pool reaches the rest.- tabs.sort((a, b) => Number(Boolean(b.active)) - Number(Boolean(a.active)));+ tabs.sort((a, b) => {+ const byTier =+ injectionPriority(a, focusedWindowId) -+ injectionPriority(b, focusedWindowId);+ if (byTier !== 0) return byTier;+ return (b.lastAccessed || 0) - (a.lastAccessed || 0);+ });for (const tab of tabs) {- jobs.push(() => injectInto(tab.id, cs.js));+ if (injectionPriority(tab, focusedWindowId) === 0) {+ urgent.push(() => injectIfMissing(tab.id, cs.js));+ } else {+ background.push(() => injectIfMissing(tab.id, cs.js, BACKFILL_GAP_MS));+ }}}- await runPool(jobs, INJECT_CONCURRENCY);+ await runPool(urgent, INJECT_CONCURRENCY);+ // Not awaited: tabs the trickle hasn't reached get injected on demand by+ // whatever needs them.+ void runPool(background, BACKFILL_CONCURRENCY);};diff --git a/src/pages/Background/utils/uninstallSurvey.js b/src/pages/Background/utils/uninstallSurvey.jsnew file mode 100644index 0000000..661e03d--- /dev/null+++ b/src/pages/Background/utils/uninstallSurvey.js@@ -0,0 +1,23 @@+import { supportContextQuery } from "../../utils/buildSupportContext";++const UNINSTALL_FORM = "https://tally.so/r/3Ex6kX";++export const syncUninstallSurvey = async () => {+ try {+ const { isLoggedIn } = await chrome.storage.local.get("isLoggedIn");+ if (isLoggedIn) {+ chrome.runtime.setUninstallURL("");+ return;+ }+ const qs = await supportContextQuery({ source: "uninstall" });+ chrome.runtime.setUninstallURL(`${UNINSTALL_FORM}?${qs}`);+ } catch {}+};++export const initUninstallSurvey = () => {+ syncUninstallSurvey();+ chrome.storage.onChanged.addListener((changes, area) => {+ if (area !== "local" || !changes.isLoggedIn) return;+ syncUninstallSurvey();+ });+};diff --git a/src/pages/Camera/Camera.jsx b/src/pages/Camera/Camera.jsxindex 0a28d01..c5d6178 100644--- a/src/pages/Camera/Camera.jsx+++ b/src/pages/Camera/Camera.jsx@@ -187,10 +187,20 @@ const Camera = () => {if (!videoRef.current || !streamRef.current?.active) return;chrome.storage.local.get(- ["surface", "recording"],+ ["surface", "recording", "isSubscribed", "instantMode", "recordingType"],(result) => {if (result.recording && result.surface) {- surfaceHandler({ surface: result.surface }, videoRef);+ // Without these two surfaceHandler reads the plan as free, and a Pro+ // monitor recording enters PiP with the camera burnt into the capture.+ surfaceHandler(+ {+ surface: result.surface,+ subscribed: Boolean(result.isSubscribed),+ instantMode: Boolean(result.instantMode),+ recordingType: result.recordingType || null,+ },+ videoRef,+ );}},);diff --git a/src/pages/Camera/context/CameraContext.js b/src/pages/Camera/context/CameraContext.jsindex 142361d..97bcb70 100644--- a/src/pages/Camera/context/CameraContext.js+++ b/src/pages/Camera/context/CameraContext.js@@ -122,10 +122,18 @@ export const CameraProvider = ({ children }) => {globalRefs.setBackgroundEffects = handleSetBackgroundEffects;globalRefs.backgroundEffectsRef = backgroundEffectsRef;+ let unmounted = false;+const initializeModel = async () => {try {const model = await loadSegmentationModel();if (model) {+ // Unmounted mid-load: close it instead of stashing a segmenter+ // nothing will ever tear down.+ if (unmounted) {+ try { model.close?.(); } catch {}+ return;+ }segmenterRef.current = model;setIsModelLoaded(true);} else {@@ -150,6 +158,10 @@ export const CameraProvider = ({ children }) => {});return () => {+ unmounted = true;+ // Nulling the ref alone leaks the wasm graph and its GL context,+ // so every camera remount stacked another one.+ try { segmenterRef.current?.close?.(); } catch {}segmenterRef.current = null;setIsModelLoaded(false);};diff --git a/src/pages/Camera/utils/cameraUtils.js b/src/pages/Camera/utils/cameraUtils.jsindex 5ef6512..cc6c88d 100644--- a/src/pages/Camera/utils/cameraUtils.js+++ b/src/pages/Camera/utils/cameraUtils.js@@ -354,8 +354,14 @@ export const surfaceHandler = async (request, videoRef) => {return;}+ // recordingType leads, surface only qualifies it: displaySurface reports+ // "monitor" for a region/tab crop too, since the crop happens after the pick.+ const CROPPED_TYPES = ["region", "tab", "camera"];+ const croppedCapture = CROPPED_TYPES.includes(request.recordingType);+ const fullMonitor = request.surface === "monitor" && !croppedCapture;+if (!CLOUD_FEATURES_ENABLED) {- const shouldEnterPip = request.surface === "monitor";+ const shouldEnterPip = fullMonitor;if (shouldEnterPip && videoRef.current) {try {await videoRef.current.requestPictureInPicture();@@ -383,7 +389,7 @@ export const surfaceHandler = async (request, videoRef) => {// the camera's part of the screen recording when it isn't// (pro+non-instant+monitor).const shouldEnterPip =- (request.surface === "monitor" && (!isSubscribed || instantMode)) ||+ (fullMonitor && (!isSubscribed || instantMode)) ||(request.surface !== "monitor" && isSubscribed && !instantMode);if (shouldEnterPip && videoRef.current) {diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex d7d357e..3442f9f 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -6,9 +6,12 @@ import {} from "../utils/recorderMessaging";import { getBitrates, getResolutionForQuality } from "./recorderConfig";import { pickEncodedDims, scaleClickEvents } from "./encodedDims";+import { planGapResend } from "./uploadGapRecovery";+import { getClientSessionId } from "./clientSessionId";import BunnyTusUploader from "./bunnyTusUploader";import localforage from "localforage";import { createVideoProject } from "./createVideoProject";+import { notifyRecordingStarted } from "./notifyRecordingStarted";import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";import { startAudioStream as acquireMicStream } from "../utils/startAudioStream";import { shouldAcquireMicAtStart } from "../utils/micAcquisitionPolicy";@@ -78,6 +81,19 @@ const DEBUG_START_FLOW =? !!window.SCREENITY_DEBUG_RECORDER ||process.env.NODE_ENV !== "production": false;+// Statuses a plain resume() recovers. Shared by the network-online handler and+// the per-track stall sweep.+const RESUMABLE_UPLOADER_STATUSES = new Set([+ "uploading",+ "paused",+ "error",+ "ready",+]);+// Stop is user-visible, so the pre-finalize gap re-send is capped.+const GAP_RESEND_BUDGET_MS = 45000;+// Off until prepareGapResend gets an in-flight guard: it rewinds offset against+// a live queue, which corrupts instead of failing.+const GAP_RESEND_ENABLED = false;const SCREEN_CHUNK_MEMORY_WINDOW = 8;const CAMERA_CHUNK_MEMORY_WINDOW = 8;const AUDIO_CHUNK_MEMORY_WINDOW = 8;@@ -292,6 +308,7 @@ const CloudRecorder = () => {// guard, both fire startStreaming → two getDisplayMedia prompts and a// silent recorder close. Mirrors the same guard in legacy Recorder.jsx.const streamingDataReceivedAt = useRef(null);+ const streamingDataRetryTimer = useRef(null);// Backup guard: even if a future code path bypasses the message-level// dedup, this prevents startStreaming itself from running twice.const startStreamingInFlight = useRef(false);@@ -316,6 +333,7 @@ const CloudRecorder = () => {const cameraChunkIndexRef = useRef(0);const screenChunkByteRangesRef = useRef([]);const cameraChunkByteRangesRef = useRef([]);+ const audioChunkByteRangesRef = useRef([]);const chunksPurgedDuringRecordingRef = useRef(false);const screenChunksPurgedCountRef = useRef(0);const cameraChunksPurgedCountRef = useRef(0);@@ -702,6 +720,9 @@ const CloudRecorder = () => {"recording_heartbeat","recording_stop_diag","recording_failed_bundle",+ // Fires when a track dies during setup, exactly when its uploader has no+ // meta yet, so the guard below would drop it silently.+ "recording_track_setup_failed_after_live",]);if (!mediaId &&@@ -768,6 +789,53 @@ const CloudRecorder = () => {typeof eventPayload.totalBytes === "number"? eventPayload.totalBytes: null,+ // Uploader emits this on upload_error but the mapping never forwarded it,+ // so a failed chunk's status was only recoverable by parsing errMsg.+ httpStatus:+ typeof eventPayload.httpStatus === "number"+ ? eventPayload.httpStatus+ : null,+ // One id per host (page load). Two ids on one bunnyVideoId means two+ // writers. The same id twice means one host re-signed.+ clientSessionId: eventPayload.clientSessionId || null,+ // Allowlisting here is necessary but not sufficient: the server sanitizer+ // needs them too. Folded into `reason`, which survives either way.+ queuedBytes:+ typeof eventPayload.queuedBytes === "number"+ ? eventPayload.queuedBytes+ : null,+ stallMs:+ typeof eventPayload.stallMs === "number" ? eventPayload.stallMs : null,+ serverOffset:+ typeof eventPayload.serverOffset === "number"+ ? eventPayload.serverOffset+ : null,+ clientOffset:+ typeof eventPayload.clientOffset === "number"+ ? eventPayload.clientOffset+ : null,+ divergence:+ typeof eventPayload.divergence === "number"+ ? eventPayload.divergence+ : null,+ gapBytes:+ typeof eventPayload.gapBytes === "number" ? eventPayload.gapBytes : null,+ sentBytes:+ typeof eventPayload.sentBytes === "number" ? eventPayload.sentBytes : null,+ stuckAtInit:+ typeof eventPayload.stuckAtInit === "boolean"+ ? eventPayload.stuckAtInit+ : null,+ siblingProgressing:+ typeof eventPayload.siblingProgressing === "boolean"+ ? eventPayload.siblingProgressing+ : null,+ resUrlMatches:+ typeof eventPayload.resUrlMatches === "boolean"+ ? eventPayload.resUrlMatches+ : null,+ trigger:+ typeof eventPayload.trigger === "string" ? eventPayload.trigger : null,// Set on recording_heartbeat. These existed in the server schema but// no client path ever sent them.availableBytes:@@ -791,7 +859,13 @@ const CloudRecorder = () => {visibilityState:typeof document !== "undefined" ? document.visibilityState : null,errCode: eventPayload.errorCode || null,- errMsg: eventPayload.message || eventPayload.error || null,+ // errMsg first: callers passing the server's own field name were+ // silently nulled here for as long as the mapping has existed.+ errMsg:+ eventPayload.errMsg ||+ eventPayload.message ||+ eventPayload.error ||+ null,reason: eventPayload.reason || null,mediaId: eventPayload.mediaId || null,bunnyVideoId: eventPayload.bunnyVideoId || null,@@ -1097,6 +1171,29 @@ const CloudRecorder = () => {return removed;};+ // Capture counters for the stuck-state report. Written to storage rather+ // than answered over messaging, which is the suspect part when the UI hangs.+ const liveProgressAt = useRef(0);+ const writeLiveProgress = () => {+ const ts = Date.now();+ if (ts - liveProgressAt.current < 2000) return;+ liveProgressAt.current = ts;+ const tracks = sessionTrackState.current || {};+ const total = (key) =>+ (tracks.screen?.[key] || 0) ++ (tracks.camera?.[key] || 0) ++ (tracks.audio?.[key] || 0);+ chrome.storage.local+ .set({+ recorderLiveProgress: {+ ts,+ chunks: total("chunkCount"),+ bytes: total("bytesRecorded"),+ },+ })+ .catch(() => {});+ };+const noteTrackChunk = (track, blob, extra = {}) => {if (!blob || !track || !sessionTrackState.current[track]) return;const current = sessionTrackState.current[track];@@ -1107,6 +1204,7 @@ const CloudRecorder = () => {lastChunkAt: Date.now(),...extra,};+ writeLiveProgress();};const patchTrackState = (track, extra = {}) => {@@ -1487,6 +1585,23 @@ const CloudRecorder = () => {const bindCameraTrack = (track) => {if (!track) return;try {+ // onmute only fires on a transition. A camera held by another app hands+ // back a live-but-muted track that delivers no frames and never fires it.+ if (track.muted === true || track.readyState !== "live") {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "cloudrecorder-camera-track-dead-at-bind",+ data: {+ label: track?.label || null,+ readyState: track?.readyState || null,+ muted: Boolean(track.muted),+ enabled: Boolean(track.enabled),+ ts: Date.now(),+ },+ });+ } catch {}+ }track.onended = () => {const diag = {reason: "camera-track-ended",@@ -2068,6 +2183,11 @@ const CloudRecorder = () => {return null;};+ // Mislabelling mp4 chunks as webm breaks decodeAudioData (and so the+ // silence check) plus the recovery download's extension.+ const audioBlobType = () =>+ trackContainers.audio === "audio/mp4" ? "audio/mp4" : "audio/webm";+const buildAudioBlobFromDurableStore = async () => {// Try IDB even if audioChunkStoreReadyRef is false: partial pre-degradation// data is more complete than the 8-chunk memory window.@@ -2086,7 +2206,7 @@ const CloudRecorder = () => {});return createBlobFromChunks(recovered.map((entry) => entry.chunk),- "audio/webm",+ audioBlobType(),);}console.info("[CloudRecorder] buildAudioBlobFromDurableStore: IDB empty, using memory", {@@ -2105,7 +2225,7 @@ const CloudRecorder = () => {error: err?.message || String(err),});}- return createBlobFromChunks(audioChunks.current, "audio/webm");+ return createBlobFromChunks(audioChunks.current, audioBlobType());};const getSessionStateKey = (sessionId) =>@@ -2490,6 +2610,230 @@ const CloudRecorder = () => {}, 5000);};+ // A paused uploader drops every chunk. The bytes still reach the durable store+ // for gap re-send, but the skip itself was silent.+ const pausedDropsRef = useRef({ screen: 0, camera: 0, audio: 0 });++ const notePausedDrop = (track, blob) => {+ const next = (pausedDropsRef.current[track] || 0) + 1;+ pausedDropsRef.current[track] = next;+ patchTrackState(track, { droppedWhilePaused: next });+ // First drop only: the rest ride track state and the finalize diag.+ if (next === 1) {+ console.warn(`[CloudRecorder] ${track} uploader paused, dropping chunks`);+ void emitUploadTelemetry("upload_chunks_dropped_while_paused", {+ trackType: track,+ reason: `paused-drop-${track}`,+ bytes: blob?.size || 0,+ });+ }+ };++ const resendUploadGap = async (track, uploaderRef, store, keyPrefix, rangesRef) => {+ const uploader = uploaderRef?.current;+ if (!uploader || !store || typeof uploader.getServerOffset !== "function") {+ return;+ }+ try {+ const serverOffset = await uploader.getServerOffset();+ if (serverOffset === null) return;+ const clientBytes = Number(uploader.totalBytes) || 0;+ const plan = planGapResend({+ ranges: rangesRef.current,+ serverOffset,+ clientBytes,+ });+ if (!plan.covered) {+ if (plan.gapBytes > 0) {+ console.warn(`[CloudRecorder] ${track} upload gap unrecoverable`, plan);+ void emitUploadTelemetry("upload_gap_unrecoverable", {+ trackType: track,+ gapBytes: plan.gapBytes,+ reason: `${plan.reason}-gap-${plan.gapBytes}`,+ serverOffset,+ clientBytes,+ });+ }+ return;+ }+ if (!uploader.prepareGapResend(serverOffset)) return;+ void emitUploadTelemetry("upload_gap_resend_started", {+ trackType: track,+ gapBytes: plan.gapBytes,+ chunks: plan.plan.length,+ serverOffset,+ clientBytes,+ });+ let sentBytes = 0;+ for (const step of plan.plan) {+ const entry = await store.getItem(`${keyPrefix}${step.index}`);+ if (!entry?.chunk) {+ // Stopping here is safe: everything sent so far was contiguous from+ // the server's offset, so the file is short, not holed.+ void emitUploadTelemetry("upload_gap_resend_incomplete", {+ trackType: track,+ missingIndex: step.index,+ sentBytes,+ gapBytes: plan.gapBytes,+ });+ break;+ }+ const blob =+ step.skipBytes > 0 ? entry.chunk.slice(step.skipBytes) : entry.chunk;+ await uploader.write(blob);+ sentBytes += step.sendBytes;+ }+ await uploader.waitForPendingUploads?.().catch(() => {});+ const afterOffset = await uploader.getServerOffset();+ void emitUploadTelemetry("upload_gap_resend_completed", {+ trackType: track,+ reason: `sent-${sentBytes}-of-${plan.gapBytes}`,+ gapBytes: plan.gapBytes,+ sentBytes,+ serverOffsetAfter: afterOffset,+ recovered: afterOffset !== null && afterOffset > serverOffset,+ });+ } catch (err) {+ console.warn(`[CloudRecorder] ${track} gap resend failed:`, err);+ void emitUploadTelemetry("upload_gap_resend_failed", {+ trackType: track,+ error: err?.message || String(err),+ });+ }+ };++ // A camera held by another app records nothing while screen keeps going, and+ // 4 chunk periods is long enough that a healthy camera has always delivered.+ const CAMERA_SILENCE_CHECK_MS = 8000;+ const cameraSilenceTimer = useRef(null);++ const scheduleCameraSilenceCheck = () => {+ if (cameraSilenceTimer.current) clearTimeout(cameraSilenceTimer.current);+ cameraSilenceTimer.current = setTimeout(() => {+ cameraSilenceTimer.current = null;+ try {+ if (isFinishing.current || sentLast.current) return;+ const cameraBytes =+ sessionTrackState.current.camera?.bytesRecorded || 0;+ if (cameraBytes > 0) return;+ const otherTrackRecording =+ (sessionTrackState.current.screen?.bytesRecorded || 0) > 0 ||+ (sessionTrackState.current.audio?.bytesRecorded || 0) > 0;+ if (!otherTrackRecording) return;+ const track = cameraStream.current?.getVideoTracks?.()[0] || null;+ const diag = {+ reason: "camera-silent-after-start",+ readyState: track?.readyState || null,+ muted: track ? Boolean(track.muted) : null,+ enabled: track ? Boolean(track.enabled) : null,+ label: track?.label || null,+ recorderState: cameraRecorder.current?.state || null,+ encoderKind: encoderKinds.camera || null,+ cameraDiag: cameraRecorder.current?.getDiagSnapshot?.() || null,+ };+ console.warn("🔴 Camera recorded nothing after start", diag);+ void emitUploadTelemetry("recording_camera_silent", {+ trackType: "camera",+ ...diag,+ });+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("cameraUnavailableToast"),+ });+ } catch (err) {+ console.warn("[CloudRecorder] camera silence check failed:", err);+ }+ }, CAMERA_SILENCE_CHECK_MS);+ };++ // The session-wide stall check below ORs the tracks together, so a healthy+ // screen masks a camera frozen at its first byte.+ const TRACK_STALL_MS = 30000;+ // mediabunny's fMP4 ftyp is 28 bytes and lands before any encoded packet, so+ // an offset this low means the muxer opened and no fragment ever closed.+ const INIT_ONLY_OFFSET = 64;++ // ts null, not 0: a falsy check would read a legitimate epoch-0 stamp as+ // "no baseline yet" and never flag the track.+ const trackStallState = useRef({+ screen: { offset: -1, ts: null, notified: false },+ camera: { offset: -1, ts: null, notified: false },+ audio: { offset: -1, ts: null, notified: false },+ });++ const uploaderFailureCounters = {+ screen: consecutiveScreenFailures,+ camera: consecutiveCameraFailures,+ audio: consecutiveAudioFailures,+ };++ const sweepStalledTracks = (now) => {+ const uploaders = {+ screen: screenUploader.current,+ camera: cameraUploader.current,+ audio: audioUploader.current,+ };+ const state = trackStallState.current;+ let anyAdvanced = false;++ for (const [track, uploader] of Object.entries(uploaders)) {+ const entry = state[track];+ if (!uploader) {+ entry.offset = -1;+ continue;+ }+ const offset = Number(uploader.offset) || 0;+ if (offset !== entry.offset) {+ entry.offset = offset;+ entry.ts = now;+ entry.notified = false;+ anyAdvanced = true;+ }+ }++ for (const [track, uploader] of Object.entries(uploaders)) {+ const entry = state[track];+ if (!uploader || entry.ts === null || entry.notified) continue;+ if (now - entry.ts <= TRACK_STALL_MS) continue;+ if (uploader.status === "completed" || uploader.status === "aborted") {+ continue;+ }+ entry.notified = true;+ // The signature from the churned-user report: one track pinned at its+ // init segment while another uploads normally.+ const stuckAtInit = entry.offset > 0 && entry.offset <= INIT_ONLY_OFFSET;+ void emitUploadTelemetry("upload_track_stalled", {+ trackType: track,+ // The mapping reads `offset`, not `offsetBytes`.+ offset: entry.offset,+ reason: `${stuckAtInit ? "stuck-at-init" : "stalled"}-${track}${+ anyAdvanced ? "-sibling-progressing" : ""+ }`,+ totalBytes: Number(uploader.totalBytes) || 0,+ queuedBytes: Number(uploader.queuedBytes) || 0,+ stallMs: now - entry.ts,+ stuckAtInit,+ siblingProgressing: anyAdvanced,+ uploaderStatus: uploader.status || null,+ errorCode: uploader.lastErrorCode || null,+ isPaused: Boolean(uploader.isPaused),+ });+ // Same action the online handler takes. resume() restarts processQueue+ // and, on a recoverable error, the heartbeat that HEAD-resyncs.+ if (RESUMABLE_UPLOADER_STATUSES.has(uploader.status)) {+ try {+ uploader.resume();+ } catch (err) {+ console.warn(`[CloudRecorder] resume ${track} after stall failed:`, err);+ }+ // Without this the write path re-pauses on the next single failure,+ // and every later chunk is dropped at the isPaused check.+ const counter = uploaderFailureCounters[track];+ if (counter) counter.current = 0;+ }+ }+ };+const startUploadHeartbeat = () => {if (uploadHeartbeatTimer.current)clearInterval(uploadHeartbeatTimer.current);@@ -2497,6 +2841,7 @@ const CloudRecorder = () => {const now = Date.now();const screenOffset = screenUploader.current?.offset || 0;const cameraOffset = cameraUploader.current?.offset || 0;+ sweepStalledTracks(now);const { screen, camera, ts } = lastUploadProgress.current;if (screenOffset !== screen || cameraOffset !== camera) {@@ -2543,6 +2888,10 @@ const CloudRecorder = () => {if (uploadHeartbeatTimer.current)clearInterval(uploadHeartbeatTimer.current);if (screenTrackMonitor.current) clearInterval(screenTrackMonitor.current);+ if (cameraSilenceTimer.current) {+ clearTimeout(cameraSilenceTimer.current);+ cameraSilenceTimer.current = null;+ }sessionHeartbeat.current = null;chunkStallTimer.current = null;uploadHeartbeatTimer.current = null;@@ -2658,6 +3007,7 @@ const CloudRecorder = () => {const exportLocalRecovery = async (reason = "upload failed") => {try {let blob = null;+ let fromMemoryWindow = false;const recovered = [];await chunksStore.iterate((value) => {recovered.push(value);@@ -2673,19 +3023,39 @@ const CloudRecorder = () => {blob =createBlobFromChunks(screenChunks.current, "video/webm") ||createBlobFromChunks(cameraChunks.current, "video/webm");+ fromMemoryWindow = Boolean(blob);}if (!blob) return;+ // Purge drops Bunny-confirmed chunks mid-recording and the memory window+ // holds only the last 8, so either source can be missing the middle.+ const partial =+ fromMemoryWindow || chunksPurgedDuringRecordingRef.current === true;const objectUrl = URL.createObjectURL(blob);try {await chrome.downloads.download({url: objectUrl,- filename: `Screenity-Recovery-${new Date().toISOString()}-${reason}.webm`,+ filename: `Screenity-${+ partial ? "Partial" : "Recovery"+ }-${new Date().toISOString()}-${reason}.webm`,saveAs: false,});chrome.runtime.sendMessage({type: "show-toast",message: "Upload stalled. A recovery file was saved locally.",});+ // reason carries the partial flag because the server sanitizer keeps+ // it. The booleans below need allowlisting before they show up.+ void emitUploadTelemetry("upload_local_backup_degraded", {+ backupType: "recovery-export",+ reason: partial+ ? `recovery-export-partial-${reason}`+ : `recovery-export-${reason}`,+ partial,+ fromMemoryWindow,+ chunkCount: recovered.length,+ purgedScreenChunks: screenChunksPurgedCountRef.current,+ purgedBytes: chunksPurgedBytesRef.current,+ });} finally {URL.revokeObjectURL(objectUrl);}@@ -3601,7 +3971,9 @@ const CloudRecorder = () => {const [screenPlan, cameraPlan, audioPlan] = await Promise.all([inspectTrackPlan({ track: "screen", probeOptions }),inspectTrackPlan({ track: "camera", probeOptions }),- inspectTrackPlan({ track: "audio" }),+ // Same stream the audio recorder gets, so the container reported to TUS+ // survives an MP4 start() that throws.+ inspectTrackPlan({ track: "audio", stream: rawMicStream.current }),]);encoderKinds.screen = screenPlan.kind;encoderKinds.camera = cameraPlan.kind;@@ -3711,6 +4083,7 @@ const CloudRecorder = () => {if (screenStream.current) {screenUploader.current = new BunnyTusUploader({+ clientSessionId: getClientSessionId(),sessionId,trackType: "screen",container: trackContainers.screen,@@ -3776,6 +4149,7 @@ const CloudRecorder = () => {if (cameraStream.current) {cameraUploader.current = new BunnyTusUploader({+ clientSessionId: getClientSessionId(),sessionId,trackType: "camera",container: trackContainers.camera,@@ -3836,6 +4210,7 @@ const CloudRecorder = () => {// without an audio track if init fails (mic supplementary).try {audioUploader.current = new BunnyTusUploader({+ clientSessionId: getClientSessionId(),sessionId,trackType: "audio",container: trackContainers.audio,@@ -3965,7 +4340,8 @@ const CloudRecorder = () => {const pickEncodingFallback = (currentMime, trackKind) => {const m = String(currentMime || "").toLowerCase();if (trackKind === "audio" || m.startsWith("audio/")) {- // Opus-in-webm is the floor for audio; nothing safer to fall to.+ // No safer audio container to fall to: webm and mp4 are both floors,+ // and swapping either mislabels the bytes already uploaded.return null;}// Don't fall from MP4 to WebM: the container was already sent as the TUS@@ -3988,14 +4364,18 @@ const CloudRecorder = () => {typeof MediaRecorder.isTypeSupported === "function" &&!MediaRecorder.isTypeSupported(requested)) {- const candidates = [- "video/webm;codecs=vp9,opus",- "video/webm;codecs=vp8,opus",- "video/webm;codecs=h264,opus",- "video/webm;codecs=avc1,opus",- "video/webm",- requested.startsWith("audio/") ? "audio/webm" : null,- ].filter(Boolean);+ // Audio-only streams get audio candidates only: video/webm can't mux a+ // stream with no video track.+ const candidates =+ trackKind === "audio" || requested.startsWith("audio/")+ ? ["audio/webm;codecs=opus", "audio/webm"]+ : [+ "video/webm;codecs=vp9,opus",+ "video/webm;codecs=vp8,opus",+ "video/webm;codecs=h264,opus",+ "video/webm;codecs=avc1,opus",+ "video/webm",+ ];const fallback = candidates.find((m) =>MediaRecorder.isTypeSupported(m),);@@ -4306,6 +4686,7 @@ const CloudRecorder = () => {index.current = 0;screenChunkByteRangesRef.current = [];cameraChunkByteRangesRef.current = [];+ audioChunkByteRangesRef.current = [];chunksPurgedDuringRecordingRef.current = false;screenChunksPurgedCountRef.current = 0;cameraChunksPurgedCountRef.current = 0;@@ -4349,6 +4730,103 @@ const CloudRecorder = () => {return;}+ // Runs once a track captures, not per track: declaring the session live is+ // what gives the content UI its toolbar and Stop button.+ let setupTrack = null;+ let liveDeclared = false;+ let liveDeclaring = false;+ const declareRecordingLive = async () => {+ // The first-chunk backstop can land mid-declare. Re-entering would+ // install a second timer interval over the first.+ if (liveDeclared || liveDeclaring) return;+ liveDeclaring = true;+ try {+ let warned = false;+ const MAX_DURATION =+ parseFloat(process.env.MAX_RECORDING_DURATION) || 60 * 60;+ const WARNING_THRESHOLD =+ parseFloat(process.env.RECORDING_WARNING_THRESHOLD) || 60;++ if (screenTimer.current.notificationInterval)+ clearInterval(screenTimer.current.notificationInterval);++ // Seed before the interval runs. Remaining track setup can outlast a+ // tick, and a back-to-back session would otherwise read the old timer.+ const declaredAt = Date.now();+ if (screenStream.current) {+ screenTimer.current.start = declaredAt;+ screenTimer.current.paused = false;+ screenTimer.current.total = 0;+ }+ if (cameraStream.current) {+ cameraTimer.current.start = declaredAt;+ cameraTimer.current.paused = false;+ cameraTimer.current.total = 0;+ }++ const timerInterval = setInterval(() => {+ if (!screenStream.current && !cameraStream.current) {+ clearInterval(timerInterval);+ cleanupTimers();+ console.warn("Recording stopped, clearing timer");+ return;+ }++ const elapsed = getActiveVideoTime() / 1000;+ const remaining = MAX_DURATION - elapsed;++ if (!warned && remaining <= WARNING_THRESHOLD) {+ warned = true;+ chrome.runtime.sendMessage({+ type: "time-warning",+ });+ }++ if (remaining <= 0) {+ clearInterval(timerInterval);+ chrome.runtime.sendMessage({+ type: "time-stopped",+ });+ sendStopRecording("max-duration");+ }+ }, 1000);++ screenTimer.current.notificationInterval = timerInterval;+ screenTimer.current.warned = warned;++ const recordingStartTime = Date.now();+ await setRecordingTimingState({+ recording: true,+ paused: false,+ recordingStartTime,+ pausedAt: null,+ totalPausedMs: 0,+ });+ liveDeclared = true;+ pausedStateRef.current = false;+ persistSessionState({ status: "recording" });+ startSessionHeartbeat();+ setStarted(true);+ await setPipelineState("recording", {+ projectId,+ sceneId:+ screenUploader.current?.getMeta()?.sceneId ||+ cameraUploader.current?.getMeta()?.sceneId ||+ null,+ });+ logDebugEvent("recording-started", {+ projectId,+ sceneId:+ screenUploader.current?.getMeta()?.sceneId ||+ cameraUploader.current?.getMeta()?.sceneId ||+ null,+ });+ } finally {+ // Left false on a throw so the first-chunk backstop can retry.+ liveDeclaring = false;+ }+ };+try {logStartFlow("recording_start", {recordingType: recordingType.current,@@ -4357,6 +4835,7 @@ const CloudRecorder = () => {hasMic: Boolean(micStream.current),});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@@ -4420,6 +4899,9 @@ const CloudRecorder = () => {syncActualVideoCodec("screen", screenRecorder.current);if (!hasChunks.current) {hasChunks.current = true;+ // Bytes on disk are proof the session is live. Recovers the UI+ // if the declare above was skipped or its storage write failed.+ declareRecordingLive().catch(() => {});lastTimecode.current = timestamp;firstChunkTime.current = timestamp;chrome.runtime@@ -4443,10 +4925,15 @@ const CloudRecorder = () => {.set({ lastChunkAt: Date.now() }).catch(() => {});+ // Claim the slot up front, like camera and audio do. Incrementing+ // at the end let the paused-drop return overwrite the last chunk.+ const chunkIndex = index.current;+ index.current++;+const writeStartedAt = performance.now();await chunksStore- .setItem(`chunk_${index.current}`, {- index: index.current,+ .setItem(`chunk_${chunkIndex}`, {+ index: chunkIndex,chunk: blob,timestamp,})@@ -4466,16 +4953,19 @@ const CloudRecorder = () => {if (writeMs >= 1000) writeStats.slowCount += 1;patchTrackState("screen", {- durableChunkCount: index.current + 1,- lastPersistedChunkIndex: index.current,+ durableChunkCount: chunkIndex + 1,+ lastPersistedChunkIndex: chunkIndex,lastPersistedAt: timestamp,});- persistSessionState({ lastChunkIndex: index.current });+ persistSessionState({ lastChunkIndex: chunkIndex });if (uploadersInitialized.current && screenUploader.current) {try {- if (screenUploader.current?.isPaused) return;+ if (screenUploader.current?.isPaused) {+ notePausedDrop("screen", blob);+ return;+ }if (screenUploader.current.queuedBytes > 15 * 1024 * 1024) {await screenUploader.current.waitForPendingUploads?.()@@ -4486,14 +4976,14 @@ const CloudRecorder = () => {const endByte =Number(screenUploader.current?.totalBytes) || 0;screenChunkByteRangesRef.current.push({- index: index.current,+ index: chunkIndex,endByte,size: blob?.size || 0,});screenRetainedPrefixRef.current = extendRetainedPrefix(screenRetainedPrefixRef.current,{- index: index.current,+ index: chunkIndex,endByte,budgetBytes: currentPrefixBudget(),},@@ -4517,8 +5007,6 @@ const CloudRecorder = () => {}}}-- index.current++;},probeOptions: {screenWidth: Number(screenSettings.width) || 1920,@@ -4530,8 +5018,12 @@ const CloudRecorder = () => {// Only WebCodecsTrackRecorder disposes the prewarm. On the// MediaRecorder fallback nothing would, leaving a configured hardware// encoder held for the whole recording (the prewarm no longer- // self-closes after 6 frames).- if (screenSelection.kind !== "webcodecs") {+ // self-closes after 6 frames). WebM is the same story: the warm+ // encoder is H.264, so that path declines to adopt it.+ if (+ screenSelection.kind !== "webcodecs" ||+ screenSelection.containerKind === "webm"+ ) {closeActiveEncoderPrewarm().catch(() => {});}encoderKinds.screen = screenSelection.kind;@@ -4557,10 +5049,15 @@ const CloudRecorder = () => {if (screenTrack) {bindScreenTrack(screenTrack);}++ // Declaring here means a mic or camera failure below can't strand a+ // live recording with no way to stop it.+ await declareRecordingLive();}// Audio recorder for transcription. webm > wav for browser support.if (rawMicStream.current?.getAudioTracks?.().length) {+ setupTrack = "audio";const audioOptions = {mimeType: "audio/webm",audioBitsPerSecond: 128000,@@ -4587,9 +5084,11 @@ const CloudRecorder = () => {(sessionTrackState.current.audio?.droppedInMemoryChunks || 0) +droppedAudio,});+ let audioPersistedIndex = null;if (audioChunkStoreReadyRef.current) {const audioChunkIndex = audioChunkIndexRef.current;audioChunkIndexRef.current += 1;+ audioPersistedIndex = audioChunkIndex;try {await audioChunksStore.setItem(`audio_chunk_${audioChunkIndex}`, {index: audioChunkIndex,@@ -4641,7 +5140,10 @@ const CloudRecorder = () => {}if (uploadersInitialized.current && audioUploader.current) {try {- if (audioUploader.current?.isPaused) return;+ if (audioUploader.current?.isPaused) {+ notePausedDrop("audio", blob);+ return;+ }if (audioUploader.current.queuedBytes > 5 * 1024 * 1024) {await audioUploader.current.waitForPendingUploads?.()@@ -4649,6 +5151,15 @@ const CloudRecorder = () => {}await audioUploader.current.write(blob);consecutiveAudioFailures.current = 0;+ // Byte ranges so a finalize-time gap can be re-sent from the+ // durable store.+ if (audioPersistedIndex !== null) {+ audioChunkByteRangesRef.current.push({+ index: audioPersistedIndex,+ endByte: Number(audioUploader.current?.totalBytes) || 0,+ size: blob?.size || 0,+ });+ }} catch (uploadErr) {console.warn("Failed to upload audio chunk to Bunny:", uploadErr);consecutiveAudioFailures.current++;@@ -4681,6 +5192,7 @@ const CloudRecorder = () => {}if (cameraStream.current) {+ setupTrack = "camera";let streamToRecord = cameraStream.current;// Camera-only carries the mic in-stream; screen+camera routes audio@@ -4787,7 +5299,10 @@ const CloudRecorder = () => {if (uploadersInitialized.current && cameraUploader.current) {try {- if (cameraUploader.current?.isPaused) return;+ if (cameraUploader.current?.isPaused) {+ notePausedDrop("camera", blob);+ return;+ }await cameraUploader.current.write(blob);consecutiveCameraFailures.current = 0;if (cameraPersistedIndex !== null) {@@ -4837,75 +5352,35 @@ const CloudRecorder = () => {});cameraRecorder.current.start(2000);+ scheduleCameraSilenceCheck();}- let warned = false;- const MAX_DURATION =- parseFloat(process.env.MAX_RECORDING_DURATION) || 60 * 60;- const WARNING_THRESHOLD =- parseFloat(process.env.RECORDING_WARNING_THRESHOLD) || 60;-- if (screenTimer.current.notificationInterval)- clearInterval(screenTimer.current.notificationInterval);-- const timerInterval = setInterval(() => {- if (!screenStream.current && !cameraStream.current) {- clearInterval(timerInterval);- cleanupTimers();- console.warn("Recording stopped, clearing timer");- return;- }-- const elapsed = getActiveVideoTime() / 1000;- const remaining = MAX_DURATION - elapsed;-- if (!warned && remaining <= WARNING_THRESHOLD) {- warned = true;- chrome.runtime.sendMessage({- type: "time-warning",- });- }-- if (remaining <= 0) {- clearInterval(timerInterval);- chrome.runtime.sendMessage({- type: "time-stopped",- });- sendStopRecording("max-duration");- }- }, 1000);-- screenTimer.current.notificationInterval = timerInterval;- screenTimer.current.warned = warned;-- const recordingStartTime = Date.now();- await setRecordingTimingState({- recording: true,- paused: false,- recordingStartTime,- pausedAt: null,- totalPausedMs: 0,- });- pausedStateRef.current = false;- persistSessionState({ status: "recording" });- startSessionHeartbeat();- setStarted(true);- await setPipelineState("recording", {- projectId,- sceneId:- screenUploader.current?.getMeta()?.sceneId ||- cameraUploader.current?.getMeta()?.sceneId ||- null,- });- logDebugEvent("recording-started", {- projectId,- sceneId:- screenUploader.current?.getMeta()?.sceneId ||- cameraUploader.current?.getMeta()?.sceneId ||- null,- });+ // Camera-only never enters the screen branch, so this is where it goes+ // live.+ await declareRecordingLive();} catch (err) {- sendRecordingError("Recording failed: " + err.message);+ const errMsg = String(err?.message || err).slice(0, 200);+ if (liveDeclared) {+ // A secondary track failed with capture already live. Tearing the+ // session down here is what orphaned recordings with no Stop button.+ console.error(+ "[Screenity][CloudRecorder] track setup failed after recording went live",+ err,+ );+ logStartFlow("track_setup_failed_after_live", {+ track: setupTrack,+ errMsg,+ });+ // Field names are the server's existing allowlist, so nothing new has+ // to be wired to keep the values.+ void emitUploadTelemetry("recording_track_setup_failed_after_live", {+ trackType: setupTrack,+ reason: "track-setup-failed-after-live",+ errMsg,+ });+ } else {+ sendRecordingError("Recording failed: " + err.message);+ }}const now = Date.now();@@ -5037,9 +5512,15 @@ const CloudRecorder = () => {return duration;};+ const screen = getDuration(screenTimer.current);+ const camera = getDuration(cameraTimer.current);+return {- screen: getDuration(screenTimer.current),- camera: getDuration(cameraTimer.current),+ 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),fallbackMs:firstChunkTime.current && lastTimecode.current? Math.max(0, lastTimecode.current - firstChunkTime.current)@@ -5274,13 +5755,6 @@ const CloudRecorder = () => {});};- const RESUMABLE_UPLOADER_STATUSES = new Set([- "uploading",- "paused",- "error",- "ready",- ]);-const onOnline = () => {networkStateRef.current = {online: true,@@ -5916,6 +6390,9 @@ const CloudRecorder = () => {pausedAt: null,totalPausedMs: 0,});+ // `recording` is false from here but the uploaders still hold the video.+ // Also the resume guard's clock, last stamped when recording started.+ await setPipelineState("finalizing", { details: reason });const { sceneId } = await chrome.storage.local.get(["sceneId"]);const uploadMeta = {@@ -5955,6 +6432,8 @@ const CloudRecorder = () => {await clearAudioChunkStore("cancelled-stop");await clearCameraChunkStore("cancelled-stop");await clearLocalScreenPlaybackOffer("cancelled-stop");+ // Releases the resume guard: nothing here is going to be finalized.+ await setPipelineState("cancelled", { details: reason });return;}@@ -5981,6 +6460,19 @@ const CloudRecorder = () => {uploaderType: "cloud_recorder",});}+ // Close any server/client byte gap before declaring a length. A track whose+ // PATCHes 2xx'd without landing still has its bytes on disk.+ if (GAP_RESEND_ENABLED) {+ await Promise.race([+ Promise.allSettled([+ resendUploadGap("screen", screenUploader, chunksStore, "chunk_", screenChunkByteRangesRef),+ resendUploadGap("camera", cameraUploader, cameraChunksStore, "camera_chunk_", cameraChunkByteRangesRef),+ resendUploadGap("audio", audioUploader, audioChunksStore, "audio_chunk_", audioChunkByteRangesRef),+ ]),+ new Promise((r) => setTimeout(r, GAP_RESEND_BUDGET_MS)),+ ]);+ }+const finalizeCalls = [screenUploader.current?.finalize?.(),cameraUploader.current?.finalize?.(),@@ -6129,9 +6621,16 @@ const CloudRecorder = () => {? fallbackSeconds: cameraDuration;+ const audioDuration = durations.audio || 0;+ const effectiveAudioDuration =+ audioDuration < MIN_DURATION_SECONDS && fallbackSeconds > 0+ ? fallbackSeconds+ : audioDuration;+const usedDurations = {screen: effectiveScreenDuration || screenDuration,camera: effectiveCameraDuration || cameraDuration,+ audio: effectiveAudioDuration || audioDuration,};if (hasValidScreen && effectiveScreenDuration > 5) {const screenOffset = uploadMeta.screen?.offset || 0;@@ -6391,9 +6890,10 @@ const CloudRecorder = () => {const isUserCaptureCancel = (err) => {const name = err?.name || "";const message = (err?.message || "").toLowerCase();+ // AbortError is NOT a cancel: the spec uses it for "failed to start capture+ // for a reason other than denial", which we were swallowing as cancel-modal.return (name === "NotAllowedError" ||- name === "AbortError" ||message.includes("cancel") ||message.includes("permission denied"));@@ -6419,6 +6919,9 @@ const CloudRecorder = () => {const canCaptureSourceAudio =streamOpts.canRequestAudioTrack !== false;const useDisplayMedia = !!streamOpts.useDisplayMedia;+ // How long the picker was up before a failure. Separates an instant reject+ // from one that lands after the user picked.+ const streamStartedAt = Date.now();// Only the screen branch supersamples; clear it so a later take can't// inherit a previous recording's value.captureCapRef.current = null;@@ -6767,6 +7270,19 @@ const CloudRecorder = () => {},}).catch(() => {});+ chrome.storage.local+ .set({+ lastStreamAcquireError: {+ ts: Date.now(),+ name: "no-stream-id",+ message: "gUM path reached with no streamId",+ api: "getUserMedia",+ isTab: !!isTab.current,+ offscreen: IS_OFFSCREEN_HOST,+ recordingType: recordingType.current || null,+ },+ })+ .catch(() => {});sendRecordingError(chrome.i18n.getMessage("screenStreamUnavailableError"),);@@ -6952,6 +7468,22 @@ const CloudRecorder = () => {stack: err?.stack || null,},}).catch(() => {});+ // offscreen-diag is DEBUG_FLOW-gated and console-only, so the reason a+ // start died was unrecoverable from a user's zip.+ chrome.storage.local+ .set({+ lastStreamAcquireError: {+ ts: Date.now(),+ name: err?.name || null,+ message: String(err?.message || "").slice(0, 200),+ api: useDisplayMedia ? "getDisplayMedia" : "getUserMedia",+ isTab: !!isTab.current,+ offscreen: IS_OFFSCREEN_HOST,+ recordingType: recordingType.current || null,+ pickerOpenMs: Date.now() - streamStartedAt,+ },+ })+ .catch(() => {});// Offscreen tab-mode: pre-acquired streamId failed; retry with getDisplayMedia.// NotReadableError ("device busy", e.g. Zoom/OBS or HW slot// contention) is worth a retry, same as Abort/NotAllowed.@@ -7001,7 +7533,9 @@ const CloudRecorder = () => {} else if (isUserCaptureCancel(err)) {stopCameraStreamIfAlive();sendRecordingError(- `User cancelled stream selection [tab-streamId-consume ${err?.name || "?"}]`,+ `User cancelled stream selection [${+ useDisplayMedia ? "gDM" : "tab-streamId-consume"+ } ${err?.name || "?"}]`,true,);return;@@ -7279,6 +7813,9 @@ const CloudRecorder = () => {}await chrome.storage.local.set({ projectId: videoId });+ // Fresh projects already carry hasRecordingSession, so only+ // reused ones need the hint.+ if (reusedProject) notifyRecordingStarted(videoId);traceStep("apiProjectCreated", {projectCreateMs,projectReused: reusedProject,@@ -7427,6 +7964,19 @@ const CloudRecorder = () => {payload: { branch },}).catch(() => {});+ // offscreen-diag is console-only, so which branch a failed start took+ // was unrecoverable from a zip.+ chrome.storage.local+ .set({+ lastStartDispatchBranch: {+ branch,+ ts: Date.now(),+ recordingType: data?.recordingType || null,+ isTab: !!isTab.current,+ offscreen: IS_OFFSCREEN_HOST,+ },+ })+ .catch(() => {});};if (data.recordingType === "camera") {_diagBranch("camera");@@ -7568,15 +8118,62 @@ const CloudRecorder = () => {: timer.current.total + (now - timer.current.start);}+ // Idempotent: the pull response and the push race each other by design.+ const consumeStreamingData = (dataStr) => {+ if (!dataStr) return;+ if (streamingDataReceivedAt.current != null) return;+ streamingDataReceivedAt.current = Date.now();+ startStreaming(JSON.parse(dataStr));+ };++ // Mirrors Recorder.jsx's requestStreamingDataWithRetry, which the cloud path+ // never got. BG answers the pull directly, so no push has to land in time.+ const pullStreamingData = (attempt = 0) => {+ if (streamingDataReceivedAt.current != null) return;+ const backoffMs = [0, 250, 500, 1000, 2000, 3000];+ const delay = backoffMs[Math.min(attempt, backoffMs.length - 1)];+ if (streamingDataRetryTimer.current) {+ clearTimeout(streamingDataRetryTimer.current);+ }+ streamingDataRetryTimer.current = setTimeout(() => {+ streamingDataRetryTimer.current = null;+ if (streamingDataReceivedAt.current != null) return;+ const retryIfNeeded = () => {+ if (+ streamingDataReceivedAt.current == null &&+ attempt + 1 < backoffMs.length+ ) {+ pullStreamingData(attempt + 1);+ }+ };+ try {+ chrome.runtime.sendMessage(+ { type: "get-streaming-data" },+ (response) => {+ if (chrome.runtime.lastError) return retryIfNeeded();+ if (response?.data) return consumeStreamingData(response.data);+ retryIfNeeded();+ },+ );+ } catch {+ retryIfNeeded();+ }+ }, delay);+ };+const onMessage = useCallback((request, sender, sendResponse) => {if (request.type === "loaded") {// BG redelivers `loaded` after an SW restart. Skip re-init if it// already ran: re-calling getStreamID would invalidate the active// tabCapture token (single-use). Just re-pull streaming-data.if (isInit.current) {- chrome.runtime.sendMessage({ type: "get-streaming-data" });+ pullStreamingData();+ // BG retries `loaded` until something confirms. Without this it can+ // only see the port close, which any extension context produces.+ sendResponse?.({ ok: true, alreadyInit: true });return;}+ sendResponse?.({ ok: true });setInitProject(false);// offscreen has no visible Warning; surface system-audio guidance as a toastif (IS_OFFSCREEN_HOST && !request.isTab) {@@ -7586,7 +8183,7 @@ const CloudRecorder = () => {// Skip payloads targeted at offscreen; otherwise both contexts race for the stream.if (request.region && request._targetHost !== "offscreen") {isInit.current = true;- chrome.runtime.sendMessage({ type: "get-streaming-data" });+ pullStreamingData();}} else if (!request.region || (IS_OFFSCREEN_HOST && request.isTab)) {// Apply tabPreferred synchronously: chrome.storage.local.get races against@@ -7611,7 +8208,7 @@ const CloudRecorder = () => {isTab.current = false;}isInit.current = true;- chrome.runtime.sendMessage({ type: "get-streaming-data" });+ pullStreamingData();}} else if (request.type === "streaming-data") {if (!isInit.current) return;@@ -7623,9 +8220,9 @@ const CloudRecorder = () => {(!IS_IFRAME_CONTEXT &&(!regionRef.current || (IS_OFFSCREEN_HOST && isTab.current)));if (!willHandle) return;- if (streamingDataReceivedAt.current != null) return;- streamingDataReceivedAt.current = Date.now();- startStreaming(JSON.parse(request.data));+ // Same as `loaded`: BG's push retries until the recorder confirms.+ sendResponse?.({ ok: true });+ consumeStreamingData(request.data);} else if (request.type === "start-recording-tab") {if (!isInit.current) return;diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.jsindex 25e7b7d..ae4cdd0 100644--- a/src/pages/CloudRecorder/bunnyTusUploader.js+++ b/src/pages/CloudRecorder/bunnyTusUploader.js@@ -94,6 +94,9 @@ export default class BunnyTusUploader {constructor(options = {}) {this.CHUNK_SIZE = options.chunkSize || 512 * 1024;this.MAX_RETRIES = options.maxRetries || 5;+ // Short writes make real progress, so they get their own budget instead of+ // the retry one. One pass per KB of a default chunk, a backstop not a limit.+ this.MAX_SHORT_WRITE_PASSES = options.maxShortWritePasses || 512;this.RETRY_DELAY = options.retryDelay || 1000;this.UPLOAD_TIMEOUT_MS = options.uploadTimeoutMs || 20000;this.HEARTBEAT_INTERVAL_MS = options.heartbeatIntervalMs || 10000;@@ -105,6 +108,9 @@ export default class BunnyTusUploader {this.onTelemetry = options.onTelemetry || null;this.onStateChange = options.onStateChange || null;this.trackType = options.trackType || null;+ // Passed by callers, not derived here: one id per host (page load), so a+ // second uploader attaching to the same video is visible in telemetry.+ this.clientSessionId = options.clientSessionId || null;// Container declared in TUS Upload-Metadata. Defaults to webm for// back-compat with pre-WebCodecs callers; cloud's WebCodecs path// overrides to "video/mp4" for screen + camera tracks. Audio always@@ -162,6 +168,13 @@ export default class BunnyTusUploader {this.finalizedAt = null;this.resumeCount = 0;this.lastServerOffset = 0;+ // Consecutive PATCHes that returned 2xx while the server offset stood still.+ this.noServerProgressCount = 0;+ this._warnedMissingOffsetHeader = false;+ // Consecutive HEADs showing the server behind the client and not catching up.+ this._offsetDivergenceCount = 0;+ this._lastDivergence = 0;+ this._reconcileTickCount = 0;this.hasEmittedClientStarted = false;this.hasEmittedFirstByte = false;this.lastProgressEventAt = 0;@@ -204,6 +217,7 @@ export default class BunnyTusUploader {codec: this.codec || null,container: this.container || null,encoderKind: this.encoderKind || null,+ clientSessionId: this.clientSessionId || null,...payload,};this.onTelemetry(event, body);@@ -624,10 +638,94 @@ export default class BunnyTusUploader {return null;}+ // Rewinds local accounting to server truth, else write() trips the+ // server-offset-regressed guard on the first re-sent PATCH.+ prepareGapResend(serverOffset) {+ if (!Number.isFinite(serverOffset) || serverOffset < 0) return false;+ if (this.isFinalizing) return false;+ this.chunkQueue = [];+ this.queuedBytes = 0;+ this.offset = serverOffset;+ this.lastServerOffset = serverOffset;+ // write() adds the re-sent bytes back on top.+ this.totalBytes = serverOffset;+ this.noServerProgressCount = 0;+ this._offsetDivergenceCount = 0;+ this._lastDivergence = 0;+ this.error = null;+ this.lastErrorCode = null;+ this.stalled = false;+ this.isPaused = false;+ this.status = "uploading";+ this.emitTelemetry("upload_gap_resend_prepared", { serverOffset });+ return true;+ }++ // A HEAD is the only authority on what Bunny holds: a PATCH can 2xx without+ // applying, and a missing Upload-Offset leaves the client on local math.+ async reconcileServerOffset(reason) {+ if (!this.uploadUrl || this.isFinalizing || this.isPaused) return;+ if (+ this.status === "completed" ||+ this.status === "aborted" ||+ this.status === "error"+ ) {+ return;+ }+ // Mid-PATCH the server legitimately trails. Reading now invents divergence.+ if (this.currentPatchAbort) return;+ const serverOffset = await this.getServerOffset();+ // Unreadable is not evidence of divergence.+ if (serverOffset === null) return;++ if (serverOffset >= this.offset) {+ this._offsetDivergenceCount = 0;+ this._lastDivergence = 0;+ // Server-derived, so purge can trust it even when PATCH responses can't.+ this.lastServerOffset = serverOffset;+ return;+ }++ const divergence = this.offset - serverOffset;+ // One in-flight chunk plus a chunk of eventual-consistency lag.+ if (divergence <= this.CHUNK_SIZE * 2) {+ this._lastDivergence = divergence;+ return;+ }+ const catchingUp =+ this._lastDivergence > 0 && divergence < this._lastDivergence;+ this._lastDivergence = divergence;+ if (catchingUp) {+ this._offsetDivergenceCount = 0;+ return;+ }++ this._offsetDivergenceCount += 1;+ this.emitTelemetry("upload_server_offset_behind", {+ reason: `offset-behind-${divergence}-conf-${this._offsetDivergenceCount}-${+ reason || "unknown"+ }`,+ clientOffset: this.offset,+ serverOffset,+ divergence,+ confirmations: this._offsetDivergenceCount,+ });+ if (this._offsetDivergenceCount >= 2) {+ // Deliberately not rewriting this.offset down: PATCHing from the server's+ // offset would skip the missing bytes and mux a hole into the file.+ this.setUploaderError("server-offset-behind-client", {+ clientOffset: this.offset,+ serverOffset,+ divergence,+ });+ }+ }+async getServerOffset() {if (!this.uploadUrl) return null;try {const headRes = await fetch(this.uploadUrl, {+ redirect: "error",method: "HEAD",headers: {"Tus-Resumable": "1.0.0",@@ -1157,6 +1255,17 @@ export default class BunnyTusUploader {const now = Math.floor(Date.now() / 1000);if (this.expires - now < this.TOKEN_REFRESH_THRESHOLD) {await this.refreshTusAuth();+ // Re-signing mid-upload is off-contract for Bunny, and the camera that+ // went silent had re-signed first. 6h TTL, so firing at all is the signal.+ this.emitTelemetry("upload_auth_refreshed_midupload", {+ reason: "auth-refresh-expiry",+ trigger: "expiry",+ offset: this.offset,+ expires: this.expires || null,+ });+ setTimeout(() => {+ this.reconcileServerOffset("post-auth-refresh").catch(() => {});+ }, 3000);if (this.isProcessingQueue) {this.pause();@@ -1165,22 +1274,32 @@ export default class BunnyTusUploader {}}async uploadChunk(chunk) {+ // Bytes the server already took, so processQueue re-queues only the tail.+ // Cleared first: arrayBuffer() can reject and a stale count slices wrong.+ this._chunkConsumedBytes = 0;// processQueue already shifted this chunk off the queue, so bailing here// drops it for good. Finalize's drain is exactly when the queue still// holds bytes we are about to declare.if (this.isFinalizing && !this.isDrainingForFinalize) return;- let data = new Uint8Array(await chunk.arrayBuffer());+ // Kept whole so a resync can re-slice from the chunk's true start. Trimming+ // the trimmed view is what dropped bytes a short write had already skipped.+ const fullData = new Uint8Array(await chunk.arrayBuffer());+ let data = fullData;const chunkStartOffset = this.offset;// One-shot 401 refresh per chunk. Re-armed each chunk so a token// expiring across many chunks keeps recovering.let didAuth401Refresh = false;+ let shortWritePasses = 0;+ let exhaustedReason = "chunk-upload-loop-exhausted";+ try {for (let attempt = 0; attempt <= this.MAX_RETRIES; attempt++) {// Hoisted so the catch can read signal.reason (wake-jump/stall-recovery/// upload-timeout) for telemetry; in-try it would be out of scope.let controller = null;try {- // AuthorizationSignature has ~20min TTL; refresh before every PATCH.+ // Signature TTL is 6h (generateBunnyUploadSignature), so this no-ops+ // until 5h55m in. Session lifetime binds to the creation expiry.await this.checkAuthExpiration();const currentOffset = this.offset;@@ -1194,6 +1313,9 @@ export default class BunnyTusUploader {);const res = await fetch(this.uploadUrl, {+ // Followed silently by default: a proxy or captive-portal 3xx sends+ // the chunk and signature onward, and its 200 reads as a good write.+ redirect: "error",method: "PATCH",headers: {"Tus-Resumable": "1.0.0",@@ -1212,34 +1334,102 @@ export default class BunnyTusUploader {if (res.ok || res.status === 204) {const serverOffsetHeader = res.headers.get("Upload-Offset");- let nextOffset;+ // Exactly this, not "at least this". A 2xx that advanced the server+ // by less means the rest of the chunk never landed.+ const expectedOffset = currentOffset + data.length;if (serverOffsetHeader) {const parsed = parseInt(serverOffsetHeader, 10);- // Validate the parsed offset. parseInt("0x100", 10) returns 0,- // which would silently reset the upload. Require a finite value- // at least equal to what was sent.- const expectedMin = currentOffset + data.length;+ // parseInt("0x100", 10) returns 0, which would silently reset the+ // upload. A regression or an overshoot is server state we can't use.if (!Number.isFinite(parsed) ||parsed < currentOffset ||- parsed > expectedMin+ parsed > expectedOffset) {this.setUploaderError("invalid-server-offset", {serverOffsetHeader,parsed,currentOffset,- expectedMin,+ expectedOffset,});throw new Error(`Invalid Upload-Offset from server: "${serverOffsetHeader}"`,);}- nextOffset = parsed;+ if (parsed < expectedOffset) {+ // Short write. Counting it as a full one is what let a camera+ // track discard 10k chunks while pinned at offset 28.+ const acceptedBytes = parsed - currentOffset;+ this.offset = parsed;+ this.lastServerOffset = parsed;+ this.noServerProgressCount =+ acceptedBytes > 0 ? 0 : this.noServerProgressCount + 1;+ this.emitTelemetry("upload_chunk_short_write", {+ reason: `short-write-accepted-${acceptedBytes}-streak-${+ this.noServerProgressCount+ }${res.url === this.uploadUrl ? "" : "-foreign-responder"}`,+ currentOffset,+ expectedOffset,+ parsed,+ acceptedBytes,+ noProgressStreak: this.noServerProgressCount,+ // Who answered. resUrl !== uploadUrl means something between us+ // and Bunny replied, which is the open question on this bug.+ httpStatus: res.status,+ resType: res.type || null,+ resUrlMatches: res.url === this.uploadUrl,+ });+ if (this.noServerProgressCount >= 3) {+ this.setUploaderError("server-offset-not-advancing", {+ parsed,+ currentOffset,+ });+ throw new Error(`Server offset stuck at ${parsed}`);+ }+ if (acceptedBytes > 0) {+ data = fullData.subarray(parsed - chunkStartOffset);+ this.recordProgress(acceptedBytes);+ }+ shortWritePasses += 1;+ // Breaks to the post-loop throw. Throwing here would be caught by+ // this loop's own catch and retried, which never terminates.+ if (shortWritePasses > this.MAX_SHORT_WRITE_PASSES) {+ exhaustedReason = "chunk-short-write-passes-exhausted";+ break;+ }+ if (acceptedBytes > 0) {+ // Real progress, so don't spend retry budget on it. Without+ // this the loop falls out mid-chunk and the tail is lost.+ attempt = -1;+ continue;+ }+ // Took nothing. Delay so a server that keeps taking nothing+ // can't be hammered. The 3-strike guard above ends it.+ await new Promise((r) =>+ setTimeout(r, 500 * Math.max(1, this.noServerProgressCount)),+ );+ continue;+ }+ this.noServerProgressCount = 0;+ this.offset = parsed;+ this.lastServerOffset = parsed;} else {- nextOffset = currentOffset + data.length;+ // No readable Upload-Offset via CORS. Advance locally to drain the+ // queue, but leave lastServerOffset, what purge deletes against.+ this.offset = expectedOffset;+ if (!this._warnedMissingOffsetHeader) {+ this._warnedMissingOffsetHeader = true;+ this.emitTelemetry("upload_offset_header_missing", {+ reason: `offset-header-missing${+ res.url === this.uploadUrl ? "" : "-foreign-responder"+ }`,+ currentOffset,+ httpStatus: res.status,+ resType: res.type || null,+ resUrlMatches: res.url === this.uploadUrl,+ });+ }}- this.offset = nextOffset;- this.lastServerOffset = this.offset;this.recordProgress(data.length);return;@@ -1254,8 +1444,14 @@ export default class BunnyTusUploader {console.warn("[bunnyTusUploader] 401 mid-PATCH; refreshing TUS auth + retrying once",);- this.emitTelemetry("upload_auth_refresh_after_401", {+ // Same event name as app-web so one query spans both clients.+ // trigger separates "Bunny rejected us" from "we resumed".+ this.emitTelemetry("upload_auth_refreshed_midupload", {+ reason: "auth-refresh-http-401",+ trigger: "http-401",attempt,+ offset: this.offset,+ httpStatus: 401,});try {await this.refreshTusAuth();@@ -1318,6 +1514,20 @@ export default class BunnyTusUploader {`Server offset regressed (${serverOffset} < ${priorOffset})`,);}+ // Absolute position in this chunk, so any mix of short writes+ // and resyncs lands on the same byte.+ const trimmedBytes = serverOffset - chunkStartOffset;+ if (trimmedBytes < 0) {+ // Below chunk start: those bytes are gone from `data`, so adopting would+ // PATCH misaligned. A CORS-stripped Upload-Offset parses as 0.+ this.emitTelemetry("upload_resync_offset_below_chunk", {+ reason: "resync-offset-below-chunk",+ serverOffset,+ chunkStartOffset,+ chunkLength: fullData.length,+ });+ continue;+ }this.lastServerOffset = serverOffset;this.offset = serverOffset;this.emitTelemetry("upload_resumed", {@@ -1326,22 +1536,22 @@ export default class BunnyTusUploader {});this.scheduleJournalPersist({ force: true });- const chunkEnd = chunkStartOffset + data.length;- if (serverOffset >= chunkEnd) {+ // Ahead of the whole chunk too: a debounced journal can resume+ // behind the server, and those chunks are already up.+ if (trimmedBytes >= fullData.length) {this.emitTelemetry("upload_chunk_skipped_after_resync", {chunkStartOffset,- chunkLength: data.length,+ chunkLength: fullData.length,serverOffset,});this.recordProgress(0);return;}- if (serverOffset > chunkStartOffset) {- const trimmedBytes = serverOffset - chunkStartOffset;- data = data.subarray(trimmedBytes);+ data = fullData.subarray(trimmedBytes);+ if (trimmedBytes > 0) {this.emitTelemetry("upload_chunk_trimmed_after_resync", {chunkStartOffset,- chunkLength: data.length + trimmedBytes,+ chunkLength: fullData.length,trimmedBytes,serverOffset,});@@ -1376,7 +1586,8 @@ export default class BunnyTusUploader {? controller.signal.reason: null;this.currentPatchAbort = null;- // Transient errors (network/timeout/stall-abort/5xx/408/429) retry forever with capped backoff.+ // Transient errors (network/timeout/stall-abort/5xx/408/423/425/429)+ // retry forever with capped backoff. 423 = Bunny's resource lock.const isExplicitAbort =this.status === "aborted" || this.isPaused === true;if (isExplicitAbort) {@@ -1387,8 +1598,13 @@ export default class BunnyTusUploader {const isTransient =err?.name === "AbortError" ||err?.name === "TypeError" ||- (status !== null && (status >= 500 || status === 408 || status === 429)) ||- /Upload failed \((?:5\d\d|408|429)\b/.test(msg) ||+ (status !== null &&+ (status >= 500 ||+ status === 408 ||+ status === 423 ||+ status === 425 ||+ status === 429)) ||+ /Upload failed \((?:5\d\d|408|423|425|429)\b/.test(msg) ||/network|Failed to fetch|timeout/i.test(msg);if (err?.name === "AbortError") {console.warn(@@ -1459,6 +1675,18 @@ export default class BunnyTusUploader {}}}+ // Falling out means the chunk never fully landed. Returning here reads as+ // success to processQueue, which then shifts the next chunk over the gap.+ this.setUploaderError(exhaustedReason, {+ chunkStartOffset,+ remaining: data.length,+ shortWritePasses,+ });+ throw new Error(`Chunk upload did not complete (${exhaustedReason})`);+ } catch (err) {+ this._chunkConsumedBytes = Math.max(0, this.offset - chunkStartOffset);+ throw err;+ }}async processQueue() {@@ -1483,8 +1711,20 @@ export default class BunnyTusUploader {} catch (err) {console.error("❌ Chunk upload failed in queue:", err);- this.chunkQueue.unshift(chunk);- this.queuedBytes += chunk.size;+ // The server may have taken a prefix before failing. Re-queueing the+ // whole chunk would re-send it at the advanced offset and overshoot.+ const consumed = Math.min(this._chunkConsumedBytes || 0, chunk.size);+ const retryChunk = consumed > 0 ? chunk.slice(consumed) : chunk;+ if (consumed > 0) {+ this.emitTelemetry("upload_chunk_requeued_tail", {+ reason: "requeue-after-partial-accept",+ consumed,+ remaining: retryChunk.size,+ });+ }+ this._chunkConsumedBytes = 0;+ this.chunkQueue.unshift(retryChunk);+ this.queuedBytes += retryChunk.size;// Don't clobber a non-recoverable code that uploadChunk already// set (e.g. "offset-conflict-head-failed", "invalid-server-offset"),@@ -1589,6 +1829,7 @@ export default class BunnyTusUploader {let serverOffset = null;try {const headRes = await fetch(this.uploadUrl, {+ redirect: "error",method: "HEAD",headers: {"Tus-Resumable": "1.0.0",@@ -1650,19 +1891,34 @@ export default class BunnyTusUploader {// Upload-Length must equal Upload-Offset to complete, and can never be// below it. Declaring the client tally when the two disagreed was what// Bunny rejected.- const res = await fetch(this.uploadUrl, {- method: "PATCH",- headers: {- "Tus-Resumable": "1.0.0",- "Content-Type": "application/offset+octet-stream",- "Upload-Offset": String(serverOffset),- "Upload-Length": String(serverOffset),- AuthorizationSignature: this.signature,- AuthorizationExpire: String(this.expires),- LibraryId: String(this.libraryId),- VideoId: this.videoId,- },- });+ // 423 = another request holds Bunny's lock, clears in about a second.+ // No outer retry here, so failing costs the whole finalize.+ let res = null;+ let lockRetries = 0;+ for (let attempt = 0; attempt < 3; attempt += 1) {+ if (attempt > 0) {+ lockRetries = attempt;+ await new Promise((r) => setTimeout(r, 1000 * attempt));+ }+ res = await fetch(this.uploadUrl, {+ redirect: "error",+ method: "PATCH",+ headers: {+ "Tus-Resumable": "1.0.0",+ "Content-Type": "application/offset+octet-stream",+ "Upload-Offset": String(serverOffset),+ "Upload-Length": String(serverOffset),+ AuthorizationSignature: this.signature,+ AuthorizationExpire: String(this.expires),+ LibraryId: String(this.libraryId),+ VideoId: this.videoId,+ },+ });+ if (res.status !== 423) break;+ console.warn(+ `[bunnyTusUploader] finalize got 423 Locked, retry ${attempt + 1}/2`,+ );+ }// 410 = Bunny reports the upload is already finalized. Treat as// success; server is the truth, retrying would just loop.@@ -1676,6 +1932,7 @@ export default class BunnyTusUploader {this.emitTelemetry("upload_finalize_completed", {finalizedBytes: this.totalBytes,alreadyFinalized: alreadyFinalized || undefined,+ lockRetries: lockRetries || undefined,// Reconciled a prior session's unjournaled bytes back in (no loss).recoveredBytes: recoveredBytes || undefined,// Finalized a truncated clean prefix; this many tail bytes were@@ -1843,6 +2100,16 @@ export default class BunnyTusUploader {this.attemptStallRecovery(diff).catch((err) => {console.warn("[bunnyTusUploader] stall recovery failed:", err);});+ return;+ }++ // Every 3rd tick (~30s). A progressing upload looks identical to one+ // whose PATCHes 2xx into the void until something reads the server.+ this._reconcileTickCount += 1;+ if (this._reconcileTickCount % 3 === 0) {+ this.reconcileServerOffset("heartbeat").catch((err) => {+ console.warn("[bunnyTusUploader] offset reconcile failed:", err);+ });}}, this.HEARTBEAT_INTERVAL_MS);}@@ -1860,6 +2127,7 @@ export default class BunnyTusUploader {// Resync via HEAD so a partially-applied PATCH doesn't dup bytes.try {const res = await fetch(this.uploadUrl, {+ redirect: "error",method: "HEAD",headers: {"Tus-Resumable": "1.0.0",@@ -1943,6 +2211,11 @@ export default class BunnyTusUploader {this.emitTelemetry("upload_first_byte", {bytes,});+ // Stuck-at-init is the reported signature, so check this one early rather+ // than waiting 30s. Off the hot path: start latency is measured.+ setTimeout(() => {+ this.reconcileServerOffset("first-byte").catch(() => {});+ }, 3000);}if (this.lastProgressEventAt === 0 ||diff --git a/src/pages/CloudRecorder/clientSessionId.js b/src/pages/CloudRecorder/clientSessionId.jsnew file mode 100644index 0000000..84b6556--- /dev/null+++ b/src/pages/CloudRecorder/clientSessionId.js@@ -0,0 +1,14 @@+// One id per page load, which is one recording host. Two ids against the same+// bunnyVideoId means two hosts were writing to it. The same id twice means one+// host re-signed. Deliberately not persisted: a reload is a new host.+let _clientSessionId = null;++export const getClientSessionId = () => {+ if (_clientSessionId) return _clientSessionId;+ try {+ _clientSessionId = crypto.randomUUID();+ } catch {+ _clientSessionId = `cs-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;+ }+ return _clientSessionId;+};diff --git a/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.js b/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.jsindex 7ff2f15..d7df075 100644--- a/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.js+++ b/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.js@@ -19,6 +19,8 @@ export class WebCodecsTrackRecorder {constructor(stream, options = {}) {this.stream = stream;this.mimeType = options.mimeType || "video/mp4";+ // WebM is the no-AAC fallback (Linux), carrying VP9 + Opus.+ this.containerKind = options.containerKind === "webm" ? "webm" : "mp4";this.videoBitsPerSecond =options.videoBitsPerSecond || 16_000_000;this.audioBitsPerSecond = options.audioBitsPerSecond || 128_000;@@ -177,13 +179,17 @@ export class WebCodecsTrackRecorder {} catch {}};- // Screen only: the prewarm is sized and hardware-preferred for screen,- // and cloud's camera track is often forced to software anyway.+ // Screen only: camera is often forced to software. The warm encoder is+ // H.264 and claimPrewarmedEncoder doesn't check codec, so WebM/VP9 can't adopt.const adoptPrewarm =- isWarmAdoptEnabled() && this.trackKind === "screen" && !this.preferSoftware;+ isWarmAdoptEnabled() &&+ this.trackKind === "screen" &&+ !this.preferSoftware &&+ this.containerKind !== "webm";this._recorder = new WebCodecsRecorder(this.stream, {allowPrewarmAdopt: adoptPrewarm,+ containerKind: this.containerKind,onChunk: handleChunk,onFinalized: handleFinalized,onError: handleError,diff --git a/src/pages/CloudRecorder/encoder/chooseEncoder.js b/src/pages/CloudRecorder/encoder/chooseEncoder.jsindex 5feb1c1..25ced76 100644--- a/src/pages/CloudRecorder/encoder/chooseEncoder.js+++ b/src/pages/CloudRecorder/encoder/chooseEncoder.js@@ -16,34 +16,60 @@ import { canStartMp4Recorder } from "../../utils/recorderCodec";// downstream (Bunny drops frames, node-av SIGSEGVs). false = VP9-WebM.const PREFER_MP4_MEDIARECORDER = true;+// MediaRecorder's audio-only WebM carries no Duration, so players report+// Infinity. false = WebM/Opus.+const PREFER_MP4_AUDIO_MEDIARECORDER = true;+// H.264 Baseline + AAC-LC. Video-only variant for audioless tracks;// isTypeSupported answers differently for the two, so probe both.const MP4_MR_WITH_AUDIO = "video/mp4;codecs=avc1.42E01E,mp4a.40.2";const MP4_MR_VIDEO_ONLY = "video/mp4;codecs=avc1.42E01E";+// AAC-LC, audio-only. Pinned: a bare audio/mp4 records Opus-in-MP4 on+// Chrome 151.+const MP4_MR_AUDIO_ONLY = "audio/mp4;codecs=mp4a.40.2";++const mimeSupported = (mime) => {+ try {+ return (+ typeof MediaRecorder !== "undefined" &&+ typeof MediaRecorder.isTypeSupported === "function" &&+ MediaRecorder.isTypeSupported(mime)+ );+ } catch {+ return false;+ }+};let _mp4MrSupport = null;const probeMp4MediaRecorder = () => {if (_mp4MrSupport !== null) return _mp4MrSupport;- const supported = (mime) => {- try {- return (- typeof MediaRecorder !== "undefined" &&- typeof MediaRecorder.isTypeSupported === "function" &&- MediaRecorder.isTypeSupported(mime)- );- } catch {- return false;- }- };_mp4MrSupport = PREFER_MP4_MEDIARECORDER? {- withAudio: supported(MP4_MR_WITH_AUDIO),- videoOnly: supported(MP4_MR_VIDEO_ONLY),+ withAudio: mimeSupported(MP4_MR_WITH_AUDIO),+ videoOnly: mimeSupported(MP4_MR_VIDEO_ONLY),}: { withAudio: false, videoOnly: false };return _mp4MrSupport;};+let _mp4AudioMrSupport = null;+// TUS filetype is fixed at uploader init, so an MP4 start() that throws later+// ships WebM bytes labelled audio/mp4. Probe the real mic stream here.+const probeMp4AudioMediaRecorder = (stream = null) => {+ if (_mp4AudioMrSupport !== null) return _mp4AudioMrSupport;+ const typeOk =+ PREFER_MP4_AUDIO_MEDIARECORDER && mimeSupported(MP4_MR_AUDIO_ONLY);+ if (!typeOk) {+ _mp4AudioMrSupport = false;+ return false;+ }+ // No stream yet: report support without caching, so the first call that has+ // one still gets to run the start probe.+ if (!stream) return true;+ _mp4AudioMrSupport = canStartMp4Recorder(stream, MP4_MR_AUDIO_ONLY);+ return _mp4AudioMrSupport;+};+// Only claim MP4 when both variants record: the container is fixed before we// know whether this track carries audio.const mediaRecorderVideoPlan = () => {@@ -55,6 +81,7 @@ const mediaRecorderVideoPlan = () => {// Null for WebM: callers pass their existing mime through unchanged.export const mediaRecorderMimeFor = ({ container, enableAudio }) => {+ if (container === "audio/mp4") return MP4_MR_AUDIO_ONLY;if (container !== "video/mp4") return null;return enableAudio ? MP4_MR_WITH_AUDIO : MP4_MR_VIDEO_ONLY;};@@ -101,6 +128,7 @@ let _stickyStatePromise = null;export const resetEncoderProbeCache = () => {_hwSlotsPromise = null;_stickyStatePromise = null;+ _mp4AudioMrSupport = null;};const ensureProbes = async (probeOptions) => {@@ -125,14 +153,19 @@ const TRACK_TO_PROBE = {// BunnyTusUploader's TUS Upload-Metadata `filetype` can be set to the// container the upcoming recorder will produce. Both inspectTrackPlan// and chooseTrackEncoder hit the same probe cache, so they always agree.-export const inspectTrackPlan = async ({ track, probeOptions }) => {+export const inspectTrackPlan = async ({ track, probeOptions, stream = null }) => {+ // Audio never uses WebCodecs: screen + camera already contend for the+ // H.264 slots. MP4 here is a muxer swap inside MediaRecorder, not an encoder.if (track === "audio") {+ const mp4 = probeMp4AudioMediaRecorder(stream);return {kind: "mediarecorder",- container: "video/webm",- codec: "opus",+ // WebM fallback keeps reporting video/webm, the filetype these+ // tracks have always uploaded under.+ container: mp4 ? "audio/mp4" : "video/webm",+ codec: mp4 ? "mp4a.40.2" : "opus",hwSlots: null,- reason: "audio-track-fixed",+ reason: mp4 ? "audio-track-mp4" : "audio-track-webm",};}const [hwSlots, sticky] = await ensureProbes(probeOptions || {});@@ -153,18 +186,17 @@ export const inspectTrackPlan = async ({ track, probeOptions }) => {reason: `hw-probe-${track}-unsupported`,};}- // MP4/WebCodecs can't carry audio without AAC. When AAC encode is missing- // (rare: Chromium with H.264 but no proprietary AAC) the WebCodecs path- // would produce a silent MP4, so route video tracks to MediaRecorder- // (VP9-WebM), which records audio natively. AAC support is device-global, so- // both inspectTrackPlan callers (TUS filetype hint and recorder) agree.+ // Linux Chromium has no AAC, so MP4 would be silent. WebM/Opus, not+ // MediaRecorder, whose VFR output jitters on render.// `=== false` so an older cached probe without the field fails open.if (hwSlots.summary.aacSupported === false) {return {- kind: "mediarecorder",- ...mediaRecorderVideoPlan(),+ kind: "webcodecs",+ container: "video/webm",+ containerKind: "webm",+ codec: "vp9",hwSlots: hwSlots.summary,- reason: "aac-unsupported",+ reason: "aac-unsupported-webm",};}if (track === "camera" && hwSlots.summary.mode === "screen-hw-camera-mr") {@@ -214,7 +246,7 @@ export const chooseTrackEncoder = async ({onDataAvailable,probeOptions,}) => {- const plan = await inspectTrackPlan({ track, probeOptions });+ const plan = await inspectTrackPlan({ track, probeOptions, stream });if (plan.kind === "mediarecorder") {// Use the plan's mime so bytes match the container we already reported (TUS@@ -229,7 +261,7 @@ export const chooseTrackEncoder = async ({if (planMime && !canStartMp4Recorder(stream, planMime)) {planMime = null;plan.container = "video/webm";- plan.codec = "vp9";+ plan.codec = track === "audio" ? "opus" : "vp9";plan.reason = `${plan.reason}+mp4-start-probe-failed`;}return {@@ -243,8 +275,8 @@ export const chooseTrackEncoder = async ({};}- // WebCodecs path. The MP4 mime type is always video/mp4, regardless of- // whether audio is included (AAC fits inside MP4 alongside H.264).+ // WebCodecs path: MP4 stays video/mp4 with or without audio. WebM is the+ // no-AAC fallback, carrying VP9 + Opus instead.// forceSoftwareEncoder storage flag biases the encoder candidate list// toward prefer-software. Playwright Chromium 1217 hits a documented// "encode() accepts, no chunks emit" HW silent-fail (see Windows MFT@@ -255,8 +287,10 @@ export const chooseTrackEncoder = async ({const s = await chrome.storage.local.get(["forceSoftwareEncoder"]);forceSoftware = Boolean(s.forceSoftwareEncoder);} catch {}+ const containerKind = plan.containerKind === "webm" ? "webm" : "mp4";const recorder = new WebCodecsTrackRecorder(stream, {- mimeType: "video/mp4",+ mimeType: containerKind === "webm" ? "video/webm" : "video/mp4",+ containerKind,videoBitsPerSecond,audioBitsPerSecond,audioChannels,diff --git a/src/pages/CloudRecorder/notifyRecordingStarted.js b/src/pages/CloudRecorder/notifyRecordingStarted.jsnew file mode 100644index 0000000..b23963c--- /dev/null+++ b/src/pages/CloudRecorder/notifyRecordingStarted.js@@ -0,0 +1,20 @@+const API_BASE = process.env.SCREENITY_API_BASE_URL;++// Tells app-web a capture is running so its auto-render sweep skips+// this project. Scheduling hint only, so failures stay silent.+export const notifyRecordingStarted = (projectId) => {+ if (!projectId || !API_BASE) return;+ (async () => {+ try {+ const { screenityToken } = await chrome.storage.local.get([+ "screenityToken",+ ]);+ await fetch(`${API_BASE}/videos/${projectId}/recording-started/`, {+ method: "POST",+ headers: screenityToken+ ? { Authorization: `Bearer ${screenityToken}` }+ : {},+ });+ } catch {}+ })();+};diff --git a/src/pages/CloudRecorder/uploadGapRecovery.js b/src/pages/CloudRecorder/uploadGapRecovery.jsnew file mode 100644index 0000000..36c5127--- /dev/null+++ b/src/pages/CloudRecorder/uploadGapRecovery.js@@ -0,0 +1,88 @@+// Finds which durable chunks cover the bytes Bunny is missing, so finalize+// can re-send them instead of declaring a length the server never received.++// ranges: [{ index, endByte, size }] in write order. covered=false means send+// nothing, since a partial re-send punches a hole rather than closing one.+export const planGapResend = ({+ ranges,+ serverOffset,+ clientBytes,+ maxGapBytes = 64 * 1024 * 1024,+}) => {+ const gapBytes = (Number(clientBytes) || 0) - (Number(serverOffset) || 0);+ if (!(gapBytes > 0)) {+ return { covered: false, plan: [], gapBytes: 0, reason: "no-gap" };+ }+ if (gapBytes > maxGapBytes) {+ return { covered: false, plan: [], gapBytes, reason: "gap-too-large" };+ }+ if (!Array.isArray(ranges) || ranges.length === 0) {+ return { covered: false, plan: [], gapBytes, reason: "no-ranges" };+ }++ const sorted = [...ranges]+ .filter(+ (r) =>+ r &&+ Number.isFinite(r.endByte) &&+ Number.isFinite(r.size) &&+ r.size > 0 &&+ r.index !== null &&+ r.index !== undefined,+ )+ .sort((a, b) => a.endByte - b.endByte);+ if (!sorted.length) {+ return { covered: false, plan: [], gapBytes, reason: "no-usable-ranges" };+ }++ // Ranges must be contiguous, or the byte positions are guesses.+ for (let i = 0; i < sorted.length; i++) {+ const startByte = sorted[i].endByte - sorted[i].size;+ const prevEnd = i === 0 ? sorted[0].endByte - sorted[0].size : sorted[i - 1].endByte;+ if (startByte !== prevEnd) {+ return {+ covered: false,+ plan: [],+ gapBytes,+ reason: "ranges-not-contiguous",+ };+ }+ }++ const firstStart = sorted[0].endByte - sorted[0].size;+ const lastEnd = sorted[sorted.length - 1].endByte;+ // The tracked window has to span the whole gap. A purged prefix, or a chunk+ // that never reached disk, can't be reconstructed.+ if (firstStart > serverOffset || lastEnd < clientBytes) {+ return { covered: false, plan: [], gapBytes, reason: "gap-outside-ranges" };+ }++ const plan = [];+ for (const r of sorted) {+ const startByte = r.endByte - r.size;+ if (r.endByte <= serverOffset) continue;+ // Partially-received chunk: skip the bytes Bunny already has.+ const skipBytes = Math.max(0, serverOffset - startByte);+ plan.push({+ index: r.index,+ skipBytes,+ sendBytes: r.size - skipBytes,+ startByte: startByte + skipBytes,+ });+ }+ if (!plan.length) {+ return { covered: false, plan: [], gapBytes, reason: "empty-plan" };+ }++ const planBytes = plan.reduce((sum, p) => sum + p.sendBytes, 0);+ if (planBytes !== gapBytes) {+ return {+ covered: false,+ plan: [],+ gapBytes,+ reason: "plan-bytes-mismatch",+ planBytes,+ };+ }+ return { covered: true, plan, gapBytes, reason: "ok" };+};diff --git a/src/pages/Content/Wrapper.jsx b/src/pages/Content/Wrapper.jsxindex b928b02..d1a3570 100644--- a/src/pages/Content/Wrapper.jsx+++ b/src/pages/Content/Wrapper.jsx@@ -253,27 +253,61 @@ const Wrapper = () => {}));}, [regionCaptureRef.current]);+ // The iframe unmounts with the popup, so drop the loaded flag with it.+ // Otherwise the next open would post into a window that hasn't loaded yet.+ useEffect(() => {+ if (contentState.showExtension) return;+ setContentState((prevContentState) =>+ prevContentState.permissionsLoaded+ ? { ...prevContentState, permissionsLoaded: false }+ : prevContentState+ );+ }, [contentState.showExtension]);++ // A single request gets lost while the iframe loads or a device wakes, leaving+ // the dropdowns on "No camera". A failed answer reports no permission at all.useEffect(() => {- if (contentState.permissionsChecked) return;- if (!permissionsRef.current) return;if (!contentState.showExtension) return;if (!contentState.permissionsLoaded) return;+ if (!permissionsRef.current) return;++ const startCount = contentStateRef.current.permissionsResponses || 0;+ let attempts = 0;+ let timer = null;++ const request = () => {+ permissionsRef.current?.contentWindow?.postMessage(+ {+ type: "screenity-get-permissions",+ },+ "*"+ );+ attempts += 1;+ timer = setTimeout(retry, 1200 * attempts);+ };- permissionsRef.current.contentWindow.postMessage(- {- type: "screenity-get-permissions",- },- "*"+ const retry = () => {+ if ((contentStateRef.current.permissionsResponses || 0) !== startCount)+ return;+ if (attempts >= 3) return;+ request();+ };++ request();++ setContentState((prevContentState) =>+ prevContentState.permissionsChecked+ ? prevContentState+ : { ...prevContentState, permissionsChecked: true });- setContentState((prevContentState) => ({- ...prevContentState,- permissionsChecked: true,- }));+ return () => {+ if (timer) clearTimeout(timer);+ };}, [- permissionsRef.current,contentState.showExtension,contentState.permissionsLoaded,+ contentState.showPopup,]);useEffect(() => {diff --git a/src/pages/Content/camera/layout/CameraToolbar.jsx b/src/pages/Content/camera/layout/CameraToolbar.jsxindex acdb637..f3997a1 100644--- a/src/pages/Content/camera/layout/CameraToolbar.jsx+++ b/src/pages/Content/camera/layout/CameraToolbar.jsx@@ -10,6 +10,8 @@ import { contentStateContext } from "../../context/ContentState";const CameraToolbar = () => {const [contentState, setContentState] = useContext(contentStateContext);+ const pipSupported =+ typeof document !== "undefined" && document.pictureInPictureEnabled;return (<Toolbar.Root className="camera-toolbar">@@ -25,7 +27,10 @@ const CameraToolbar = () => {><CameraCloseIcon /></Toolbar.Button>- {contentState.recording && contentState.surface === "monitor" && (+ {/* Manual toggle, deliberately not gated on surface or recordingType.+ Auto-PiP is decided in surfaceHandler; this is the way back into PiP+ after closing it, and `surface` is not reliably set on every flow. */}+ {pipSupported && (<TooltipWrapcontent={chrome.i18n.getMessage("togglePictureinPictureModeTooltip")}>diff --git a/src/pages/Content/camera/layout/CameraWrap.jsx b/src/pages/Content/camera/layout/CameraWrap.jsxindex 90735ad..0ff6600 100644--- a/src/pages/Content/camera/layout/CameraWrap.jsx+++ b/src/pages/Content/camera/layout/CameraWrap.jsx@@ -122,31 +122,21 @@ const CameraWrap = (props) => {};}, []);+ const idle = !contentState.recording && !contentState.pendingRecording;+ // Keyed off the real PiP window, not `surface`, which arrives only after an+ // auth round-trip. pipActive false until "pip-started" keeps the bubble.+ const hidden =+ !idle &&+ (contentState.pipActive ||+ (contentState.isSubscribed &&+ (!contentState.instantMode || contentState.multiMode)) ||+ contentState.onboarding);+return (<divstyle={{- visibility:- !contentState.recording && !contentState.pendingRecording- ? "visible"- : (!contentState.pipEnded &&- contentState.surface === "monitor" &&- (contentState.pendingRecording || contentState.recording)) ||- (contentState.isSubscribed &&- (!contentState.instantMode || contentState.multiMode)) ||- contentState.onboarding- ? "hidden"- : "visible",- pointerEvents:- !contentState.recording && !contentState.pendingRecording- ? "auto"- : (!contentState.pipEnded &&- contentState.surface === "monitor" &&- (contentState.pendingRecording || contentState.recording)) ||- (contentState.isSubscribed &&- (!contentState.instantMode || contentState.multiMode)) ||- contentState.onboarding- ? "none"- : "auto",+ visibility: hidden ? "hidden" : "visible",+ pointerEvents: hidden ? "none" : "auto",}}><Rnddiff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsxindex dbf0e7d..6144cfe 100644--- a/src/pages/Content/context/ContentState.jsx+++ b/src/pages/Content/context/ContentState.jsx@@ -24,6 +24,16 @@ import {setStartFlowOutcome,} from "../../utils/startFlowTrace";import { triggerSupportDownload } from "../../utils/triggerSupportDownload";+import { apiIssueCopy } from "../utils/apiIssueCopy";++// Re-asking can't change these, so the retry would only re-open the modal.+// Anything else (a busy or still-waking device) is worth another pass.+const PERMISSION_TERMINAL_ERRORS = new Set([+ "NotAllowedError",+ "NotFoundError",+ "SecurityError",+ "OverconstrainedError",+]);export const contentStateContext = createContext();// Split out of contentStateContext: the 1s clock tick was re-rendering every@@ -67,6 +77,9 @@ const ContentState = (props) => {);const startBeepRef = useRef(null);const stopBeepRef = useRef(null);+ // True while the "can't reach Screenity" modal is the one on screen, so it+ // can close itself when the API answers again.+ const apiIssueModalRef = useRef(false);const prevRecordingRef = useRef(null);const hydratedRef = useRef(false);const suppressStopBeepRef = useRef(false);@@ -372,6 +385,7 @@ const ContentState = (props) => {timeWarning: false,tabCaptureFrame: false,pipEnded: false,+ pipActive: false,// Preserve tool state in multi so reopen-popup-multi can// carry it to the next scene....(isMulti@@ -429,6 +443,7 @@ const ContentState = (props) => {timeWarning: false,tabCaptureFrame: false,pipEnded: false,+ pipActive: false,showExtension: wasMulti ? true : false,showPopup: wasMulti ? true : true,// Preserve tool state in multi-mode (see editor-open cleanup@@ -524,6 +539,7 @@ const ContentState = (props) => {pendingRecording: false,preparingRecording: false,pipEnded: false,+ pipActive: false,blurMode: false,drawingMode: false,// Mirror the storage write to avoid a frame where the cursor overlay@@ -665,7 +681,17 @@ const ContentState = (props) => {type: "check-storage-quota",});- const { success, canUpload, error } = storageResponse;+ const { success, canUpload, error, reachability } = storageResponse;++ if (reachability) {+ // Always restamp: this verdict is live, and the banner treats an old+ // `at` as unproven and hides itself.+ setContentState((prev) => ({+ ...prev,+ apiReachability: reachability,+ apiReachabilityAt: Date.now(),+ }));+ }if (success && canUpload === false) {contentStateRef.current.openModal(@@ -697,19 +723,40 @@ const ContentState = (props) => {}));}+ // Blaming the storage check for a dead connection or a 502 sends people+ // to look at their storage settings. Name the real problem.+ const issue = isAuthError ? null : apiIssueCopy(reachability);+ const title = issue+ ? issue.title+ : chrome.i18n.getMessage("storageCheckFailTitle");const message = isAuthError? chrome.i18n.getMessage("storageCheckFailAuthDescription")- : chrome.i18n.getMessage("storageCheckFailDescription");+ : issue+ ? issue.description+ : chrome.i18n.getMessage("storageCheckFailDescription");++ apiIssueModalRef.current = Boolean(issue);contentStateRef.current.openModal(- chrome.i18n.getMessage("storageCheckFailTitle"),+ title,message,- chrome.i18n.getMessage("retryButtonLabel"),+ isAuthError+ ? chrome.i18n.getMessage("loginButtonLabel")+ : chrome.i18n.getMessage("retryButtonLabel"),chrome.i18n.getMessage("closeModalLabel"),- async () => {- window.location.reload();+ () => {+ // Retry the start, not the page: the old reload dropped whatever+ // the user had open and never re-ran the check.+ apiIssueModalRef.current = false;+ if (isAuthError) {+ chrome.runtime.sendMessage({ type: "handle-login" });+ } else {+ startStreaming();+ }+ },+ () => {+ apiIssueModalRef.current = false;},- () => {},);}@@ -872,6 +919,7 @@ const ContentState = (props) => {surface: "default",pipEnded: false,+ pipActive: false,}));},() => {@@ -923,6 +971,7 @@ const ContentState = (props) => {surface: "default",pipEnded: false,+ pipActive: false,}));}}, [contentStateRef]);@@ -974,12 +1023,22 @@ const ContentState = (props) => {const cameraPermission = data.cameraPermission;const microphonePermission = data.microphonePermission;+ // Empty on a granted device is Chrome lagging, not an absent device.+ // Keep the old list rather than show "None" until the page reloads.setContentState((prevContentState) => ({...prevContentState,- audioInput: audioInput,- videoInput: videoInput,+ audioInput:+ microphonePermission && !audioInput?.length && prevContentState.audioInput?.length+ ? prevContentState.audioInput+ : audioInput,+ videoInput:+ cameraPermission && !videoInput?.length && prevContentState.videoInput?.length+ ? prevContentState.videoInput+ : videoInput,cameraPermission: cameraPermission,microphonePermission: microphonePermission,+ // Wrapper watches this to know its request was answered.+ permissionsResponses: (prevContentState.permissionsResponses || 0) + 1,}));const audioInputById = Array.isArray(audioInput)@@ -1062,6 +1121,11 @@ const ContentState = (props) => {...prevContentState,cameraPermission: false,microphonePermission: false,+ // A settled refusal is still an answer. Without it the Wrapper retry+ // reads the iframe as never having replied and re-runs the prompt.+ permissionsResponses: PERMISSION_TERMINAL_ERRORS.has(data?.error)+ ? (prevContentState.permissionsResponses || 0) + 1+ : prevContentState.permissionsResponses || 0,}));if (contentStateRef.current.askForPermissions) {if (contentStateRef.current.sitePermissionsBlocked) {@@ -1177,6 +1241,7 @@ const ContentState = (props) => {startStreaming: startStreaming,setToolbarMode: null,openModal: null,+ closeModal: null,openToast: null,// Page-level Permissions-Policy disallows camera/mic. Lets us show a// site-specific warning instead of the misleading "check your permissions" one.@@ -1260,12 +1325,16 @@ const ContentState = (props) => {useOffscreenCloud: true,isAddingImage: false,pipEnded: false,+ pipActive: false,tabCaptureFrame: false,showOnboardingArrow: false,offline: false,updateChrome: false,permissionsChecked: false,permissionsLoaded: false,+ permissionsResponses: 0,+ apiReachability: "ok",+ apiReachabilityAt: null,parentRef: null,shadowRef: null,settingsOpen: false,@@ -1479,32 +1548,38 @@ const ContentState = (props) => {let timer = null;let fired = false;+ // Bytes moving while the UI still waits means the recorder started and+ // only the UI is stuck. Zero means the start itself never happened.+ const reportStuck = async (state, timeoutMs) => {+ if (fired) return;+ fired = true;+ let live = null;+ try {+ const snap = await chrome.storage.local.get(["recorderLiveProgress"]);+ live = snap?.recorderLiveProgress || null;+ } catch {}+ setStartFlowOutcome("stuck", {+ stuck: {+ state,+ since: Date.now() - timeoutMs,+ durationMs: timeoutMs,+ liveChunks: live?.chunks ?? null,+ liveBytes: live?.bytes ?? null,+ liveAt: live?.ts ?? null,+ },+ });+ };+if (contentState.pendingRecording &&!contentState.preparingRecording) {timer = setTimeout(() => {- if (fired) return;- fired = true;- setStartFlowOutcome("stuck", {- stuck: {- state: "pending",- since: Date.now() - PENDING_TIMEOUT_MS,- durationMs: PENDING_TIMEOUT_MS,- },- });+ reportStuck("pending", PENDING_TIMEOUT_MS);}, PENDING_TIMEOUT_MS);} else if (contentState.preparingRecording) {timer = setTimeout(() => {- if (fired) return;- fired = true;- setStartFlowOutcome("stuck", {- stuck: {- state: "preparing",- since: Date.now() - PREPARING_TIMEOUT_MS,- durationMs: PREPARING_TIMEOUT_MS,- },- });+ reportStuck("preparing", PREPARING_TIMEOUT_MS);}, PREPARING_TIMEOUT_MS);}@@ -1793,11 +1868,69 @@ const ContentState = (props) => {};}, []);+ // Background records reachability from the API calls it already makes.+ // The browser's own offline flag overrides it.+ useEffect(() => {+ const applyState = (state, at = Date.now()) => {+ setContentState((prev) =>+ prev.apiReachability === state && prev.apiReachabilityAt === at+ ? prev+ : { ...prev, apiReachability: state, apiReachabilityAt: at },+ );+ };++ chrome.storage.local.get("apiReachability", (result) => {+ if (navigator.onLine === false) {+ applyState("offline");+ return;+ }+ const stored = result?.apiReachability;+ // Carry the timestamp: last night's outage is not evidence about now,+ // and the banner refuses to run on a verdict that old.+ applyState(stored?.state || "ok", stored?.at || Date.now());+ });++ const onOffline = () => applyState("offline");+ const onOnline = () => {+ applyState("ok");+ chrome.runtime.sendMessage({ type: "recheck-api-reachability" }, (res) => {+ if (chrome.runtime.lastError) return;+ if (res?.state) applyState(res.state);+ });+ };++ window.addEventListener("offline", onOffline);+ window.addEventListener("online", onOnline);+ return () => {+ window.removeEventListener("offline", onOffline);+ window.removeEventListener("online", onOnline);+ };+ }, []);++ useEffect(() => {+ if (contentState.apiReachability !== "ok") return;+ if (!apiIssueModalRef.current) return;+ apiIssueModalRef.current = false;+ contentState.closeModal?.();+ }, [contentState.apiReachability, contentState.closeModal]);+useEffect(() => {const onChanged = (changes, area) => {if (area !== "local") return;let shouldUpdateTimer = false;+ if (changes.apiReachability) {+ const next = changes.apiReachability.newValue;+ const state = next?.state || "ok";+ const at = next?.at || Date.now();+ setContentState((prev) =>+ (prev.apiReachability === state && prev.apiReachabilityAt === at) ||+ navigator.onLine === false+ ? prev+ : { ...prev, apiReachability: state, apiReachabilityAt: at },+ );+ }+if (changes.activeTab) {activeTabRef.current = changes.activeTab.newValue ?? null;}@@ -1950,6 +2083,7 @@ const ContentState = (props) => {timeWarning: false,tabCaptureFrame: false,pipEnded: false,+ pipActive: false,showExtension: wasMulti ? true : false,showPopup: wasMulti ? true : true,// Preserve tool state in multi so the user's drawingdiff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.jsindex 10c31ad..ec19325 100644--- a/src/pages/Content/context/messaging/handlers.js+++ b/src/pages/Content/context/messaging/handlers.js@@ -754,6 +754,7 @@ export const setupHandlers = () => {recording: false,paused: false,pipEnded: false,+ pipActive: false,time: 0,timer: 0,}));@@ -792,8 +793,13 @@ export const setupHandlers = () => {state.openToast("Upload complete.", () => {}, 4000);}});- registerMessage("recording-error", () => {- setStartFlowOutcome("error");+ registerMessage("recording-error", (message) => {+ // Sender carries why/errorCode. Dropping them landed every+ // error-triggered report with a null cause.+ setStartFlowOutcome("error", {+ error: message?.why || message?.error || null,+ errorCode: message?.errorCode || null,+ });setContentState((prev) => ({...prev,pendingRecording: false,@@ -803,6 +809,7 @@ export const setupHandlers = () => {time: 0,timer: 0,pipEnded: false,+ pipActive: false,}));const state = getState();if (state && typeof state.openModal === "function") {@@ -911,24 +918,24 @@ export const setupHandlers = () => {}));});+ // pipActive tracks whether PiP is really on screen and is what hides the+ // bubble. Both edges land outside a recording too, or a failed PiP hides it.registerMessage("pip-ended", () => {const state = getState();- if (state.recording || state.pendingRecording) {- setContentState((prev) => ({- ...prev,- pipEnded: true,- }));- }+ setContentState((prev) => ({+ ...prev,+ pipActive: false,+ ...(state.recording || state.pendingRecording ? { pipEnded: true } : {}),+ }));});registerMessage("pip-started", () => {const state = getState();- if (state.recording || state.pendingRecording) {- setContentState((prev) => ({- ...prev,- pipEnded: false,- }));- }+ setContentState((prev) => ({+ ...prev,+ pipActive: true,+ ...(state.recording || state.pendingRecording ? { pipEnded: false } : {}),+ }));});registerMessage("setup-complete", () => {@@ -1153,6 +1160,7 @@ export const setupHandlers = () => {showExtension: true,recording: true,pipEnded: true,+ pipActive: false,}));updateFromStorage(false, sender.id);}@@ -1165,6 +1173,7 @@ export const setupHandlers = () => {pendingRecording: false,preparingRecording: false,pipEnded: false,+ pipActive: false,}));});@@ -1198,6 +1207,7 @@ export const setupHandlers = () => {timeWarning: false,tabCaptureFrame: false,pipEnded: false,+ pipActive: false,// Seed multi-mode + scene count + project id from storage. This// is the field set that gates the popup's "Done" button (uses// multiMode + multiSceneCount > 0); if either is stale, thediff --git a/src/pages/Content/context/utils/updateFromStorage.js b/src/pages/Content/context/utils/updateFromStorage.jsindex 6659215..22a3e78 100644--- a/src/pages/Content/context/utils/updateFromStorage.js+++ b/src/pages/Content/context/utils/updateFromStorage.js@@ -18,8 +18,8 @@ const deriveCursorMode = (effects, fallbackMode) => {export const updateFromStorage = (check = true, id = null) => {chrome.storage.local.get([- "audioInput",- "videoInput",+ "audioinput",+ "videoinput","defaultAudioInput","defaultVideoInput","defaultAudioInputLabel",@@ -94,14 +94,14 @@ export const updateFromStorage = (check = true, id = null) => {setContentState((prevContentState) => ({...prevContentState,- audioInput:- result.audioInput !== undefined && result.audioInput !== null- ? result.audioInput- : prevContentState.audioInput,- videoInput:- result.videoInput !== undefined && result.videoInput !== null- ? result.videoInput- : prevContentState.videoInput,+ // Permissions.html writes these lowercase. Seeding from the cache keeps+ // the dropdowns populated when the live enumeration is slow or fails.+ audioInput: Array.isArray(result.audioinput)+ ? result.audioinput+ : prevContentState.audioInput,+ videoInput: Array.isArray(result.videoinput)+ ? result.videoinput+ : prevContentState.videoInput,defaultAudioInput:result.defaultAudioInput !== undefined &&result.defaultAudioInput !== nulldiff --git a/src/pages/Content/modal/Modal.jsx b/src/pages/Content/modal/Modal.jsxindex c750df5..3558f84 100644--- a/src/pages/Content/modal/Modal.jsx+++ b/src/pages/Content/modal/Modal.jsx@@ -56,16 +56,22 @@ const Modal = (props) => {});+ const closeModal = useCallback(() => {+ setShowModal(false);+ }, []);+useEffect(() => {setContentState((prevContentState) => ({...prevContentState,openModal: openModal,+ closeModal: closeModal,}));return () => {setContentState((prevContentState) => ({...prevContentState,openModal: null,+ closeModal: null,}));};}, []);diff --git a/src/pages/Content/popup/components/ApiIssueWarning.jsx b/src/pages/Content/popup/components/ApiIssueWarning.jsxnew file mode 100644index 0000000..f697efd--- /dev/null+++ b/src/pages/Content/popup/components/ApiIssueWarning.jsx@@ -0,0 +1,124 @@+import React, { useContext, useEffect, useRef, useState } from "react";++import { contentStateContext } from "../../context/ContentState";+import { apiIssueCopy } from "../../utils/apiIssueCopy";+import { NoInternet } from "../../toolbar/components/SVG";++const CLOUD_FEATURES_ENABLED =+ process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";++// Backs off so a long outage doesn't hammer the API, still recovers within+// seconds of the server coming back.+const RECHECK_DELAYS_MS = [5000, 10000, 20000, 30000];++// A verdict older than this proves nothing about right now, so the banner waits+// for a fresh check instead of reporting last night's outage.+const VERDICT_FRESH_MS = 60000;++const ApiIssueWarning = () => {+ const [contentState] = useContext(contentStateContext);+ const [checking, setChecking] = useState(false);+ const attemptsRef = useRef(0);++ const state = contentState.apiReachability;+ const at = contentState.apiReachabilityAt;+ const failing =+ // Free recording never touches the API, so this is only ever a Pro problem.+ CLOUD_FEATURES_ENABLED &&+ contentState.isLoggedIn &&+ contentState.isSubscribed &&+ state &&+ state !== "ok";+ // The browser's own offline flag needs no confirming. An API verdict does.+ const stale =+ failing &&+ state !== "offline" &&+ (!at || Date.now() - at > VERDICT_FRESH_MS);+ const blocking = failing && !stale;++ const runCheck = () =>+ new Promise((resolve) => {+ // The browser already knows it's offline, no point asking the network.+ if (navigator.onLine === false) {+ resolve();+ return;+ }+ setChecking(true);+ chrome.runtime.sendMessage({ type: "recheck-api-reachability" }, () => {+ // The verdict arrives as a storage change, this only clears the flag.+ if (chrome.runtime.lastError) {+ // The service worker was restarting. The next tick tries again.+ }+ setChecking(false);+ resolve();+ });+ });++ // Stale verdict: confirm it now rather than showing it. Nothing renders until+ // the answer lands, so a recovered API never gets accused on popup open.+ useEffect(() => {+ if (!stale) return;+ if (checking) return;+ runCheck();+ }, [stale]);++ useEffect(() => {+ if (!blocking) {+ attemptsRef.current = 0;+ return;+ }+ let cancelled = false;+ let timer = null;++ const schedule = () => {+ const delay =+ RECHECK_DELAYS_MS[+ Math.min(attemptsRef.current, RECHECK_DELAYS_MS.length - 1)+ ];+ timer = setTimeout(() => {+ attemptsRef.current += 1;+ runCheck().then(() => {+ if (!cancelled) schedule();+ });+ }, delay);+ };++ schedule();+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ }, [blocking, state]);++ if (!blocking) return null;++ const copy = apiIssueCopy(state);+ if (!copy) return null;++ return (+ <div className="popup-warning">+ <div className="popup-warning-left">+ <NoInternet />+ </div>+ <div className="popup-warning-middle">+ <div className="popup-warning-title">{copy.title}</div>+ <div className="popup-warning-description">{copy.description}</div>+ </div>+ <div className="popup-warning-right">+ <a+ href="#"+ onClick={(e) => {+ e.preventDefault();+ if (checking) return;+ attemptsRef.current = 0;+ runCheck();+ }}+ >+ {chrome.i18n.getMessage("offlineLabelTryAgain")}+ </a>+ </div>+ </div>+ );+};++export default ApiIssueWarning;diff --git a/src/pages/Content/popup/components/Dropdown.jsx b/src/pages/Content/popup/components/Dropdown.jsxindex 902b27f..8aa1428 100644--- a/src/pages/Content/popup/components/Dropdown.jsx+++ b/src/pages/Content/popup/components/Dropdown.jsx@@ -165,6 +165,14 @@ const Dropdown = (props) => {};const clickedIcon = useRef(false);+ // Guards onOpenChange while the icon handles its own click. Cleared next tick+ // because onClick runs after onMouseUp, which left the flag stuck true.+ const guardIconClick = () => {+ clickedIcon.current = true;+ setTimeout(() => {+ clickedIcon.current = false;+ }, 0);+ };return (<Select.Root@@ -260,7 +268,7 @@ const Dropdown = (props) => {e.stopPropagation();e.preventDefault();setOpen(false);- clickedIcon.current = true;+ guardIconClick();}}onMouseDown={(e) => {e.stopPropagation();@@ -278,7 +286,7 @@ const Dropdown = (props) => {e.stopPropagation();setOpen(false);toggleActive(e);- clickedIcon.current = true;+ guardIconClick();}}onMouseDown={(e) => {e.stopPropagation();diff --git a/src/pages/Content/popup/layout/RecordingType.jsx b/src/pages/Content/popup/layout/RecordingType.jsxindex f6bcbf9..f08172e 100644--- a/src/pages/Content/popup/layout/RecordingType.jsx+++ b/src/pages/Content/popup/layout/RecordingType.jsx@@ -9,8 +9,9 @@ import { CameraOffBlue, MicOffBlue } from "../../images/popup/images";import TooltipWrap from "../components/TooltipWrap";import BackgroundEffects from "../components/BackgroundEffects";+import ApiIssueWarning from "../components/ApiIssueWarning";-import { AlertIcon, TimeIcon, NoInternet } from "../../toolbar/components/SVG";+import { AlertIcon, TimeIcon } from "../../toolbar/components/SVG";const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";@@ -131,22 +132,7 @@ const RecordingType = (props) => {</div></div>)}- {/*contentState.offline && (- <div className="popup-warning">- <div className="popup-warning-left">- <NoInternet />- </div>- <div className="popup-warning-middle">- <div className="popup-warning-title">You are currently offline</div>- <div className="popup-warning-description">- Some features are unavailable- </div>- </div>- <div className="popup-warning-right">- <a href="#">Try again</a>- </div>- </div>- )*/}+ <ApiIssueWarning />{!cropActive &&contentState.recordingType === "region" &&!contentState.offline && (diff --git a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx b/src/pages/Content/toolbar/layout/ToolbarWrap.jsxindex d836341..df72349 100644--- a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx+++ b/src/pages/Content/toolbar/layout/ToolbarWrap.jsx@@ -374,6 +374,7 @@ const ToolbarWrap = () => {setContentState((prevContentState) => ({...prevContentState,pipEnded: true,+ pipActive: false,}));};diff --git a/src/pages/Content/utils/apiIssueCopy.js b/src/pages/Content/utils/apiIssueCopy.jsnew file mode 100644index 0000000..7451e11--- /dev/null+++ b/src/pages/Content/utils/apiIssueCopy.js@@ -0,0 +1,23 @@+// Only the browser's own offline flag lets us blame the user's connection.+// Every other state names our end or stays neutral about whose end broke.+export const apiIssueCopy = (state) => {+ if (state === "offline") {+ return {+ title: chrome.i18n.getMessage("offlineLabelTitle"),+ description: chrome.i18n.getMessage("offlineLabelDescription"),+ };+ }+ if (state === "server") {+ return {+ title: chrome.i18n.getMessage("serverIssueTitle"),+ description: chrome.i18n.getMessage("serverIssueDescription"),+ };+ }+ if (state === "unreachable") {+ return {+ title: chrome.i18n.getMessage("serverUnreachableTitle"),+ description: chrome.i18n.getMessage("serverUnreachableDescription"),+ };+ }+ return null;+};diff --git a/src/pages/Download/Download.jsx b/src/pages/Download/Download.jsxindex 576ef79..0342dfd 100644--- a/src/pages/Download/Download.jsx+++ b/src/pages/Download/Download.jsx@@ -3,6 +3,11 @@ import React, { useState, useCallback, useEffect } from "react";import localforage from "localforage";import { openExistingChunksStore } from "../CloudRecorder/recorderStorage/chooseChunksStore";import { destroySessionDir } from "../CloudRecorder/recorderStorage/opfsKvStore";+import {+ MP4_CONTAINER,+ containerFromMime,+ containerFromFileName,+} from "../utils/downloadContainer";localforage.config({driver: localforage.INDEXEDDB,@@ -10,8 +15,8 @@ localforage.config({version: 1,});-// Default IDB instances for legacy paths (recover-indexed-db, recover-indexed-db-mp4)-// that don't go through CloudRecorder's per-session backend choice.+// 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" });const cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });const audioChunksStore = localforage.createInstance({ name: "audioChunks" });@@ -69,26 +74,6 @@ const Download = () => {URL.revokeObjectURL(url);window.close();});- } else if (message.type === "recover-indexed-db") {- const chunkArray = [];- chunksStore- .iterate((value, key, iterationNumber) => {- chunkArray.push(value.chunk);- })- .then(() => {- const blob = new Blob(chunkArray, { type: "video/webm" });- const url = URL.createObjectURL(blob);- chrome.downloads- .download({- url: url,- filename: "recovered-video.webm",- saveAs: true,- })- .then(() => {- URL.revokeObjectURL(url);- window.close();- });- });} else if (message.type === "recover-cloud-indexed-db") {(async () => {const ts = new Date().toISOString().replace(/[:.]/g, "-");@@ -128,7 +113,7 @@ const Download = () => {// Per-track container drives the recovery-file extension. Sessions// recorded under WebCodecs put screen+camera in fragmented MP4;- // older / fallback sessions stay on WebM. Audio stays on WebM.+ // older / fallback sessions stay on WebM. Audio is mp4 or webm.const containers = prefetchedSession?.trackContainers || {screen: "video/webm",camera: "video/webm",@@ -138,7 +123,8 @@ const Download = () => {c === "video/mp4" ? "mp4" : "webm";const screenExt = containerToExt(containers.screen);const cameraExt = containerToExt(containers.camera);- const audioExt = "webm";+ const audioIsMp4 = containers.audio === "audio/mp4";+ const audioExt = audioIsMp4 ? "m4a" : "webm";// Clear only tracks that actually downloaded — without this a// failing track keeps ALL chunks, so retry re-downloads the@@ -183,7 +169,12 @@ const Download = () => {containers.camera || "video/webm",cameraExt,);- await downloadTrack(audioStore, "Audio", "audio/webm", audioExt);+ await downloadTrack(+ audioStore,+ "Audio",+ audioIsMp4 ? "audio/mp4" : "audio/webm",+ audioExt,+ );// Let the download manager fetch the blob URLs first.await new Promise((r) => setTimeout(r, 2000));@@ -260,6 +251,7 @@ const Download = () => {// modal silently failed.(async () => {let blob = null;+ let container = MP4_CONTAINER;try {const { lastRecordingBackendRef } = await chrome.storage.local.get(["lastRecordingBackendRef",@@ -275,7 +267,11 @@ const Download = () => {);const file = await handle.getFile();if (file && file.size > 0) {- blob = new Blob([file], { type: "video/mp4" });+ container = containerFromFileName(+ lastRecordingBackendRef.fileName,+ MP4_CONTAINER,+ );+ blob = new Blob([file], { type: container.mime });}} catch (err) {console.warn(@@ -293,9 +289,13 @@ const Download = () => {});chunkArray.sort((a, b) => a.index - b.index);if (chunkArray.length > 0) {+ container = containerFromMime(+ chunkArray[0]?.chunk?.type,+ MP4_CONTAINER,+ );blob = new Blob(chunkArray.map((entry) => entry.chunk),- { type: "video/mp4" },+ { type: container.mime },);}}@@ -308,7 +308,7 @@ const Download = () => {return;}const url = URL.createObjectURL(blob);- const filename = `screenity-recording-${Date.now()}.mp4`;+ const filename = `screenity-recording-${Date.now()}.${container.ext}`;try {await chrome.downloads.download({url,diff --git a/src/pages/Editor/mediabunny/lib/videoConverter.ts b/src/pages/Editor/mediabunny/lib/videoConverter.tsindex 0f9b9f2..2264d25 100644--- a/src/pages/Editor/mediabunny/lib/videoConverter.ts+++ b/src/pages/Editor/mediabunny/lib/videoConverter.ts@@ -20,6 +20,9 @@ export interface ConversionOptions {preferredVideoCodec?: VideoCodec;audioCodec?: AudioCodec;onProgress?: (progress: number) => void;+ // Fires when the source had audio the output can't hold, so the caller can+ // fall back instead of shipping a silent file.+ onAudioDropped?: (reason: string, codec: string) => void;verbose?: boolean;// When provided (e.g. a StreamTarget writing to OPFS), output streams to it// and convert() resolves to null; the caller owns the written file. Used by@@ -76,13 +79,13 @@ export class VideoConverter {async canEncodeCodec(codec: VideoCodec): Promise<boolean> {if (typeof VideoEncoder === "undefined") return false;- try {- const testConfig = this.getEncoderConfig(codec);- const support = await VideoEncoder.isConfigSupported(testConfig);- return support.supported ?? false;- } catch {- return false;+ for (const testConfig of this.getEncoderConfigs(codec)) {+ try {+ const support = await VideoEncoder.isConfigSupported(testConfig);+ if (support.supported) return true;+ } catch {}}+ return false;}clearCache(): void {@@ -101,6 +104,7 @@ export class VideoConverter {preferredVideoCodec,audioCodec,onProgress,+ onAudioDropped,} = options;const cache = targetFormat === "mp4" ? this.cachedMP4Codec : this.cachedWebMCodec;@@ -144,6 +148,17 @@ export class VideoConverter {audio: { codec: finalAudioCodec, bitrate: audioBitrate },});+ // mediabunny reports a conversion valid while silently discarding audio.+ // Its own warning prints "[object Object]", so serialize the real reason.+ if (onAudioDropped) {+ const dropped = conversion.discardedTracks.find(+ (t) => t.track.type === "audio"+ );+ if (dropped) {+ onAudioDropped(String(dropped.reason), String(dropped.track.codec));+ }+ }+if (!conversion.isValid) {const reasons = conversion.discardedTracks.map((t) => `${t.track.type}: ${t.reason}`)@@ -166,15 +181,19 @@ export class VideoConverter {});}- private getEncoderConfig(codec: VideoCodec): VideoEncoderConfig {+ private getEncoderConfigs(codec: VideoCodec): VideoEncoderConfig[] {const baseConfig = { width: 1920, height: 1080, bitrate: 5_000_000 };switch (codec) {+ // Trailing byte is the H.264 level. Level 3.0 (1E) tops out near 720x576,+ // so probing at 1080p always failed into HEVC on macOS, VP9 on Linux.case "avc":- return { ...baseConfig, codec: "avc1.42E01E" };+ return ["avc1.64002A", "avc1.4D401F", "avc1.42E01E", "avc1.42001F"].map(+ (c) => ({ ...baseConfig, codec: c })+ );case "hevc":- return { ...baseConfig, codec: "hev1.1.6.L93.B0" };+ return [{ ...baseConfig, codec: "hev1.1.6.L93.B0" }];default:- return { ...baseConfig, codec };+ return [{ ...baseConfig, codec }];}}}diff --git a/src/pages/EditorApp/context/ContentState.jsx b/src/pages/EditorApp/context/ContentState.jsxindex e412802..e9ec871 100644--- a/src/pages/EditorApp/context/ContentState.jsx+++ b/src/pages/EditorApp/context/ContentState.jsx@@ -3152,8 +3152,13 @@ const ContentState = (props) => {const outputBlob = new Blob([file], {type: kind === "webm" ? "video/webm" : "video/mp4",});- devLog("offscreen-remux-ok", { outputBytes: outputBlob.size });- return outputBlob;+ devLog("offscreen-remux-ok", {+ outputBytes: outputBlob.size,+ audioCarried: response.audioCarried,+ });+ // audioCarried is undefined on the paths that don't measure it, so only+ // an explicit false counts as a drop.+ return { blob: outputBlob, audioCarried: response.audioCarried };} finally {chrome.runtime.onMessage.removeListener(progressListener);// never delete the recording itself@@ -3242,10 +3247,11 @@ const ContentState = (props) => {let remuxPath = null;try {diagForward("remux-offscreen-start", { inputBytes: inputSize });- remuxedBlob = await runRemuxWithStallGuard(+ const offscreen = await runRemuxWithStallGuard((pg) => remuxViaOffscreenOpfs(blob, pg),sharedFinalizeProgress,);+ remuxedBlob = offscreen?.blob || null;remuxPath = "offscreen-opfs";diagForward("remux-offscreen-ok", { inputBytes: inputSize });} catch (err) {@@ -3305,15 +3311,20 @@ const ContentState = (props) => {);diagForward("editor-transcode-ok", {inputBytes,- outputBytes: out?.size || 0,+ outputBytes: out?.blob?.size || 0,+ audioCarried: out?.audioCarried,});- return { blob: out, path: "webm-transcode" };+ return {+ blob: out?.blob || null,+ path: "webm-transcode",+ audioCarried: out?.audioCarried,+ };} catch (err) {diagForward("editor-transcode-fail", {inputBytes,reason: String(err?.message || err).slice(0, 120),});- return { blob: null, path: null };+ return { blob: null, path: null, audioCarried: null };}};@@ -3321,7 +3332,8 @@ const ContentState = (props) => {// an edit (which produces a new blob) re-finalizes.const ensureStandardMp4 = () => {const blob = contentStateRef.current?.blob;- if (!blob) return Promise.resolve({ blob: null, path: null });+ if (!blob)+ return Promise.resolve({ blob: null, path: null, audioCarried: null });if (blob.type !== "video/mp4") {const cur = standardMp4Ref.current;if (cur && cur.forBlob === blob && cur.status !== "failed") {@@ -3334,6 +3346,7 @@ const ContentState = (props) => {forBlob: blob,blob: res.blob,path: res.path,+ audioCarried: res.audioCarried,};return res;});@@ -3429,6 +3442,7 @@ const ContentState = (props) => {const remuxStartedAt = Date.now();let remuxedBlob = null;let remuxPath = null;+ let audioDropped = false;// Reuse the background pre-warm if it finished (instant) or is in flight// (await it); otherwise this runs the finalize now. Keyed on the blob, so@@ -3437,6 +3451,12 @@ const ContentState = (props) => {const res = await ensureStandardMp4();remuxedBlob = res.blob;remuxPath = res.path;+ // Transcode lost the audio, so the MP4 would be silent. Fall back to+ // the source, which still has sound.+ if (res?.audioCarried === false) {+ audioDropped = true;+ remuxedBlob = null;+ }} catch (err) {console.warn("[Screenity] standard mp4 finalize failed", err);}@@ -3464,7 +3484,22 @@ const ContentState = (props) => {if (downloadCancelledRef.current) return;try {- if (remuxedBlob) {+ if (audioDropped) {+ // Source keeps its real extension. WebM bytes named .mp4 won't open in+ // QuickTime.+ const fallbackBlob = contentState.blob;+ const fallbackExt = String(fallbackBlob?.type || "").includes("webm")+ ? ".webm"+ : ".mp4";+ const url = URL.createObjectURL(fallbackBlob);+ await requestDownload(url, fallbackExt);+ URL.revokeObjectURL(url);+ setContentState((prev) => ({ ...prev, saved: true }));+ diagForward("editor-audio-dropped-fallback", {+ inputBytes: inputSize,+ ext: fallbackExt,+ });+ } else if (remuxedBlob) {const url = URL.createObjectURL(remuxedBlob);await requestDownload(url, ".mp4");URL.revokeObjectURL(url);@@ -3602,7 +3637,7 @@ const ContentState = (props) => {if (ENABLE_OFFSCREEN_WEBM) {let webmBlob = null;try {- webmBlob = await runRemuxWithStallGuard(+ const out = await runRemuxWithStallGuard((pg) => remuxViaOffscreenOpfs(sourceBlob, pg, "webm"),(p) =>setContentState((prev) => ({@@ -3610,6 +3645,7 @@ const ContentState = (props) => {processingProgress: Math.round(p * 100),})),);+ webmBlob = out?.blob || null;} catch (err) {console.warn("[Screenity] offscreen webm convert failed, falling back",diff --git a/src/pages/EditorApp/editorOps.js b/src/pages/EditorApp/editorOps.jsindex a019027..a7804f4 100644--- a/src/pages/EditorApp/editorOps.js+++ b/src/pages/EditorApp/editorOps.js@@ -7,12 +7,29 @@ import { fixWebmDurationOffThread } from "../Editor/utils/fixWebmDurationOffThreconst lazyUtil = (importFn) =>(...args) =>importFn().then((m) => m.default(...args));-const addAudioToVideo = lazyUtil(() => import("../Editor/utils/addAudioToVideo"));-const convertWebmToMp4 = lazyUtil(() => import("../Editor/utils/convertWebmToMp4"));-const cropVideo = lazyUtil(() => import("../Editor/utils/cropVideo"));-const cutVideo = lazyUtil(() => import("../Editor/utils/cutVideo"));-const muteVideo = lazyUtil(() => import("../Editor/utils/muteVideo"));-const reencodeVideo = lazyUtil(() => import("../Editor/utils/reencodeVideo"));+// These ops write MP4 audio, which must be AAC. Linux browsers have none, so+// the wasm encoder is registered here, best-effort.+const lazyMp4Util = (importFn) =>+ async (...args) => {+ try {+ const { ensureAacEncoder } = await import("../utils/aacPolyfill");+ await ensureAacEncoder();+ } catch {}+ const m = await importFn();+ return m.default(...args);+ };+const addAudioToVideo = lazyMp4Util(() =>+ import("../Editor/utils/addAudioToVideo"),+);+const convertWebmToMp4 = lazyMp4Util(() =>+ import("../Editor/utils/convertWebmToMp4"),+);+const cropVideo = lazyMp4Util(() => import("../Editor/utils/cropVideo"));+const cutVideo = lazyMp4Util(() => import("../Editor/utils/cutVideo"));+const muteVideo = lazyMp4Util(() => import("../Editor/utils/muteVideo"));+const reencodeVideo = lazyMp4Util(() =>+ import("../Editor/utils/reencodeVideo"),+);const toGIF = lazyUtil(() => import("../Editor/utils/toGIF"));const getFrame = lazyUtil(() => import("../Editor/utils/getFrame"));const convertMp4ToWebm = lazyUtil(() => import("../Editor/utils/convertMp4ToWebm"));diff --git a/src/pages/OffscreenRecorder/resumeJournal.js b/src/pages/OffscreenRecorder/resumeJournal.jsindex f85b927..448ebd2 100644--- a/src/pages/OffscreenRecorder/resumeJournal.js+++ b/src/pages/OffscreenRecorder/resumeJournal.js@@ -1,5 +1,7 @@import localforage from "localforage";import BunnyTusUploader from "../CloudRecorder/bunnyTusUploader";+import { getClientSessionId } from "../CloudRecorder/clientSessionId";+import { TRACK_KEY_PREFIX } from "../CloudRecorder/recorderStorage/chooseChunksStore";import { openExistingChunksStore } from "../CloudRecorder/recorderStorage/chooseChunksStore";localforage.config({@@ -10,8 +12,10 @@ localforage.config({const JOURNAL_KEY_PREFIX = "uploadJournal-";+// 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.const trackName = (trackType) =>- trackType === "camera" ? "camera" : "screen";+ trackType === "camera" || trackType === "audio" ? trackType : "screen";// Pulls per-journal storage backend from the persisted recorder session.// Journals written before the OPFS migration default to IDB. The uploader@@ -56,7 +60,7 @@ const resolveBackendForJournal = async (journal) => {};const chunkKeyPrefixForTrack = (trackType) =>- trackType === "camera" ? "camera_chunk_" : "chunk_";+ TRACK_KEY_PREFIX[trackType] || "chunk_";const loadChunksSorted = async (store, prefix = "chunk_") => {const items = [];@@ -170,7 +174,10 @@ export const resumeOneJournal = async (journal) => {return { ok: false, error: "chunks-missing" };}- const uploader = new BunnyTusUploader({ trackType });+ const uploader = new BunnyTusUploader({+ trackType,+ clientSessionId: getClientSessionId(),+ });try {await uploader.initialize(projectId, {diff --git a/src/pages/Permissions/Permissions.jsx b/src/pages/Permissions/Permissions.jsxindex 68a14bb..8315fd0 100644--- a/src/pages/Permissions/Permissions.jsx+++ b/src/pages/Permissions/Permissions.jsx@@ -77,120 +77,143 @@ const Recorder = () => {// permissions.query() asks the iframe's own origin and reports// "prompt"/"denied" even when getUserMedia would succeed via- // the parent's `allow="camera *; microphone *"`. Probe directly.- try {- const probeStream = await navigator.mediaDevices.getUserMedia({- audio: true,- video: true,- });- // It worked; clean up the probe tracks immediately. The- // subsequent enumerateDevices() call will request its own- // stream when it actually needs the data; this probe was just- // a permission test.- probeStream.getTracks().forEach((t) => t.stop());- enumerateDevices(true, true);- return;- } catch (probeErr) {- // Real permission failure (NotAllowedError, NotFoundError if- // no devices, NotReadableError if device in use). Surface- // the modal.- window.parent.postMessage(- {- type: "screenity-permissions",- success: false,- error: probeErr?.name || "unknown",- },- "*"- );- }+ // the parent's `allow="camera *; microphone *"`. Probing is left+ // to enumerateDevices, which tries each kind on its own.+ await enumerateDevices(true, true);} catch (err) {enumerateDevices();}};+ // Bluetooth/USB devices report NotReadableError for a second or two after+ // wake, and the camera preview can hold the device while we probe.+ const TRANSIENT = new Set(["NotReadableError", "AbortError"]);+ const openStream = async (constraints) => {+ for (let attempt = 0; attempt < 2; attempt += 1) {+ try {+ return {+ stream: await navigator.mediaDevices.getUserMedia(constraints),+ };+ } catch (err) {+ if (attempt === 0 && TRANSIENT.has(err?.name)) {+ await new Promise((resolve) => setTimeout(resolve, 400));+ continue;+ }+ return { error: err };+ }+ }+ return { error: new Error("unreachable") };+ };+const enumerateDevices = async (camGranted = true, micGranted = true) => {- try {- const stream = await navigator.mediaDevices.getUserMedia({- audio: micGranted,- video: camGranted,- });+ const streams = [];+ let camOk = false;+ let micOk = false;+ let lastError = null;++ if (camGranted && micGranted) {+ const { stream, error } = await openStream({ audio: true, video: true });+ if (stream) {+ streams.push(stream);+ camOk = true;+ micOk = true;+ } else {+ lastError = error;+ }+ }- const devicesInfo = await navigator.mediaDevices.enumerateDevices();-- let audioinput = [];- let audiooutput = [];- let videoinput = [];-- if (micGranted) {- // Filter by audio input- audioinput = devicesInfo- .filter((device) => device.kind === "audioinput")- .map((device) => ({- deviceId: device.deviceId,- label: device.label,- }));-- // Filter by audio output and extract relevant properties- audiooutput = devicesInfo- .filter((device) => device.kind === "audiooutput")- .map((device) => ({- deviceId: device.deviceId,- label: device.label,- }));+ // A combined request fails outright when either device is missing or busy,+ // so retry each kind alone. A denial covers both, so skip re-asking.+ const denied = lastError?.name === "NotAllowedError";++ if (camGranted && !camOk && !denied) {+ const { stream, error } = await openStream({ video: true });+ if (stream) {+ streams.push(stream);+ camOk = true;+ } else {+ lastError = error || lastError;+ }+ }+ if (micGranted && !micOk && !denied) {+ const { stream, error } = await openStream({ audio: true });+ if (stream) {+ streams.push(stream);+ micOk = true;+ } else {+ lastError = error || lastError;}+ }- if (camGranted) {- // Filter by video input and extract relevant properties- videoinput = devicesInfo- .filter((device) => device.kind === "videoinput")- .map((device) => ({- deviceId: device.deviceId,- label: device.label,- }));+ let devicesInfo = [];+ try {+ devicesInfo = await navigator.mediaDevices.enumerateDevices();+ // Chrome's device list lags the grant, so an empty answer for a kind we+ // hold a live stream for is worth one more look.+ const missingGranted = () =>+ (camOk && !devicesInfo.some((d) => d.kind === "videoinput")) ||+ (micOk && !devicesInfo.some((d) => d.kind === "audioinput"));+ if (missingGranted()) {+ await new Promise((r) => setTimeout(r, 300));+ devicesInfo = await navigator.mediaDevices.enumerateDevices();}+ } catch (err) {+ lastError = err;+ }- // Save in Chrome local storage- chrome.storage.local.set({- // Set available devices- audioinput: audioinput,- audiooutput: audiooutput,- videoinput: videoinput,- cameraPermission: camGranted,- microphonePermission: micGranted,- });+ const pick = (kind) =>+ devicesInfo+ .filter((device) => device.kind === kind)+ .map((device) => ({+ deviceId: device.deviceId,+ label: device.label,+ }));- // Post message to parent window- window.parent.postMessage(- {- type: "screenity-permissions",- success: true,- audioinput: audioinput,- audiooutput: audiooutput,- videoinput: videoinput,- cameraPermission: camGranted,- microphonePermission: micGranted,- },- "*"- );+ // Labels only appear once the permission is granted, so a labelled list+ // proves the grant even when the stream just failed as busy.+ const hasLabels = (kind) =>+ devicesInfo.some((device) => device.kind === kind && device.label);+ camOk = camOk || (camGranted && hasLabels("videoinput"));+ micOk = micOk || (micGranted && hasLabels("audioinput"));- //sendResponse({ success: true, audioinput, audiooutput, videoinput });+ streams.forEach((stream) => stream.getTracks().forEach((t) => t.stop()));- // End the stream- stream.getTracks().forEach(function (track) {- track.stop();- });- } catch (err) {- // Post message to parent window+ if (!camOk && !micOk) {window.parent.postMessage({type: "screenity-permissions",success: false,- error: err.name,+ error: lastError?.name || "unknown",},"*");- //sendResponse({ success: false, error: err.name });+ return;}++ const audioinput = micOk ? pick("audioinput") : [];+ const audiooutput = micOk ? pick("audiooutput") : [];+ const videoinput = camOk ? pick("videoinput") : [];++ chrome.storage.local.set({+ audioinput: audioinput,+ audiooutput: audiooutput,+ videoinput: videoinput,+ cameraPermission: camOk,+ microphonePermission: micOk,+ });++ window.parent.postMessage(+ {+ type: "screenity-permissions",+ success: true,+ audioinput: audioinput,+ audiooutput: audiooutput,+ videoinput: videoinput,+ cameraPermission: camOk,+ microphonePermission: micOk,+ },+ "*"+ );};const onMessage = (message) => {diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex df8df21..a4398e1 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -48,6 +48,7 @@ import { chooseWriter } from "./recorderStorage/chooseWriter";import { chooseReader } from "./recorderStorage/chooseReader";import { lifecycle } from "../utils/lifecycleLog";import { perfMark, perfSpan } from "../utils/perfMarks";+import { markStartProgress } from "../utils/startProgress";import {debugRecordingEvent,resetRecordingDebugSession,@@ -1332,6 +1333,7 @@ const Recorder = () => {}perfMark("Recorder.preflight.enter");+ markStartProgress("preflight-enter");const endChunksClear = perfSpan("Recorder.preflight chunksStore.clear");if (prewarmChunksClearRef.current) {await prewarmChunksClearRef.current;@@ -1404,11 +1406,13 @@ const Recorder = () => {// guess could disagree with the probe and leave bytes the editor// can't read. Parallel probe + storage reads drop preflight from// ~340ms to <50ms on cache hit.+ markStartProgress("encoder-probe");const [userSettingRaw, stickyState, probeResult] = await Promise.all([chrome.storage.local.get(["useWebCodecsRecorder"]),getFastRecorderStickyState(),probeFastRecorderSupport(),]);+ markStartProgress("encoder-probe-done");const userSetting = resolveFastRecorderUserSetting(userSettingRaw.useWebCodecsRecorder,);@@ -1505,6 +1509,7 @@ const Recorder = () => {} catch {}endBackendRefSet();perfMark("Recorder.preflight.done");+ markStartProgress("preflight-done");if (process.env.SCREENITY_DEV_MODE === "true") {console.log("[recorder-opfs][recorder] writer-open", {backend: selection.backend,@@ -2343,6 +2348,7 @@ const Recorder = () => {},});} catch {}+ markStartProgress("webcodecs-start");const ok = await recorder.current.start();debug("WebCodecsRecorder.start() result", ok);@@ -2519,6 +2525,7 @@ const Recorder = () => {})(),});};+ markStartProgress("mediarecorder-start");recorder.current.start(5000);debug("MediaRecorder.start(5000) called");@@ -2722,6 +2729,7 @@ const Recorder = () => {const isLikelyContinuityMic = /\biphone\b/i.test(trackLabel);const diagnosticInfo = {reason: "audio-track-ended",+ ts: Date.now(),savedChunks: savedCount.current,lastTimecode: lastTimecode.current,recordingDuration,@@ -2810,6 +2818,8 @@ const Recorder = () => {const track = liveStream.current?.getVideoTracks?.()[0] || null;const diagnosticInfo = {reason: "liveStream-video-track-ended",+ // BG start-fail re-check compares this against its dispatch time+ ts: Date.now(),savedChunks: savedCount.current,lastTimecode: lastTimecode.current,recordingDuration: recordingStartTime.current@@ -2844,6 +2854,7 @@ const Recorder = () => {// Log detailed diagnostics for debuggingconst diagnosticInfo = {reason: "helperVideoStream-video-track-ended",+ ts: Date.now(),savedChunks: savedCount.current,lastTimecode: lastTimecode.current,recordingDuration: recordingStartTime.currentdiff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.jsindex dc2197f..fa7db11 100644--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js@@ -1199,6 +1199,19 @@ export class WebCodecsRecorder {this._stopping = false;}+ // cleanup() nulls _videoStartUs, so this reads null once it has run. The+ // finalize-time capture in WebCodecsTrackRecorder lands before that.+ _effectiveOutputFps() {+ if (this._videoStartUs == null || !(this.frameCount > 0)) return null;+ let pausedUs = this.totalPausedDurationUs || 0;+ if (this.paused && this.pauseStartUs != null) {+ pausedUs += performance.now() * 1000 - this.pauseStartUs;+ }+ const elapsedUs = performance.now() * 1000 - this._videoStartUs - pausedUs;+ if (!(elapsedUs > 0)) return null;+ return Math.round((this.frameCount / (elapsedUs / 1e6)) * 100) / 100;+ }+// Readable at any time: stop() early-returns once the recorder isn't// running, so onFinalized is missing on exactly the sessions worth// explaining (zero-frame exit, spent stall budget, failed start).@@ -1222,6 +1235,9 @@ export class WebCodecsRecorder {),// Submissions to encode(), not muxer output (that's chunksOut).framesEncoded: this.frameCount ?? null,+ // framesEncoded over elapsed capture time, pause excluded so a paused+ // session doesn't read as a slow encoder.+ effectiveOutputFps: this._effectiveOutputFps(),chunksOut: this._chunksOut ?? null,steadyQueueCap: this._encoderMaxQueueSize ?? null,// Drops inside the startup window were judged against this, not thediff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsxindex 49d6c47..ddd3e2d 100644--- a/src/pages/Region/Recorder.jsx+++ b/src/pages/Region/Recorder.jsx@@ -41,6 +41,7 @@ import { chooseWriter } from "../Recorder/recorderStorage/chooseWriter";import { chooseReader } from "../Recorder/recorderStorage/chooseReader";import { lifecycle } from "../utils/lifecycleLog";import { perfMark, perfSpan } from "../utils/perfMarks";+import { markStartProgress } from "../utils/startProgress";import localforage from "localforage";@@ -930,7 +931,11 @@ const Recorder = () => {]);const userSetting = resolveFastRecorderUserSetting(useWebCodecsRecorder);const stickyState = await getFastRecorderStickyState();+ // Keeps the BG start-fail re-check from tearing down a slow encoder+ // probe. Same heartbeat the tab/offscreen recorder writes.+ markStartProgress("encoder-probe");const probeResult = await probeFastRecorderSupport();+ markStartProgress("encoder-probe-done");const shouldUseFast = shouldUseFastRecorder(userSetting,probeResult,diff --git a/src/pages/RemuxOffscreen/index.js b/src/pages/RemuxOffscreen/index.jsindex d1cbfb5..f3f2269 100644--- a/src/pages/RemuxOffscreen/index.js+++ b/src/pages/RemuxOffscreen/index.js@@ -47,9 +47,15 @@ const ensureWorker = () => {devLog("worker-done", {requestId: msg.requestId,outputFileName: msg.outputFileName,+ audioCarried: msg.audioCarried,});pending.delete(msg.requestId);- entry?.sendResponse?.({ ok: true, outputFileName: msg.outputFileName });+ entry?.sendResponse?.({+ ok: true,+ outputFileName: msg.outputFileName,+ audioCarried: msg.audioCarried,+ aacPath: msg.aacPath,+ });return;}if (msg.type === "error") {diff --git a/src/pages/RemuxOffscreen/worker.js b/src/pages/RemuxOffscreen/worker.jsindex 99998a5..c12c5f8 100644--- a/src/pages/RemuxOffscreen/worker.js+++ b/src/pages/RemuxOffscreen/worker.js@@ -17,6 +17,7 @@ import {} from "mediabunny";import { createOpfsWritable } from "./opfsTarget";import { videoConverter } from "../Editor/mediabunny/lib/videoConverter";+import { ensureAacEncoder, getAacPath } from "../utils/aacPolyfill";const TEMP_FILE_PREFIX = "remux-";const STALE_AGE_MS = 5 * 60 * 1000;@@ -30,8 +31,16 @@ const postProgress = (requestId, progress) => {self.postMessage({ type: "progress", requestId, progress });};-const postDone = (requestId, outputFileName) => {- self.postMessage({ type: "done", requestId, outputFileName });+// audioCarried: false means the source had audio the output couldn't hold.+// null means nothing measured it, which the caller must not read as a drop.+const postDone = (requestId, outputFileName, audioCarried = null, aacPath = null) => {+ self.postMessage({+ type: "done",+ requestId,+ outputFileName,+ audioCarried,+ aacPath,+ });};const postError = (requestId, error) => {@@ -208,7 +217,11 @@ const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {if (videoResult.status === "rejected") {throw videoResult.reason;}+ // Callers discard on false, so null here lets a silent file through as+ // a success.+ let audioCarried = null;if (pipeResults[1].status === "rejected") {+ if (audioSource && audioTrack) audioCarried = false;devLog("audio-pipe-failed", {err: String(pipeResults[1].reason?.message || pipeResults[1].reason).slice(0, 200),});@@ -228,7 +241,7 @@ const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {durationMs: Date.now() - startedAt,outputBytes: finalSize,});- postDone(requestId, outputFileName);+ postDone(requestId, outputFileName, audioCarried);} catch (err) {devLog("error", {err: String(err?.message || err).slice(0, 200),@@ -289,9 +302,20 @@ const convertViaEncoder = async (const writable = createOpfsWritable(syncHandle);+ // Linux Chromium has no AAC encoder, so without the wasm one the MP4+ // comes back silent.+ if (targetFormat === "mp4") {+ await ensureAacEncoder();+ }++ let audioDropped = false;const convertOptions = {target: new StreamTarget(writable),onProgress: (p) => postProgress(requestId, p),+ onAudioDropped: (reason, codec) => {+ audioDropped = true;+ devLog(`${targetFormat}-audio-dropped`, { reason, codec });+ },};// Without this the converter falls back to its 5 Mbps default, which is a// 1080p figure: a 4K screencast came back visibly blocky on text.@@ -315,8 +339,14 @@ const convertViaEncoder = async (devLog(`${targetFormat}-done`, {durationMs: Date.now() - startedAt,outputBytes: finalSize,+ audioCarried: audioDropped ? false : null,});- postDone(requestId, outputFileName);+ postDone(+ requestId,+ outputFileName,+ audioDropped ? false : null,+ targetFormat === "mp4" ? getAacPath() : null,+ );} catch (err) {devLog(`${targetFormat}-error`, {err: String(err?.message || err).slice(0, 200),diff --git a/src/pages/utils/aacPolyfill.js b/src/pages/utils/aacPolyfill.jsnew file mode 100644index 0000000..716e429--- /dev/null+++ b/src/pages/utils/aacPolyfill.js@@ -0,0 +1,133 @@+// MP4 audio needs AAC and Linux Chromium ships no AAC encoder, so the MP4+// transcode drops the track and hands back a silent file. Polyfill it in wasm.+import {+ Input,+ Output,+ BufferTarget,+ BlobSource,+ Mp4OutputFormat,+ ALL_FORMATS,+ AudioSample,+ AudioSampleSource,+ canEncodeAudio,+} from "mediabunny";++// The polyfill spawns its worker from a blob URL. That works in MV3 today only+// because crbug/1504703 is unpatched, and a CSP block would hang, not throw.+const PROBE_TIMEOUT_MS = 8000;++const PROBE_SAMPLE_RATE = 48000;+const PROBE_CHANNELS = 2;+const PROBE_FRAMES = 1024;+const PROBE_CHUNKS = 4;++const devLog =+ process.env.SCREENITY_DEV_MODE === "true"+ ? (label, data) => console.log("[remux][aac]", label, data || "")+ : () => {};++let verdict = null;+let resolvedPath = "unresolved";++// Reported on the done message so a silent-audio report shows whether the+// wasm fallback ran at all.+export const getAacPath = () => resolvedPath;++// Encodes silence and reads it back: registerAacEncoder() succeeding proves+// nothing about the wasm worker actually coming up.+const probeAacEncoder = async () => {+ const target = new BufferTarget();+ const output = new Output({+ format: new Mp4OutputFormat({ fastStart: false }),+ target,+ });+ const source = new AudioSampleSource({ codec: "aac", bitrate: 128000 });+ output.addAudioTrack(source);+ await output.start();++ const silence = new Float32Array(PROBE_FRAMES * PROBE_CHANNELS);+ for (let i = 0; i < PROBE_CHUNKS; i += 1) {+ const sample = new AudioSample({+ data: silence,+ format: "f32",+ numberOfChannels: PROBE_CHANNELS,+ sampleRate: PROBE_SAMPLE_RATE,+ timestamp: (i * PROBE_FRAMES) / PROBE_SAMPLE_RATE,+ });+ await source.add(sample);+ sample.close();+ }++ await output.finalize();++ const buffer = target.buffer;+ if (!buffer || buffer.byteLength === 0) return false;++ const input = new Input({+ formats: ALL_FORMATS,+ source: new BlobSource(new Blob([buffer])),+ });+ const track = await input.getPrimaryAudioTrack().catch(() => null);+ return track?.codec === "aac";+};++// Machines with native AAC never reach the polyfill, so tests name the worker+// to exercise it anyway. Nothing in the extension sets this.+const FORCE_WORKER_NAME = "screenity-force-aac-polyfill";++// Worker realms only. A page's window.name is attacker-influenceable.+const isForced = () =>+ typeof WorkerGlobalScope !== "undefined" &&+ typeof self !== "undefined" &&+ self.name === FORCE_WORKER_NAME;++const resolveAacEncoder = async () => {+ const forced = isForced();+ try {+ if (!forced && (await canEncodeAudio("aac"))) {+ devLog("native");+ resolvedPath = "native";+ return true;+ }+ } catch {}++ try {+ const { registerAacEncoder } = await import("@mediabunny/aac-encoder");+ registerAacEncoder();+ } catch (err) {+ devLog("register-failed", {+ err: String(err?.message || err).slice(0, 200),+ });+ resolvedPath = "register-failed";+ return false;+ }++ let timer = null;+ try {+ // A blocked worker never settles, so the timeout is the only exit.+ const ok = await Promise.race([+ probeAacEncoder(),+ new Promise((resolve) => {+ timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);+ }),+ ]);+ devLog(ok ? "polyfill-ok" : "polyfill-unusable");+ resolvedPath = ok ? "polyfill" : "polyfill-unusable";+ return ok;+ } catch (err) {+ devLog("probe-failed", {+ err: String(err?.message || err).slice(0, 200),+ });+ resolvedPath = "probe-failed";+ return false;+ } finally {+ if (timer !== null) clearTimeout(timer);+ }+};++// Cached for the realm's lifetime: the result is device-global, and a failed+// probe must not be retried per download.+export const ensureAacEncoder = () => {+ if (!verdict) verdict = resolveAacEncoder();+ return verdict;+};diff --git a/src/pages/utils/buildDiagnosticZip.js b/src/pages/utils/buildDiagnosticZip.jsindex 2e960bf..f2a28bc 100644--- a/src/pages/utils/buildDiagnosticZip.js+++ b/src/pages/utils/buildDiagnosticZip.js@@ -66,6 +66,15 @@ const FAST_RECORDER_KEYS = ["lastFailedValidation","webcodecsConstructSnapshot","recorderStartTimings",+ // Names the startup step a dead start hung on.+ "recorderStartProgress",+ // Chunks and bytes captured so far. Splits a stuck UI from a dead start.+ "recorderLiveProgress",+ // offscreen-diag carries this too but is console-only, so a start that+ // died on stream acquisition was unreadable from a zip.+ "lastStreamAcquireError",+ // Which start-dispatch branch ran (offscreen gDM, pre-acquired tab, picker).+ "lastStartDispatchBranch","countdownFinishedAt","lastStartRecordingCaller","lastCountdownFinishedDecision",@@ -165,6 +174,9 @@ export const buildDiagnosticZip = async ({devicePixelRatio: window.devicePixelRatio,},deviceMemory: navigator.deviceMemory || null,+ // Tells a localhost dev build apart from a store build when a report says+ // an API call just failed to fetch.+ apiBase: process.env.SCREENITY_API_BASE_URL || null,});files["config.json"] = JSON.stringify({diff --git a/src/pages/utils/diagnosticLog.js b/src/pages/utils/diagnosticLog.jsindex f4c853f..4f4c625 100644--- a/src/pages/utils/diagnosticLog.js+++ b/src/pages/utils/diagnosticLog.js@@ -279,6 +279,7 @@ export const getStorageFlags = async () => {"isLoggedIn","isSubscribed","proSubscription",+ "apiReachability",];try {return await chrome.storage.local.get(keys);diff --git a/src/pages/utils/downloadContainer.js b/src/pages/utils/downloadContainer.jsnew file mode 100644index 0000000..f302c65--- /dev/null+++ b/src/pages/utils/downloadContainer.js@@ -0,0 +1,25 @@+// Salvage-download bytes can be WebM even on the mp4 branch: the encoder probe+// falls back to VP9/Opus without a viable H.264/AAC config. Chrome and VLC+// sniff a mislabelled file, QuickTime and Windows Media Player refuse it.++export const MP4_CONTAINER = { mime: "video/mp4", ext: "mp4" };+export const WEBM_CONTAINER = { mime: "video/webm", ext: "webm" };++// MediaRecorder blob types carry a codecs suffix (video/webm;codecs=vp9,opus).+export const containerFromMime = (mime, fallback) => {+ const base = String(mime || "")+ .split(";")[0]+ .trim()+ .toLowerCase();+ if (base === "video/mp4") return MP4_CONTAINER;+ if (base === "video/webm") return WEBM_CONTAINER;+ return fallback;+};++// The OPFS writer names the file with the extension it actually wrote.+export const containerFromFileName = (name, fallback) => {+ const lower = String(name || "").toLowerCase();+ if (lower.endsWith(".webm")) return WEBM_CONTAINER;+ if (lower.endsWith(".mp4")) return MP4_CONTAINER;+ return fallback;+};diff --git a/src/pages/utils/startProgress.js b/src/pages/utils/startProgress.jsnew file mode 100644index 0000000..5d0b8d9--- /dev/null+++ b/src/pages/utils/startProgress.js@@ -0,0 +1,10 @@+// Stage heartbeat for the BG start-fail re-check. Startup outlasts one window+// on a slow encoder probe, and the background reads that silence as a dead+// recorder and tears the start down.+export function markStartProgress(stage) {+ try {+ chrome.storage.local.set({+ recorderStartProgress: { ts: Date.now(), stage },+ });+ } catch {}+}diff --git a/webpack.config.js b/webpack.config.jsindex d05fb8e..0f9f776 100755--- a/webpack.config.js+++ b/webpack.config.js@@ -105,13 +105,12 @@ const entryPoints = {"RemuxOffscreen","index.js"),- remuxworker: path.join(- __dirname,- "src",- "pages",- "RemuxOffscreen",- "worker.js"- ),+ // chunkLoading: a worker has no document, so the default DOM script-tag+ // loader would throw on the lazy AAC encoder import.+ remuxworker: {+ import: path.join(__dirname, "src", "pages", "RemuxOffscreen", "worker.js"),+ chunkLoading: "import-scripts",+ },recorderopfsworker: path.join(__dirname,"src",