The free and privacy-friendly screen recorder with no limits 🎥
JavaScript annotationannotation-toolaudiocamerachrome-extensiondesigneditorffmpegjavascriptproductivityrecorderscreen-capturescreen-recorderscreencasttensorflowvideo
Cloud recorder reliability + opfs + tooling
Alyssa X71ebdff6cc4a
diff --git a/.gitignore b/.gitignoreindex c9833dc..6e4d643 100644--- a/.gitignore+++ b/.gitignore@@ -12,5 +12,10 @@ node_modules/.env.production.env.*.localbuild/+*.zip+.cws-credentials.jsondocs/-tools/\ No newline at end of file+tests/+test-results/+playwright-report/+tools/diagnostics-viewer/diff --git a/package-lock.json b/package-lock.jsonindex 4f0ac07..3667e5d 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "screenity",- "version": "4.3.0",+ "version": "4.4.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "screenity",- "version": "4.3.0",+ "version": "4.4.0","hasInstallScript": true,"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",@@ -59,9 +59,11 @@"@babel/plugin-transform-runtime": "^7.27.1","@babel/preset-env": "^7.20.2","@babel/preset-react": "^7.27.1",+ "@playwright/test": "^1.59.1","@types/react": "^18.3.21","@types/react-dom": "^18.3.7","babel-loader": "^9.1.3",+ "browserstack-local": "^1.5.13","copy-webpack-plugin": "^7.0.0","cross-env": "^7.0.3","css-loader": "^6.7.2",@@ -71,6 +73,7 @@"prettier": "^2.7.1","sass": "^1.97.3","sass-loader": "^16.0.7",+ "selenium-webdriver": "^4.43.0","source-map-loader": "^3.0.1","style-loader": "^3.3.1","stylelint": "^17.8.0",@@ -1615,6 +1618,13 @@"node": ">=6.9.0"}},+ "node_modules/@bazel/runfiles": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/@bazel/runfiles/-/runfiles-6.5.0.tgz",+ "integrity": "sha512-RzahvqTkfpY2jsDxo8YItPX+/iZ6hbiikw1YhE0bA9EKBR5Og8Pa6FHn9PO9M0zaXRVsr0GFQLKbB/0rzy9SzA==",+ "dev": true,+ "license": "Apache-2.0"+ },"node_modules/@cacheable/memory": {"version": "2.0.8","resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.0.8.tgz",@@ -2317,6 +2327,22 @@"node": ">=0.10"}},+ "node_modules/@playwright/test": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz",+ "integrity": "sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright": "1.59.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/@radix-ui/number": {"version": "1.0.1","resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.0.1.tgz",@@ -4617,7 +4643,7 @@"version": "6.0.2","resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz","integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",- "optional": true,+ "devOptional": true,"dependencies": {"debug": "4"},@@ -5070,6 +5096,19 @@"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"}},+ "node_modules/browserstack-local": {+ "version": "1.5.13",+ "resolved": "https://registry.npmjs.org/browserstack-local/-/browserstack-local-1.5.13.tgz",+ "integrity": "sha512-7helY+Ms3ss4BtIQZTIyshdAFZSvS9A7ZpEB9stRaobeZ9BM1BkJFTuMakQNTOj78llv0+/qDI5Ak+bkGWV1xg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "agent-base": "^6.0.2",+ "https-proxy-agent": "^5.0.1",+ "is-running": "^2.1.0",+ "tree-kill": "^1.2.2"+ }+ },"node_modules/buffer": {"version": "6.0.3","resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",@@ -7429,7 +7468,7 @@"version": "5.0.1","resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz","integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",- "optional": true,+ "devOptional": true,"dependencies": {"agent-base": "6","debug": "4"@@ -7820,6 +7859,13 @@"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==","optional": true},+ "node_modules/is-running": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/is-running/-/is-running-2.1.0.tgz",+ "integrity": "sha512-mjJd3PujZMl7j+D395WTIO5tU5RIDBfVSRtRR4VOJou3H66E38UjbjvDGh3slJzPuolsb+yQFqwHNNdyp5jg3w==",+ "dev": true,+ "license": "BSD"+ },"node_modules/is-stream": {"version": "2.0.1","resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",@@ -9018,6 +9064,53 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/playwright": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",+ "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.59.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.59.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",+ "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/playwright/node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },"node_modules/plyr": {"version": "3.7.8","resolved": "https://registry.npmjs.org/plyr/-/plyr-3.7.8.tgz",@@ -10106,6 +10199,32 @@"integrity": "sha512-mEugaLK+YfkijB4fx0e6kImuJdCIt2LxCRcbEYPqRGCs4F2ogyfZU5IAZRdjCP8JPq2AtdNoC/Dux63d9Kiryg==","dev": true},+ "node_modules/selenium-webdriver": {+ "version": "4.43.0",+ "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-4.43.0.tgz",+ "integrity": "sha512-dV4zBTT37or3Z3/8uD6rS8zvd4ZxPuG4EJVlqYIbZCGZCYttZm7xb9rlFLSk4rrsQHAeDYvudl7cquo0vWpHjg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/SeleniumHQ"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/selenium"+ }+ ],+ "license": "Apache-2.0",+ "dependencies": {+ "@bazel/runfiles": "^6.5.0",+ "jszip": "^3.10.1",+ "tmp": "^0.2.5",+ "ws": "^8.20.0"+ },+ "engines": {+ "node": ">= 20.0.0"+ }+ },"node_modules/selfsigned": {"version": "2.4.1","resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.4.1.tgz",@@ -11973,10 +12092,11 @@}},"node_modules/ws": {- "version": "8.18.3",- "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",- "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",+ "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==","devOptional": true,+ "license": "MIT","engines": {"node": ">=10.0.0"},diff --git a/package.json b/package.jsonindex 70214c1..079404f 100755--- a/package.json+++ b/package.json@@ -1,11 +1,12 @@{"name": "screenity",- "version": "4.3.0",+ "version": "4.4.0","description": "The free and privacy-friendly screen recorder with no sign in needed.","scripts": {"build": "cross-env NODE_ENV=development node utils/build.js","build:prod": "cross-env NODE_ENV=production node utils/build.js","build:release": "cross-env NODE_ENV=production SCREENITY_SKIP_ENV=true node utils/build.js",+ "build:bs": "cross-env NODE_ENV=production SCREENITY_BS_BUILD=1 node utils/build.js","start": "cross-env NODE_ENV=development node utils/server.js","dev": "npm run hot-reload","watch": "cross-env NODE_ENV=development webpack --watch",@@ -16,7 +17,10 @@"package:release": "npm run build:release && cd build && zip -r ../extension.zip . && cd ..","clean": "rm -rf build && mkdir build","lint": "eslint src/**/*.js --fix",- "build:content-css": "sass src/pages/Content/styles/app.scss src/pages/Content/styles/app.css --no-source-map"+ "build:content-css": "sass src/pages/Content/styles/app.scss src/pages/Content/styles/app.css --no-source-map",+ "check:i18n": "node scripts/check-i18n.mjs",+ "verify:zip": "node scripts/verify-no-secrets.mjs",+ "release": "node scripts/release.mjs"},"dependencies": {"@babel/plugin-transform-react-jsx": "^7.27.1",@@ -69,9 +73,11 @@"@babel/plugin-transform-runtime": "^7.27.1","@babel/preset-env": "^7.20.2","@babel/preset-react": "^7.27.1",+ "@playwright/test": "^1.59.1","@types/react": "^18.3.21","@types/react-dom": "^18.3.7","babel-loader": "^9.1.3",+ "browserstack-local": "^1.5.13","copy-webpack-plugin": "^7.0.0","cross-env": "^7.0.3","css-loader": "^6.7.2",@@ -81,6 +87,7 @@"prettier": "^2.7.1","sass": "^1.97.3","sass-loader": "^16.0.7",+ "selenium-webdriver": "^4.43.0","source-map-loader": "^3.0.1","style-loader": "^3.3.1","stylelint": "^17.8.0",diff --git a/scripts/check-i18n.mjs b/scripts/check-i18n.mjsnew file mode 100755index 0000000..beb78ac--- /dev/null+++ b/scripts/check-i18n.mjs@@ -0,0 +1,94 @@+#!/usr/bin/env node+// validates non-en locale parity with en/messages.json so missing keys+// don't ship as __MSG_xxx__ in the UI.+// usage: --fix copies missing en keys in as untranslated stubs.++import { readFileSync, writeFileSync, readdirSync, statSync } from "node:fs";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const LOCALES_DIR = join(__dirname, "..", "src", "_locales");+const FIX = process.argv.includes("--fix");++const readLocale = (locale) => {+ const path = join(LOCALES_DIR, locale, "messages.json");+ return JSON.parse(readFileSync(path, "utf8"));+};++const writeLocale = (locale, data) => {+ const path = join(LOCALES_DIR, locale, "messages.json");+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n");+};++const en = readLocale("en");+const enKeys = new Set(Object.keys(en));++const locales = readdirSync(LOCALES_DIR).filter((name) => {+ if (name === "en") return false;+ return statSync(join(LOCALES_DIR, name)).isDirectory();+});++let totalMissing = 0;+let totalOrphan = 0;+const fixedLocales = [];++for (const locale of locales) {+ const data = readLocale(locale);+ const keys = new Set(Object.keys(data));++ const missing = [...enKeys].filter((k) => !keys.has(k));+ const orphan = [...keys].filter((k) => !enKeys.has(k));++ if (missing.length === 0 && orphan.length === 0) continue;++ console.log(`\n[${locale}]`);+ if (missing.length) {+ console.log(` missing (${missing.length}):`);+ for (const k of missing) console.log(` - ${k}`);+ totalMissing += missing.length;+ }+ if (orphan.length) {+ console.log(` orphan (${orphan.length}):`);+ for (const k of orphan) console.log(` - ${k}`);+ totalOrphan += orphan.length;+ }++ if (FIX && missing.length > 0) {+ const next = { ...data };+ for (const k of missing) {+ // Stub with en's value; revisit before shipping.+ next[k] = en[k];+ }+ writeLocale(locale, next);+ fixedLocales.push({ locale, added: missing.length });+ }+}++console.log("");+if (totalMissing === 0 && totalOrphan === 0) {+ console.log("All locales in sync with en.");+ process.exit(0);+}++console.log(+ `Summary: ${totalMissing} missing key(s), ${totalOrphan} orphan key(s) across ${locales.length} locales.`,+);++if (FIX) {+ if (fixedLocales.length) {+ console.log("\nStubbed missing keys (copied from en):");+ for (const { locale, added } of fixedLocales) {+ console.log(` ${locale}: +${added}`);+ }+ console.log("\nReview the stubs and translate before release.");+ }+ if (totalOrphan > 0) {+ console.log("\nOrphan keys remain - review and remove if obsolete.");+ process.exit(1);+ }+ process.exit(0);+}++console.log("\nRun with --fix to stub missing keys from en.");+process.exit(1);diff --git a/scripts/release.mjs b/scripts/release.mjsnew file mode 100755index 0000000..f7e4acc--- /dev/null+++ b/scripts/release.mjs@@ -0,0 +1,161 @@+#!/usr/bin/env node+// release builder: bumps manifest + package version, runs i18n check,+// builds self-hosted (no env), verifies no secrets in the zip, prints+// the manual upload checklist. doesn't write release notes, push, or+// upload, those stay manual.+//+// usage: node scripts/release.mjs <patch|minor|major> [--dry-run]++import { execSync } from "node:child_process";+import { readFileSync, writeFileSync, statSync } from "node:fs";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++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 BUILD_DIR = join(ROOT, "build");+const ZIP_PATH = join(ROOT, "build.zip");++const args = process.argv.slice(2);+const DRY_RUN = args.includes("--dry-run");+const bumpKind = args.find((a) => ["patch", "minor", "major"].includes(a));++if (!bumpKind) {+ console.error("Usage: node scripts/release.mjs [--dry-run] patch|minor|major");+ process.exit(2);+}++const sh = (cmd, opts = {}) =>+ execSync(cmd, { stdio: "inherit", cwd: ROOT, ...opts });++const shCapture = (cmd) =>+ execSync(cmd, { cwd: ROOT, encoding: "utf8" }).trim();++const bumpSemver = (version, kind) => {+ const m = version.match(/^(\d+)\.(\d+)\.(\d+)$/);+ if (!m) throw new Error(`Cannot parse version: ${version}`);+ let [, major, minor, patch] = m.map(Number);+ if (kind === "major") {+ major += 1;+ minor = 0;+ patch = 0;+ } else if (kind === "minor") {+ minor += 1;+ patch = 0;+ } else {+ patch += 1;+ }+ return `${major}.${minor}.${patch}`;+};++const formatBytes = (n) => {+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / 1024 / 1024).toFixed(1)} MB`;+};++try {+ const status = shCapture("git status --porcelain");+ if (status) {+ console.warn(+ "Warning: working tree has uncommitted changes. Continuing anyway.\n",+ );+ }+} catch {}++const manifest = JSON.parse(readFileSync(MANIFEST_PATH, "utf8"));+const pkg = JSON.parse(readFileSync(PACKAGE_PATH, "utf8"));+const currentManifestVersion = manifest.version;+const currentPkgVersion = pkg.version;++if (currentManifestVersion !== currentPkgVersion) {+ console.warn(+ `Warning: manifest (${currentManifestVersion}) and package.json (${currentPkgVersion}) versions differ.`,+ );+ console.warn(`Bumping from manifest version (${currentManifestVersion}).\n`);+}++const nextVersion = bumpSemver(currentManifestVersion, bumpKind);++console.log(`Version bump: ${currentManifestVersion} -> ${nextVersion}`);++if (DRY_RUN) {+ console.log("\n--dry-run: no files written, no build run.");+ process.exit(0);+}++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");++console.log("Running i18n drift check...");+try {+ sh("node scripts/check-i18n.mjs");+} catch {+ console.error(+ "\ni18n drift detected. Run `npm run check:i18n -- --fix` to stub missing keys, then translate before release.",+ );+ process.exit(1);+}+console.log("");++console.log("Building self-hosted bundle (build:release)...");+sh("npm run build:release");+console.log("");++console.log("Verifying build/ for secret leaks...");+sh("node scripts/verify-no-secrets.mjs");+console.log("");++console.log("Creating build.zip...");+try {+ sh("rm -f build.zip");+} catch {}+sh("cd build && zip -rq ../build.zip .");+const zipSize = formatBytes(statSync(ZIP_PATH).size);+console.log(`Created build.zip (${zipSize}).\n`);++const shasum = shCapture(`shasum -a 256 ${ZIP_PATH}`).split(/\s+/)[0];++// Commit list since prior tag (raw input, no formatting).+let commitsBlock = "";+try {+ const lastTag = shCapture("git describe --tags --abbrev=0").trim();+ const log = shCapture(`git log --oneline ${lastTag}..HEAD`);+ commitsBlock = log+ ? `Commits since ${lastTag}:\n${log+ .split("\n")+ .map((l) => ` ${l}`)+ .join("\n")}`+ : `No commits since ${lastTag}.`;+} catch {+ // No prior tag.+ const log = shCapture("git log --oneline -20");+ commitsBlock = `No prior tag found. Last 20 commits:\n${log+ .split("\n")+ .map((l) => ` ${l}`)+ .join("\n")}`;+}++const bar = "-".repeat(60);+console.log(bar);+console.log(`Release v${nextVersion} ready`);+console.log("");+console.log(`Artifact: build.zip (${zipSize})`);+console.log(`sha256: ${shasum}`);+console.log("");+console.log(commitsBlock);+console.log("");+console.log("Next steps (manual):");+console.log(` 1. Review the diff and squash-merge to master`);+console.log(` 2. Tag: git tag v${nextVersion} && git push origin v${nextVersion}`);+console.log(` 3. Open a GitHub Release at v${nextVersion}`);+console.log(` 4. Write release notes in your voice (commits above are reference only)`);+console.log(` 5. Attach build.zip and paste this under it:`);+console.log(` sha256:${shasum}`);+console.log(` 6. Build the env-baked CWS bundle separately and upload via dashboard`);+console.log(bar);diff --git a/scripts/verify-no-secrets.mjs b/scripts/verify-no-secrets.mjsnew file mode 100755index 0000000..06f76d2--- /dev/null+++ b/scripts/verify-no-secrets.mjs@@ -0,0 +1,96 @@+#!/usr/bin/env node+// gate before publishing the self-hosted zip: scan build/ for API URLs,+// OAuth client IDs, sentry DSNs, raw .env values. build:release with+// SCREENITY_SKIP_ENV should already strip these; this is the catch-all.+// usage: node scripts/verify-no-secrets.mjs [build-dir] (default: build/)++import { readFileSync, readdirSync, statSync } from "node:fs";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const BUILD_DIR = process.argv[2] || join(__dirname, "..", "build");++// Allowed (do not flag): public homepage URLs, OAuth client_ids, public+// CDN endpoints (dead code when CLOUD_FEATURES_ENABLED=false).+// Forbidden: JWT/bearer tokens, API keys, .env values, Sentry DSNs.+const FORBIDDEN_PATTERNS = [+ /https?:\/\/[a-f0-9]{16,}@[a-z0-9.]+\.ingest\.sentry\.io/i,+ /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,+ /\bAKIA[0-9A-Z]{16}\b/,+ /\bghp_[A-Za-z0-9]{36}\b/,+ /\bsk_live_[A-Za-z0-9]{16,}\b/,+ /['"]Bearer\s+[A-Za-z0-9_.\-]{20,}['"]/,+ /\bAIza[A-Za-z0-9_-]{35}\b/,+];++const SKIP_EXTENSIONS = new Set([+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".svg",+ ".woff",+ ".woff2",+ ".ttf",+ ".otf",+ ".ico",+ ".mp3",+ ".mp4",+ ".webm",+ ".wasm",+ ".bin",+]);++const walk = (dir) => {+ const out = [];+ for (const name of readdirSync(dir)) {+ const path = join(dir, name);+ const s = statSync(path);+ if (s.isDirectory()) {+ out.push(...walk(path));+ } else {+ out.push(path);+ }+ }+ return out;+};++let hits = 0;+const findings = [];++for (const file of walk(BUILD_DIR)) {+ const ext = file.slice(file.lastIndexOf("."));+ if (SKIP_EXTENSIONS.has(ext)) continue;++ let contents;+ try {+ contents = readFileSync(file, "utf8");+ } catch {+ continue;+ }++ for (const pattern of FORBIDDEN_PATTERNS) {+ const match = contents.match(pattern);+ if (match) {+ const rel = file.slice(BUILD_DIR.length + 1);+ findings.push({ file: rel, pattern: pattern.source, match: match[0] });+ hits += 1;+ }+ }+}++if (hits === 0) {+ console.log(`No forbidden secrets found in ${BUILD_DIR}.`);+ process.exit(0);+}++console.log(`Found ${hits} secret leak(s) in ${BUILD_DIR}:\n`);+for (const f of findings) {+ console.log(` ${f.file}`);+ console.log(` pattern: ${f.pattern}`);+ console.log(` match: ${f.match.slice(0, 80)}`);+ console.log("");+}+console.log("This zip must NOT be published. Rebuild with build:release.");+process.exit(1);diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.jsonindex b249b4d..dd8153f 100644--- a/src/_locales/ca/messages.json+++ b/src/_locales/ca/messages.json@@ -63,6 +63,18 @@"message": "Sembla que la configuració de seguretat d'aquest lloc web impedeix que les extensions del navegador utilitzin la càmera o el micròfon en aquesta pàgina. Per gravar amb ells, inicia una gravació des d'una altra pestanya i torna aquí un cop comenci.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "No es pot carregar la teva gravació",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Sembla que Screenity no ha pogut carregar la gravació de l'emmagatzematge del teu dispositiu. És possible que s'hagi esborrat o mogut. Si això continua passant, contacta amb nosaltres a [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Gravació aturada per un problema d'emmagatzematge. La gravació parcial s'ha desat.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Permet l'accés a la càmera","description": "Botó per permetre l'accés a la càmera"@@ -359,6 +371,18 @@"message": "Deixa aquesta pestanya oberta. S'actualitzarà amb la teva gravació quan estigui llesta.","description": "Descripció a la pàgina de l'àrea de proves mentre es grava/guarda"},+ "sandboxFinalizingRecording": {+ "message": "Finalitzant gravació...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Revertit a l'original",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Canvis desats",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Títol a la navegació de la pàgina de l'editor de l'àrea de proves"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Cancel·la","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Encara preparant la teva gravació…"+ },+ "editorStuckDescription": {+ "message": "Screenity està trigant més del normal a carregar la teva gravació. Les teves dades poden seguir en aquest dispositiu. Prova de recuperar-la, o contacta'ns si no torna."+ },+ "editorStuckTryRecover": {+ "message": "Prova de recuperar"+ },+ "editorStuckGetHelp": {+ "message": "Obtenir ajuda"+ },+ "editorRecoveryFailedTitle": {+ "message": "No s'ha pogut obrir la teva gravació"+ },+ "editorRecoveryFailedDescription": {+ "message": "Alguna cosa ha anat malament en carregar la teva gravació a l'editor. Pot ser que encara estigui desada al teu dispositiu. Pots provar de recuperar-la ara."+ },+ "downloadGIFTooLongToast": {+ "message": "L'exportació a GIF té un límit de 30 segons. Retalla el teu clip i torna-ho a provar."+ },+ "audioSilentToast": {+ "message": "No s'ha detectat àudio. Revisa el micròfon, el botó de silenci o el dispositiu d'àudio."+ },+ "restartFailedToast": {+ "message": "No s'ha pogut reiniciar la teva gravació. Atura-la i torna a començar."+ },+ "recordingFailedModalTitle": {+ "message": "No s'ha pogut iniciar la gravació"+ },+ "recordingFailedModalDescription": {+ "message": "Alguna cosa ha impedit que la gravació s'iniciés. Torna-ho a provar. Si segueix passant, escriu-nos a [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "El fitxer d'àudio és massa gran"+ },+ "editAudioTooLargeDescription": {+ "message": "Prova amb un clip d'àudio més curt. Els fitxers grans no es poden processar al navegador. La teva gravació original està segura."+ },+ "restoreEmptyToast": {+ "message": "No s'ha trobat cap gravació recuperable. Les dades poden haver estat esborrades."+ },+ "restoreTimeoutToast": {+ "message": "La recuperació està trigant massa. La teva gravació està segura. Torna a fer clic a Recuperar d'aquí a un moment."+ },+ "cameraUnavailableToast": {+ "message": "Càmera desconnectada. Es continua gravant la pantalla."+ },+ "downloadInterruptedLargeToast": {+ "message": "Descàrrega interrompuda. La gravació és massa gran per reintentar-la automàticament. Torna a desar-la des de l'editor."+ },+ "recordingCorruptToast": {+ "message": "Aquesta gravació no es pot reproduir. El fitxer pot estar incomplet o malmès. Descarrega el fitxer original des del menú Desar."}}diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.jsonindex 2904e94..eaef8c7 100644--- a/src/_locales/de/messages.json+++ b/src/_locales/de/messages.json@@ -63,6 +63,18 @@"message": "Die Sicherheitseinstellungen dieser Website verhindern, dass Browser-Erweiterungen auf dieser Seite deine Kamera oder dein Mikrofon verwenden. Um mit ihnen aufzunehmen, starte die Aufnahme in einem anderen Tab und wechsle zurück hierher, sobald sie begonnen hat.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Aufnahme kann nicht geladen werden",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Screenity konnte die Aufnahme aus dem Speicher deines Geräts nicht laden. Sie wurde möglicherweise gelöscht oder verschoben. Falls dies weiterhin geschieht, kontaktiere uns unter [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Aufnahme wegen eines Speicherproblems gestoppt. Deine Teilaufnahme wurde gespeichert.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Kamerazugriff zulassen","description": "Schaltfläche 'Kamerazugriff zulassen'"@@ -359,6 +371,18 @@"message": "Halten Sie diesen Tab geöffnet. Er wird sich aktualisieren, wenn Ihre Aufnahme fertig ist.","description": "Beschreibung auf der Sandbox-Seite während der Aufnahme / Speicherung"},+ "sandboxFinalizingRecording": {+ "message": "Aufnahme wird abgeschlossen...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Auf Original zurückgesetzt",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Änderungen gespeichert",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Titel in der Navigation der Sandbox-Editor-Seite"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Abbrechen","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Ihre Aufnahme wird noch vorbereitet…"+ },+ "editorStuckDescription": {+ "message": "Screenity benötigt länger als gewöhnlich, um Ihre Aufnahme zu laden. Ihre Daten befinden sich möglicherweise noch auf diesem Gerät. Versuchen Sie, sie wiederherzustellen, oder melden Sie sich, falls sie nicht zurückkommt."+ },+ "editorStuckTryRecover": {+ "message": "Wiederherstellen"+ },+ "editorStuckGetHelp": {+ "message": "Hilfe erhalten"+ },+ "editorRecoveryFailedTitle": {+ "message": "Aufnahme konnte nicht geöffnet werden"+ },+ "editorRecoveryFailedDescription": {+ "message": "Beim Laden Ihrer Aufnahme in den Editor ist ein Fehler aufgetreten. Ihre Aufnahme ist möglicherweise noch auf Ihrem Gerät gespeichert. Sie können jetzt versuchen, sie wiederherzustellen."+ },+ "downloadGIFTooLongToast": {+ "message": "Der GIF-Export ist auf 30 Sekunden begrenzt. Kürzen Sie Ihren Clip und versuchen Sie es erneut."+ },+ "audioSilentToast": {+ "message": "Kein Audio erkannt. Überprüfen Sie Ihr Mikrofon, den Stummschalter oder Ihr Audiogerät."+ },+ "restartFailedToast": {+ "message": "Ihre Aufnahme konnte nicht neu gestartet werden. Stoppen Sie sie und starten Sie sie erneut."+ },+ "recordingFailedModalTitle": {+ "message": "Aufnahme konnte nicht gestartet werden"+ },+ "recordingFailedModalDescription": {+ "message": "Etwas hat den Start der Aufnahme verhindert. Bitte versuchen Sie es erneut. Wenn das Problem weiterhin besteht, kontaktieren Sie uns unter [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "Audiodatei ist zu groß"+ },+ "editAudioTooLargeDescription": {+ "message": "Versuchen Sie es mit einem kürzeren Audioclip. Große Dateien können nicht im Browser verarbeitet werden. Ihre Originalaufnahme bleibt erhalten."+ },+ "restoreEmptyToast": {+ "message": "Keine wiederherstellbare Aufnahme gefunden. Die Daten wurden möglicherweise gelöscht."+ },+ "restoreTimeoutToast": {+ "message": "Die Wiederherstellung dauert zu lange. Ihre Aufnahme ist sicher. Klicken Sie in einem Moment erneut auf Wiederherstellen."+ },+ "cameraUnavailableToast": {+ "message": "Kamera getrennt. Bildschirmaufnahme läuft weiter."+ },+ "downloadInterruptedLargeToast": {+ "message": "Download unterbrochen. Die Aufnahme ist zu groß, um automatisch erneut zu starten. Versuchen Sie, sie erneut über den Editor zu speichern."+ },+ "recordingCorruptToast": {+ "message": "Diese Aufnahme kann nicht abgespielt werden. Die Datei ist möglicherweise unvollständig oder beschädigt. Versuchen Sie, die Rohdatei über das Speichern-Menü herunterzuladen."}}diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.jsonindex 4c0a439..85f85b2 100644--- a/src/_locales/en/messages.json+++ b/src/_locales/en/messages.json@@ -63,6 +63,42 @@"message": "Looks like this website's security settings prevent browser extensions from using your camera or microphone on this page. To record with them, start a recording from another tab and switch back here once it begins.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Can't load your recording",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Looks like Screenity couldn't load the recording from your device's storage. It may have been cleared or moved. If this keeps happening, please contact us at [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "editorStuckTitle": {+ "message": "Still preparing your recording…",+ "description": "Modal title shown when the editor has been waiting on the post-stop pipeline for too long"+ },+ "editorStuckDescription": {+ "message": "Screenity is taking longer than usual to load your recording. Your data may still be on this device. Try recovering it, or get in touch if it doesn't come back.",+ "description": "Modal description for the editor-stuck modal, offering recovery and help"+ },+ "editorStuckTryRecover": {+ "message": "Try to recover",+ "description": "Primary button on the editor-stuck modal — runs the restore-recording flow"+ },+ "editorStuckGetHelp": {+ "message": "Get help",+ "description": "Secondary button on the editor-stuck modal — opens the support form"+ },+ "editorRecoveryFailedTitle": {+ "message": "Couldn't open your recording",+ "description": "Modal title shown when the post-stop editor pipeline failed (tab load timeout, message delivery failure)"+ },+ "editorRecoveryFailedDescription": {+ "message": "Something went wrong while loading your recording into the editor. Your recording may still be saved on your device. You can try to recover it now.",+ "description": "Modal description shown when the post-stop editor pipeline failed; offers recovery"+ },+ "recordingWriterFailedToast": {+ "message": "Recording stopped due to a storage issue. Your partial recording was saved.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Allow camera access","description": "Allow camera access button"@@ -359,6 +395,18 @@"message": "Keep this tab open. It will update with your recording when it's ready.","description": "Description in sandbox page while recording / saving"},+ "sandboxFinalizingRecording": {+ "message": "Finalizing recording...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Reverted to original",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Changes saved",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Title in navigation of the sandbox editor page"@@ -611,6 +659,18 @@"message": "Export a GIF (max 30 seconds)","description": "Download GIF label"},+ "downloadGIFTooLongToast": {+ "message": "GIF export is capped at 30 seconds. Trim your clip and try again.",+ "description": "Toast shown when the user clicks Download as GIF on a clip longer than 30s — explains the silent gate that previously did nothing"+ },+ "audioSilentToast": {+ "message": "No audio detected. Check your mic, mute switch, or audio device.",+ "description": "Toast shown when the recorder has detected 30s of complete silence on the captured audio track. The recording continues — it's a heads-up, not an error."+ },+ "restartFailedToast": {+ "message": "Couldn't restart your recording. Try stopping and starting again.",+ "description": "Toast shown when the user clicks Restart but the BG handler couldn't reach or replace the recorder tab — previously left the popup stuck on 'restarting' silently."+ },"shareModalSandboxTitle": {"message": "Ready to level up your recordings?","description": "Share modal title in sandbox editor page"@@ -1525,6 +1585,14 @@"message": "Low disk space. Saving your recording now. Everything captured so far is safe.","description": "Toast when disk space drops below critical threshold during recording"},+ "recordingFailedModalTitle": {+ "message": "Recording couldn't start",+ "description": "Title of the modal shown when recording fails to start"+ },+ "recordingFailedModalDescription": {+ "message": "Something prevented the recording from starting. Please try again. If this keeps happening, contact us at [email protected].",+ "description": "Description of the modal shown when recording fails to start"+ },"toastStorageLow": {"message": "Storage is running low. Upload reliability may degrade for long recordings.","description": "Toast shown when available storage drops below the warning threshold during recording"@@ -1573,6 +1641,14 @@"message": "Something went wrong during processing. Your original recording is safe. You can try again or download as-is.","description": "Alert body for edit failure"},+ "editAudioTooLargeTitle": {+ "message": "Audio file is too large",+ "description": "Alert title when the audio file uploaded for Add Audio is too large to process in-browser"+ },+ "editAudioTooLargeDescription": {+ "message": "Try a shorter audio clip. Large files can't be processed in-browser. Your original recording is safe.",+ "description": "Alert body for audio-too-large error during Add Audio"+ },"videoTrackEndedToast": {"message": "Screen sharing stopped. Saving your recording now. Everything captured so far is safe.","description": "Toast shown when the video track ends mid-recording (e.g. monitor disconnected, screen share revoked)"@@ -1588,5 +1664,25 @@"stopAckTimeoutToast": {"message": "Saving is taking longer than expected. Your captured data is safe. The editor will open shortly.","description": "Toast shown when the recorder does not acknowledge the stop request within a few seconds"+ },+ "restoreEmptyToast": {+ "message": "No recoverable recording found. The data may have been cleared.",+ "description": "Toast shown when restoreRecording finds no OPFS file and no IDB chunks"+ },+ "restoreTimeoutToast": {+ "message": "Recovery is taking too long. Your recording is safe. Try clicking Recover again in a moment.",+ "description": "Toast shown when the recovery editor tab fails to load within 30 seconds"+ },+ "cameraUnavailableToast": {+ "message": "Camera disconnected. Still recording your screen.",+ "description": "Toast shown when the camera bubble fails during an active recording but the screen recording continues"+ },+ "downloadInterruptedLargeToast": {+ "message": "Download interrupted. The recording is too large to retry automatically. Try saving again from the editor.",+ "description": "Toast shown when a download is interrupted and the file is too large for the in-process base64 retry path"+ },+ "recordingCorruptToast": {+ "message": "This recording can't be played back. The file may be incomplete or corrupted. Try downloading the raw file from the Save menu.",+ "description": "Toast shown when the editor's video element fails to decode the recording (corrupt or zero-byte file)"}}diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.jsonindex 127367b..f4f8d04 100644--- a/src/_locales/es/messages.json+++ b/src/_locales/es/messages.json@@ -63,6 +63,18 @@"message": "Parece que la configuración de seguridad de este sitio web impide que las extensiones del navegador utilicen tu cámara o micrófono en esta página. Para grabar con ellos, inicia una grabación en otra pestaña y vuelve aquí una vez que comience.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "No se puede cargar tu grabación",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Parece que Screenity no pudo cargar la grabación desde el almacenamiento de tu dispositivo. Puede haber sido eliminada o movida. Si esto sigue ocurriendo, contáctanos en [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Grabación detenida por un problema de almacenamiento. Tu grabación parcial se guardó.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Permitir acceso a la cámara","description": "Botón de permitir acceso a la cámara"@@ -359,6 +371,18 @@"message": "Deja esta pestaña abierta. Se actualizará con tu grabación cuando esté lista.","description": "Descripción en la página de pruebas mientras se graba/guarda"},+ "sandboxFinalizingRecording": {+ "message": "Finalizando grabación...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Revertido al original",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Cambios guardados",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Título en la navegación de la página del editor de pruebas"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Cancelar","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Aún preparando tu grabación…"+ },+ "editorStuckDescription": {+ "message": "Screenity está tardando más de lo habitual en cargar tu grabación. Tus datos podrían seguir en este dispositivo. Intenta recuperarla, o contáctanos si no aparece."+ },+ "editorStuckTryRecover": {+ "message": "Intentar recuperar"+ },+ "editorStuckGetHelp": {+ "message": "Obtener ayuda"+ },+ "editorRecoveryFailedTitle": {+ "message": "No se pudo abrir tu grabación"+ },+ "editorRecoveryFailedDescription": {+ "message": "Algo salió mal al cargar tu grabación en el editor. Puede que siga guardada en tu dispositivo. Puedes intentar recuperarla ahora."+ },+ "downloadGIFTooLongToast": {+ "message": "La exportación a GIF tiene un límite de 30 segundos. Recorta tu clip e inténtalo de nuevo."+ },+ "audioSilentToast": {+ "message": "No se detectó audio. Revisa tu micrófono, el botón de silencio o el dispositivo de audio."+ },+ "restartFailedToast": {+ "message": "No se pudo reiniciar tu grabación. Detenla y vuelve a iniciarla."+ },+ "recordingFailedModalTitle": {+ "message": "No se pudo iniciar la grabación"+ },+ "recordingFailedModalDescription": {+ "message": "Algo impidió que la grabación se iniciara. Inténtalo de nuevo. Si sigue ocurriendo, escríbenos a [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "El archivo de audio es demasiado grande"+ },+ "editAudioTooLargeDescription": {+ "message": "Prueba con un clip de audio más corto. Los archivos grandes no se pueden procesar en el navegador. Tu grabación original está a salvo."+ },+ "restoreEmptyToast": {+ "message": "No se encontró ninguna grabación recuperable. Los datos pueden haberse borrado."+ },+ "restoreTimeoutToast": {+ "message": "La recuperación está tardando demasiado. Tu grabación está a salvo. Vuelve a hacer clic en Recuperar en un momento."+ },+ "cameraUnavailableToast": {+ "message": "Cámara desconectada. Se sigue grabando la pantalla."+ },+ "downloadInterruptedLargeToast": {+ "message": "Descarga interrumpida. La grabación es demasiado grande para reintentarla automáticamente. Vuelve a guardarla desde el editor."+ },+ "recordingCorruptToast": {+ "message": "Esta grabación no se puede reproducir. El archivo puede estar incompleto o dañado. Descarga el archivo original desde el menú Guardar."}}diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.jsonindex 6fa40bb..caf88c9 100644--- a/src/_locales/fr/messages.json+++ b/src/_locales/fr/messages.json@@ -63,6 +63,18 @@"message": "Il semble que les paramètres de sécurité de ce site empêchent les extensions de navigateur d'utiliser votre caméra ou votre microphone sur cette page. Pour enregistrer avec eux, démarrez un enregistrement depuis un autre onglet et revenez ici une fois qu'il a commencé.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Impossible de charger votre enregistrement",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Il semble que Screenity n'ait pas pu charger l'enregistrement depuis le stockage de votre appareil. Il a peut-être été effacé ou déplacé. Si cela se reproduit, contactez-nous à [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Enregistrement arrêté en raison d'un problème de stockage. Votre enregistrement partiel a été sauvegardé.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Autoriser l'accès à la caméra","description": "Bouton d'autorisation d'accès à la caméra"@@ -359,6 +371,18 @@"message": "Laissez cet onglet ouvert. Il se mettra à jour avec votre enregistrement une fois prêt.","description": "Description sur la page de test pendant l'enregistrement/sauvegarde"},+ "sandboxFinalizingRecording": {+ "message": "Finalisation de l'enregistrement...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Rétabli à l'original",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Modifications enregistrées",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Éditeur","description": "Titre dans la navigation de la page de l'éditeur de test"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Annuler","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Préparation de votre enregistrement en cours…"+ },+ "editorStuckDescription": {+ "message": "Screenity met plus de temps que d'habitude à charger votre enregistrement. Vos données sont peut-être encore sur cet appareil. Essayez de le récupérer, ou contactez-nous s'il ne revient pas."+ },+ "editorStuckTryRecover": {+ "message": "Essayer de récupérer"+ },+ "editorStuckGetHelp": {+ "message": "Obtenir de l'aide"+ },+ "editorRecoveryFailedTitle": {+ "message": "Impossible d'ouvrir votre enregistrement"+ },+ "editorRecoveryFailedDescription": {+ "message": "Une erreur s'est produite lors du chargement de votre enregistrement dans l'éditeur. Il est peut-être encore enregistré sur votre appareil. Vous pouvez essayer de le récupérer maintenant."+ },+ "downloadGIFTooLongToast": {+ "message": "L'export GIF est limité à 30 secondes. Raccourcissez votre clip et réessayez."+ },+ "audioSilentToast": {+ "message": "Aucun son détecté. Vérifiez votre micro, le bouton muet ou votre périphérique audio."+ },+ "restartFailedToast": {+ "message": "Impossible de redémarrer votre enregistrement. Arrêtez-le et relancez-le."+ },+ "recordingFailedModalTitle": {+ "message": "Impossible de démarrer l'enregistrement"+ },+ "recordingFailedModalDescription": {+ "message": "Quelque chose a empêché le démarrage de l'enregistrement. Réessayez. Si le problème persiste, écrivez-nous à [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "Le fichier audio est trop volumineux"+ },+ "editAudioTooLargeDescription": {+ "message": "Essayez avec un clip audio plus court. Les fichiers volumineux ne peuvent pas être traités dans le navigateur. Votre enregistrement d'origine est intact."+ },+ "restoreEmptyToast": {+ "message": "Aucun enregistrement récupérable trouvé. Les données ont peut-être été effacées."+ },+ "restoreTimeoutToast": {+ "message": "La récupération prend trop de temps. Votre enregistrement est en sécurité. Recliquez sur Récupérer dans un instant."+ },+ "cameraUnavailableToast": {+ "message": "Caméra déconnectée. L'enregistrement de l'écran continue."+ },+ "downloadInterruptedLargeToast": {+ "message": "Téléchargement interrompu. L'enregistrement est trop volumineux pour réessayer automatiquement. Enregistrez-le à nouveau depuis l'éditeur."+ },+ "recordingCorruptToast": {+ "message": "Cet enregistrement ne peut pas être lu. Le fichier est peut-être incomplet ou corrompu. Téléchargez le fichier brut depuis le menu Enregistrer."}}diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.jsonindex 862b0d1..49a9ed1 100644--- a/src/_locales/hi/messages.json+++ b/src/_locales/hi/messages.json@@ -63,6 +63,18 @@"message": "ऐसा लगता है कि इस वेबसाइट की सुरक्षा सेटिंग्स ब्राउज़र एक्सटेंशन को इस पेज पर आपके कैमरा या माइक्रोफोन का उपयोग करने से रोकती हैं। इनके साथ रिकॉर्ड करने के लिए, किसी अन्य टैब से रिकॉर्डिंग शुरू करें और रिकॉर्डिंग शुरू होने के बाद यहाँ वापस आएँ।","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "आपकी रिकॉर्डिंग लोड नहीं हो सकी",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "ऐसा लगता है कि Screenity आपके डिवाइस के स्टोरेज से रिकॉर्डिंग लोड नहीं कर सका। यह मिटा दी गई हो या हटाई गई हो सकती है। अगर यह समस्या बार-बार हो, तो कृपया [email protected] पर हमसे संपर्क करें।",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "स्टोरेज समस्या के कारण रिकॉर्डिंग बंद हो गई। आपकी आंशिक रिकॉर्डिंग सहेज ली गई है।",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "कैमरा अनुमति दें","description": "कैमरा अनुमति दें बटन"@@ -359,6 +371,18 @@"message": "इस टैब को खुला रखें। यह आपकी रेकॉर्डिंग तैयार होने पर अपडेट हो जाएगा।","description": "सैंडबॉक्स पृष्ठ में रेकॉर्डिंग / सहेजने के दौरान विवरण"},+ "sandboxFinalizingRecording": {+ "message": "रिकॉर्डिंग पूरी की जा रही है...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "मूल पर वापस लाया गया",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "बदलाव सहेजे गए",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "संपादक","description": "सैंडबॉक्स संपादक पृष्ठ में नेविगेशन का शीर्षक"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "रद्द करें","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "आपकी रिकॉर्डिंग अभी भी तैयार हो रही है…"+ },+ "editorStuckDescription": {+ "message": "Screenity को आपकी रिकॉर्डिंग लोड करने में सामान्य से अधिक समय लग रहा है। आपका डेटा अब भी इस डिवाइस पर हो सकता है। इसे रिकवर करने का प्रयास करें, या यदि यह वापस न आए तो हमसे संपर्क करें।"+ },+ "editorStuckTryRecover": {+ "message": "रिकवर करने का प्रयास करें"+ },+ "editorStuckGetHelp": {+ "message": "मदद लें"+ },+ "editorRecoveryFailedTitle": {+ "message": "आपकी रिकॉर्डिंग नहीं खुल सकी"+ },+ "editorRecoveryFailedDescription": {+ "message": "रिकॉर्डिंग को एडिटर में लोड करते समय कुछ गड़बड़ हो गई। आपकी रिकॉर्डिंग अब भी आपके डिवाइस पर सहेजी हो सकती है। आप इसे अभी रिकवर करने का प्रयास कर सकते हैं।"+ },+ "downloadGIFTooLongToast": {+ "message": "GIF एक्सपोर्ट की सीमा 30 सेकंड है। अपनी क्लिप को छोटा करें और फिर से प्रयास करें।"+ },+ "audioSilentToast": {+ "message": "कोई ऑडियो नहीं मिला। अपना माइक, म्यूट स्विच, या ऑडियो डिवाइस जांचें।"+ },+ "restartFailedToast": {+ "message": "आपकी रिकॉर्डिंग दोबारा शुरू नहीं हो सकी। रोककर फिर से शुरू करने का प्रयास करें।"+ },+ "recordingFailedModalTitle": {+ "message": "रिकॉर्डिंग शुरू नहीं हो सकी"+ },+ "recordingFailedModalDescription": {+ "message": "किसी कारण से रिकॉर्डिंग शुरू नहीं हो पाई। कृपया फिर से प्रयास करें। यदि यह बार-बार हो रहा है, तो हमें [email protected] पर संपर्क करें।"+ },+ "editAudioTooLargeTitle": {+ "message": "ऑडियो फ़ाइल बहुत बड़ी है"+ },+ "editAudioTooLargeDescription": {+ "message": "छोटी ऑडियो क्लिप आज़माएं। बड़ी फ़ाइलें ब्राउज़र में प्रोसेस नहीं हो सकतीं। आपकी मूल रिकॉर्डिंग सुरक्षित है।"+ },+ "restoreEmptyToast": {+ "message": "कोई रिकवर करने योग्य रिकॉर्डिंग नहीं मिली। डेटा क्लियर हो चुका हो सकता है।"+ },+ "restoreTimeoutToast": {+ "message": "रिकवरी में बहुत समय लग रहा है। आपकी रिकॉर्डिंग सुरक्षित है। थोड़ी देर में रिकवर पर फिर से क्लिक करें।"+ },+ "cameraUnavailableToast": {+ "message": "कैमरा डिस्कनेक्ट हो गया। स्क्रीन रिकॉर्डिंग जारी है।"+ },+ "downloadInterruptedLargeToast": {+ "message": "डाउनलोड बाधित हुआ। रिकॉर्डिंग इतनी बड़ी है कि स्वचालित रूप से दोबारा प्रयास नहीं हो सकता। एडिटर से दोबारा सहेजने का प्रयास करें।"+ },+ "recordingCorruptToast": {+ "message": "यह रिकॉर्डिंग प्ले नहीं की जा सकती। फ़ाइल अधूरी या ख़राब हो सकती है। सेव मेनू से रॉ फ़ाइल डाउनलोड करने का प्रयास करें।"}}diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.jsonindex 92cf761..b3f53b6 100644--- a/src/_locales/id/messages.json+++ b/src/_locales/id/messages.json@@ -63,6 +63,18 @@"message": "Tampaknya pengaturan keamanan situs web ini mencegah ekstensi peramban menggunakan kamera atau mikrofon Anda di halaman ini. Untuk merekam dengan keduanya, mulai rekaman dari tab lain dan beralih kembali ke sini setelah rekaman dimulai.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Tidak dapat memuat rekaman Anda",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Sepertinya Screenity tidak dapat memuat rekaman dari penyimpanan perangkat Anda. Rekaman mungkin telah dihapus atau dipindahkan. Jika ini terus terjadi, hubungi kami di [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Perekaman dihentikan karena masalah penyimpanan. Rekaman parsial Anda telah disimpan.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Izinkan akses kamera","description": "Tombol izinkan akses kamera"@@ -359,6 +371,18 @@"message": "Simpan tab ini terbuka. Ini akan diperbarui dengan perekaman Anda saat sudah siap.","description": "Deskripsi halaman sandbox saat merekam / menyimpan"},+ "sandboxFinalizingRecording": {+ "message": "Menyelesaikan rekaman...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Dikembalikan ke asli",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Perubahan disimpan",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Judul navigasi halaman editor sandbox"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Batal","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Masih menyiapkan rekaman Anda…"+ },+ "editorStuckDescription": {+ "message": "Screenity membutuhkan waktu lebih lama dari biasanya untuk memuat rekaman Anda. Data Anda mungkin masih tersimpan di perangkat ini. Coba pulihkan, atau hubungi kami jika rekaman tidak kembali."+ },+ "editorStuckTryRecover": {+ "message": "Coba pulihkan"+ },+ "editorStuckGetHelp": {+ "message": "Dapatkan bantuan"+ },+ "editorRecoveryFailedTitle": {+ "message": "Tidak dapat membuka rekaman Anda"+ },+ "editorRecoveryFailedDescription": {+ "message": "Terjadi masalah saat memuat rekaman ke editor. Rekaman Anda mungkin masih tersimpan di perangkat. Anda dapat mencoba memulihkannya sekarang."+ },+ "downloadGIFTooLongToast": {+ "message": "Ekspor GIF dibatasi hingga 30 detik. Pangkas klip Anda dan coba lagi."+ },+ "audioSilentToast": {+ "message": "Tidak ada audio terdeteksi. Periksa mikrofon, sakelar bisu, atau perangkat audio Anda."+ },+ "restartFailedToast": {+ "message": "Tidak dapat memulai ulang rekaman Anda. Coba hentikan lalu mulai lagi."+ },+ "recordingFailedModalTitle": {+ "message": "Rekaman tidak dapat dimulai"+ },+ "recordingFailedModalDescription": {+ "message": "Sesuatu menghalangi rekaman untuk dimulai. Silakan coba lagi. Jika hal ini terus terjadi, hubungi kami di [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "File audio terlalu besar"+ },+ "editAudioTooLargeDescription": {+ "message": "Coba klip audio yang lebih pendek. File besar tidak dapat diproses di browser. Rekaman asli Anda tetap aman."+ },+ "restoreEmptyToast": {+ "message": "Tidak ada rekaman yang dapat dipulihkan. Data mungkin telah dihapus."+ },+ "restoreTimeoutToast": {+ "message": "Pemulihan memakan waktu terlalu lama. Rekaman Anda aman. Coba klik Pulihkan lagi sebentar lagi."+ },+ "cameraUnavailableToast": {+ "message": "Kamera terputus. Perekaman layar tetap berjalan."+ },+ "downloadInterruptedLargeToast": {+ "message": "Unduhan terputus. Rekaman terlalu besar untuk dicoba ulang secara otomatis. Coba simpan lagi dari editor."+ },+ "recordingCorruptToast": {+ "message": "Rekaman ini tidak dapat diputar. File mungkin tidak lengkap atau rusak. Coba unduh file mentah dari menu Simpan."}}diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.jsonindex 717c47f..8a9c94a 100644--- a/src/_locales/it/messages.json+++ b/src/_locales/it/messages.json@@ -63,6 +63,18 @@"message": "Sembra che le impostazioni di sicurezza di questo sito impediscano alle estensioni del browser di utilizzare la fotocamera o il microfono in questa pagina. Per registrare con essi, avvia una registrazione da un'altra scheda e torna qui una volta iniziata.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Impossibile caricare la registrazione",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Sembra che Screenity non sia riuscito a caricare la registrazione dall'archiviazione del dispositivo. Potrebbe essere stata cancellata o spostata. Se il problema persiste, contattaci a [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Registrazione interrotta a causa di un problema di archiviazione. La registrazione parziale è stata salvata.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Consenti accesso alla fotocamera","description": "Pulsante per consentire l'accesso alla fotocamera"@@ -359,6 +371,18 @@"message": "Lascia aperta questa scheda. Si aggiornerà con il tuo video una volta pronto.","description": "Descrizione nella pagina di registrazione mentre si sta registrando/salvando"},+ "sandboxFinalizingRecording": {+ "message": "Finalizzazione della registrazione...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Ripristinato all'originale",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Modifiche salvate",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Titolo nella navigazione della pagina dell'editor di prova"@@ -1568,5 +1592,74 @@"cancelButton": {"message": "Annulla","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Stiamo ancora preparando la tua registrazione…"+ },+ "editorStuckDescription": {+ "message": "Screenity sta impiegando più del solito a caricare la tua registrazione. I tuoi dati potrebbero essere ancora su questo dispositivo. Prova a recuperarla, o contattaci se non torna."+ },+ "editorStuckTryRecover": {+ "message": "Prova a recuperare"+ },+ "editorStuckGetHelp": {+ "message": "Ottieni aiuto"+ },+ "editorRecoveryFailedTitle": {+ "message": "Impossibile aprire la tua registrazione"+ },+ "editorRecoveryFailedDescription": {+ "message": "Qualcosa è andato storto durante il caricamento della tua registrazione nell'editor. La registrazione potrebbe essere ancora salvata sul tuo dispositivo. Puoi provare a recuperarla ora."+ },+ "downloadGIFTooLongToast": {+ "message": "L'esportazione GIF ha un limite di 30 secondi. Taglia la clip e riprova."+ },+ "audioSilentToast": {+ "message": "Nessun audio rilevato. Controlla il microfono, il pulsante di muto o il dispositivo audio."+ },+ "restartFailedToast": {+ "message": "Impossibile riavviare la tua registrazione. Fermala e ricominciala."+ },+ "recordingFailedModalTitle": {+ "message": "Impossibile avviare la registrazione"+ },+ "recordingFailedModalDescription": {+ "message": "Qualcosa ha impedito l'avvio della registrazione. Riprova. Se continua a succedere, scrivici a [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "Il file audio è troppo grande"+ },+ "editAudioTooLargeDescription": {+ "message": "Prova con una clip audio più breve. I file grandi non possono essere elaborati nel browser. La tua registrazione originale è al sicuro."+ },+ "restoreEmptyToast": {+ "message": "Nessuna registrazione recuperabile trovata. I dati potrebbero essere stati cancellati."+ },+ "restoreTimeoutToast": {+ "message": "Il recupero sta richiedendo troppo tempo. La tua registrazione è al sicuro. Riprova a fare clic su Recupera tra un momento."+ },+ "cameraUnavailableToast": {+ "message": "Fotocamera disconnessa. La registrazione dello schermo continua."+ },+ "downloadInterruptedLargeToast": {+ "message": "Download interrotto. La registrazione è troppo grande per riprovare automaticamente. Salvala di nuovo dall'editor."+ },+ "recordingCorruptToast": {+ "message": "Questa registrazione non può essere riprodotta. Il file potrebbe essere incompleto o danneggiato. Scarica il file originale dal menu Salva."+ },+ "overLimitModalTitle": {+ "message": "Il video è troppo lungo per essere elaborato sul tuo dispositivo"+ },+ "overLimitModalDescription": {+ "message": "Dato che Screenity è completamente privato e gira in locale, è limitato dall'hardware del tuo dispositivo. Elaborare un video di questa durata richiederebbe troppo tempo e molte risorse. Tranquillo, puoi comunque scaricare il file WEBM o la registrazione grezza, ma la modifica e l'esportazione MP4 non sono disponibili. Detto questo, puoi comunque provare a elaborare il video, se accetti i rischi."+ },+ "overLimitModalDescriptionFastPath": {+ "message": "Dato che Screenity è completamente privato e gira in locale, è limitato dall'hardware del tuo dispositivo. Elaborare un video di questa durata richiederebbe troppo tempo e molte risorse. Il tuo MP4 è pronto da scaricare così com'è, ma la modifica nel browser non è disponibile per clip così lunghe. Puoi comunque provare a elaborare il video, se accetti i rischi."+ },+ "overLimitModalButton": {+ "message": "Capisco i rischi, prova comunque"+ },+ "overLimitModalLearnMore": {+ "message": "Scopri di più sull'elaborazione di video lunghi."}}diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.jsonindex 1b4e4c0..f42bde2 100644--- a/src/_locales/ko/messages.json+++ b/src/_locales/ko/messages.json@@ -63,6 +63,18 @@"message": "이 웹사이트의 보안 설정이 브라우저 확장 프로그램에서 이 페이지의 카메라나 마이크를 사용하지 못하게 차단하고 있어요. 카메라와 마이크를 사용해 녹화하려면, 다른 탭에서 녹화를 시작한 뒤 녹화가 시작되면 이 탭으로 돌아오세요.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "녹화를 불러올 수 없어요",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Screenity가 기기 저장소에서 녹화 파일을 불러오지 못했어요. 삭제되었거나 이동되었을 수 있어요. 계속 발생하면 [email protected]로 문의해 주세요.",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "저장소 문제로 녹화가 중지되었어요. 부분 녹화는 저장되었어요.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "카메라 액세스 허용","description": "Allow camera access button"@@ -359,6 +371,18 @@"message": "이 탭을 열어둡니다. 녹화가 준비되면 업데이트됩니다.","description": "Description in sandbox page while recording / saving"},+ "sandboxFinalizingRecording": {+ "message": "녹화 마무리 중...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "원본으로 되돌림",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "변경 사항 저장됨",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "편집기","description": "Title in navigation of the sandbox editor page"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "취소","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "녹화를 준비하는 중입니다…"+ },+ "editorStuckDescription": {+ "message": "스크리니티가 평소보다 녹화를 불러오는 데 시간이 더 걸리고 있습니다. 데이터는 이 기기에 남아 있을 수 있습니다. 복구를 시도해 보시거나, 복구되지 않으면 문의해 주세요."+ },+ "editorStuckTryRecover": {+ "message": "복구 시도"+ },+ "editorStuckGetHelp": {+ "message": "도움 받기"+ },+ "editorRecoveryFailedTitle": {+ "message": "녹화를 열 수 없습니다"+ },+ "editorRecoveryFailedDescription": {+ "message": "편집기에 녹화를 불러오는 중 문제가 발생했습니다. 녹화 파일은 기기에 저장되어 있을 수 있습니다. 지금 복구를 시도해 보세요."+ },+ "downloadGIFTooLongToast": {+ "message": "GIF 내보내기는 최대 30초까지 가능합니다. 클립을 자른 뒤 다시 시도해 주세요."+ },+ "audioSilentToast": {+ "message": "오디오가 감지되지 않았습니다. 마이크, 음소거 스위치 또는 오디오 장치를 확인해 주세요."+ },+ "restartFailedToast": {+ "message": "녹화를 다시 시작할 수 없습니다. 중지한 뒤 다시 시작해 주세요."+ },+ "recordingFailedModalTitle": {+ "message": "녹화를 시작할 수 없습니다"+ },+ "recordingFailedModalDescription": {+ "message": "녹화를 시작하지 못했습니다. 다시 시도해 주세요. 문제가 계속되면 [email protected]로 문의해 주세요."+ },+ "editAudioTooLargeTitle": {+ "message": "오디오 파일이 너무 큽니다"+ },+ "editAudioTooLargeDescription": {+ "message": "더 짧은 오디오 클립을 사용해 보세요. 큰 파일은 브라우저에서 처리할 수 없습니다. 원본 녹화는 안전하게 보관되어 있습니다."+ },+ "restoreEmptyToast": {+ "message": "복구할 수 있는 녹화를 찾을 수 없습니다. 데이터가 삭제되었을 수 있습니다."+ },+ "restoreTimeoutToast": {+ "message": "복구에 시간이 오래 걸리고 있습니다. 녹화는 안전합니다. 잠시 후 복구를 다시 눌러 보세요."+ },+ "cameraUnavailableToast": {+ "message": "카메라 연결이 끊어졌습니다. 화면 녹화는 계속됩니다."+ },+ "downloadInterruptedLargeToast": {+ "message": "다운로드가 중단되었습니다. 파일이 너무 커서 자동으로 다시 시도할 수 없습니다. 편집기에서 다시 저장해 보세요."+ },+ "recordingCorruptToast": {+ "message": "이 녹화는 재생할 수 없습니다. 파일이 불완전하거나 손상되었을 수 있습니다. 저장 메뉴에서 원본 파일을 다운로드해 보세요."}}diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.jsonindex 3517afe..02d7208 100644--- a/src/_locales/pl/messages.json+++ b/src/_locales/pl/messages.json@@ -63,6 +63,18 @@"message": "Wygląda na to, że ustawienia bezpieczeństwa tej witryny uniemożliwiają rozszerzeniom przeglądarki korzystanie z kamery i mikrofonu na tej stronie. Aby nagrywać z ich użyciem, rozpocznij nagrywanie z innej karty i wróć tutaj po jego rozpoczęciu.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Nie można załadować nagrania",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Wygląda na to, że Screenity nie mógł załadować nagrania z pamięci urządzenia. Mogło zostać usunięte lub przeniesione. Jeśli problem się powtarza, skontaktuj się z nami pod adresem [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Nagrywanie zatrzymane z powodu problemu z pamięcią. Częściowe nagranie zostało zapisane.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Zezwól na dostęp do kamery","description": "Przycisk zezwalający na dostęp do kamery"@@ -359,6 +371,18 @@"message": "Zachowaj tę kartę otwartą. Zaktualizuje się z twoim nagraniem, gdy będzie gotowe.","description": "Opis na stronie piaskownicy podczas nagrywania/zapisywania"},+ "sandboxFinalizingRecording": {+ "message": "Finalizowanie nagrania...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Przywrócono oryginał",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Zmiany zapisane",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Edytor","description": "Tytuł w nawigacji strony edytora piaskownicy"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Anuluj","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Nagranie wciąż się przygotowuje…"+ },+ "editorStuckDescription": {+ "message": "Ładowanie nagrania w Screenity trwa dłużej niż zwykle. Twoje dane mogą wciąż być na tym urządzeniu. Spróbuj je odzyskać lub skontaktuj się z nami, jeśli nie wrócą."+ },+ "editorStuckTryRecover": {+ "message": "Spróbuj odzyskać"+ },+ "editorStuckGetHelp": {+ "message": "Uzyskaj pomoc"+ },+ "editorRecoveryFailedTitle": {+ "message": "Nie udało się otworzyć nagrania"+ },+ "editorRecoveryFailedDescription": {+ "message": "Coś poszło nie tak podczas ładowania nagrania w edytorze. Twoje nagranie może wciąż być zapisane na urządzeniu. Możesz teraz spróbować je odzyskać."+ },+ "downloadGIFTooLongToast": {+ "message": "Eksport do GIF jest ograniczony do 30 sekund. Skróć klip i spróbuj ponownie."+ },+ "audioSilentToast": {+ "message": "Nie wykryto dźwięku. Sprawdź mikrofon, przełącznik wyciszenia lub urządzenie audio."+ },+ "restartFailedToast": {+ "message": "Nie udało się zrestartować nagrania. Zatrzymaj je i uruchom ponownie."+ },+ "recordingFailedModalTitle": {+ "message": "Nie udało się rozpocząć nagrywania"+ },+ "recordingFailedModalDescription": {+ "message": "Coś przeszkodziło w rozpoczęciu nagrywania. Spróbuj ponownie. Jeśli problem się powtarza, napisz do nas na [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "Plik audio jest za duży"+ },+ "editAudioTooLargeDescription": {+ "message": "Spróbuj krótszego klipu audio. Dużych plików nie można przetworzyć w przeglądarce. Twoje oryginalne nagranie jest bezpieczne."+ },+ "restoreEmptyToast": {+ "message": "Nie znaleziono nagrania do odzyskania. Dane mogły zostać wyczyszczone."+ },+ "restoreTimeoutToast": {+ "message": "Odzyskiwanie trwa zbyt długo. Twoje nagranie jest bezpieczne. Za chwilę kliknij Odzyskaj ponownie."+ },+ "cameraUnavailableToast": {+ "message": "Kamera odłączona. Nagrywanie ekranu trwa dalej."+ },+ "downloadInterruptedLargeToast": {+ "message": "Pobieranie przerwane. Nagranie jest zbyt duże, aby ponowić automatycznie. Spróbuj zapisać je ponownie z edytora."+ },+ "recordingCorruptToast": {+ "message": "Tego nagrania nie można odtworzyć. Plik może być niekompletny lub uszkodzony. Spróbuj pobrać surowy plik z menu Zapisz."}}diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.jsonindex 328042a..e7f00fd 100644--- a/src/_locales/pt_BR/messages.json+++ b/src/_locales/pt_BR/messages.json@@ -63,6 +63,18 @@"message": "Parece que as configurações de segurança deste site impedem que extensões do navegador usem sua câmera ou microfone nesta página. Para gravar com eles, inicie uma gravação em outra aba e volte para cá assim que ela começar.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Não foi possível carregar sua gravação",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Parece que o Screenity não conseguiu carregar a gravação do armazenamento do seu dispositivo. Ela pode ter sido apagada ou movida. Se isso continuar acontecendo, entre em contato conosco em [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Gravação interrompida devido a um problema de armazenamento. Sua gravação parcial foi salva.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Permitir acesso à câmera","description": "Botão de permitir acesso à câmera"@@ -359,6 +371,18 @@"message": "Mantenha esta guia aberta. Ela será atualizada com sua gravação quando estiver pronta.","description": "Descrição na página de testes durante a gravação/salvamento"},+ "sandboxFinalizingRecording": {+ "message": "Finalizando gravação...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Revertido ao original",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Alterações salvas",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Título na navegação da página do editor de testes"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Cancelar","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Ainda preparando sua gravação…"+ },+ "editorStuckDescription": {+ "message": "O Screenity está demorando mais que o normal para carregar sua gravação. Seus dados podem ainda estar neste dispositivo. Tente recuperá-la, ou entre em contato se ela não voltar."+ },+ "editorStuckTryRecover": {+ "message": "Tentar recuperar"+ },+ "editorStuckGetHelp": {+ "message": "Obter ajuda"+ },+ "editorRecoveryFailedTitle": {+ "message": "Não foi possível abrir sua gravação"+ },+ "editorRecoveryFailedDescription": {+ "message": "Algo deu errado ao carregar sua gravação no editor. Ela pode ainda estar salva no seu dispositivo. Você pode tentar recuperá-la agora."+ },+ "downloadGIFTooLongToast": {+ "message": "A exportação para GIF tem limite de 30 segundos. Corte seu clipe e tente novamente."+ },+ "audioSilentToast": {+ "message": "Nenhum áudio detectado. Verifique seu microfone, o botão de mudo ou o dispositivo de áudio."+ },+ "restartFailedToast": {+ "message": "Não foi possível reiniciar sua gravação. Pare e comece novamente."+ },+ "recordingFailedModalTitle": {+ "message": "Não foi possível iniciar a gravação"+ },+ "recordingFailedModalDescription": {+ "message": "Algo impediu o início da gravação. Tente novamente. Se continuar acontecendo, fale com a gente em [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "O arquivo de áudio é muito grande"+ },+ "editAudioTooLargeDescription": {+ "message": "Tente um clipe de áudio mais curto. Arquivos grandes não podem ser processados no navegador. Sua gravação original está segura."+ },+ "restoreEmptyToast": {+ "message": "Nenhuma gravação recuperável encontrada. Os dados podem ter sido apagados."+ },+ "restoreTimeoutToast": {+ "message": "A recuperação está demorando demais. Sua gravação está segura. Clique em Recuperar novamente em um instante."+ },+ "cameraUnavailableToast": {+ "message": "Câmera desconectada. A gravação da tela continua."+ },+ "downloadInterruptedLargeToast": {+ "message": "Download interrompido. A gravação é grande demais para tentar novamente de forma automática. Salve novamente pelo editor."+ },+ "recordingCorruptToast": {+ "message": "Esta gravação não pode ser reproduzida. O arquivo pode estar incompleto ou corrompido. Baixe o arquivo original pelo menu Salvar."}}diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.jsonindex b6e52b5..15b92d2 100644--- a/src/_locales/pt_PT/messages.json+++ b/src/_locales/pt_PT/messages.json@@ -63,6 +63,18 @@"message": "Parece que as definições de segurança deste site impedem que extensões do navegador utilizem a tua câmara ou microfone nesta página. Para gravar com eles, inicia uma gravação noutro separador e volta para aqui assim que começar.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Não é possível carregar a sua gravação",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Parece que o Screenity não conseguiu carregar a gravação do armazenamento do teu dispositivo. Pode ter sido apagada ou movida. Se isto continuar a acontecer, contacta-nos em [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Gravação interrompida devido a um problema de armazenamento. A gravação parcial foi guardada.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Permitir acesso à câmara","description": "Botão de permitir acesso à câmara"@@ -359,6 +371,18 @@"message": "Mantém este separador aberto. Será atualizado com a tua gravação quando estiver pronta.","description": "Descrição na página de testes durante a gravação/salvamento"},+ "sandboxFinalizingRecording": {+ "message": "A finalizar gravação...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Revertido para o original",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Alterações guardadas",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editor","description": "Título na navegação da página do editor de testes"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Cancelar","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Ainda a preparar a tua gravação…"+ },+ "editorStuckDescription": {+ "message": "O Screenity está a demorar mais do que o habitual a carregar a tua gravação. Os teus dados podem ainda estar neste dispositivo. Tenta recuperá-la, ou contacta-nos se não voltar."+ },+ "editorStuckTryRecover": {+ "message": "Tentar recuperar"+ },+ "editorStuckGetHelp": {+ "message": "Obter ajuda"+ },+ "editorRecoveryFailedTitle": {+ "message": "Não foi possível abrir a tua gravação"+ },+ "editorRecoveryFailedDescription": {+ "message": "Algo correu mal ao carregar a tua gravação no editor. Pode ainda estar guardada no teu dispositivo. Podes tentar recuperá-la agora."+ },+ "downloadGIFTooLongToast": {+ "message": "A exportação para GIF tem limite de 30 segundos. Corta o teu clipe e tenta novamente."+ },+ "audioSilentToast": {+ "message": "Não foi detetado áudio. Verifica o microfone, o botão de silêncio ou o dispositivo de áudio."+ },+ "restartFailedToast": {+ "message": "Não foi possível reiniciar a tua gravação. Pára e começa de novo."+ },+ "recordingFailedModalTitle": {+ "message": "Não foi possível iniciar a gravação"+ },+ "recordingFailedModalDescription": {+ "message": "Algo impediu o início da gravação. Tenta novamente. Se continuar a acontecer, fala connosco em [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "O ficheiro de áudio é demasiado grande"+ },+ "editAudioTooLargeDescription": {+ "message": "Tenta um clipe de áudio mais curto. Ficheiros grandes não podem ser processados no navegador. A tua gravação original está segura."+ },+ "restoreEmptyToast": {+ "message": "Nenhuma gravação recuperável encontrada. Os dados podem ter sido apagados."+ },+ "restoreTimeoutToast": {+ "message": "A recuperação está a demorar demasiado. A tua gravação está segura. Clica em Recuperar novamente daqui a um momento."+ },+ "cameraUnavailableToast": {+ "message": "Câmara desligada. A gravação do ecrã continua."+ },+ "downloadInterruptedLargeToast": {+ "message": "Transferência interrompida. A gravação é demasiado grande para tentar novamente de forma automática. Guarda-a novamente a partir do editor."+ },+ "recordingCorruptToast": {+ "message": "Esta gravação não pode ser reproduzida. O ficheiro pode estar incompleto ou corrompido. Transfere o ficheiro original a partir do menu Guardar."}}diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.jsonindex ef594a1..0ca44ec 100644--- a/src/_locales/ru/messages.json+++ b/src/_locales/ru/messages.json@@ -63,6 +63,18 @@"message": "Похоже, настройки безопасности этого сайта не позволяют расширениям браузера использовать камеру или микрофон на этой странице. Чтобы записывать с их использованием, начните запись в другой вкладке и переключитесь сюда после её начала.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Не удалось загрузить запись",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Похоже, Screenity не смог загрузить запись из хранилища вашего устройства. Возможно, она была удалена или перемещена. Если это продолжится, напишите нам на [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Запись остановлена из-за проблемы с хранилищем. Ваша частичная запись сохранена.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Разрешить доступ к камере","description": "Кнопка разрешения доступа к камере"@@ -359,6 +371,18 @@"message": "Оставьте эту вкладку открытой. Она будет обновлена с вашей записью, как только она будет готова.","description": "Описание на странице песочницы во время записи / сохранения"},+ "sandboxFinalizingRecording": {+ "message": "Завершение записи...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Возвращено к оригиналу",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Изменения сохранены",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Редактор","description": "Заголовок в навигации страницы редактора песочницы"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "Отмена","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Запись ещё готовится…"+ },+ "editorStuckDescription": {+ "message": "Screenity загружает вашу запись дольше обычного. Возможно, данные всё ещё хранятся на этом устройстве. Попробуйте восстановить её или свяжитесь с нами, если она не вернётся."+ },+ "editorStuckTryRecover": {+ "message": "Восстановить"+ },+ "editorStuckGetHelp": {+ "message": "Получить помощь"+ },+ "editorRecoveryFailedTitle": {+ "message": "Не удалось открыть запись"+ },+ "editorRecoveryFailedDescription": {+ "message": "При загрузке записи в редактор что-то пошло не так. Возможно, ваша запись всё ещё сохранена на устройстве. Вы можете попробовать восстановить её сейчас."+ },+ "downloadGIFTooLongToast": {+ "message": "Экспорт в GIF ограничен 30 секундами. Обрежьте клип и попробуйте снова."+ },+ "audioSilentToast": {+ "message": "Звук не обнаружен. Проверьте микрофон, переключатель отключения звука или аудиоустройство."+ },+ "restartFailedToast": {+ "message": "Не удалось перезапустить запись. Остановите её и начните заново."+ },+ "recordingFailedModalTitle": {+ "message": "Не удалось начать запись"+ },+ "recordingFailedModalDescription": {+ "message": "Что-то помешало запустить запись. Пожалуйста, попробуйте снова. Если это повторяется, напишите нам на [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "Аудиофайл слишком большой"+ },+ "editAudioTooLargeDescription": {+ "message": "Попробуйте более короткий аудиоклип. Большие файлы нельзя обработать в браузере. Ваша оригинальная запись в сохранности."+ },+ "restoreEmptyToast": {+ "message": "Записей для восстановления не найдено. Возможно, данные были удалены."+ },+ "restoreTimeoutToast": {+ "message": "Восстановление занимает слишком много времени. Ваша запись в сохранности. Через мгновение нажмите Восстановить снова."+ },+ "cameraUnavailableToast": {+ "message": "Камера отключена. Запись экрана продолжается."+ },+ "downloadInterruptedLargeToast": {+ "message": "Загрузка прервана. Запись слишком большая для автоматического повтора. Попробуйте сохранить её снова из редактора."+ },+ "recordingCorruptToast": {+ "message": "Эту запись невозможно воспроизвести. Возможно, файл повреждён или неполный. Попробуйте скачать исходный файл через меню Сохранить."}}diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.jsonindex c98fc82..6da60ec 100644--- a/src/_locales/ta/messages.json+++ b/src/_locales/ta/messages.json@@ -63,6 +63,18 @@"message": "இந்த வலைத்தளத்தின் பாதுகாப்பு அமைப்புகள் உலாவி நீட்டிப்புகள் இந்தப் பக்கத்தில் உங்கள் கேமராவையோ அல்லது மைக்ரோஃபோனையோ பயன்படுத்துவதைத் தடுக்கின்றன. இவற்றுடன் பதிவு செய்ய, மற்றொரு தாவலில் பதிவைத் தொடங்கி, அது தொடங்கியதும் இங்கே திரும்பவும்.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "உங்கள் பதிவை ஏற்ற முடியவில்லை",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Screenity உங்கள் சாதனத்தின் சேமிப்பகத்திலிருந்து பதிவை ஏற்ற முடியவில்லை. அது அழிக்கப்பட்டிருக்கலாம் அல்லது நகர்த்தப்பட்டிருக்கலாம். இது தொடர்ந்து நடந்தால், [email protected] இல் எங்களை தொடர்பு கொள்ளவும்.",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "சேமிப்பக சிக்கல் காரணமாக பதிவு நிறுத்தப்பட்டது. உங்கள் பகுதி பதிவு சேமிக்கப்பட்டது.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "கேமரா அணுகலை அனுமதிக்கவும்","description": "கேமரா அணுகலை அனுமதிக்க பொத்தான்"@@ -359,6 +371,18 @@"message": "இந்த உதவியை மூட வேண்டும். அது உங்கள் பதிவு சேமிக்கப்பட்ட பிறகு அப்டேட் செய்யும்.","description": "பதிவு பக்கத்தில் விளக்கம்"},+ "sandboxFinalizingRecording": {+ "message": "பதிவு முடிக்கப்படுகிறது...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "மூலத்திற்கு மீட்டமைக்கப்பட்டது",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "மாற்றங்கள் சேமிக்கப்பட்டன",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "எடிட்டர்","description": "மையத்தின் வழிமுறைப்பு பக்கத்தின் தலைப்பு"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "ரத்துசெய்","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "உங்கள் பதிவு இன்னும் தயாராகிறது…"+ },+ "editorStuckDescription": {+ "message": "Screenity உங்கள் பதிவை ஏற்ற வழக்கத்தை விட அதிக நேரம் எடுக்கிறது. உங்கள் தரவு இந்தச் சாதனத்தில் இருக்கக்கூடும். மீட்க முயற்சிக்கவும், அது திரும்ப வரவில்லை எனில் எங்களைத் தொடர்பு கொள்ளவும்."+ },+ "editorStuckTryRecover": {+ "message": "மீட்க முயற்சிக்கவும்"+ },+ "editorStuckGetHelp": {+ "message": "உதவி பெறவும்"+ },+ "editorRecoveryFailedTitle": {+ "message": "உங்கள் பதிவைத் திறக்க முடியவில்லை"+ },+ "editorRecoveryFailedDescription": {+ "message": "பதிவை எடிட்டரில் ஏற்றும் போது சிக்கல் ஏற்பட்டது. உங்கள் பதிவு இன்னும் உங்கள் சாதனத்தில் சேமிக்கப்பட்டிருக்கலாம். இப்போது அதை மீட்க முயற்சிக்கலாம்."+ },+ "downloadGIFTooLongToast": {+ "message": "GIF ஏற்றுமதி அதிகபட்சம் 30 வினாடிகள். உங்கள் கிளிப்பை குறைத்து மீண்டும் முயற்சிக்கவும்."+ },+ "audioSilentToast": {+ "message": "ஆடியோ எதுவும் கண்டறியப்படவில்லை. உங்கள் மைக், முடக்கு சுவிட்ச் அல்லது ஆடியோ சாதனத்தை சரிபார்க்கவும்."+ },+ "restartFailedToast": {+ "message": "உங்கள் பதிவை மீண்டும் தொடங்க முடியவில்லை. நிறுத்திவிட்டு மீண்டும் தொடங்க முயற்சிக்கவும்."+ },+ "recordingFailedModalTitle": {+ "message": "பதிவு தொடங்க முடியவில்லை"+ },+ "recordingFailedModalDescription": {+ "message": "பதிவு தொடங்குவதில் சிக்கல் ஏற்பட்டது. மீண்டும் முயற்சிக்கவும். இது தொடர்ந்து நடந்தால், [email protected] மூலம் எங்களைத் தொடர்பு கொள்ளவும்."+ },+ "editAudioTooLargeTitle": {+ "message": "ஆடியோ கோப்பு மிகப் பெரியது"+ },+ "editAudioTooLargeDescription": {+ "message": "குறுகிய ஆடியோ கிளிப்பை முயற்சிக்கவும். பெரிய கோப்புகளை உலாவியில் செயலாக்க முடியாது. உங்கள் அசல் பதிவு பாதுகாப்பாக உள்ளது."+ },+ "restoreEmptyToast": {+ "message": "மீட்க முடியக்கூடிய பதிவு எதுவும் கிடைக்கவில்லை. தரவு அழிக்கப்பட்டிருக்கலாம்."+ },+ "restoreTimeoutToast": {+ "message": "மீட்பு அதிக நேரம் எடுக்கிறது. உங்கள் பதிவு பாதுகாப்பாக உள்ளது. சிறிது நேரத்தில் மீட்பு பொத்தானை மீண்டும் கிளிக் செய்யவும்."+ },+ "cameraUnavailableToast": {+ "message": "கேமரா துண்டிக்கப்பட்டது. திரைப் பதிவு தொடர்கிறது."+ },+ "downloadInterruptedLargeToast": {+ "message": "பதிவிறக்கம் தடைப்பட்டது. கோப்பு மிகப் பெரியதாக இருப்பதால் தானாக மீண்டும் முயற்சிக்க முடியாது. எடிட்டரில் இருந்து மீண்டும் சேமிக்க முயற்சிக்கவும்."+ },+ "recordingCorruptToast": {+ "message": "இந்தப் பதிவை இயக்க முடியாது. கோப்பு முழுமையடையாமல் அல்லது சேதமடைந்திருக்கலாம். சேமி மெனுவில் இருந்து மூலக் கோப்பைப் பதிவிறக்க முயற்சிக்கவும்."}}diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.jsonindex c621ea9..c060f34 100644--- a/src/_locales/tr/messages.json+++ b/src/_locales/tr/messages.json@@ -63,6 +63,18 @@"message": "Görünüşe göre bu web sitesinin güvenlik ayarları, tarayıcı uzantılarının bu sayfada kameranızı veya mikrofonunuzu kullanmasını engelliyor. Bunlarla kayıt yapmak için başka bir sekmede kayda başlayın ve kayıt başladıktan sonra buraya geri dönün.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Kaydınız yüklenemedi",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Görünüşe göre Screenity kaydı cihazınızın deposundan yükleyemedi. Silinmiş veya taşınmış olabilir. Bu sorun devam ederse, lütfen [email protected] adresinden bizimle iletişime geçin.",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Depolama sorunu nedeniyle kayıt durdu. Kısmi kaydınız kaydedildi.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Kamera erişimine izin ver","description": "Kamera erişimine izin verme düğmesi"@@ -359,6 +371,18 @@"message": "Bu sekme açık kalmalıdır. Kaydınız hazır olduğunda güncellenecektir.","description": "Kum havuzu sayfasındaki açıklama (kayıt / kaydediliyor)"},+ "sandboxFinalizingRecording": {+ "message": "Kayıt sonlandırılıyor...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Orijinaline geri alındı",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Değişiklikler kaydedildi",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Editör","description": "Kum havuzu editör sayfasındaki başlık"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "İptal","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Kaydınız hâlâ hazırlanıyor…"+ },+ "editorStuckDescription": {+ "message": "Screenity, kaydınızı yüklemekte normalden daha uzun sürüyor. Verileriniz hâlâ bu cihazda olabilir. Kurtarmayı deneyin veya kayıt geri gelmezse bizimle iletişime geçin."+ },+ "editorStuckTryRecover": {+ "message": "Kurtarmayı deneyin"+ },+ "editorStuckGetHelp": {+ "message": "Yardım alın"+ },+ "editorRecoveryFailedTitle": {+ "message": "Kaydınız açılamadı"+ },+ "editorRecoveryFailedDescription": {+ "message": "Kayıt düzenleyiciye yüklenirken bir sorun oluştu. Kaydınız hâlâ cihazınızda kayıtlı olabilir. Şimdi kurtarmayı deneyebilirsiniz."+ },+ "downloadGIFTooLongToast": {+ "message": "GIF dışa aktarımı en fazla 30 saniyedir. Klibinizi kısaltıp tekrar deneyin."+ },+ "audioSilentToast": {+ "message": "Ses algılanmadı. Mikrofonunuzu, sessize alma düğmesini veya ses cihazınızı kontrol edin."+ },+ "restartFailedToast": {+ "message": "Kaydınız yeniden başlatılamadı. Durdurup yeniden başlatmayı deneyin."+ },+ "recordingFailedModalTitle": {+ "message": "Kayıt başlatılamadı"+ },+ "recordingFailedModalDescription": {+ "message": "Bir şey kaydın başlamasını engelledi. Lütfen tekrar deneyin. Sorun devam ederse [email protected] adresinden bize ulaşın."+ },+ "editAudioTooLargeTitle": {+ "message": "Ses dosyası çok büyük"+ },+ "editAudioTooLargeDescription": {+ "message": "Daha kısa bir ses klibi deneyin. Büyük dosyalar tarayıcıda işlenemez. Orijinal kaydınız güvendedir."+ },+ "restoreEmptyToast": {+ "message": "Kurtarılabilir kayıt bulunamadı. Veriler silinmiş olabilir."+ },+ "restoreTimeoutToast": {+ "message": "Kurtarma çok uzun sürüyor. Kaydınız güvende. Birazdan Kurtar düğmesine tekrar tıklayın."+ },+ "cameraUnavailableToast": {+ "message": "Kamera bağlantısı kesildi. Ekran kaydı devam ediyor."+ },+ "downloadInterruptedLargeToast": {+ "message": "İndirme kesintiye uğradı. Kayıt, otomatik olarak yeniden denenemeyecek kadar büyük. Düzenleyiciden tekrar kaydetmeyi deneyin."+ },+ "recordingCorruptToast": {+ "message": "Bu kayıt oynatılamıyor. Dosya eksik veya bozuk olabilir. Kaydet menüsünden ham dosyayı indirmeyi deneyin."}}diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.jsonindex 04300bf..32c5529 100644--- a/src/_locales/uk/messages.json+++ b/src/_locales/uk/messages.json@@ -63,6 +63,18 @@"message": "Схоже, налаштування безпеки цього сайту не дозволяють розширенням браузера використовувати камеру або мікрофон на цій сторінці. Щоб записувати з ними, почніть запис в іншій вкладці та поверніться сюди після її початку.","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "Не вдалося завантажити запис",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Схоже, Screenity не зміг завантажити запис зі сховища вашого пристрою. Можливо, його було очищено або переміщено. Якщо це повторюється, зв'яжіться з нами за адресою [email protected].",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "Запис зупинено через проблему зі сховищем. Частковий запис збережено.",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "Дозволити доступ до камери","description": "Allow camera access button"@@ -359,6 +371,18 @@"message": "Залиште цю вкладку відкритою. Вона оновиться з вашим записом, коли він буде готовий.","description": "Description in sandbox page while recording / saving"},+ "sandboxFinalizingRecording": {+ "message": "Завершення запису...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "Повернуто до оригіналу",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "Зміни збережено",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "Редактор","description": "Title in navigation of the sandbox editor page"@@ -1580,5 +1604,65 @@"cancelButton": {"message": "Скасувати","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "Запис ще готується…"+ },+ "editorStuckDescription": {+ "message": "Screenity завантажує ваш запис довше, ніж зазвичай. Можливо, ваші дані ще зберігаються на цьому пристрої. Спробуйте відновити запис або зв'яжіться з нами, якщо він не повернеться."+ },+ "editorStuckTryRecover": {+ "message": "Спробувати відновити"+ },+ "editorStuckGetHelp": {+ "message": "Отримати допомогу"+ },+ "editorRecoveryFailedTitle": {+ "message": "Не вдалося відкрити запис"+ },+ "editorRecoveryFailedDescription": {+ "message": "Під час завантаження запису в редактор сталася помилка. Можливо, ваш запис ще збережено на пристрої. Ви можете спробувати відновити його зараз."+ },+ "downloadGIFTooLongToast": {+ "message": "Експорт у GIF обмежено 30 секундами. Обріжте кліп і спробуйте знову."+ },+ "audioSilentToast": {+ "message": "Звук не виявлено. Перевірте мікрофон, перемикач вимкнення звуку або аудіопристрій."+ },+ "restartFailedToast": {+ "message": "Не вдалося перезапустити запис. Зупиніть його та почніть знову."+ },+ "recordingFailedModalTitle": {+ "message": "Не вдалося розпочати запис"+ },+ "recordingFailedModalDescription": {+ "message": "Щось завадило розпочати запис. Будь ласка, спробуйте ще раз. Якщо це повторюється, напишіть нам на [email protected]."+ },+ "editAudioTooLargeTitle": {+ "message": "Аудіофайл завеликий"+ },+ "editAudioTooLargeDescription": {+ "message": "Спробуйте коротший аудіокліп. Великі файли неможливо обробити в браузері. Ваш оригінальний запис у безпеці."+ },+ "restoreEmptyToast": {+ "message": "Запису для відновлення не знайдено. Можливо, дані було очищено."+ },+ "restoreTimeoutToast": {+ "message": "Відновлення триває надто довго. Ваш запис у безпеці. За мить натисніть Відновити знову."+ },+ "cameraUnavailableToast": {+ "message": "Камеру відключено. Запис екрана триває."+ },+ "downloadInterruptedLargeToast": {+ "message": "Завантаження перервано. Запис завеликий, щоб повторити автоматично. Спробуйте зберегти його знову з редактора."+ },+ "recordingCorruptToast": {+ "message": "Цей запис неможливо відтворити. Файл може бути неповним або пошкодженим. Спробуйте завантажити вихідний файл через меню Зберегти."+ },+ "hostBannerTitle": {+ "message": "Подобається Screenity? Підтримайте подальший розвиток!"+ },+ "hostBannerDescription": {+ "message": "Screenity створює один інді-розробник. Самостійний хостинг безкоштовний, але якщо програма вам корисна, підтримайте її через Pro ❤️"}}diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.jsonindex 3b8e066..b428478 100644--- a/src/_locales/zh_CN/messages.json+++ b/src/_locales/zh_CN/messages.json@@ -63,6 +63,18 @@"message": "此网站的安全设置阻止浏览器扩展在此页面上使用您的摄像头或麦克风。如需使用它们录制,请从另一个标签页开始录制,并在录制开始后切换回此处。","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "无法加载您的录制内容",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Screenity 无法从您设备的存储中加载录制内容。它可能已被清除或移动。如果此问题持续存在,请通过 [email protected] 联系我们。",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "录制因存储问题停止。您的部分录制已保存。",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "允许摄像头访问","description": "Allow camera access button"@@ -359,6 +371,18 @@"message": "保持此选项卡打开。录制/保存完成后,它将更新。","description": "Description in sandbox page while recording / saving"},+ "sandboxFinalizingRecording": {+ "message": "正在完成录制...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "已还原为原始",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "已保存更改",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "编辑器","description": "Title in navigation of the sandbox editor page"@@ -1584,5 +1608,62 @@"cancelButton": {"message": "取消","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "正在准备您的录制…"+ },+ "editorStuckDescription": {+ "message": "Screenity 加载录制的时间比平时更长。您的数据可能仍保存在此设备上。请尝试恢复,如果仍无法加载,请与我们联系。"+ },+ "editorStuckTryRecover": {+ "message": "尝试恢复"+ },+ "editorStuckGetHelp": {+ "message": "获取帮助"+ },+ "editorRecoveryFailedTitle": {+ "message": "无法打开您的录制"+ },+ "editorRecoveryFailedDescription": {+ "message": "将录制加载到编辑器时出现问题。您的录制可能仍保存在设备上。您可以现在尝试恢复。"+ },+ "downloadGIFTooLongToast": {+ "message": "GIF 导出最长为 30 秒。请裁剪您的片段后重试。"+ },+ "audioSilentToast": {+ "message": "未检测到音频。请检查您的麦克风、静音开关或音频设备。"+ },+ "restartFailedToast": {+ "message": "无法重新开始录制。请先停止再重新开始。"+ },+ "recordingFailedModalTitle": {+ "message": "无法开始录制"+ },+ "recordingFailedModalDescription": {+ "message": "录制未能开始。请重试。如果问题持续出现,请通过 [email protected] 与我们联系。"+ },+ "editAudioTooLargeTitle": {+ "message": "音频文件过大"+ },+ "editAudioTooLargeDescription": {+ "message": "请尝试更短的音频片段。过大的文件无法在浏览器中处理。您的原始录制不会受到影响。"+ },+ "restoreEmptyToast": {+ "message": "未找到可恢复的录制。数据可能已被清除。"+ },+ "restoreTimeoutToast": {+ "message": "恢复用时较长。您的录制是安全的。请稍候再次点击“恢复”。"+ },+ "cameraUnavailableToast": {+ "message": "摄像头已断开。屏幕录制继续。"+ },+ "downloadInterruptedLargeToast": {+ "message": "下载已中断。文件过大,无法自动重试。请从编辑器中重新保存。"+ },+ "recordingCorruptToast": {+ "message": "此录制无法播放。文件可能不完整或已损坏。请从“保存”菜单下载原始文件。"+ },+ "stopRecording": {+ "message": "停止录制"}}diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.jsonindex 2b26222..1676e85 100644--- a/src/_locales/zh_TW/messages.json+++ b/src/_locales/zh_TW/messages.json@@ -63,6 +63,18 @@"message": "此網站的安全設定禁止瀏覽器擴充功能在此頁面上使用您的相機或麥克風。若要使用它們錄製,請從另一個分頁開始錄製,並在錄製開始後切換回此處。","description": "Modal description shown when the current page's Permissions-Policy header blocks browser extensions from using camera or microphone"},+ "opfsLoadErrorTitle": {+ "message": "無法載入您的錄製內容",+ "description": "Modal title shown when the editor cannot read the recording file from the device's storage"+ },+ "opfsLoadErrorDescription": {+ "message": "Screenity 無法從您的裝置儲存空間載入錄製內容。它可能已被清除或移動。如果此情況持續發生,請透過 [email protected] 聯絡我們。",+ "description": "Modal description shown when the editor cannot read the recording file from the device's storage"+ },+ "recordingWriterFailedToast": {+ "message": "錄製因儲存問題停止。您的部分錄製已儲存。",+ "description": "Toast shown when the recording chunk writer fails mid-recording and the partial file is preserved"+ },"allowCameraAccessButton": {"message": "允許攝影機存取","description": "Allow camera access button"@@ -359,6 +371,18 @@"message": "請維持這個分頁開啟。您的錄影就緒後它便會更新並顯示您的錄影。Keep this tab open. It will update with your recording when it's ready.","description": "Description in sandbox page while recording / saving"},+ "sandboxFinalizingRecording": {+ "message": "正在完成錄影...",+ "description": "Shown over the player when the editor is waiting for the recorder to finish flushing the recording to disk"+ },+ "sandboxToastReverted": {+ "message": "已還原為原始",+ "description": "Toast confirmation shown when the user reverts edits to the original recording"+ },+ "sandboxToastSaved": {+ "message": "已儲存變更",+ "description": "Toast confirmation shown when the user saves an edit operation"+ },"sandboxEditorMainTitle": {"message": "編輯器","description": "Title in navigation of the sandbox editor page"@@ -1588,5 +1612,59 @@"cancelButton": {"message": "取消","description": "Generic cancel button label"+ },+ "editorStuckTitle": {+ "message": "正在準備您的錄影…"+ },+ "editorStuckDescription": {+ "message": "Screenity 載入錄影的時間比平常更長。您的資料可能仍保存在此裝置上。請嘗試復原,若仍無法載入,請與我們聯絡。"+ },+ "editorStuckTryRecover": {+ "message": "嘗試復原"+ },+ "editorStuckGetHelp": {+ "message": "取得協助"+ },+ "editorRecoveryFailedTitle": {+ "message": "無法開啟您的錄影"+ },+ "editorRecoveryFailedDescription": {+ "message": "將錄影載入編輯器時發生問題。您的錄影可能仍儲存在裝置上。您可以立即嘗試復原。"+ },+ "downloadGIFTooLongToast": {+ "message": "GIF 匯出最長為 30 秒。請修剪您的片段後再試一次。"+ },+ "audioSilentToast": {+ "message": "未偵測到音訊。請檢查您的麥克風、靜音開關或音訊裝置。"+ },+ "restartFailedToast": {+ "message": "無法重新開始錄影。請先停止再重新開始。"+ },+ "recordingFailedModalTitle": {+ "message": "無法開始錄影"+ },+ "recordingFailedModalDescription": {+ "message": "錄影未能開始。請再試一次。若問題持續發生,請透過 [email protected] 與我們聯絡。"+ },+ "editAudioTooLargeTitle": {+ "message": "音訊檔案過大"+ },+ "editAudioTooLargeDescription": {+ "message": "請嘗試較短的音訊片段。過大的檔案無法在瀏覽器中處理。您的原始錄影不會受到影響。"+ },+ "restoreEmptyToast": {+ "message": "找不到可復原的錄影。資料可能已被清除。"+ },+ "restoreTimeoutToast": {+ "message": "復原花費較長時間。您的錄影是安全的。請稍候再次點擊「復原」。"+ },+ "cameraUnavailableToast": {+ "message": "攝影機已中斷連線。螢幕錄影繼續。"+ },+ "downloadInterruptedLargeToast": {+ "message": "下載已中斷。檔案過大,無法自動重試。請從編輯器中重新儲存。"+ },+ "recordingCorruptToast": {+ "message": "此錄影無法播放。檔案可能不完整或已損毀。請從「儲存」選單下載原始檔案。"}}diff --git a/src/manifest.json b/src/manifest.jsonindex 6f21076..a87fdf1 100755--- a/src/manifest.json+++ b/src/manifest.json@@ -3,7 +3,7 @@"name": "__MSG_extName__","description": "__MSG_extDesc__","default_locale": "en",- "version": "4.3.9",+ "version": "4.4.0","background": {"service_worker": "background.bundle.js"},diff --git a/src/media/fastRecorderGate.ts b/src/media/fastRecorderGate.tsindex af7cbe1..d4f09e4 100644--- a/src/media/fastRecorderGate.ts+++ b/src/media/fastRecorderGate.ts@@ -1,7 +1,13 @@declare const chrome: any;-// @ts-ignore — mediabunny ships types but this file is loose with any-import { Input, BlobSource, ALL_FORMATS } from "mediabunny";+// mediabunny is ~3MB; defer until validateFastRecorderOutputBlob runs.+let _mediabunnyPromise: Promise<typeof import("mediabunny")> | null = null;+const loadMediabunny = () => {+ if (!_mediabunnyPromise) {+ _mediabunnyPromise = import("mediabunny");+ }+ return _mediabunnyPromise;+};export type FastRecorderProbeResult = {ok: boolean;@@ -90,11 +96,45 @@ export const getFastRecorderStickyState = async (): Promise<FastRecorderStickySt}};+// Stream-setup failures, not codec issues. Don't sticky-disable on these.+const TRANSIENT_ERROR_PATTERNS = [+ /no video track/i,+ /stream missing/i,+ /display stream missing/i,+ /track ended/i,+ /track inactive/i,+ /capture stream is not ready/i,+ // Hardware codec reclaimed by Chrome (idle/background/pressure).+ /codec reclaimed/i,+ /reclaimed due to inactivity/i,+ // stop() raced with an in-flight encode/flush.+ /encoder.*closed/i,+ /encoder is closed/i,+];++export const isTransientFastRecorderError = (errorString: string) => {+ if (!errorString) return false;+ return TRANSIENT_ERROR_PATTERNS.some((re) => re.test(errorString));+};+const isTransientError = isTransientFastRecorderError;+export const markFastRecorderFailure = async (reasonCode: string,details: Record<string, any> = {}) => {try {+ const errStr = typeof details?.error === "string" ? details.error : "";+ if (isTransientError(errStr)) {+ await chrome.storage.local.set({+ [STORAGE_KEYS.lastFailureAt]: Date.now(),+ fastRecorderTransientFailure: {+ reasonCode,+ details,+ at: Date.now(),+ },+ });+ return;+ }await chrome.storage.local.set({[STORAGE_KEYS.stickyDisabled]: true,[STORAGE_KEYS.stickyReason]: reasonCode,@@ -294,9 +334,7 @@ export const probeFastRecorderSupport = async (): Promise<FastRecorderProbeResulawait chrome.storage.local.set({[STORAGE_KEYS.probe]: { ok, reasons, details, at },});- } catch {- // ignore- }+ } catch {}return { ok, reasons, details, at };} catch (err: any) {@@ -315,9 +353,7 @@ export const probeFastRecorderSupport = async (): Promise<FastRecorderProbeResulawait chrome.storage.local.set({[STORAGE_KEYS.probe]: result,});- } catch {- // ignore- }+ } catch {}return result;}};@@ -366,14 +402,10 @@ export const validateFastRecorderOutputBlob = async (details.recordingId = opts.recordingId;}- // Structural validation via the mediabunny demuxer. Handles moov-at-end- // (fastStart: false) efficiently, unlike the <video> element which has to- // scan the full file. This replaces the earlier <video>.onloadedmetadata +- // seek + requestVideoFrameCallback + black-frame pixel sample pipeline —- // those were designed around paranoia when we had no other structural check,- // and they stacked to ~3-4s of sequential timeouts against fastStart-false- // MP4s.+ // mediabunny handles moov-at-end without the ~3-4s timeout stacking+ // the old <video>+seek+rVFC pipeline incurred.try {+ const { Input, BlobSource, ALL_FORMATS } = await loadMediabunny();const demuxInput: any = new Input({formats: ALL_FORMATS,source: new BlobSource(blob),@@ -434,9 +466,7 @@ export const validateFastRecorderOutputBlob = async (ts: Date.now(),},});- } catch {- // ignore- }+ } catch {}return { ok, hardFail, reasons, details };};diff --git a/src/pages/Background/alarms/handleAlarm.js b/src/pages/Background/alarms/handleAlarm.jsindex 19a3f84..a907536 100644--- a/src/pages/Background/alarms/handleAlarm.js+++ b/src/pages/Background/alarms/handleAlarm.js@@ -1,7 +1,9 @@import { stopRecording } from "../recording/stopRecording.js";import { sendMessageTab } from "../tabManagement";import { sendMessageRecord } from "../recording/sendMessageRecord.js";+import { handleRecordingError } from "../recording/recordingHelpers.js";import { diagEvent } from "../../utils/diagnosticLog";+import { lifecycle } from "../../utils/lifecycleLog";import { chunksStore } from "../recording/chunkHandler";import { emitRecordingTelemetry } from "../recording/emitRecordingTelemetry";import {@@ -16,17 +18,8 @@ import {export { FIRST_CHUNK_WATCHDOG_ALARM, RECORDER_KEEPALIVE_ALARM };-// Best-effort attempt to salvage a recording whose tab missed the watchdog.-// Sends stop-recording-tab and waits for `video-ready` (the signal that the-// recorder's normal stop/flush/finalize pipeline succeeded). If the tab is-// only partially hung (e.g. main thread briefly pinned, background-throttled-// then resumed), this can recover an otherwise-lost recording. If the tab is-// truly dead, the timeout fires and the caller proceeds with the error path.-//-// For WebCodecs specifically this matters a lot: the muxer only finalizes-// inside the recorder tab, so without this path the MP4's moov box is never-// written and chunks on disk are unplayable. For MediaRecorder it still helps-// by draining any pending in-memory samples that hadn't yet reached IDB.+// WebCodecs muxer only finalizes inside the recorder tab; without this salvage+// step the MP4 moov never gets written and chunks on disk are unplayable.const STALL_RECOVERY_TIMEOUT_MS = 5000;const attemptStallRecovery = (recordingTabId) => {return new Promise((resolve) => {@@ -49,8 +42,7 @@ const attemptStallRecovery = (recordingTabId) => {recordingTabId,{ type: "stop-recording-tab", reason: "stall-recovery" },() => {- // Swallow lastError — the tab may be unresponsive; the timeout- // below is the authoritative signal.+ // timeout below is authoritative; swallow lastErrorvoid chrome.runtime.lastError;},);@@ -64,11 +56,8 @@ const attemptStallRecovery = (recordingTabId) => {});};-// Utility to handle tab messaging logic.-// `tab` is an optional Chrome Tab object used as a fallback when the stored-// activeTab is no longer valid (e.g. when called from an action-button click).-// When called from an alarm — where there is no current tab — pass null;-// the function will skip the fallback branch gracefully.+// `tab` fallback used when stored activeTab is stale (e.g. action-button click).+// Alarms pass null since no current tab is available.const handleTabMessaging = async (tab) => {const { activeTab } = await chrome.storage.local.get(["activeTab"]);@@ -78,7 +67,6 @@ const handleTabMessaging = async (tab) => {if (targetTab) {sendMessageTab(activeTab, { type: "stop-recording-tab" });} else if (tab?.id) {- // Only reachable when a real tab object was provided (not from alarms).sendMessageTab(tab.id, { type: "stop-recording-tab" });chrome.storage.local.set({ activeTab: tab.id });}@@ -87,8 +75,18 @@ const handleTabMessaging = async (tab) => {}};+// Coalesce stacked post-wake alarm ticks to one per 30s.+let _lastKeepaliveTickAt = 0;+export const handleAlarm = async (alarm) => {if (alarm.name === RECORDER_KEEPALIVE_ALARM) {+ const now = Date.now();+ if (now - _lastKeepaliveTickAt < 30_000) {+ // stacked post-wake tick; real alarms fire every 60s+ return;+ }+ _lastKeepaliveTickAt = now;+const snap = await chrome.storage.local.get(["recordingTab","recording",@@ -117,7 +115,6 @@ export const handleAlarm = async (alarm) => {const WATCHDOG_STALE_MS = 90_000; // chunks arrive every 2s; 45x headroomconst notReady = !snap.firstChunkAt;const pausedNow = !!snap.paused;- const now = Date.now();const age = now - (snap.lastChunkAt || 0);const stallLevel = snap.recordingStallLevel || 0;@@ -156,13 +153,7 @@ export const handleAlarm = async (alarm) => {tabId: snap.recordingTab,});- // Before giving up, ask the recorder tab to run its normal stop- // pipeline. A tab that's only partially hung (main thread briefly- // pinned, background-throttled then resumed) can still process this- // and deliver a valid recording via `video-ready`. For WebCodecs this- // is especially important — the muxer only finalizes inside the- // recorder tab, so without this pathway the MP4's moov atom is never- // written and chunks on disk are unplayable.+ // partially hung tabs can still deliver via `video-ready`const recovered = await attemptStallRecovery(snap.recordingTab);if (recovered) {diagEvent("recording-stall-recovered", {@@ -192,14 +183,15 @@ export const handleAlarm = async (alarm) => {lastChunkAt: null,});} catch {}- chrome.runtime- .sendMessage({- type: "recording-error",+ try {+ await handleRecordingError({error: "stream-error",why: "Recording stopped: the recorder tab became unresponsive.",errorCode: "recording-stall-unrecoverable",- })- .catch(() => {});+ });+ } catch (err) {+ console.warn("[Screenity][BG] stall-unrecoverable handler failed", err);+ }return;}return;@@ -212,9 +204,6 @@ export const handleAlarm = async (alarm) => {diagEvent("alarm-fired");stopRecording();sendMessageRecord({ type: "stop-recording-tab" });- // Pass null: alarms fire without a user-initiated tab context.- // handleTabMessaging will use the stored activeTab and skip the- // tab-object fallback branch when null is provided.await handleTabMessaging(null);}@@ -223,16 +212,45 @@ export const handleAlarm = async (alarm) => {}if (alarm.name === FIRST_CHUNK_WATCHDOG_ALARM) {- // No data received from MediaRecorder within the timeoutconst { recording } = await chrome.storage.local.get(["recording"]);if (recording) {diagEvent("error", { note: "first-chunk-watchdog-fired" });- sendMessageRecord({- type: "recording-error",- error: "stream-error",- why: "Recording failed — no video data received within 8 seconds. The tab may have been throttled. Please try again.",- errorCode: "no-first-chunk",- }).catch(() => {});+ // 1500ms cap so a wedged tab can't delay the user-facing error+ let snapshot = null;+ let snapshotError = null;+ try {+ snapshot = await Promise.race([+ sendMessageRecord({ type: "recorder-state-snapshot" }),+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error("snapshot-timeout")), 1500),+ ),+ ]);+ } catch (err) {+ snapshotError = err?.message || String(err);+ }+ lifecycle("BG.watchdog", "first-chunk-fired", {+ snapshot: snapshot || null,+ snapshotError,+ });+ try {+ await chrome.storage.local.set({+ lastFirstChunkWatchdog: {+ ts: Date.now(),+ snapshot: snapshot || null,+ snapshotError,+ },+ });+ } catch {}+ // handleRecordingError (not sendMessageRecord) so the editor gets notified+ try {+ await handleRecordingError({+ error: "stream-error",+ why: "Recording failed: no video data received within 8 seconds. The tab may have been throttled. Please try again.",+ errorCode: "no-first-chunk",+ });+ } catch (err) {+ console.warn("[Screenity][BG] first-chunk watchdog handler failed", err);+ }}await chrome.alarms.clear(FIRST_CHUNK_WATCHDOG_ALARM);return;@@ -258,7 +276,7 @@ export const handleAlarm = async (alarm) => {const hasActiveRecording = Boolean(recording || pendingRecording || restarting);if (hasActiveRecording) {- // Never clear local chunks while a new recording is active; retry soon.+ // never clear chunks during an active recordingconst retryAt = Date.now() + 5 * 60 * 1000;await chrome.alarms.create(CLOUD_LOCAL_PLAYBACK_ALARM, { when: retryAt })diff --git a/src/pages/Background/auth/loginWithWebsite.js b/src/pages/Background/auth/loginWithWebsite.jsindex 56db40d..c750072 100644--- a/src/pages/Background/auth/loginWithWebsite.js+++ b/src/pages/Background/auth/loginWithWebsite.js@@ -4,13 +4,33 @@ const API_BASE = process.env.SCREENITY_API_BASE_URL;const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";-export const loginWithWebsite = async () => {+const MAX_REFRESH_DEPTH = 2;++// MV3 SW fetch has no default timeout; cap so hung connections fall through to cached auth.+const AUTH_FETCH_TIMEOUT_MS = 15000;+const fetchWithTimeout = (url, opts = {}) => {+ // reject as AbortError so timeout-path callers handle this identically+ if (typeof navigator !== "undefined" && navigator.onLine === false) {+ const err = new Error("auth-fetch-offline");+ err.name = "AbortError";+ return Promise.reject(err);+ }+ const controller = new AbortController();+ const timer = setTimeout(+ () => controller.abort("auth-fetch-timeout"),+ AUTH_FETCH_TIMEOUT_MS,+ );+ return fetch(url, { ...opts, signal: controller.signal }).finally(() =>+ clearTimeout(timer),+ );+};++export const loginWithWebsite = async (_depth = 0) => {if (!CLOUD_FEATURES_ENABLED) {return { authenticated: false, instantMode: false };}- // User explicitly chose to stay logged out — respect that until they- // initiate a login themselves (handle-login clears this flag).+ // cleared by handle-login when user re-initiates loginconst { stayLoggedOut } = await chrome.storage.local.get(["stayLoggedOut"]);if (stayLoggedOut) {return { authenticated: false, instantMode: false };@@ -29,7 +49,7 @@ export const loginWithWebsite = async () => {}const now = Date.now();- const FRESH_FOR = 1000 * 60 * 60 * 4; // 4 hours+ const FRESH_FOR = 1000 * 60 * 60 * 4;let isTokenInvalid = false;if (lastAuthCheck && now - lastAuthCheck < FRESH_FOR) {@@ -46,7 +66,7 @@ export const loginWithWebsite = async () => {]);if (screenityUser) {- // Single storage write to avoid multiple onChanged events+ // single write to avoid multiple onChanged eventsawait chrome.storage.local.set({onboarding: false,isLoggedIn: true,@@ -71,12 +91,12 @@ export const loginWithWebsite = async () => {};}- // Cache is marked fresh but user payload is missing; force a verify call.+ // fresh marker but missing user payload; force a verify callawait chrome.storage.local.set({ lastAuthCheck: 0 });}try {- const response = await fetch(`${API_BASE}/auth/verify`, {+ const response = await fetchWithTimeout(`${API_BASE}/auth/verify`, {headers: {Authorization: `Bearer ${screenityToken}`,},@@ -114,7 +134,6 @@ export const loginWithWebsite = async () => {const { originalTabId } = await chrome.storage.local.get("originalTabId");if (originalTabId) {- // Clear immediately so subsequent cached calls don't re-fire.await chrome.storage.local.remove("originalTabId");chrome.tabs.update(originalTabId, { active: true });@@ -137,21 +156,28 @@ export const loginWithWebsite = async () => {};} catch (err) {if (isTokenInvalid) {- try {- const refreshRes = await fetch(`${API_BASE}/auth/refresh`, {- credentials: "include",- });- if (refreshRes.ok) {- const { token: newToken } = await refreshRes.json();- await chrome.storage.local.set({ screenityToken: newToken });-- return await loginWithWebsite();+ if (_depth >= MAX_REFRESH_DEPTH) {+ console.warn(+ "[Auth] verify-after-refresh still failing; forcing logout to break loop",+ );+ } else {+ try {+ const refreshRes = await fetchWithTimeout(+ `${API_BASE}/auth/refresh`,+ { credentials: "include" },+ );+ if (refreshRes.ok) {+ const { token: newToken } = await refreshRes.json();+ await chrome.storage.local.set({ screenityToken: newToken });++ return await loginWithWebsite(_depth + 1);+ }+ } catch (refreshErr) {+ console.error("❌ Refresh failed:", refreshErr.message);}- } catch (refreshErr) {- console.error("❌ Refresh failed:", refreshErr.message);}- // Token is invalid and refresh failed: perform full logout.+ // refresh failed; full logoutawait chrome.storage.local.remove(["screenityToken","screenityUser",@@ -163,7 +189,7 @@ export const loginWithWebsite = async () => {return { authenticated: false, instantMode: false };}- // Network/transient error: keep existing auth state instead of forcing logout.+ // transient error: keep existing auth stateconst {screenityUser,isSubscribed,diff --git a/src/pages/Background/backup/initBackup.js b/src/pages/Background/backup/initBackup.jsindex 0f7dae0..d5cb936 100644--- a/src/pages/Background/backup/initBackup.js+++ b/src/pages/Background/backup/initBackup.js@@ -14,16 +14,30 @@ export const initBackup = async (request, id) => {},(tab) => {chrome.storage.local.set({ backupTab: tab.id });- chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {+ let settled = false;+ const safetyId = setTimeout(() => {+ if (settled) return;+ settled = true;+ chrome.tabs.onUpdated.removeListener(listener);+ console.warn(+ "[Screenity][BG] backup tab load timed out",+ tab.id,+ );+ }, 30000);+ function listener(tabId, changeInfo) {if (tabId === tab.id && changeInfo.status === "complete") {+ if (settled) return;+ settled = true;+ clearTimeout(safetyId);+ chrome.tabs.onUpdated.removeListener(listener);sendMessageTab(tab.id, {type: "init-backup",request: request,tabId: id,});- chrome.tabs.onUpdated.removeListener(listener);}- });+ }+ chrome.tabs.onUpdated.addListener(listener);});};diff --git a/src/pages/Background/drive/handleSaveToDrive.js b/src/pages/Background/drive/handleSaveToDrive.jsindex d443f94..36077c4 100644Binary files a/src/pages/Background/drive/handleSaveToDrive.js and b/src/pages/Background/drive/handleSaveToDrive.js differdiff --git a/src/pages/Background/drive/handleSignOutDrive.js b/src/pages/Background/drive/handleSignOutDrive.jsindex c28122f..70e5332 100644--- a/src/pages/Background/drive/handleSignOutDrive.js+++ b/src/pages/Background/drive/handleSignOutDrive.js@@ -1,7 +1,11 @@export const handleSignOutDrive = async () => {const { token } = await chrome.storage.local.get(["token"]);- var url = "https://accounts.google.com/o/oauth2/revoke?token=" + token;- fetch(url);+ // POST keeps the token out of URL history, referrer headers, and access logs.+ fetch("https://accounts.google.com/o/oauth2/revoke", {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: `token=${encodeURIComponent(token)}`,+ });chrome.identity.removeCachedAuthToken({ token: token });chrome.storage.local.set({ token: false });diff --git a/src/pages/Background/index.js b/src/pages/Background/index.jsindex 5be91bd..7cb5fd7 100644--- a/src/pages/Background/index.js+++ b/src/pages/Background/index.js@@ -5,12 +5,14 @@ import {messageDispatcher,} from "../../messaging/messageRouter";import { hydrateDiagnosticLog, diagEvent } from "../utils/diagnosticLog";+import { initCountdownFallback } from "./recording/countdownFallback";+import { initLifecycleObserver } from "./lifecycleObserver";+import {+ listSessionDirs,+ destroySessionDir,+} from "../CloudRecorder/recorderStorage/opfsKvStore";-// Clear any storage flags that act as in-progress locks and could have been-// left in a "true" state if the service worker was killed mid-operation.-// Must run before any message handler or alarm handler has a chance to bail-// out on a stale lock. Storage reads/writes are fast enough that they-// complete well before any queued event is dispatched to the worker.+// Must run before any message/alarm handler can bail on a stale lock.const clearStaleLocks = async () => {try {const {@@ -18,6 +20,9 @@ const clearStaleLocks = async () => {postStopEditorOpening,postStopEditorOpened,recording,+ pendingRecording,+ restarting,+ recordingTab,multiMode,region,} = await chrome.storage.local.get([@@ -25,6 +30,9 @@ const clearStaleLocks = async () => {"postStopEditorOpening","postStopEditorOpened","recording",+ "pendingRecording",+ "restarting",+ "recordingTab","multiMode","region",]);@@ -32,15 +40,59 @@ const clearStaleLocks = async () => {const stale = {};if (sendingChunks) {stale.sendingChunks = false;- console.warn("[Screenity][BG] Stale lock found on startup: sendingChunks — clearing");+ console.warn("[Screenity][BG] Stale lock found on startup: sendingChunks, clearing");}if (postStopEditorOpening) {stale.postStopEditorOpening = false;- console.warn("[Screenity][BG] Stale lock found on startup: postStopEditorOpening — clearing");+ console.warn("[Screenity][BG] Stale lock found on startup: postStopEditorOpening, clearing");}if (postStopEditorOpened) {stale.postStopEditorOpened = false;- console.warn("[Screenity][BG] Stale lock found on startup: postStopEditorOpened — clearing");+ console.warn("[Screenity][BG] Stale lock found on startup: postStopEditorOpened, clearing");+ }++ // SW died mid-dispatch or tab closed+ if (recording || pendingRecording || restarting) {+ let tabAlive = false;+ if (recordingTab) {+ try {+ await new Promise((resolve) => {+ chrome.tabs.get(recordingTab, (tab) => {+ tabAlive = !chrome.runtime.lastError && Boolean(tab);+ resolve();+ });+ });+ } catch {+ tabAlive = false;+ }+ }+ if (!tabAlive) {+ stale.recording = false;+ stale.pendingRecording = false;+ stale.restarting = false;+ stale.recordingTab = null;+ // stale stallLevel=1 from a prior crash would skip wake-aggressive next run+ stale.recordingStallLevel = 0;+ stale.firstChunkAt = null;+ stale.lastChunkAt = null;+ stale.customRegion = false;+ stale.offscreen = false;+ stale.memoryError = false;+ // keep editorRecordingError + sandboxTab; the editor reads them on mount+ // and onTabRemovedListener clears sandboxTab when the editor closes.+ stale.backup = false;+ stale.backupSetup = false;+ stale.backupTab = null;+ stale.paused = false;+ stale.pausedAt = null;+ stale.totalPausedMs = 0;+ stale.tabRecordedID = null;+ stale.recordingUiTabId = null;+ console.warn(+ "[Screenity][BG] Stale recording state on startup (no live recorderTab) - clearing",+ { recording, pendingRecording, restarting, recordingTab },+ );+ }}if (multiMode && !recording) {@@ -48,12 +100,12 @@ const clearStaleLocks = async () => {stale.multiSceneCount = 0;stale.multiProjectId = null;stale.multiLastSceneId = null;- console.warn("[Screenity][BG] Stale multi-mode state found on startup — clearing");+ console.warn("[Screenity][BG] Stale multi-mode state found on startup, clearing");}if (region && !recording) {stale.region = false;- console.warn("[Screenity][BG] Stale region state found on startup — clearing");+ console.warn("[Screenity][BG] Stale region state found on startup, clearing");}if (Object.keys(stale).length > 0) {@@ -63,29 +115,122 @@ const clearStaleLocks = async () => {Object.keys(stale).join(", "),);}++ // drain deferred logout-token-clear if its inline listener died with the SW+ try {+ const {+ logoutPendingTokenClear,+ recording,+ pendingRecording,+ stayLoggedOut,+ } = await chrome.storage.local.get([+ "logoutPendingTokenClear",+ "recording",+ "pendingRecording",+ "stayLoggedOut",+ ]);+ if (+ logoutPendingTokenClear &&+ !recording &&+ !pendingRecording+ ) {+ if (stayLoggedOut === true) {+ await chrome.storage.local.remove([+ "screenityToken",+ "logoutPendingTokenClear",+ ]);+ console.info(+ "[Screenity][BG] Drained deferred logout token-clear on startup",+ );+ } else {+ // re-login during SW death; just clear the marker+ await chrome.storage.local.remove(["logoutPendingTokenClear"]);+ }+ }+ } catch {}++ // setIcon persists across SW restarts; reconcile so a stuck red icon clears+ try {+ const { recording: finalRecording } = await chrome.storage.local.get([+ "recording",+ ]);+ chrome.action.setIcon({+ path: finalRecording+ ? "assets/recording-logo.png"+ : "assets/icon-34.png",+ });+ } catch (err) {+ console.warn("[Screenity][BG] icon reconciliation failed:", err);+ }} catch (err) {console.error("[Screenity][BG] Failed to clear stale startup locks:", err);}};-// Event listeners must be registered synchronously at module evaluation time-// so Chrome counts them for service worker keep-alive.+// reaps cloud-chunks/ session dirs not referenced by any+// cloudRecorderSession:* snapshot or the latest recorderSession.+// without this, an SW kill mid-recording leaks chunks forever.+const cleanupOrphanOpfsSessions = async () => {+ try {+ const dirs = await listSessionDirs();+ if (!dirs.length) return;++ const all = await new Promise((resolve) => {+ try {+ chrome.storage.local.get(null, (snap) => resolve(snap || {}));+ } catch {+ resolve({});+ }+ });++ const liveIds = new Set();+ if (all.recorderSession?.id) liveIds.add(all.recorderSession.id);+ if (all.recorderSession?.opfsSessionId) {+ liveIds.add(all.recorderSession.opfsSessionId);+ }+ for (const key of Object.keys(all)) {+ if (!key.startsWith("cloudRecorderSession:")) continue;+ const session = all[key];+ if (session?.id) liveIds.add(session.id);+ if (session?.opfsSessionId) liveIds.add(session.opfsSessionId);+ }+ // Upload journals can also reference a sessionId whose chunks may still+ // be needed for resume, keep their dirs around.+ for (const [key, value] of Object.entries(all)) {+ if (!key.startsWith("uploadJournal-")) continue;+ if (value?.sessionId) liveIds.add(value.sessionId);+ }++ const orphans = dirs.filter((id) => !liveIds.has(id));+ if (!orphans.length) return;++ await Promise.allSettled(orphans.map((id) => destroySessionDir(id)));+ console.info(+ "[Screenity][BG] Reaped orphan OPFS cloud-chunks sessions:",+ orphans.length,+ );+ } catch (err) {+ console.warn(+ "[Screenity][BG] cleanupOrphanOpfsSessions failed:",+ err,+ );+ }+};++// listeners must register synchronously at module eval so Chrome counts them for SW keep-alivemessageRouter();initializeListeners();setupHandlers();+initCountdownFallback();+initLifecycleObserver();-// Fire-and-forget: clears stale locks from a previous crashed session.-// Runs after listener registration (required synchronous) but before Chrome-// can dispatch any queued events to this worker.+// runs after listener registration, before queued events dispatchclearStaleLocks();+cleanupOrphanOpfsSessions();-// One-time migration for users upgrading from 4.3.7. The finalize-hang bug on-// abrupt stream end caused sticky-disable to fire for many WebCodecs users;-// the underlying cause is fixed in this release (fragmented MP4 + streaming),-// so the sticky flags are no longer warranted and should be cleared once so-// affected users get WebCodecs again on their next recording. The user's-// explicit opt-out (useWebCodecsRecorder === false) is preserved.-const CURRENT_MIGRATION_VERSION = "4.3.9";+// 4.3.7 finalize-hang bug sticky-disabled WebCodecs for many users; clear once.+// User's explicit opt-out (useWebCodecsRecorder === false) is preserved by overwrite anyway.+const CURRENT_MIGRATION_VERSION = "4.3.9-clearStickyTransient3";const runUpgradeMigrations = async () => {try {const { screenityMigratedForVersion } = await chrome.storage.local.get([@@ -103,6 +248,7 @@ const runUpgradeMigrations = async () => {"lastWebCodecsFailureAt","lastWebCodecsFailureCode","lastFailedValidation",+ "useWebCodecsRecorder",]);await chrome.storage.local.set({screenityMigratedForVersion: CURRENT_MIGRATION_VERSION,@@ -116,7 +262,42 @@ const runUpgradeMigrations = async () => {};runUpgradeMigrations();-// Hydrate the diagnostic log from storage and record that the SW (re)started.-hydrateDiagnosticLog().then(() => {- diagEvent("sw-init", { ts: Date.now() });+// records whether a recording was active when the previous SW shut down+hydrateDiagnosticLog().then(async () => {+ let priorState = null;+ try {+ const snap = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "recordingTab",+ "recordingStartTime",+ "swLastSeenAt",+ ]);+ priorState = {+ recording: !!snap.recording,+ pendingRecording: !!snap.pendingRecording,+ hadRecordingTab: snap.recordingTab != null,+ msSinceLastBeat:+ typeof snap.swLastSeenAt === "number"+ ? Date.now() - snap.swLastSeenAt+ : null,+ msSinceRecordingStart:+ typeof snap.recordingStartTime === "number"+ ? Date.now() - snap.recordingStartTime+ : null,+ };+ } catch {}+ diagEvent("sw-init", { ts: Date.now(), priorState });});++// alarms (not setInterval) so the SW can idle-evict between ticks+try {+ chrome.storage.local.set({ swLastSeenAt: Date.now() }).catch(() => {});+ chrome.alarms.create("sw-heartbeat", {+ periodInMinutes: 1,+ });+ chrome.alarms.onAlarm.addListener((alarm) => {+ if (alarm?.name !== "sw-heartbeat") return;+ chrome.storage.local.set({ swLastSeenAt: Date.now() }).catch(() => {});+ });+} catch {}diff --git a/src/pages/Background/lifecycleObserver.js b/src/pages/Background/lifecycleObserver.jsnew file mode 100644index 0000000..4b7b7b7--- /dev/null+++ b/src/pages/Background/lifecycleObserver.js@@ -0,0 +1,59 @@+// watches chrome.storage.local for transitions on a fixed set of+// recording-state keys and logs them to lifecycleLog so we don't have+// to instrument each BG call site. wired once at SW startup.+import { lifecycle } from "../utils/lifecycleLog";++// Keys whose transitions we care about for cross-recording bug analysis.+// `lifecycleLog` itself is excluded to avoid infinite recursion.+const TRACKED_KEYS = new Set([+ "recordingTab",+ "recordingUiTabId",+ "tabRecordedID",+ "sandboxTab",+ "recording",+ "pendingRecording",+ "restarting",+ "offscreen",+ "region",+ "customRegion",+ "recordingType",+ "useWebCodecsRecorder",+ "fastRecorderInUse",+ "fastRecorderDisabledForDevice",+ "memoryError",+ "lastRecordingBackendRef",+ "backup",+ "backupSetup",+ "backupTab",+ "editorRecordingError",+]);++const summarizeValue = (v) => {+ if (v === null || v === undefined) return v;+ if (typeof v === "object") {+ try {+ const json = JSON.stringify(v);+ return json.length > 120 ? json.slice(0, 117) + "..." : v;+ } catch {+ return "[unserializable]";+ }+ }+ return v;+};++export const initLifecycleObserver = () => {+ chrome.storage.onChanged.addListener((changes, area) => {+ if (area !== "local") return;+ for (const key of Object.keys(changes)) {+ if (!TRACKED_KEYS.has(key)) continue;+ const { oldValue, newValue } = changes[key];+ // Skip no-op writes (same value).+ if (oldValue === newValue) continue;+ lifecycle("BG.storage", "set", {+ key,+ from: summarizeValue(oldValue),+ to: summarizeValue(newValue),+ });+ }+ });+};diff --git a/src/pages/Background/listeners/index.js b/src/pages/Background/listeners/index.jsindex 36169fe..abbeaa0 100644--- a/src/pages/Background/listeners/index.js+++ b/src/pages/Background/listeners/index.js@@ -1,5 +1,6 @@import { onCommandListener } from "./onCommandListener";import { onInstalledListener } from "./onInstalledListener";+import { onUpdateAvailableListener } from "./onUpdateAvailableListener";import { onTabRemovedListener } from "./onTabRemovedListener";import { onTabActivatedListener } from "./onTabActivatedListener";import { onTabUpdatedListener } from "./onTabUpdatedListener";@@ -8,10 +9,10 @@ import { onActionButtonClickedListener } from "./onActionButtonClickedListener";import { onStartupListener } from "./onStartupListener";import { onMessageExternalListener } from "./onMessageExternalListener";-// Initialize all listenersexport const initializeListeners = () => {onCommandListener();onInstalledListener();+ onUpdateAvailableListener();onTabRemovedListener();onTabActivatedListener();onTabUpdatedListener();diff --git a/src/pages/Background/listeners/onActionButtonClickedListener.js b/src/pages/Background/listeners/onActionButtonClickedListener.jsindex d5b5746..caff76d 100644--- a/src/pages/Background/listeners/onActionButtonClickedListener.js+++ b/src/pages/Background/listeners/onActionButtonClickedListener.js@@ -11,7 +11,6 @@ import { tryResumePendingUploads } from "../recording/resumePendingUploads";const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";-// Utility to handle tab messaging logicconst handleTabMessaging = async (tab) => {const { activeTab, recordingUiTabId, offscreen } =await chrome.storage.local.get([@@ -56,7 +55,6 @@ const handleTabMessaging = async (tab) => {}};-// Utility to open Playground or inject popupconst openPlaygroundOrPopup = async (tab) => {const editorUrlPattern =/https:\/\/app\.screenity\.io\/editor\/([^\/]+)(\/edit)?\/?/;@@ -118,11 +116,13 @@ const openPlaygroundOrPopup = async (tab) => {"stackoverflow.com/",];- const isForbidden = forbiddenURLs.some((url) => tab.url.startsWith(url));+ const tabUrl = String(tab?.url || "");+ const isForbidden = forbiddenURLs.some((url) => tabUrl.startsWith(url));const isPlaygroundOrSetup =- tab.url.includes("/playground.html") || tab.url.includes("/setup.html");+ tabUrl.includes("/playground.html") || tabUrl.includes("/setup.html");- if ((!isForbidden || isPlaygroundOrSetup) && navigator.onLine) {+ // never gate on navigator.onLine; that caused duplicate playground tabs+ if (!isForbidden || isPlaygroundOrSetup) {sendMessageTab(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)));@@ -146,7 +146,6 @@ const openPlaygroundOrPopup = async (tab) => {}};-/** Check whether a tab ID refers to a tab that actually exists. */const doesTabExist = async (tabId) => {if (!Number.isInteger(tabId)) return false;try {@@ -157,7 +156,6 @@ const doesTabExist = async (tabId) => {}};-/** Check whether an offscreen document is actually running. */const isOffscreenAlive = async () => {try {const contexts = await chrome.runtime.getContexts({});@@ -167,7 +165,6 @@ const isOffscreenAlive = async () => {}};-// Main action button listenerexport const onActionButtonClickedListener = () => {chrome.action.onClicked.addListener(async (tab) => {tryResumePendingUploads({ trigger: "actionClick" }).catch(() => {});@@ -258,7 +255,6 @@ export const onActionButtonClickedListener = () => {}} else {console.log("[Screenity][ActionClick] branch: normal-popup");- // Reset storage keys before opening the popupawait chrome.storage.local.set({recordingToScene: false,projectId: null,diff --git a/src/pages/Background/listeners/onCommandListener.js b/src/pages/Background/listeners/onCommandListener.jsindex 911a30a..eb043b7 100644--- a/src/pages/Background/listeners/onCommandListener.js+++ b/src/pages/Background/listeners/onCommandListener.js@@ -1,6 +1,5 @@import { sendMessageTab, getCurrentTab } from "../tabManagement";-// Main command listenerexport const onCommandListener = () => {let lastToggleDrawingAt = 0;const TOGGLE_DRAWING_COOLDOWN_MS = 400;@@ -10,20 +9,29 @@ export const onCommandListener = () => {if (!activeTab || !activeTab.id) return;if (command === "start-recording") {- // Validate if it's possible to inject into content+ // shortcut pressed from another window must not start a second recording+ try {+ const { recording, pendingRecording, restarting } =+ await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "restarting",+ ]);+ if (recording || pendingRecording || restarting) {+ return;+ }+ } catch {}+ const tabUrl = String(activeTab.url || "");if (!(- (navigator.onLine === false &&- !activeTab.url.includes("/playground.html") &&- !activeTab.url.includes("/setup.html")) ||- activeTab.url.startsWith("chrome://") ||- (activeTab.url.startsWith("chrome-extension://") &&- !activeTab.url.includes("/playground.html") &&- !activeTab.url.includes("/setup.html"))+ tabUrl.startsWith("chrome://") ||+ (tabUrl.startsWith("chrome-extension://") &&+ !tabUrl.includes("/playground.html") &&+ !tabUrl.includes("/setup.html"))) &&- !activeTab.url.includes("stackoverflow.com/") &&- !activeTab.url.includes("chrome.google.com/webstore") &&- !activeTab.url.includes("chromewebstore.google.com")+ !tabUrl.includes("stackoverflow.com/") &&+ !tabUrl.includes("chrome.google.com/webstore") &&+ !tabUrl.includes("chromewebstore.google.com")) {sendMessageTab(activeTab.id, { type: "start-stream" });} else {@@ -35,7 +43,6 @@ export const onCommandListener = () => {.then((tab) => {chrome.storage.local.set({ activeTab: tab.id });- // Wait for the tab to loadchrome.tabs.onUpdated.addListener(function _(tabId, changeInfo) {if (tabId === tab.id && changeInfo.status === "complete") {setTimeout(() => {diff --git a/src/pages/Background/listeners/onInstalledListener.js b/src/pages/Background/listeners/onInstalledListener.jsindex 4ef6c00..62c1b8b 100644--- a/src/pages/Background/listeners/onInstalledListener.js+++ b/src/pages/Background/listeners/onInstalledListener.js@@ -12,10 +12,8 @@ export const onInstalledListener = () => {const locale = chrome.i18n.getMessage("@@ui_locale");if (details.reason === "install") {- // Clear storage on fresh installchrome.storage.local.clear();- // Set uninstall URL based on localeconst installQs = await supportContextQuery({ source: "uninstall" });const installUrl = `https://tally.so/r/w8Zro5?${installQs}`;chrome.runtime.setUninstallURL(@@ -39,12 +37,10 @@ export const onInstalledListener = () => {});} else if (details.reason === "update") {if (details.previousVersion === "2.8.6") {- // Do not clear local storage on update; preserve onboarding/versioned keys.chrome.storage.local.set({ updatingFromOld: true });} else {chrome.storage.local.set({ updatingFromOld: false });- // Onboarding for new cloud versionif (details.previousVersion === "3.1.16" && cloudFeaturesEnabled) {chrome.storage.local.set({showProSplash: cloudFeaturesEnabled,@@ -63,15 +59,10 @@ export const onInstalledListener = () => {);}- // Disable backups for older Chrome versions- if (navigator.userAgent.includes("Chrome/")) {- const chromeVersion = parseInt(- navigator.userAgent.match(/Chrome\/([0-9]+)/)?.[1] ?? "0"- );- if (chromeVersion <= 109) {- chrome.storage.local.set({ backup: false });- }- }+ // Backup mode is deprecated: hidden from the settings dropdown and+ // forced off for all users on install/update. OPFS-backed recording+ // covers the same crash-resilience without the picker UX.+ chrome.storage.local.set({ backup: false, backupSetup: false });if (details.reason === "install") {chrome.storage.local.set({ systemAudio: true });@@ -83,7 +74,10 @@ export const onInstalledListener = () => {removeTab(backupTab);}- executeScripts();+ // update only; manifest auto-injects on page load. install would double-mount React on dev.+ if (details.reason === "update") {+ executeScripts();+ }setTimeout(() => {tryResumePendingUploads({ trigger: `onInstalled:${details.reason}` }).catch(diff --git a/src/pages/Background/listeners/onMessageExternalListener.js b/src/pages/Background/listeners/onMessageExternalListener.jsindex 1626622..f203863 100644--- a/src/pages/Background/listeners/onMessageExternalListener.js+++ b/src/pages/Background/listeners/onMessageExternalListener.js@@ -6,6 +6,7 @@ import {clearEditorTabReference,} from "../tabManagement";import { loginWithWebsite } from "../auth/loginWithWebsite";+import { handleFinishMultiRecording } from "../messaging/handlers";const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";@@ -16,8 +17,6 @@ export const onMessageExternalListener = () => {chrome.runtime.onMessageExternal.addListener(async (message, sender, sendResponse) => {if (message.type === "AUTH_SUCCESS" && message.token) {- // User explicitly chose to stay logged out — ignore incoming tokens- // until they initiate a login themselves.const { stayLoggedOut } = await chrome.storage.local.get(["stayLoggedOut",]);@@ -34,6 +33,8 @@ export const onMessageExternalListener = () => {onboarding: false,showProSplash: false,});+ // otherwise the drain listener clobbers this fresh token on next recording-end+ await chrome.storage.local.remove(["logoutPendingTokenClear"]);const auth = await loginWithWebsite();@@ -64,12 +65,11 @@ export const onMessageExternalListener = () => {sendMessageTab(originalTabId, { type: "LOGIN_SUCCESS" });if (sender.tab?.id) {- chrome.tabs.remove(sender.tab.id); // Close login tab+ chrome.tabs.remove(sender.tab.id);}await chrome.storage.local.remove("originalTabId");- // Message tab to update from storagesendMessageTab(originalTabId, {type: "check-auth",senderId: sender.tab.id,@@ -78,7 +78,6 @@ export const onMessageExternalListener = () => {return true;} else if (message.type === "SIGN_OUT") {- // Clear all auth-related storageawait chrome.storage.local.remove(["screenityToken","screenityUser",@@ -172,6 +171,13 @@ export const onMessageExternalListener = () => {} else if (message.type === "PING_FROM_WEBAPP") {sendResponse({ success: true, message: "pong" });+ return true;+ } else if (message.type === "FINISH_MULTI_RECORDING") {+ // Same logic as clicking the popup's Finish button. Used by+ // web-app "I'm done adding scenes" flows and by e2e tests where+ // we can't drive the popup UI directly.+ await handleFinishMultiRecording();+ sendResponse({ success: true });return true;}}diff --git a/src/pages/Background/listeners/onTabRemovedListener.js b/src/pages/Background/listeners/onTabRemovedListener.jsindex a32fae4..8dfe9e8 100644--- a/src/pages/Background/listeners/onTabRemovedListener.js+++ b/src/pages/Background/listeners/onTabRemovedListener.js@@ -1,30 +1,17 @@import { sendMessageTab, clearEditorTabReference } from "../tabManagement";import { removeTab } from "../tabManagement/removeTab";import { sendMessageRecord } from "../recording/sendMessageRecord";+import { isRecordingStartInFlight } from "../recording/startRecording";import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";-/**- * Listener for when a tab is removed.- * It checks if the removed tab is the active recording tab and handles cleanup if so.- */export const onTabRemovedListener = () => {chrome.tabs.onRemoved.addListener(async (tabId) => {try {- const {- recording,- pendingRecording,- restarting,- recordingTab,- tabRecordedID,- recordingUiTabId,- activeTab,- recorderSession,- editorTab,- sandboxTab,- } = await chrome.storage.local.get([+ const flags = await chrome.storage.local.get(["recording","pendingRecording","restarting",+ "recordingStartingAt","recordingTab","tabRecordedID","recordingUiTabId",@@ -33,14 +20,28 @@ export const onTabRemovedListener = () => {"editorTab","sandboxTab",]);+ const {+ recording,+ pendingRecording,+ restarting,+ recordingTab,+ tabRecordedID,+ recordingUiTabId,+ activeTab,+ recorderSession,+ editorTab,+ sandboxTab,+ } = flags;+ // `recording` isn't true yet during start, so without this guard+ // the cleanup below tears down the recorder tab being prepared.+ const startInFlight = isRecordingStartInFlight(flags);if (tabId === editorTab) {await clearEditorTabReference("editor-tab-closed", { tabId });}- // Editor/sandbox tab closed — close the orphaned recorder tab (pinned- // recorder.html) so it doesn't linger. stopRecording() opens editors as- // sandboxTab (not editorTab), so we must check both.+ // close orphaned recorder.html when editor/sandbox closes.+ // stopRecording opens as sandboxTab (not editorTab), so check both.const isEditorOrSandbox = tabId === editorTab || tabId === sandboxTab;if (isEditorOrSandbox) {if (tabId === sandboxTab) {@@ -49,7 +50,12 @@ export const onTabRemovedListener = () => {const isStillRecording =recording ||(recorderSession && recorderSession.status === "recording");- if (!isStillRecording && recordingTab && recordingTab !== tabId) {+ if (+ !startInFlight &&+ !isStillRecording &&+ recordingTab &&+ recordingTab !== tabId+ ) {try {const recTab = await chrome.tabs.get(recordingTab);const recUrl = recTab?.url || "";@@ -59,16 +65,15 @@ export const onTabRemovedListener = () => {) {removeTab(recordingTab);}- } catch {- // Tab already gone- }+ } catch {}chrome.storage.local.set({ recordingTab: null });}}- const recordedTabId = tabRecordedID || recordingTab;+ // tabRecordedID only; non-region tab capture handles close via stream death,+ // and recordingTab fallback would misclassify a recorder.html close.+ const recordedTabId = tabRecordedID || null;- // Check both recording flag AND recorderSessionconst isActivelyRecording =recording ||(recorderSession && recorderSession.status === "recording");@@ -101,14 +106,11 @@ export const onTabRemovedListener = () => {}}- // If the removed tab is the one being recorded (for tab capture)if (!restarting && isActivelyRecording && tabId === recordedTabId) {diagEvent("recorded-tab-closed");- // Clear reference to the removed tabchrome.storage.local.set({ recordingTab: null, tabRecordedID: null });- // Send stop directly to the recorder, not through content script- // This is more reliable as the content script tab may not exist+ // direct to recorder; content script tab may not existtry {await sendMessageRecord({type: "stop-recording-tab",@@ -118,7 +120,6 @@ export const onTabRemovedListener = () => {console.warn("Could not message recorder to stop:", err);}- // Also try to notify the active tab for UI cleanupconst { activeTab } = await chrome.storage.local.get(["activeTab"]);if (activeTab && activeTab !== tabId) {sendMessageTab(activeTab, { type: "stop-pending" }).catch(() => {});@@ -127,18 +128,21 @@ export const onTabRemovedListener = () => {chrome.action.setIcon({ path: "assets/icon-34.png" });}- // If the CloudRecorder tab itself was closed, that's a critical failure+ // recorder.html/cloudrecorder.html closed mid-recording; nothing else writes recording=false hereif (!restarting &&isActivelyRecording &&- tabId === recordingTab &&- recordingTab !== recordedTabId+ tabId === recordingTab) {- diagEvent("crash", { reason: "cloud-recorder-tab-closed", tabId });+ diagEvent("crash", { reason: "recorder-tab-closed", tabId });endDiagSession("crashed");- console.error("CloudRecorder tab was closed during recording!");+ console.error("Recorder tab was closed during recording!");chrome.storage.local.set({recording: false,+ recordingTab: null,+ recordingUiTabId: null,+ tabRecordedID: null,+ pendingRecording: false,recorderSession: recorderSession? { ...recorderSession, status: "crashed", crashedAt: Date.now() }: null,@@ -150,13 +154,10 @@ export const onTabRemovedListener = () => {chrome.action.setIcon({ path: "assets/icon-34.png" });}- // If the recorder tab (recorder.html) is closed after recording ends,- // clear the stale reference so it doesn't break the next recording start.if (tabId === recordingTab && !isActivelyRecording && !pendingRecording) {chrome.storage.local.set({ recordingTab: null });}- // If recorder tab is closed before recording starts, clear pending UI state.const pendingOnly =pendingRecording && !isActivelyRecording && !restarting;if (tabId === recordingTab && pendingOnly) {diff --git a/src/pages/Background/listeners/onUpdateAvailableListener.js b/src/pages/Background/listeners/onUpdateAvailableListener.jsnew file mode 100644index 0000000..dfca697--- /dev/null+++ b/src/pages/Background/listeners/onUpdateAvailableListener.js@@ -0,0 +1,104 @@+// hold extension auto-updates while recording or uploading. otherwise+// chrome applies the update at the next SW idle, the recorder tab's+// runtime context goes invalid mid-session, every chrome.* call throws+// "Extension context invalidated", and the recording is lost.+// re-check on a timer + on storage.onChanged so we reload promptly once+// the surface is idle.+import { diagEvent } from "../../utils/diagnosticLog";++const RECHECK_INTERVAL_MS = 60_000;++let pendingUpdateDetails = null;+let recheckTimer = null;+let storageListener = null;++const hasPendingUploadJournal = async () => {+ try {+ const all = await new Promise((resolve) => {+ try {+ chrome.storage.local.get(null, (s) => resolve(s || {}));+ } catch {+ resolve({});+ }+ });+ for (const [key, value] of Object.entries(all)) {+ if (!key.startsWith("uploadJournal-")) continue;+ if (!value || typeof value !== "object") continue;+ if (value.trackType === "audio") continue;+ if (value.status === "completed") continue;+ return true;+ }+ } catch {}+ return false;+};++const tryApplyUpdate = async () => {+ if (!pendingUpdateDetails) return;+ let snap = {};+ try {+ snap = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "restarting",+ "resumeInProgress",+ ]);+ } catch {+ // storage unreachable, defer+ return;+ }+ const recordingBusy =+ Boolean(snap?.recording) ||+ Boolean(snap?.pendingRecording) ||+ Boolean(snap?.restarting) ||+ Boolean(snap?.resumeInProgress);+ if (recordingBusy) return;+ // Also defer if any non-completed upload journal exists, applying+ // the update would tear down the offscreen doc that resumes them.+ if (await hasPendingUploadJournal()) return;+ diagEvent("extension-update-applied-deferred", {+ version: pendingUpdateDetails?.version || null,+ });+ // chrome.runtime.reload() restarts the extension on the new version.+ // Open extension pages reload as a side-effect; since we've gated on+ // !recording, the recorder tab is already gone or never existed.+ try {+ chrome.runtime.reload();+ } catch (err) {+ console.warn("[Screenity][BG] runtime.reload failed", err);+ }+};++const armRecheck = () => {+ if (recheckTimer) return;+ recheckTimer = setInterval(tryApplyUpdate, RECHECK_INTERVAL_MS);+ if (!storageListener) {+ storageListener = (changes, area) => {+ if (area !== "local") return;+ // A relevant flag flipped, try immediately rather than waiting for+ // the next interval tick. Avoids a 60s stale-update window after+ // the user stops a recording.+ if (+ changes.recording ||+ changes.pendingRecording ||+ changes.restarting ||+ changes.resumeInProgress+ ) {+ tryApplyUpdate();+ }+ };+ chrome.storage.onChanged.addListener(storageListener);+ }+};++export const onUpdateAvailableListener = () => {+ chrome.runtime.onUpdateAvailable.addListener((details) => {+ pendingUpdateDetails = details || { version: null };+ diagEvent("extension-update-available-deferred", {+ version: details?.version || null,+ });+ // Try once immediately, if nothing's recording, apply right away.+ tryApplyUpdate();+ // Otherwise, wait for the recording to finish.+ armRecheck();+ });+};diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.jsindex b407c2b..fb775d9 100644--- a/src/pages/Background/messaging/handlers.js+++ b/src/pages/Background/messaging/handlers.js@@ -1,4 +1,5 @@import { registerMessage } from "../../../messaging/messageRouter";+import { perfMark, perfSpan } from "../../utils/perfMarks";import {focusTab,createTab,@@ -8,12 +9,15 @@ import {} from "../tabManagement";import { startAfterCountdown, startRecording } from "../recording/startRecording";+import { noteCountdownStarted } from "../recording/countdownFallback";import {handleStopRecordingTab,handleStopRecordingTabBackup,} from "../recording/stopRecording";import { sendChunks } from "../recording/sendChunks";import { chunksStore } from "../recording/chunkHandler";+import { openExistingChunksStore } from "../../CloudRecorder/recorderStorage/chooseChunksStore";+import { destroySessionDir } from "../../CloudRecorder/recorderStorage/opfsKvStore";import { handleSaveToDrive } from "../drive/handleSaveToDrive";import { addAlarmListener } from "../alarms/addAlarmListener";import { cancelRecording, handleDismiss } from "../recording/cancelRecording";@@ -30,6 +34,8 @@ import {sendMessageTab,parseEditorTargetUrl,resolveEditorTabForTarget,+ getValidatedEditorTab,+ setEditorTabReference,} from "../tabManagement";import {handleRestart,@@ -78,9 +84,30 @@ import { supportContextQuery } from "../../utils/buildSupportContext";const API_BASE = process.env.SCREENITY_API_BASE_URL;const APP_BASE = process.env.SCREENITY_APP_BASE;++// Flip a project to isPublic:true after recording finishes. v2 removed+// the publish system, so isPublic is the only access gate — without+// this PATCH the share URL we copy to clipboard would 404 for viewers.+// Fire-and-forget; clipboard/toast UX is identical on success or failure.+const markProjectPublic = async (projectId) => {+ if (!projectId || !API_BASE) return;+ try {+ const { screenityToken } = await chrome.storage.local.get("screenityToken");+ if (!screenityToken) return;+ await fetch(`${API_BASE}/videos/${projectId}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${screenityToken}`,+ },+ body: JSON.stringify({ isPublic: true }),+ });+ } catch (err) {+ console.warn("markProjectPublic failed:", err?.message || err);+ }+};const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";-// Debug toggle for post-stop/chunk flowconst DEBUG_POSTSTOP = false;const STOP_RECORDING_TAB_DEBOUNCE_MS = 1200;const CLOUD_LOCAL_PLAYBACK_MAX_BYTES = 250 * 1024 * 1024;@@ -119,6 +146,22 @@ const normalizeLocalPlaybackOffer = (offer = {}) => {const estimatedBytes = Math.max(0, Number(offer.estimatedBytes) || 0);const createdAt = Number(offer.createdAt) || now;+ // storageBackend / opfsSessionId let the read-chunk + clear handlers route+ // to the same backend the writer used. Older offers without these fields+ // default to IDB to match pre-OPFS behaviour.+ const storageBackend =+ offer.storageBackend === "opfs" ? "opfs" : "idb";+ const opfsSessionId =+ storageBackend === "opfs" && offer.opfsSessionId+ ? String(offer.opfsSessionId)+ : null;+ // Container is the mimeType the editor's <video> should use. Defaults+ // to webm for back-compat; WebCodecs sessions overwrite to video/mp4.+ const container =+ offer.container === "video/mp4" ? "video/mp4" : "video/webm";+ const encoderKind =+ offer.encoderKind === "webcodecs" ? "webcodecs" : "mediarecorder";+return {offerId: offer.offerId || crypto.randomUUID(),projectId: offer.projectId || null,@@ -131,12 +174,30 @@ const normalizeLocalPlaybackOffer = (offer = {}) => {estimatedBytes,mediaId: offer.mediaId || null,bunnyVideoId: offer.bunnyVideoId || null,+ storageBackend,+ opfsSessionId,+ container,+ encoderKind,createdAt,expiresAt,updatedAt: now,};};+const offerScreenStore = (offer) => {+ if (offer?.storageBackend === "opfs" && offer.opfsSessionId) {+ return openExistingChunksStore({+ sessionId: offer.opfsSessionId,+ track: "screen",+ backend: "opfs",+ }).store;+ }+ // Pre-migration default: cloud screen track was a localforage instance+ // sharing the regular Recorder's IDB DB / "chunks" store name. The+ // imported chunksStore matches that exactly.+ return chunksStore;+};+const isLocalPlaybackOfferExpired = (offer) =>!offer || Number(offer.expiresAt || 0) <= Date.now();@@ -173,12 +234,19 @@ const clearStoredLocalPlaybackOffer = async ({}if (clearChunks) {- await chunksStore.clear().catch((err) => {+ const targetStore = offerScreenStore(existing);+ await targetStore.clear().catch((err) => {console.warn(- "[Screenity][BG] Failed to clear chunksStore while clearing local playback offer",+ "[Screenity][BG] Failed to clear screen chunks while clearing local playback offer",err,);});+ if (+ existing?.storageBackend === "opfs" &&+ existing?.opfsSessionId+ ) {+ await destroySessionDir(existing.opfsSessionId).catch(() => {});+ }}await chrome.storage.local.set({@@ -235,8 +303,7 @@ const ensureAudioOffscreen = async () => {const hasAnyOffscreen = contexts.some((context) => context.contextType === "OFFSCREEN_DOCUMENT",);- // If an offscreen document already exists (e.g. the recorder), reuse it- // — Chrome only allows one offscreen document per extension.+ // reuse existing offscreen doc if any; Chrome only allows one per extensionif (hasAnyOffscreen) return true;await chrome.offscreen.createDocument({url: "audiooffscreen.html",@@ -389,8 +456,7 @@ const handleCheckStorageQuota = async (retried = false) => {credentials: "include",});- // On 401, invalidate auth cache and retry once so loginWithWebsite()- // in the outer handler can refresh the token on the next attempt.+ // 401: invalidate auth cache so loginWithWebsite refreshes the tokenif (res.status === 401 && !retried) {await chrome.storage.local.set({ lastAuthCheck: 0 });const refresh = await loginWithWebsite();@@ -416,7 +482,7 @@ const handleCheckStorageQuota = async (retried = false) => {}};-const handleFinishMultiRecording = async () => {+export const handleFinishMultiRecording = async () => {try {const { recordingToScene } = await chrome.storage.local.get(["recordingToScene",@@ -438,27 +504,11 @@ const handleFinishMultiRecording = async () => {return;}- const res = await fetch(- `${API_BASE}/videos/${multiProjectId}/auto-publish`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${await chrome.storage.local- .get("screenityToken")- .then((r) => r.screenityToken)}`,- },- },- );-const url = `${process.env.SCREENITY_APP_BASE}/editor/${multiProjectId}/edit?share=true`;const publicUrl = `${process.env.SCREENITY_APP_BASE}/view/${multiProjectId}/`;- if (!res.ok) {- console.warn("Failed to auto-publish multi recording", res.status);- }+ markProjectPublic(multiProjectId);- // Open the editor directlycreateTab(url, true, true).then(() => {if (publicUrl) {copyToClipboard(publicUrl);@@ -469,8 +519,7 @@ const handleFinishMultiRecording = async () => {}});} else {- // Multi recording on existing project: only reuse editorTab if it still- // matches this project and expected editor/view URL.+ // existing-project multi recording: only reuse editorTab if it still matchesconst { projectId, instantMode } = await chrome.storage.local.get(["projectId","instantMode",@@ -529,7 +578,6 @@ const handleFinishMultiRecording = async () => {}}- // Reset multi-mode stateawait chrome.storage.local.set({multiMode: false,multiSceneCount: 0,@@ -584,10 +632,18 @@ const registerRecordingTabListener = (ownerTabId) => {}recordingTabListener = (closedTabId) => {if (closedTabId === ownerTabId) {- chrome.runtime.sendMessage({- type: "stop-recording-tab",- reason: "recorder-owner-tab-closed",- tabId: closedTabId,+ // chrome.runtime.sendMessage from the SW doesn't fire BG's own listeners,+ // so call the stop handler directly+ Promise.resolve(+ handleStopRecordingTab({+ reason: "recorder-owner-tab-closed",+ tabId: closedTabId,+ }),+ ).catch((err) => {+ console.error(+ "[Screenity][BG] handleStopRecordingTab failed in tab-removed",+ err,+ );});clearRecordingSessionSafe("owner-tab-removed", { closedTabId });}@@ -614,7 +670,6 @@ const normalizeIncomingSession = (incoming = {}, sender) => {...incoming,recorderTabId: ownerTabId,capturedTabId,- // Keep tabId for backward compatibility.tabId: capturedTabId,};};@@ -710,7 +765,6 @@ export const copyToClipboard = (text) => {});};-// Initialize message router and register all handlersexport const setupHandlers = () => {registerProxyStorageHandlers();registerMessage("desktop-capture", async (message, sender) => {@@ -755,6 +809,135 @@ export const setupHandlers = () => {return { ok: false, error: err?.message || String(err) };}});+ // Forward a scene-create payload to the editor tab, which does the+ // POST itself (same-origin cookie auth). Sidesteps the MV3 SW-fetch+ // hang we hit when the cloud recorder tab tears down right after+ // dispatching the request. The editor confirms via reply message.+ registerMessage("forward-create-scene", async (message) => {+ const { projectId, payload } = message || {};+ if (!projectId || !payload) {+ return { ok: false, error: "missing-projectId-or-payload" };+ }+ let validated = await getValidatedEditorTab({+ expectedProjectId: projectId,+ expectedKind: "editor",+ reason: "forward-create-scene",+ });+ let openedTabId = null;+ if (!validated.ok || !validated.tab?.id) {+ // No editor tab; happens in multi-mode between scenes. Open one+ // in the background as a same-origin proxy: same-origin POST is+ // immune to the MV3 SW-fetch lifecycle hang we hit when posting+ // bearer-auth from the SW alone. The tab stays open to serve+ // subsequent scenes; finish-multi-recording will reuse/focus it.+ const targetUrl = `${process.env.SCREENITY_APP_BASE}/editor/${projectId}/edit?load=true`;+ try {+ const tab = await chrome.tabs.create({+ url: targetUrl,+ active: false,+ });+ if (tab?.id) {+ openedTabId = tab.id;+ await setEditorTabReference({+ tabId: tab.id,+ tabUrl: targetUrl,+ source: "forward-create-scene:auto-open",+ expectedProjectId: projectId,+ });+ validated = { ok: true, tab: { id: tab.id }, reason: null };+ }+ } catch (err) {+ return {+ ok: false,+ error: `failed-to-open-editor-tab:${err?.message || err}`,+ };+ }+ if (!validated.tab?.id) {+ return { ok: false, error: "no-editor-tab" };+ }+ }+ const requestId =+ (typeof crypto !== "undefined" && crypto.randomUUID?.()) ||+ `scene-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;+ // Editor tab was just opened by prepare-open-editor; the content+ // script may not have mounted yet. Retry with backoff until it can+ // receive messages, capped at ~10s total.+ const backoffsMs = [0, 200, 400, 800, 1200, 1600, 2000, 2400, 2800];+ let lastErr = null;+ for (const wait of backoffsMs) {+ if (wait > 0) {+ await new Promise((r) => setTimeout(r, wait));+ }+ try {+ const reply = await chrome.tabs.sendMessage(+ validated.tab.id,+ {+ type: "proxy-create-scene",+ projectId,+ requestId,+ payload,+ },+ // Target top frame only: content script also runs in any+ // sub-iframes (manifest matches <all_urls>), and a postMessage+ // from a sub-iframe doesn't bubble to the editor's top window.+ { frameId: 0 },+ );+ return reply || { ok: false, error: "no-reply-from-editor" };+ } catch (err) {+ lastErr = err?.message || String(err);+ if (!/Receiving end does not exist|Could not establish/i.test(lastErr)) {+ // Different error; don't keep retrying.+ break;+ }+ }+ }+ return { ok: false, error: lastErr || "tabs-sendMessage-failed" };+ });++ // Bearer-auth API call routed through the SW so it survives the calling+ // tab's teardown (e.g. cloud recorder closing post-stop). Restricted to the+ // configured Screenity API base. Kept for non-cloud-recorder callers; the+ // cloud recorder uses the port-based path above instead.+ registerMessage("pro-api-fetch", async (message) => {+ // Heartbeat resets the SW idle timer for the duration of the fetch,+ // helpful when the originating tab tears down right after dispatch.+ const ping = () => {+ try {+ chrome.runtime.getPlatformInfo(() => void chrome.runtime.lastError);+ } catch {}+ };+ ping();+ const keepAlive = setInterval(ping, 10_000);+ try {+ const { path, method = "GET", body } = message || {};+ if (typeof path !== "string" || !path.startsWith("/")) {+ return { ok: false, error: "invalid-path" };+ }+ if (!API_BASE) return { ok: false, error: "no-api-base" };+ const { screenityToken } = await chrome.storage.local.get([+ "screenityToken",+ ]);+ const headers = { "Content-Type": "application/json" };+ if (screenityToken) headers.Authorization = `Bearer ${screenityToken}`;+ const res = await fetch(`${API_BASE}${path}`, {+ method,+ headers,+ body: body != null ? JSON.stringify(body) : undefined,+ keepalive: true,+ });+ const text = await res.text();+ let json = null;+ try {+ json = text ? JSON.parse(text) : null;+ } catch {}+ return { ok: res.ok, status: res.status, body: json, text };+ } catch (err) {+ return { ok: false, error: err?.message || String(err) };+ } finally {+ clearInterval(keepAlive);+ }+ });+registerMessage("offscreen-diag", async (message) => {console.warn("[Screenity][OffscreenDiag]", message.source, message.payload);return { ok: true };@@ -768,9 +951,35 @@ export const setupHandlers = () => {chrome.runtime.sendMessage(pendingOffscreenLoad).catch(() => {});return { ok: true, delivered: true };});+ // Offscreen recorder can't call chrome.scripting; SW proxies the viewport+ // probe so the recorder can size tab-capture constraints to the tab's+ // actual aspect ratio (avoiding the default 1920x1080 pillarbox).+ registerMessage("get-tab-viewport", async (message) => {+ const tabId = Number(message?.tabId);+ if (!Number.isFinite(tabId) || tabId < 0) {+ return { ok: false, error: "invalid-tab-id" };+ }+ try {+ const results = await chrome.scripting.executeScript({+ target: { tabId },+ func: () => ({+ w: Math.round(window.innerWidth * (window.devicePixelRatio || 1)),+ h: Math.round(window.innerHeight * (window.devicePixelRatio || 1)),+ }),+ });+ const r = results?.[0]?.result;+ if (r && r.w > 0 && r.h > 0) {+ return { ok: true, width: r.w, height: r.h };+ }+ return { ok: false, error: "no-result" };+ } catch (err) {+ return { ok: false, error: err?.message || String(err) };+ }+ });+registerMessage("offscreen-request-stream", async (message, sender) => {try {- // Fall back to recordingUiTabId so the picker anchors to the user's tab, not the offscreen doc.+ // anchor picker to user's tab, not the offscreen doclet initiatingTabId = message.initiatingTabId || null;if (!initiatingTabId) {const { recordingUiTabId } = await chrome.storage.local.get([@@ -799,14 +1008,12 @@ export const setupHandlers = () => {resetActiveTabRestart(message),);registerMessage("video-ready", async (message) => {+ perfMark("BG.handlers video-ready.received");await videoReady(message);await clearRecordingSessionSafe("video-ready");});- // Download-path remux request from the sandbox. Ensures the remux- // offscreen document is open, forwards the request, and returns the- // response. On any SW-side failure the caller falls back to the- // in-sandbox BufferTarget remux.+ // download-path remux request from sandbox; falls back to in-sandbox BufferTarget on failureregisterMessage("remux-request", async (message) => {if (!message?.requestId ||@@ -824,13 +1031,28 @@ export const setupHandlers = () => {};}try {- const response = await chrome.runtime.sendMessage({- type: "remux-start",- requestId: message.requestId,- inputFileName: message.inputFileName,- outputFileName: message.outputFileName,- });- return response || { ok: false, error: "no-offscreen-response" };+ // deterministic timeout so a wedged offscreen can't hang the caller forever+ const REMUX_TIMEOUT_MS = 60_000;+ let timeoutId = null;+ try {+ const response = await Promise.race([+ chrome.runtime.sendMessage({+ type: "remux-start",+ requestId: message.requestId,+ inputFileName: message.inputFileName,+ outputFileName: message.outputFileName,+ }),+ new Promise((_, reject) => {+ timeoutId = setTimeout(+ () => reject(new Error("remux-offscreen-timeout")),+ REMUX_TIMEOUT_MS,+ );+ }),+ ]);+ return response || { ok: false, error: "no-offscreen-response" };+ } finally {+ if (timeoutId) clearTimeout(timeoutId);+ }} catch (err) {return {ok: false,@@ -839,8 +1061,7 @@ export const setupHandlers = () => {}});- // Fired by Region/Recorder.jsx pagehide — the iframe is being torn down- // because the user navigated away from the recorded tab.+ // pagehide from Region/Recorder.jsx; user navigated away from the recorded tabregisterMessage("region-iframe-destroyed", async () => {const { recording, recorderSession, customRegion } =await chrome.storage.local.get([@@ -852,19 +1073,17 @@ export const setupHandlers = () => {recording ||(recorderSession && recorderSession.status === "recording");if (!isActivelyRecording) return;- // Only treat as a real region-recording teardown when the iframe was- // actually hosting the MediaRecorder (customRegion flow). Plain- // tab-area records in the pinned recorder tab, so navigation of the- // recorded page must not tear it down.+ // only customRegion hosts MediaRecorder in the iframe; plain tab capture lives+ // in the pinned recorder tab and must not be torn down by recorded-page navigationif (!customRegion) return;diagEvent("region-iframe-destroyed");await chrome.storage.local.set({recording: false,customRegion: false,- // Clear recordingTab so stopRecording() doesn't think the editor was- // already opened by the stop-recording-tab flow (recordingTab points- // to the pinned recorder.html tab which didn't open any editor).+ // recordingTab points to pinned recorder.html which didn't open the editor;+ // clear it so stopRecording() doesn't skip editor open+recordingTab: null,postStopEditorOpening: false,postStopEditorOpened: false,@@ -873,12 +1092,14 @@ export const setupHandlers = () => {: null,});- // If no chunks were persisted (user navigated almost immediately),- // show a toast instead of opening an empty editor.+ // user navigated before any chunks persisted; toast instead of empty editorconst chunkCount = await chunksStore.length().catch(() => 0);if (chunkCount === 0) {diagEvent("region-nav-no-chunks");- const { activeTab } = await chrome.storage.local.get(["activeTab"]);+ const { activeTab, sandboxTab } = await chrome.storage.local.get([+ "activeTab",+ "sandboxTab",+ ]);if (activeTab) {sendMessageTab(activeTab, {type: "show-toast",@@ -886,13 +1107,28 @@ export const setupHandlers = () => {timeout: 5000,}).catch(() => {});}+ // editor opened pre-unload would otherwise hang at "Preparing recording..."+ if (Number.isInteger(sandboxTab)) {+ try {+ await chrome.storage.local.set({+ editorRecordingError: {+ ts: Date.now(),+ sandboxTab,+ error: "stream-error",+ why: "Recording stopped before any data was captured",+ errorCode: "REC_REGION_NAV_NO_CHUNKS",+ source: "region-iframe-destroyed",+ },+ });+ } catch {}+ }return;}await videoReady();});- registerMessage("start-recording", (message) => startRecording(message));+ registerMessage("start-recording", (message) => startRecording("start-recording-message"));registerMessage("countdown-finished", async (message) => {const { recording, restarting, pendingRecording } =await chrome.storage.local.get([@@ -900,9 +1136,8 @@ export const setupHandlers = () => {"restarting","pendingRecording",]);- // pendingRecording/restarting are expected transitional flags while countdown- // runs. During restart, `recording` may still be true briefly from the- // previous session, so only block when recording is active AND not restarting.+ // restart leaves `recording: true` briefly from the previous session, so block+ // only when recording is active AND not restartingif (recording && !restarting) {diagEvent("countdown-finished", { skipped: true, reason: "already-recording" });const decisionAt = Date.now();@@ -936,18 +1171,20 @@ export const setupHandlers = () => {started: true,},});- startAfterCountdown();+ startAfterCountdown("countdown-finished");return { ok: true };});registerMessage("restarted", (message) => restartActiveTab(message));const sendChunksToSandbox = async (sender) => {+ perfMark("BG.handlers sendChunksToSandbox.enter", {+ senderTab: sender?.tab?.id || null,+ });if (DEBUG_POSTSTOP)console.debug("[Screenity][BG] sendChunksToSandbox invoked", {senderTab: sender?.tab?.id,});const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);- // Prefer stored sandboxTab but fall back to the caller tab if availableconst targetTab = sandboxTab || sender?.tab?.id || null;if (!targetTab) {if (DEBUG_POSTSTOP)@@ -955,38 +1192,8 @@ export const setupHandlers = () => {throw new Error("no-sandbox-tab");}- const pingReady = async () => {- return new Promise((resolve) => {- chrome.runtime.sendMessage(- { type: "ping", _targetTabId: targetTab },- (response) => {- resolve(response?.status === "ready");- },- );- });- };-- const maxPingAttempts = 10;- let pingOk = false;- for (let attempt = 1; attempt <= maxPingAttempts; attempt += 1) {- // eslint-disable-next-line no-await-in-loop- pingOk = await pingReady();- if (DEBUG_POSTSTOP)- console.debug("[Screenity][BG] ping attempt", { attempt, pingOk });- if (pingOk) break;- // eslint-disable-next-line no-await-in-loop- await new Promise((r) => setTimeout(r, 200));- }-- if (!pingOk) {- if (DEBUG_POSTSTOP)- console.warn(- "[Screenity][BG] sandbox not ready after pings, proceeding anyway",- { targetTab },- );- // Proceed even if ping failed — runtime message ports can be unreliable- // during page load; we'll attempt to send chunks regardless.- }+ // sandboxed iframes don't receive runtime.sendMessage; chunk delivery uses+ // tabs.sendMessage with frameId which does reach them, so no ping neededconst maxAttempts = 6;const delayMs = 250;@@ -1055,6 +1262,10 @@ export const setupHandlers = () => {);registerMessage("cancel-recording", (message) => cancelRecording(message));registerMessage("stop-recording-tab", (message, sender, sendResponse) => {+ perfMark("BG.handlers stop-recording-tab.received", {+ reason: message?.reason || null,+ senderTabId: sender?.tab?.id || null,+ });logStopRecordingTabEvent(message, sender);const now = Date.now();if (@@ -1101,17 +1312,22 @@ export const setupHandlers = () => {});registerMessage("set-mic-active-tab", (message) => setMicActiveTab(message));- // Diagnostic events routed from content scripts / sandbox- registerMessage("diag-countdown-started", () => diagEvent("countdown-started"));+ registerMessage("diag-countdown-started", () => {+ diagEvent("countdown-started");+ // countdown started means stream setup is done; extend the fallback window+ // so it doesn't fire during countdown (and start the recording too early)+ noteCountdownStarted();+ });registerMessage("diag-countdown-cancelled", () => diagEvent("countdown-cancelled"));registerMessage("diag-editor-ready", (message) =>diagEvent("editor-load-ready", { path: message?.path || null }),);- // Only accept "sandbox-" / "sw-" prefixed events so a compromised context can't spoof lifecycle events.+ // prefix allowlist so a compromised context can't spoof lifecycle eventsregisterMessage("diag-forward", (message) => {const ev = typeof message?.event === "string" ? message.event : null;if (!ev) return;- if (!ev.startsWith("sandbox-") && !ev.startsWith("sw-")) return;+ const allowedPrefixes = ["sandbox-", "sw-", "opfs-", "recorder-"];+ if (!allowedPrefixes.some((p) => ev.startsWith(p))) return;diagEvent(ev, message?.data ?? null);});registerMessage("open-editor-recovery", async () => {@@ -1126,18 +1342,43 @@ export const setupHandlers = () => {error: message?.error || null,});});+ // camera bubble failed but recording is live; surface as toast, never tear down+ registerMessage("camera-bubble-unavailable", async (message) => {+ try {+ const { tabRecordedID, recordingUiTabId } = await chrome.storage.local.get([+ "tabRecordedID",+ "recordingUiTabId",+ ]);+ const target = tabRecordedID || recordingUiTabId;+ if (target) {+ sendMessageTab(target, {+ type: "show-toast",+ message:+ chrome.i18n.getMessage("cameraUnavailableToast") ||+ "Camera disconnected. Still recording your screen.",+ timeout: 6000,+ }).catch((err) => {+ diagEvent("warning", {+ note: "camera-unavailable-toast undelivered",+ err: String(err).slice(0, 80),+ });+ });+ }+ } catch {}+ });registerMessage("on-get-permissions", (message) =>handleOnGetPermissions(message),);registerMessage("recording-complete",- async (message, sender) => await handleRecordingComplete(message, sender),+ async (message, sender) => {+ perfMark("BG.handlers recording-complete.received");+ return await handleRecordingComplete(message, sender);+ },);registerMessage("check-recording", (message) => checkRecording(message));registerMessage("open-download-mp4", async () => {- // If cloud features are enabled and the user is signed in, block the- // local "fast MP4" recovery flow to avoid diverging from the pro/server- // workflow. Show a toast instead.+ // cloud-enabled signed-in users skip local fast-MP4 recovery to stay on the pro flowif (CLOUD_FEATURES_ENABLED) {try {const { authenticated } = await loginWithWebsite();@@ -1240,7 +1481,6 @@ export const setupHandlers = () => {const errorWhy = message?.errorWhy || null;const source = message?.source || "error-modal";- // Check auth for form routinglet user = null;let isLoggedIn = false;if (CLOUD_FEATURES_ENABLED) {@@ -1343,7 +1583,6 @@ export const setupHandlers = () => {keepalive: true,}).catch(() => {});} catch {- // best effort}});registerMessage("restore-recording", (message) => restoreRecording(message));@@ -1377,7 +1616,7 @@ export const setupHandlers = () => {);registerMessage("is-pinned", async () => await isPinned());- // Prevent Chrome from discarding the CloudRecorder tab during recording+ // prevent Chrome from discarding the CloudRecorder tab while recordingregisterMessage("set-tab-auto-discardable", (message, sender) =>setTabAutoDiscardableSafe(message, sender),);@@ -1449,8 +1688,9 @@ export const setupHandlers = () => {console.warn("Cloud features disabled, cannot handle login");return;}- // User is explicitly initiating login — clear the stay-logged-out flag.await chrome.storage.local.set({ stayLoggedOut: false });+ // cancel deferred-logout token clear; otherwise drain listener clobbers fresh token+ await chrome.storage.local.remove(["logoutPendingTokenClear"]);const currentTab = await getCurrentTab();@@ -1467,17 +1707,26 @@ export const setupHandlers = () => {sendResponse({ success: false, message: "Cloud features disabled" });return true;}- await chrome.storage.local.remove([- "screenityToken",+ // keep screenityToken during active recording for bunnyTusUploader.refreshTusAuth;+ // removed by recording-end cleanup+ const { recording, pendingRecording } = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ ]);+ const recordingBusy = Boolean(recording || pendingRecording);+ const removeKeys = ["screenityUser","lastAuthCheck","isSubscribed","isLoggedIn","proSubscription",- ]);+ ];+ if (!recordingBusy) {+ removeKeys.push("screenityToken");+ }+ await chrome.storage.local.remove(removeKeys);- // Preserve a post-logout marker so popup can render the LoggedOut state.- // stayLoggedOut blocks auto-login until the user explicitly clicks "Log in".+ // stayLoggedOut blocks auto-login until user explicitly clicks "Log in"await chrome.storage.local.set({isLoggedIn: false,wasLoggedIn: true,@@ -1485,9 +1734,44 @@ export const setupHandlers = () => {isSubscribed: false,proSubscription: null,screenityUser: null,+ ...(recordingBusy ? { logoutPendingTokenClear: true } : {}),});- sendResponse({ success: true });+ if (recordingBusy) {+ // drain listener; don't await, sendResponse must fire immediately+ const drainListener = async (changes, area) => {+ if (area !== "local") return;+ if (+ !(changes.recording || changes.pendingRecording)+ )+ return;+ const snap = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "logoutPendingTokenClear",+ "stayLoggedOut",+ ]);+ if (snap.recording || snap.pendingRecording) return;+ if (!snap.logoutPendingTokenClear) {+ // flag cleared by re-login+ chrome.storage.onChanged.removeListener(drainListener);+ return;+ }+ // gate on stayLoggedOut so a stray flag write can't silently log user out+ if (snap.stayLoggedOut !== true) {+ chrome.storage.onChanged.removeListener(drainListener);+ await chrome.storage.local.remove(["logoutPendingTokenClear"]);+ return;+ }+ chrome.storage.onChanged.removeListener(drainListener);+ await chrome.storage.local.remove([+ "screenityToken",+ "logoutPendingTokenClear",+ ]);+ };+ chrome.storage.onChanged.addListener(drainListener);+ }+ sendResponse({ success: true, deferredTokenClear: recordingBusy });return true;});@@ -1496,7 +1780,6 @@ export const setupHandlers = () => {const { x, y, surface, region, isTab } = payload;const senderWindowId = sender.tab?.windowId;- // Ask Recorder for current video timesendMessageRecord({ type: "get-video-time" }, (response) => {const videoTime = response?.videoTime ?? null;@@ -1558,10 +1841,33 @@ export const setupHandlers = () => {});});+ // serialize to avoid read-modify-write race losing clicks; cap array for long recordings+ const CLICK_EVENTS_MAX = 5000;+ let _clickWriteQueue = Promise.resolve();function storeClick(click) {- chrome.storage.local.get({ clickEvents: [] }, (data) => {- chrome.storage.local.set({ clickEvents: [...data.clickEvents, click] });- });+ _clickWriteQueue = _clickWriteQueue+ .catch(() => {})+ .then(async () => {+ try {+ // 2s cap so a wedged storage call can't block subsequent click writes+ await Promise.race([+ (async () => {+ const { clickEvents = [] } = await chrome.storage.local.get({+ clickEvents: [],+ });+ const next = clickEvents.concat(click);+ if (next.length > CLICK_EVENTS_MAX) {+ next.splice(0, next.length - CLICK_EVENTS_MAX);+ }+ await chrome.storage.local.set({ clickEvents: next });+ })(),+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error("click-write-timeout")), 2000),+ ),+ ]);+ } catch {+ }+ });}function getMonitorForWindow(message, sender, sendResponse) {@@ -1588,7 +1894,6 @@ export const setupHandlers = () => {console.warn("[get-monitor-for-window] No matching monitor");sendResponse({ error: "No matching monitor" });} else {- // Save monitor info directly into chrome.storage.localchrome.storage.local.set({displays,@@ -1765,8 +2070,7 @@ export const setupHandlers = () => {}});registerMessage("preparing-recording", async () => {- // Prefer stored activeTab over getCurrentTab() which can return- // the pinned recorder tab instead of the user's page.+ // getCurrentTab can return the pinned recorder tab; prefer stored activeTabconst { activeTab } = await chrome.storage.local.get(["activeTab"]);const tabId = activeTab || (await getCurrentTab())?.id;if (tabId) {@@ -1829,31 +2133,13 @@ export const setupHandlers = () => {chrome.runtime.sendMessage({ type: "turn-off-pip" });- // Copy to clipboard immediately after focusTab, before the auto-publish- // network request. The auto-publish await can take hundreds of ms, during- // which the renderer may lose document focus — causing navigator.clipboard- // to throw "Document is not focused". Copying here gives the best chance- // the tab is still the topmost focused document.+ // New-project recordings are user-facing public-shareable, so+ // flip isPublic before we hand the share URL to the clipboard.+ markProjectPublic(projectId);+if (publicUrl) {copyToClipboard(publicUrl);}-- if (projectId) {- await fetch(- `${API_BASE}/videos/${projectId}/auto-publish`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${await chrome.storage.local- .get("screenityToken")- .then((r) => r.screenityToken)}`,- },- },- ).catch((err) =>- console.warn("[Screenity][BG] Failed to auto-publish project", err),- );- }} else if (message.multiMode) {messageTab = (await getCurrentTab())?.id || null;} else {@@ -1868,9 +2154,8 @@ export const setupHandlers = () => {chrome.runtime.sendMessage({ type: "turn-off-pip" });}- // Copy for the non-newProject paths (scene additions are excluded because- // publicUrl is null there; multiMode new-project is excluded because it- // goes through handleFinishMultiRecording which has its own clipboard call).+ // non-newProject paths only; scene additions have null publicUrl, multiMode+ // new-project goes through handleFinishMultiRecording with its own clipboardif (publicUrl && !message.newProject) {copyToClipboard(publicUrl);}@@ -1985,15 +2270,20 @@ export const setupHandlers = () => {return { ok: false, error: "chunk-index-out-of-range", index };}- const item = await chunksStore.getItem(`chunk_${index}`).catch(() => null);+ const targetStore = offerScreenStore(offer);+ const item = await targetStore.getItem(`chunk_${index}`).catch(() => null);if (!item?.chunk) {return { ok: false, error: "chunk-missing", index };}+ // OPFS-stored Blobs come back with type "" (raw bytes); reconstruct+ // the mimeType from the offer's recorded container so the editor's+ // <video> element knows whether it's MP4 or WebM.+ const containerMime = offer.container || "video/webm";const blob =- item.chunk instanceof Blob+ item.chunk instanceof Blob && item.chunk.type? item.chunk- : new Blob([item.chunk], { type: "video/webm" });+ : new Blob([item.chunk], { type: containerMime });const arrayBuffer = await blob.arrayBuffer();const base64 = btoa(new Uint8Array(arrayBuffer).reduce(@@ -2007,7 +2297,7 @@ export const setupHandlers = () => {chunk: {index,size: blob.size,- mimeType: blob.type || "video/webm",+ mimeType: blob.type || containerMime,base64,},offer: {@@ -2155,7 +2445,7 @@ export const setupHandlers = () => {registerMessage("clear-recording-alarm", async () => {await chrome.alarms.clear("recording-alarm");});- // Relay toasts to the active content script (extension pages can't reach it directly).+ // extension pages can't message content scripts directlyregisterMessage("show-toast", async (message) => {try {const { activeTab } = await chrome.storage.local.get(["activeTab"]);diff --git a/src/pages/Background/offscreen/discardOffscreenDocuments.js b/src/pages/Background/offscreen/discardOffscreenDocuments.jsindex e94a894..9c8e8a2 100644--- a/src/pages/Background/offscreen/discardOffscreenDocuments.js+++ b/src/pages/Background/offscreen/discardOffscreenDocuments.js@@ -1,15 +1,12 @@import { closeOffscreenDocumentWithFlush } from "./closeOffscreenDocumentWithFlush";+import { perfSpan } from "../../utils/perfMarks";-/**- * Closes any active offscreen document if it exists.- * Runs the flush handshake so in-flight recording state has a chance to- * drain before teardown, then clears the offscreen storage flag.- */export const discardOffscreenDocuments = async ({reason = "discard",flush = true,} = {}) => {console.warn("[Screenity][discardOffscreenDocuments]", { reason, flush, stack: new Error().stack });+ const endFlush = perfSpan("BG.offscreen discardOffscreenDocuments", { reason, flush });try {if (flush) {await closeOffscreenDocumentWithFlush({ reason });@@ -25,5 +22,16 @@ export const discardOffscreenDocuments = async ({} catch (error) {console.error("Failed to discard offscreen documents:", error.message);}- chrome.storage.local.set({ offscreen: false });+ // verify gone before clearing flag; otherwise sendMessageRecord routes to dead listener+ try {+ const remaining = await chrome.runtime.getContexts({});+ const stillExists = remaining.some(+ (c) => c.contextType === "OFFSCREEN_DOCUMENT",+ );+ chrome.storage.local.set({ offscreen: stillExists });+ endFlush({ stillExists });+ } catch {+ chrome.storage.local.set({ offscreen: false });+ endFlush({ result: "getContexts-failed" });+ }};diff --git a/src/pages/Background/recording/cancelRecording.js b/src/pages/Background/recording/cancelRecording.jsindex aaf9832..70ab19d 100644--- a/src/pages/Background/recording/cancelRecording.js+++ b/src/pages/Background/recording/cancelRecording.js@@ -1,4 +1,5 @@import { sendMessageTab, focusTab } from "../tabManagement";+import { removeTab } from "../tabManagement/removeTab";import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";import { resetWatchdogState } from "./resetWatchdogState";@@ -33,24 +34,58 @@ export const handleDismiss = async () => {export const cancelRecording = async () => {try {- // Reset the icon to its default statechrome.action.setIcon({ path: "assets/icon-34.png" });- // Get the active tab from storage- const { activeTab, recordingUiTabId, tabRecordedID } =+ const { activeTab, recordingUiTabId, tabRecordedID, recordingTab } =await chrome.storage.local.get(["activeTab","recordingUiTabId","tabRecordedID",+ "recordingTab",]);await chrome.storage.local.set({pendingRecording: false,recordingUiTabId: null,tabRecordedID: null,+ recordingTab: null,+ // mirror stopRecording's cleared fields so cancel can't leak into next attempt+ region: false,+ customRegion: false,+ recording: false,+ restarting: false,+ offscreen: false,+ memoryError: false,+ backup: false,+ backupSetup: false,+ backupTab: null,});- // Send stop message, focus the tab, and clean up+ // URL-guard so we never close a user tab by mistake+ if (recordingTab) {+ try {+ const tab = await chrome.tabs.get(recordingTab);+ const url = tab?.url || "";+ if (+ url.includes("recorder.html") ||+ url.includes("cloudrecorder.html")+ ) {+ try {+ await removeTab(recordingTab);+ } catch (removeErr) {+ // distinguish benign "No tab with id" race from real failures+ const msg = String(removeErr?.message || removeErr);+ if (!/No tab with id/i.test(msg)) {+ console.warn(+ "[Screenity][BG] cancelRecording: removeTab failed",+ { tabId: recordingTab, err: msg },+ );+ }+ }+ }+ } catch {}+ }+const candidateTabs = [activeTab, recordingUiTabId, tabRecordedID].filter((id, idx, arr) => Number.isInteger(id) && arr.indexOf(id) === idx,);diff --git a/src/pages/Background/recording/chunkHandler.js b/src/pages/Background/recording/chunkHandler.jsindex 28938af..e775901 100644--- a/src/pages/Background/recording/chunkHandler.js+++ b/src/pages/Background/recording/chunkHandler.js@@ -2,6 +2,7 @@ import localforage from "localforage";import { blobToBase64 } from "../utils/blobToBase64";import { sendMessageTab } from "../tabManagement";import { diagEvent } from "../../utils/diagnosticLog";+import { perfMark, perfSpan } from "../../utils/perfMarks";localforage.config({driver: localforage.INDEXEDDB,@@ -9,13 +10,8 @@ localforage.config({version: 1,});-// In-memory lock for handleChunks. The previous storage-based `sendingChunks`-// flag was check-then-set via async chrome.storage calls — two concurrent-// handleChunks triggers (one from the recorder's stop flow, one from the-// sandbox's send-chunks-to-sandbox request) could both pass the check before-// either wrote the flag. That caused duplicate batches to interleave at the-// sandbox and scramble chunk order. An in-process promise chain is atomic in-// the SW event loop and strictly serializes handleChunks calls.+// in-memory promise chain. storage-based sendingChunks flag was racy:+// check-then-set via async chrome.storage let two concurrent triggers pass.let _sendChain = Promise.resolve();export const chunksStore = localforage.createInstance({ name: "chunks" });@@ -33,12 +29,6 @@ export const clearAllRecordings = async () => {};export const handleChunks = async (chunks, override = false, target = null) => {- // Serialize via in-memory promise chain. Atomic in the SW event loop, so- // two concurrent triggers (e.g. the automatic send on stop and the- // sandbox's `send-chunks-to-sandbox` request) run back-to-back instead of- // overlapping. Prevents duplicate batches from interleaving at the sandbox- // and scrambling chunk order. The old storage-based `sendingChunks` flag- // is racy — async read + async write leaves a gap where both callers pass.const priorChain = _sendChain;let releaseChain;_sendChain = new Promise((resolve) => {@@ -48,9 +38,7 @@ export const handleChunks = async (chunks, override = false, target = null) => {await priorChain;} catch {}- // From here down, any early return or throw must still release the lock.- // The inner try/finally below covers the main body; this wrapper catches- // anything before it (e.g. a failing storage read).+ // outer try/finally guarantees lock release even if the storage read throwslet mainCompleted = false;try {const { sandboxTab, bannerSupport } = await chrome.storage.local.get([@@ -65,7 +53,7 @@ export const handleChunks = async (chunks, override = false, target = null) => {override,});- // Keep the legacy storage flag in sync for anything still reading it.+ // legacy flag kept in sync for callers still reading itawait chrome.storage.local.set({ sendingChunks: true });try {@@ -168,7 +156,7 @@ export const handleChunks = async (chunks, override = false, target = null) => {};let currentIndex = 0;- // Sample first 3, last 3, every ~totalBatches/10 between - caps at ~10 diag events.+ // sample first 3, last 3, ~every totalBatches/10 between; caps diag at ~10 eventsconst totalBatches = Math.max(1, Math.ceil(chunks.length / batchSize));const sampleStride = Math.max(1, Math.floor(totalBatches / 10));const shouldEmitBatch = (batchIndex) => {@@ -181,6 +169,9 @@ export const handleChunks = async (chunks, override = false, target = null) => {const end = Math.min(currentIndex + batchSize, chunks.length);const rawBatch = chunks.slice(currentIndex, end);+ const endEncode = perfSpan("BG.chunkHandler batch-base64", {+ batchLen: rawBatch.length,+ });const batch = await Promise.all(rawBatch.map(async (chunk) => {try {@@ -191,6 +182,11 @@ export const handleChunks = async (chunks, override = false, target = null) => {}}),);+ const totalBytes = batch.reduce(+ (s, b) => s + (b?.chunk?.length || 0),+ 0,+ );+ endEncode({ totalBytes });const filtered = batch.filter(Boolean);if (filtered.length > 0) {@@ -200,7 +196,12 @@ export const handleChunks = async (chunks, override = false, target = null) => {filteredLen: filtered.length,currentIndex,});+ const endSend = perfSpan("BG.chunkHandler batch-send", {+ batchLen: filtered.length,+ bytes: totalBytes,+ });const ok = await sendBatch(filtered);+ endSend({ ok });if (shouldEmitBatch(batchIndex)) {diagEvent("sw-sendchunks-batch", {batchIndex,@@ -235,8 +236,6 @@ export const handleChunks = async (chunks, override = false, target = null) => {mainCompleted = true;}} finally {- // Release the in-memory lock so queued callers can proceed, regardless of- // whether the inner body completed normally.void mainCompleted;if (releaseChain) releaseChain();}diff --git a/src/pages/Background/recording/countdownFallback.js b/src/pages/Background/recording/countdownFallback.jsnew file mode 100644index 0000000..194b32a--- /dev/null+++ b/src/pages/Background/recording/countdownFallback.js@@ -0,0 +1,78 @@+// Watchdog for the countdown → start-recording bridge. The countdown UI+// lives in the content script tab, so a navigation/unload during countdown+// kills it and the "countdown-finished" message never lands, leaving the+// recorder tab orphaned. Arm on diag-countdown-started, fire a fallback+// startAfterCountdown if recording hasn't begun in time.+//+// Don't arm on pendingRecording: custom region setup runs 5-6s before+// countdown begins, so the timer fires while the iframe isn't ready and+// we get spurious "failed to start" modals.+import { startAfterCountdown } from "./startRecording";++// 3s countdown + 1s END_HOLD_MS + POST_HIDE_START_DELAY_MS + slack+const FALLBACK_AFTER_COUNTDOWN_STARTED_MS = 8000;++let fallbackTimerId = null;++const clearFallback = () => {+ if (fallbackTimerId !== null) {+ clearTimeout(fallbackTimerId);+ fallbackTimerId = null;+ }+};++const scheduleFallback = (delayMs = FALLBACK_AFTER_COUNTDOWN_STARTED_MS) => {+ clearFallback();+ fallbackTimerId = setTimeout(async () => {+ fallbackTimerId = null;+ try {+ const { pendingRecording, recording, restarting } =+ await chrome.storage.local.get([+ "pendingRecording",+ "recording",+ "restarting",+ ]);+ // Only auto-dispatch if still pending and recording hasn't started.+ // Skip during restart - that flow has its own start sequencing.+ if (!pendingRecording || recording || restarting) return;+ console.info(+ "[Screenity][BG] countdown-finished missing after delay, auto-dispatching start",+ );+ try {+ startAfterCountdown("countdownFallback");+ } catch (err) {+ console.error(+ "[Screenity][BG] countdownFallback startAfterCountdown failed",+ err,+ );+ }+ } catch (err) {+ console.error("[Screenity][BG] countdownFallback storage read failed", err);+ }+ }, delayMs);+};++// Called when the countdown UI actually starts ticking (content script+// sends diag-countdown-started). This is the only trigger for the+// fallback timer.+export const noteCountdownStarted = () => {+ scheduleFallback();+};++export const initCountdownFallback = () => {+ chrome.storage.onChanged.addListener((changes, area) => {+ if (area !== "local") return;+ // pendingRecording true → false (user cancelled): clear any armed timer.+ if (+ changes.pendingRecording &&+ changes.pendingRecording.newValue === false+ ) {+ clearFallback();+ return;+ }+ // recording transitioned to true (start succeeded): clear.+ if (changes.recording && changes.recording.newValue === true) {+ clearFallback();+ }+ });+};diff --git a/src/pages/Background/recording/desktopCapture.js b/src/pages/Background/recording/desktopCapture.jsindex d8c5206..304fa54 100644--- a/src/pages/Background/recording/desktopCapture.js+++ b/src/pages/Background/recording/desktopCapture.js@@ -2,25 +2,52 @@ import { getCurrentTab } from "../tabManagement";import { initBackup } from "../backup/initBackup";import { startRecorderSession } from "./openRecorderTab";import { localDirectoryStore } from "./chunkHandler";+import { perfMark } from "../../utils/perfMarks";export const desktopCapture = async (request) => {+ perfMark("BG.desktopCapture.enter", {+ region: Boolean(request?.region),+ camera: Boolean(request?.camera),+ customRegion: Boolean(request?.customRegion),+ });console.log("[Screenity][desktopCapture] entered", request);- const { backup } = await chrome.storage.local.get(["backup"]);- const { backupSetup } = await chrome.storage.local.get(["backupSetup"]);+ // batched: two sequential gets added 80-160ms of storage-queue latency+ const { backup, backupSetup, onboarding } = await chrome.storage.local.get([+ "backup",+ "backupSetup",+ "onboarding",+ ]);++ // onboarding gate: prevent recorder tab opening behind the Welcome splash+ if (onboarding === true) {+ perfMark("BG.desktopCapture.blocked-by-onboarding");+ console.log(+ "[Screenity][desktopCapture] blocked: onboarding active",+ );+ return;+ }- // Ensure that chunk sending is marked as not in progresschrome.storage.local.set({ sendingChunks: false });+ // getCurrentTab uses lastFocusedWindow which races with editor-open focus pulls;+ // prefer the explicit sender tab id+ const initiatingTabId =+ typeof request?.initiatingTabId === "number"+ ? request.initiatingTabId+ : null;+if (backup) {- // Clear the local directory store if backup hasn't been set upif (!backupSetup) {localDirectoryStore.clear();}- // Get the current active tab and initialize backup- const activeTab = await getCurrentTab();- initBackup(request, activeTab.id);+ let id = initiatingTabId;+ if (id == null) {+ const activeTab = await getCurrentTab();+ id = activeTab?.id ?? null;+ }+ initBackup(request, id);} else {- startRecorderSession(request);+ startRecorderSession(request, initiatingTabId);}};diff --git a/src/pages/Background/recording/discardRecording.js b/src/pages/Background/recording/discardRecording.jsindex cc1eacd..1af1e4e 100644--- a/src/pages/Background/recording/discardRecording.js+++ b/src/pages/Background/recording/discardRecording.js@@ -7,7 +7,7 @@ export const discardRecording = async () => {sendMessageRecord({ type: "dismiss-recording" });chrome.action.setIcon({ path: "assets/icon-34.png" });- // Await teardown before flipping recording:false - otherwise handleAlarm fires against a torn-down offscreen.+ // await teardown before recording:false; otherwise handleAlarm fires against torn-down offscreentry {await discardOffscreenDocuments();} catch {}@@ -20,7 +20,6 @@ export const discardRecording = async () => {"recordingTab",]);- // Close the recorder tab if it's an extension pageif (recordingTab) {try {const tab = await chrome.tabs.get(recordingTab);@@ -30,7 +29,7 @@ export const discardRecording = async () => {} catch {}}- // Keep multiMode on but reset project state if no scenes were saved+ // keep multiMode but reset project state when no scenes saved yetconst multiState = multiMode? {multiMode: true,@@ -54,6 +53,12 @@ export const discardRecording = async () => {pendingRecording: false,offscreen: false,postStopEditorOpened: false,+ region: false,+ customRegion: false,+ memoryError: false,+ backup: false,+ backupSetup: false,+ backupTab: null,...multiState,});chrome.storage.local.set({ pipForceClose: Date.now() });diff --git a/src/pages/Background/recording/openRecorderTab.js b/src/pages/Background/recording/openRecorderTab.jsindex 2b22bc5..4b3534f 100644--- a/src/pages/Background/recording/openRecorderTab.js+++ b/src/pages/Background/recording/openRecorderTab.js@@ -5,6 +5,7 @@ import { closeOffscreenDocument } from "../offscreen/closeOffscreenDocument.js";import { loginWithWebsite } from "../auth/loginWithWebsite.js";import { traceStep } from "../../utils/startFlowTrace.js";import { handleGetStreamingData } from "./recordingHelpers.js";+import { perfMark, perfSpan } from "../../utils/perfMarks";const openRecorderTab = async (activeTab,@@ -13,10 +14,16 @@ const openRecorderTab = async (camera = false,request) => {+ perfMark("BG.openRecorderTab.enter", {+ isRegion,+ camera,+ activeTabId: activeTab?.id || null,+ });let switchTab = true;- // Check subscription status+ const endLogin = perfSpan("BG.openRecorderTab loginWithWebsite");const { authenticated, subscribed, cached, transient, error: authError } = await loginWithWebsite();+ endLogin({ authenticated, subscribed, cached: Boolean(cached) });const isCloudRecorder = authenticated && subscribed;const recorderUrl = isCloudRecorder? chrome.runtime.getURL("cloudrecorder.html")@@ -31,15 +38,12 @@ const openRecorderTab = async ();}- // Cloud recordings need the tab active briefly so keepalive can start+ // cloud recordings need the tab active briefly so keepalive can startif (isCloudRecorder && !switchTab) {switchTab = true;}- // Close any leftover recorder tab from a previous recording so we don't- // end up with two pinned tabs. Only close actual extension recorder pages -- // for region recordings, recordingTab can temporarily point to the user's- // active page, which we must NOT close.+ // URL-guard: region recordings point recordingTab at the user's tab, never close thatconst { recordingTab: prevRecTab } = await chrome.storage.local.get(["recordingTab",]);@@ -53,31 +57,81 @@ const openRecorderTab = async () {await removeTab(prevRecTab);}- } catch {- // Tab doesn't exist - just clear the reference- }+ } catch {}chrome.storage.local.set({ recordingTab: null });}const finalUrl = isRegion ? `${recorderUrl}?tab=true` : recorderUrl;+ // Close any leftover setup.html: a user starting cloud recording has+ // moved past onboarding, and if it's still open it tends to steal focus+ // back from the editor when the recorder tab closes post-stop.+ try {+ const setupUrl = chrome.runtime.getURL("setup.html");+ const allTabs = await chrome.tabs.query({});+ const stale = allTabs.filter(+ (t) => t.id != null && t.url && t.url.startsWith(setupUrl),+ );+ if (stale.length > 0) {+ await chrome.tabs.remove(stale.map((t) => t.id));+ }+ } catch {}++ const endTabCreate = perfSpan("BG.openRecorderTab tabs.create");const tab = await chrome.tabs.create({url: finalUrl,pinned: true,index: 0,- // FLAG: Check this is ok?active: switchTab,});+ endTabCreate({ tabId: tab?.id });+ // tabs.create can fulfill with no id in rare MV3 states (window-closed, profile-locked)+ if (!tab || typeof tab.id !== "number") {+ console.error(+ "[Screenity][BG] openRecorderTab: tabs.create returned no usable tab",+ tab,+ );+ chrome.runtime+ .sendMessage({+ type: "recording-error",+ error: "stream-error",+ why: "recorder tab create returned no id",+ errorCode: "REC_START_NO_TAB",+ })+ .catch(() => {});+ return;+ }++ // Set recordingTab before the autoDiscardable retry loop (up to ~1.25s+ // of awaits) so listeners that fire during it don't see a stale tab id.+ chrome.storage.local.set({+ recordingTab: tab.id,+ offscreen: false,+ region: false,+ wasRegion: true,+ clickEvents: [],+ recordingUiTabId: activeTab.id,+ ...(isRegion ? { tabRecordedID: activeTab.id } : {}),+ });- // Apply autoDiscardable before the load listener so the tab can't be discarded pre-mount.+ // under memory pressure the set can succeed silently while the property stays true;+ // verify via tabs.get roundtrip and retry with backofflet autoDiscardableApplied = false;- for (let attempt = 0; attempt < 2; attempt += 1) {+ let autoDiscardableVerified = false;+ const backoffsMs = [50, 200, 1000];+ for (let attempt = 0; attempt < backoffsMs.length; attempt += 1) {try {await chrome.tabs.update(tab.id, { autoDiscardable: false });autoDiscardableApplied = true;- break;+ try {+ const tabState = await chrome.tabs.get(tab.id);+ if (tabState && tabState.autoDiscardable === false) {+ autoDiscardableVerified = true;+ break;+ }+ } catch {}} catch (err) {- if (attempt === 1) {+ if (attempt === backoffsMs.length - 1) {console.warn("[Screenity] autoDiscardable failed for recorder tab",tab.id,@@ -90,32 +144,28 @@ const openRecorderTab = async (error: String(err),},});- } else {- await new Promise((r) => setTimeout(r, 50));}}+ if (attempt < backoffsMs.length - 1) {+ await new Promise((r) => setTimeout(r, backoffsMs[attempt]));+ }}chrome.storage.local.set({- recordingTab: tab.id,- offscreen: false,- region: false,- wasRegion: true,- clickEvents: [],- recordingUiTabId: activeTab.id,autoDiscardableApplied,- ...(isRegion ? { tabRecordedID: activeTab.id } : {}),+ autoDiscardableVerified,});chrome.tabs.onUpdated.addListener(function _(tabId, changeInfo) {if (tabId === tab.id && changeInfo.status === "complete") {chrome.tabs.onUpdated.removeListener(_);+ perfMark("BG.openRecorderTab tab-status-complete", { tabId });traceStep("recorderTabCreated");- // Include tabPreferred in the message so CloudRecorder can use it- // synchronously without racing against its own storage read.+ // tabPreferred lets CloudRecorder use it synchronously without racing storageconst isPlayground = activeTab.url.includes(chrome.runtime.getURL("playground.html"));+ perfMark("BG.openRecorderTab loaded.sent");sendMessageRecord({type: "loaded",request: request,@@ -128,11 +178,7 @@ const openRecorderTab = async (}: {}),});- // Proactively push streaming-data shortly after "loaded". The tab- // also pulls it, but that pull can drop if the SW is still waking- // or the tab's listener is not yet mounted. This push plus the- // tab-side retry plus the tab's idempotency guard give the handshake- // multiple chances to succeed before the start gate times out.+ // push streaming-data; tab also pulls but pull can drop on cold-SW/late-mountsetTimeout(() => {handleGetStreamingData().catch(() => {});}, 300);@@ -141,9 +187,18 @@ const openRecorderTab = async (};export const startRecorderSession = async (request, tabId = null) => {+ perfMark("BG.startRecorderSession.enter", {+ customRegion: Boolean(request?.customRegion),+ region: Boolean(request?.region),+ camera: Boolean(request?.camera),+ });console.log("[Screenity][startRecorderSession] entered", { request, tabId });+ const endStorage = perfSpan("BG.startRecorderSession storage.read");const { backup } = await chrome.storage.local.get(["backup"]);+ endStorage();+ const endTab = perfSpan("BG.startRecorderSession getCurrentTab");let activeTab = await getCurrentTab();+ endTab({ tabId: activeTab?.id || null });if (tabId !== null) {activeTab = await chrome.tabs.get(tabId);@@ -162,7 +217,9 @@ export const startRecorderSession = async (request, tabId = null) => {chrome.storage.local.set({ tabPreferred: false });}+ const endCloseOffscreen = perfSpan("BG.startRecorderSession closeOffscreenDocument");await closeOffscreenDocument();+ endCloseOffscreen();if (request.region) {if (tabId !== null) chrome.tabs.update(tabId, { active: true });@@ -174,12 +231,20 @@ export const startRecorderSession = async (request, tabId = null) => {region: true,recordingUiTabId: activeTab.id,});+ const endSendLoaded = perfSpan("BG.startRecorderSession customRegion.sendLoaded");sendMessageRecord({type: "loaded",request: request,backup: backup,region: true,- });+ })+ .then(() => endSendLoaded({ ok: true }))+ .catch((err) =>+ endSendLoaded({+ ok: false,+ err: String(err?.message || err).slice(0, 100),+ }),+ );} else {chrome.storage.local.set({recordingTab: activeTab.id,@@ -190,6 +255,7 @@ export const startRecorderSession = async (request, tabId = null) => {await openRecorderTab(activeTab, backup, true, false, request);}} else {+ chrome.storage.local.set({ region: false });await openRecorderTab(activeTab, backup, false, request.camera, request);}};diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.jsindex 7adab74..889ea0d 100644--- a/src/pages/Background/recording/recordingHelpers.js+++ b/src/pages/Background/recording/recordingHelpers.js@@ -10,20 +10,45 @@ import { addAlarmListener } from "../alarms/addAlarmListener";import { getStreamingData } from "./getStreamingData";import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";+import { perfMark, perfSpan } from "../../utils/perfMarks";import { classifyError } from "../../utils/errorCodes";import { resetWatchdogState } from "./resetWatchdogState";++// Mirrors CloudRecorder.appendUploadTelemetryEvent so BG-side projectId mutations+// land in the same `cloudUploadTelemetryEvents` storage key surfaced by+// buildDiagnosticZip → upload-telemetry.json. Diagnostic-only; best-effort.+const BG_UPLOAD_TELEMETRY_KEY = "cloudUploadTelemetryEvents";+const BG_UPLOAD_TELEMETRY_MAX = 300;+const appendBgUploadTelemetryEvent = async (payload) => {+ try {+ const existing = await chrome.storage.local.get([BG_UPLOAD_TELEMETRY_KEY]);+ const current = Array.isArray(existing?.[BG_UPLOAD_TELEMETRY_KEY])+ ? existing[BG_UPLOAD_TELEMETRY_KEY]+ : [];+ const eventPayload = {+ ts: Date.now(),+ uploaderType: "bg_recording",+ ...payload,+ };+ const next = [...current, eventPayload].slice(-BG_UPLOAD_TELEMETRY_MAX);+ await chrome.storage.local.set({+ [BG_UPLOAD_TELEMETRY_KEY]: next,+ lastUploadTelemetryEvent: eventPayload,+ });+ } catch {+ // best-effort; telemetry must never break recording+ }+};+export const checkCapturePermissions = async ({ isLoggedIn, isSubscribed }) => {const permissions = ["desktopCapture", "alarms", "offscreen"];- // Add clipboardWrite and notifications only for subscribed usersif (isLoggedIn && isSubscribed) {permissions.push("clipboardWrite");}- // Must be the first await. Any preceding await consumes the user-gesture- // context propagated from the content-script click, and Chrome rejects- // request() with "must be called during a user gesture" even when all- // perms are already granted.+ // MUST be the first await; preceding awaits consume the user-gesture context+ // and Chrome rejects request() with "must be called during a user gesture"const granted = await new Promise((resolve) => {chrome.permissions.request({ permissions }, resolve);});@@ -46,7 +71,6 @@ export const handlePip = async (started = false) => {};export const handleOnGetPermissions = async (request) => {- // Send a message to (actual) active tabconst activeTab = await getCurrentTab();if (activeTab) {sendMessageTab(activeTab.id, {@@ -57,30 +81,43 @@ export const handleOnGetPermissions = async (request) => {};export const handleRecordingComplete = async () => {- const { recordingTab } = await chrome.storage.local.get(["recordingTab"]);+ perfMark("BG.recordingHelpers handleRecordingComplete.enter");+ const { recordingTab, completingRecordingTab } =+ await chrome.storage.local.get([+ "recordingTab",+ "completingRecordingTab",+ ]);- if (recordingTab) {- chrome.tabs.get(recordingTab, (tab) => {+ // snapshot at stop time; live recordingTab may belong to a new session by now+ const target = completingRecordingTab ?? null;++ if (target) {+ chrome.tabs.get(target, (tab) => {if (chrome.runtime.lastError || !tab) return;- // Check if tab url contains chrome-extension and recorder.htmlif (tab.url.includes("chrome-extension") &&tab.url.includes("recorder.html")) {- // FLAG: For testing purposes -> comment to debug- removeTab(recordingTab);+ removeTab(target);}});}- // Clear so subsequent recordings don't conflict- chrome.storage.local.set({ recordingTab: null, offscreen: false });- console.log("[Screenity][BG] handleRecordingComplete fired, recordingTab:", recordingTab);++ // null recordingTab only if still pointing at the tab we just finished+ const updates = { offscreen: false, completingRecordingTab: null };+ if (target != null && recordingTab === target) {+ updates.recordingTab = null;+ }+ chrome.storage.local.set(updates);+ console.log(+ "[Screenity][BG] handleRecordingComplete fired",+ { target, liveRecordingTab: recordingTab, cleared: target === recordingTab },+ );};export const handleRecordingError = async (request) => {console.warn("[Screenity][handleRecordingError]", request);- // Propagate or derive error codeconst errorCode =request?.errorCode ||classifyError(request?.why || "", request?.error || "");@@ -117,8 +154,7 @@ export const handleRecordingError = async (request) => {errorCode,});- // For stream-ended, we just notify the user but DON'T stop the recording- // The user can decide whether to continue or stop+ // stream-ended: notify only, never stop. user decides whether to continueif (isWarningOnly) {sendMessageTab(activeTab, {type: "stream-ended-warning",@@ -126,21 +162,80 @@ export const handleRecordingError = async (request) => {}).catch((err) => {diagEvent("warning", { note: "stream-ended-warning undelivered", err: String(err).slice(0, 80) });});- return; // Don't continue with the normal error handling+ return;}endDiagSession("error");+ // mirrors discardRecording: 1+ scenes saved -> preserve project for retry+ const {+ multiMode,+ multiSceneCount,+ projectId: projectIdBeforeClear,+ sceneId: sceneIdBeforeClear,+ recordingAttemptId: attemptIdAtClear,+ } = await chrome.storage.local.get([+ "multiMode",+ "multiSceneCount",+ "projectId",+ "sceneId",+ "recordingAttemptId",+ ]);+ const preserveMultiProject =+ Boolean(multiMode) && Number(multiSceneCount) > 0;+ // sceneId/sceneIdStatus/pendingSceneIndex must clear with projectId. Otherwise a+ // retry attempt inherits a sceneId tied to a project that no longer exists, and+ // the cloudrecorder reaches startRecording with projectId=null while sceneIdStatus+ // still says "recording". See the no-project-id failure pattern in diagnostics.+ const multiState = preserveMultiProject+ ? {}+ : {+ multiMode: false,+ multiSceneCount: 0,+ multiProjectId: null,+ multiLastSceneId: null,+ recordingToScene: false,+ projectId: null,+ activeSceneId: null,+ sceneId: null,+ sceneIdStatus: null,+ pendingSceneIndex: null,+ };+await chrome.storage.local.set({recording: false,recordingUiTabId: null,tabRecordedID: null,offscreen: false,postStopEditorOpened: false,+ // releases the editor-opening lock; otherwise next stopRecording refuses to open editor+ postStopEditorOpening: false,region: false,customRegion: false,+ // PiP + pause must follow recording down; otherwise next session inherits paused=true+ pipForceClose: Date.now(),+ paused: false,+ pausedAt: null,+ totalPausedMs: 0,+ ...multiState,});+ if (!preserveMultiProject && projectIdBeforeClear) {+ void appendBgUploadTelemetryEvent({+ event: "project_state_change",+ source: "bg-recording-error",+ from: projectIdBeforeClear,+ to: null,+ sceneId: sceneIdBeforeClear || null,+ reason: request?.error || "recording-error",+ why: request?.why || null,+ errorCode,+ recordingAttemptId: attemptIdAtClear || null,+ });+ }++ chrome.runtime.sendMessage({ type: "turn-off-pip" }).catch(() => {});+chrome.runtime.sendMessage({type: "clear-recording-session-safe",@@ -150,6 +245,36 @@ export const handleRecordingError = async (request) => {diagEvent("warning", { note: "clear-session-safe undelivered", err: String(err).slice(0, 80) });});+ // sandboxed editor: runtime.onMessage unreliable, storage.onChanged fires.+ // try message first, ALWAYS write the storage flag.+ const { sandboxTab } = await chrome.storage.local.get(["sandboxTab"]);+ let sandboxAlive = false;+ if (Number.isInteger(sandboxTab)) {+ try {+ await chrome.tabs.get(sandboxTab);+ sandboxAlive = true;+ sendMessageTab(sandboxTab, {+ type: "recording-error",+ error: request?.error || null,+ why: request?.why || null,+ errorCode,+ }).catch(() => {});+ } catch {}+ }+ // a later-mounting editor reads this on boot to surface the modal;+ // sandboxTab filters stale entries from prior sessions+ try {+ await chrome.storage.local.set({+ editorRecordingError: {+ ts: Date.now(),+ sandboxTab: Number.isInteger(sandboxTab) ? sandboxTab : null,+ error: request?.error || null,+ why: request?.why || null,+ errorCode,+ },+ });+ } catch {}+sendMessageRecord({ type: "recording-error" }).then(() => {const candidateTabs = [activeTab, recordingUiTabId, tabRecordedID].filter((id, idx, arr) => Number.isInteger(id) && arr.indexOf(id) === idx,@@ -157,7 +282,10 @@ export const handleRecordingError = async (request) => {candidateTabs.forEach((id) => {sendMessageTab(id, { type: "stop-pending" }).catch(() => {});});- focusTab(activeTab);+ // refocus only when no editor is open+ if (!sandboxAlive) {+ focusTab(activeTab);+ }if (request.error === "stream-error") {sendMessageTab(activeTab, { type: "stream-error", errorCode });} else if (request.error === "backup-error") {@@ -172,9 +300,7 @@ export const handleRecordingError = async (request) => {if (tab?.url?.startsWith(chrome.runtime.getURL(""))) {removeTab(recordingTab);}- } catch {- // Tab doesn't exist- }+ } catch {}}chrome.storage.local.set({ recordingTab: null });try {@@ -184,26 +310,29 @@ export const handleRecordingError = async (request) => {};export const handleGetStreamingData = async () => {+ perfMark("BG.handleGetStreamingData.enter");const data = await getStreamingData();const payload = { type: "streaming-data", data: JSON.stringify(data) };- // Retry delivery. The recorder tab's message listener may not be mounted- // yet when the tab first loads, or the tab may be briefly throttled by- // Chrome. A dropped delivery here is what causes REC_START_NO_STREAM_MSG- // at the tab's 12s start gate. Tab-side handler is idempotent (first- // delivery wins), so extra retries are safe.+ // dropped delivery causes REC_START_NO_STREAM_MSG at the tab's 12s gate;+ // tab-side is idempotent so retries are safeconst backoffMs = [0, 300, 800];for (let attempt = 0; attempt < backoffMs.length; attempt++) {if (backoffMs[attempt] > 0) {await new Promise((r) => setTimeout(r, backoffMs[attempt]));}+ const endSend = perfSpan("BG.handleGetStreamingData sendMessageRecord", {+ attempt,+ });try {await sendMessageRecord(payload);+ endSend({ ok: true });if (attempt > 0) {diagEvent("sw-streaming-data-send-ok", { attempt });}return;} catch (err) {+ endSend({ ok: false, err: String(err?.message || err).slice(0, 80) });diagEvent("sw-streaming-data-send-fail", {attempt,err: String(err?.message || err).slice(0, 120),@@ -219,6 +348,7 @@ export const handleGetStreamingData = async () => {};export const videoReady = async () => {+ perfMark("BG.recordingHelpers videoReady.enter");const { backupTab, recordingDuration } = await chrome.storage.local.get(["backupTab","recordingDuration",diff --git a/src/pages/Background/recording/restartRecording.js b/src/pages/Background/recording/restartRecording.jsindex bc649cc..0b1d34c 100644--- a/src/pages/Background/recording/restartRecording.js+++ b/src/pages/Background/recording/restartRecording.js@@ -1,9 +1,11 @@import { sendMessageRecord } from "./sendMessageRecord";import { resetActiveTabRestart } from "../tabManagement/resetActiveTab";import { diagEvent } from "../../utils/diagnosticLog";+import { lifecycle } from "../../utils/lifecycleLog";import { resetWatchdogState } from "./resetWatchdogState";const RESTART_ACK_TIMEOUT_MS = 7000;+const RESTART_HISTORY_MAX = 20;const withTimeout = (promise, timeoutMs) =>Promise.race([@@ -14,13 +16,19 @@ const withTimeout = (promise, timeoutMs) =>]);const persistRestartFlow = async (phase, details = {}) => {- await chrome.storage.local.set({- lastRestartFlow: {- phase,- ts: Date.now(),- ...details,- },- });+ const entry = { phase, ts: Date.now(), ...details };+ try {+ const { restartFlowHistory } = await chrome.storage.local.get([+ "restartFlowHistory",+ ]);+ const history = Array.isArray(restartFlowHistory) ? restartFlowHistory : [];+ history.push(entry);+ while (history.length > RESTART_HISTORY_MAX) history.shift();+ await chrome.storage.local.set({+ lastRestartFlow: entry,+ restartFlowHistory: history,+ });+ } catch {}};const resolveSourceTabId = (message, sender) =>@@ -28,7 +36,32 @@ const resolveSourceTabId = (message, sender) =>export const handleRestart = async (message = {}, sender = null) => {const sourceTabId = resolveSourceTabId(message, sender);- // Reset watchdog BEFORE the round-trip so a mid-flight alarm can't fire tier-3 against stale keys.+ const attemptId = `restart-${Date.now().toString(36)}-${Math.random()+ .toString(36)+ .slice(2, 8)}`;++ let preflight = {};+ try {+ preflight = await chrome.storage.local.get([+ "recordingTab",+ "recording",+ "pendingRecording",+ "offscreen",+ "recorderSession",+ ]);+ } catch {}+ const preflightSummary = {+ recordingTab: preflight.recordingTab ?? null,+ recording: Boolean(preflight.recording),+ pendingRecording: Boolean(preflight.pendingRecording),+ offscreen: Boolean(preflight.offscreen),+ recorderSessionTab:+ preflight.recorderSession?.recorderTabId ||+ preflight.recorderSession?.tabId ||+ null,+ };++ // reset before round-trip so a mid-flight alarm can't fire tier-3 against stale keysawait resetWatchdogState();await chrome.storage.local.set({restarting: true,@@ -36,36 +69,98 @@ export const handleRestart = async (message = {}, sender = null) => {? { activeTab: sourceTabId, recordingUiTabId: sourceTabId }: {}),});- await persistRestartFlow("requested", { sourceTabId });- diagEvent("restart-requested");+ await persistRestartFlow("requested", {+ attemptId,+ sourceTabId,+ preflight: preflightSummary,+ });+ lifecycle("BG.restart", "requested", {+ attemptId,+ sourceTabId,+ ...preflightSummary,+ });+ diagEvent("restart-requested", { attemptId, sourceTabId });try {const response = await withTimeout(sendMessageRecord({type: "restart-recording-tab",sourceTabId,+ attemptId,}),RESTART_ACK_TIMEOUT_MS,);+ lifecycle("BG.restart", "ack-received", {+ attemptId,+ ok: Boolean(response?.ok),+ restarted: Boolean(response?.restarted),+ error: response?.error || null,+ recorderState: response?.recorderState || null,+ });+if (!response?.ok || response?.restarted !== true) {- throw new Error(response?.error || "restart-ack-failed");+ const err = new Error(response?.error || "restart-ack-failed");+ err._recorderState = response?.recorderState || null;+ err._stage = "ack-rejected";+ throw err;}await persistRestartFlow("ack", {+ attemptId,sourceTabId,restarted: Boolean(response?.restarted),+ recorderState: response?.recorderState || null,});await resetActiveTabRestart({ sourceTabId });- await persistRestartFlow("countdown-dispatched", { sourceTabId });- diagEvent("restart-completed");+ await persistRestartFlow("countdown-dispatched", { attemptId, sourceTabId });+ lifecycle("BG.restart", "completed", { attemptId, sourceTabId });+ diagEvent("restart-completed", { attemptId });return { ok: true, restarted: true };} catch (error) {const reason = error?.message || String(error);+ const stage =+ error?._stage ||+ (reason.includes("Receiving end does not exist") ||+ reason.includes("No tab with id") ||+ reason.includes("No recording tab available")+ ? "send-no-tab"+ : reason.includes("restart-ack-timeout")+ ? "ack-timeout"+ : "send-error");await chrome.storage.local.set({ restarting: false });- await persistRestartFlow("failed", { sourceTabId, reason });- diagEvent("restart-failed", { reason });- return { ok: false, error: reason };+ await persistRestartFlow("failed", {+ attemptId,+ sourceTabId,+ stage,+ reason,+ recorderState: error?._recorderState || null,+ });+ lifecycle("BG.restart", "failed", {+ attemptId,+ sourceTabId,+ stage,+ reason,+ recorderState: error?._recorderState || null,+ });+ diagEvent("restart-failed", { attemptId, stage, reason });+ // Content caller is fire-and-forget; toast the user directly+ try {+ const targetTabId =+ sourceTabId ||+ (await chrome.storage.local.get(["activeTab"])).activeTab ||+ null;+ if (Number.isInteger(targetTabId)) {+ chrome.tabs+ .sendMessage(targetTabId, {+ type: "show-toast",+ message: chrome.i18n.getMessage("restartFailedToast"),+ timeout: 6000,+ })+ .catch(() => {});+ }+ } catch {}+ return { ok: false, error: reason, stage };}};diff --git a/src/pages/Background/recording/restoreCloudRecording.js b/src/pages/Background/recording/restoreCloudRecording.jsindex 6303f6d..f01a8f8 100644--- a/src/pages/Background/recording/restoreCloudRecording.js+++ b/src/pages/Background/recording/restoreCloudRecording.js@@ -1,6 +1,6 @@-import localforage from "localforage";import { createTab, sendMessageTab } from "../tabManagement";import { resetWatchdogState } from "./resetWatchdogState";+import { openExistingChunksStore } from "../../CloudRecorder/recorderStorage/chooseChunksStore";const RECOVERABLE_CLOUD_STATUSES = new Set(["recording",@@ -11,12 +11,39 @@ const RECOVERABLE_CLOUD_STATUSES = new Set(["upload-stalled",]);-// Mirror the store names CloudRecorder.jsx uses. createInstance({ name }) sets-// the IndexedDB database name directly, so these reach the same databases-// regardless of any global localforage.config() call.-const cloudScreenStore = localforage.createInstance({ name: "chunks" });-const cloudCameraStore = localforage.createInstance({ name: "cameraChunks" });-const cloudAudioStore = localforage.createInstance({ name: "audioChunks" });+// Per-track .length() against whatever backend the previous session used.+// Sessions persisted before the OPFS migration carry no storageBackends+// field, so default to IDB across all three tracks so legacy state still+// recovers.+const countChunks = async (storedSession) => {+ const backends = storedSession?.storageBackends || {+ screen: "idb",+ audio: "idb",+ camera: "idb",+ };+ const opfsSessionId =+ storedSession?.opfsSessionId || storedSession?.id || null;++ const counts = await Promise.all(+ ["screen", "camera", "audio"].map(async (track) => {+ try {+ const { store } = openExistingChunksStore({+ sessionId: opfsSessionId,+ track,+ backend: backends[track] || "idb",+ });+ return await store.length().catch(() => 0);+ } catch {+ return 0;+ }+ }),+ );+ return {+ screenCount: counts[0],+ cameraCount: counts[1],+ audioCount: counts[2],+ };+};export const checkCloudRestore = async () => {try {@@ -30,11 +57,9 @@ export const checkCloudRestore = async () => {return { cloudRestore: false };}- const [screenCount, cameraCount, audioCount] = await Promise.all([- cloudScreenStore.length().catch(() => 0),- cloudCameraStore.length().catch(() => 0),- cloudAudioStore.length().catch(() => 0),- ]);+ const { screenCount, cameraCount, audioCount } = await countChunks(+ recorderSession,+ );return {cloudRestore: screenCount > 0 || cameraCount > 0 || audioCount > 0,@@ -54,10 +79,24 @@ export const restoreCloudRecording = async () => {const tab = await createTab("download.html", true, true);if (!tab?.id) return;- chrome.tabs.onUpdated.addListener(function listener(tabId, info) {+ let settled = false;+ const safetyId = setTimeout(() => {+ if (settled) return;+ settled = true;+ chrome.tabs.onUpdated.removeListener(listener);+ console.warn(+ "[Screenity][BG] cloud-restore tab load timed out",+ tab.id,+ );+ }, 30000);+ function listener(tabId, info) {if (info.status === "complete" && tabId === tab.id) {+ if (settled) return;+ settled = true;+ clearTimeout(safetyId);chrome.tabs.onUpdated.removeListener(listener);sendMessageTab(tab.id, { type: "recover-cloud-indexed-db" });}- });+ }+ chrome.tabs.onUpdated.addListener(listener);};diff --git a/src/pages/Background/recording/restoreRecording.js b/src/pages/Background/recording/restoreRecording.jsindex cfdfafd..4e45646 100644--- a/src/pages/Background/recording/restoreRecording.js+++ b/src/pages/Background/recording/restoreRecording.js@@ -1,69 +1,226 @@-import { sendMessageTab } from "../tabManagement";+import { sendMessageTab, getCurrentTab } from "../tabManagement";import { chunksStore } from "./chunkHandler";-export const checkRestore = async () => {- const chunks = [];- await chunksStore.iterate((value, key) => {- chunks.push(value);- });+// pass explicitTabId so toasts land on the original tab even after a switch+const notifyRestoreToast = async (message, explicitTabId = null) => {+ try {+ let tabId = explicitTabId;+ if (!tabId) {+ const tab = await getCurrentTab();+ tabId = tab?.id || null;+ }+ if (!tabId) return;+ sendMessageTab(tabId, {+ type: "show-toast",+ message,+ timeout: 6000,+ }).catch(() => {});+ } catch {}+};- if (chunks.length === 0) {- return { restore: false, chunks: [] };+const notifyRestoreEmpty = (tabId = null) =>+ notifyRestoreToast(+ chrome.i18n.getMessage("restoreEmptyToast") ||+ "No recoverable recording found.",+ tabId,+ );++const notifyRestoreTimeout = (tabId = null) =>+ notifyRestoreToast(+ chrome.i18n.getMessage("restoreTimeoutToast") ||+ "Recovery is taking too long. Try opening the recovered file again.",+ tabId,+ );++const OPFS_RECORDING_PREFIX = "recording-";+// mirrors reader-side threshold; below this the editor can't open the file+const MIN_VALID_RECORDING_BYTES = 4096;++// skip tiny files so crashed-session empties don't surface+const listOpfsRecordings = async () => {+ try {+ if (!navigator.storage || typeof navigator.storage.getDirectory !== "function") {+ return [];+ }+ const dir = await navigator.storage.getDirectory();+ const files = [];+ for await (const [name, handle] of dir.entries()) {+ if (!name.startsWith(OPFS_RECORDING_PREFIX)) continue;+ if (!name.endsWith(".mp4")) continue;+ try {+ const file = await handle.getFile();+ if (file.size < MIN_VALID_RECORDING_BYTES) continue;+ files.push({ name, lastModified: file.lastModified, size: file.size });+ } catch {}+ }+ return files;+ } catch {+ return [];}- return { restore: true };+};++export const checkRestore = async () => {+ const [idbChunkCount, opfsFiles] = await Promise.all([+ (async () => {+ let count = 0;+ try {+ await chunksStore.iterate(() => {+ count += 1;+ });+ } catch {}+ return count;+ })(),+ listOpfsRecordings(),+ ]);+ const restore = idbChunkCount > 0 || opfsFiles.length > 0;+ return { restore };};export const restoreRecording = async () => {const { fastRecorderInUse } = await chrome.storage.local.get(["fastRecorderInUse",]);- //const hasWebCodecs = supportsWebCodecs();++ // capture trigger tab now; restore can take 30s+ and the user may switch+ let triggerTabId = null;+ try {+ const trigger = await getCurrentTab();+ triggerTabId = trigger?.id || null;+ } catch {}++ // WebCodecs (4.4.0+) writes here; prefer most recent+ const opfsFiles = await listOpfsRecordings();+ if (opfsFiles.length > 0) {+ opfsFiles.sort((a, b) => b.lastModified - a.lastModified);+ const latest = opfsFiles[0];+ await chrome.storage.local.set({+ lastRecordingBackendRef: {+ backend: "opfs",+ fileName: latest.name,+ },+ // orphan from a prior session, writer is gone, reader can skip polling+ lastRecordingFinalizedFileName: latest.name,+ });+ const editorUrl = "editorwebcodecs.html?mode=recover";+ chrome.tabs.create({ url: editorUrl, active: true }, async (tab) => {+ chrome.storage.local.set({ sandboxTab: tab.id });+ await new Promise((resolve) => {+ let settled = false;+ const safetyId = setTimeout(() => {+ if (settled) return;+ settled = true;+ chrome.tabs.onUpdated.removeListener(listener);+ console.warn(+ "[Screenity][BG] restore-recording (opfs) tab load timed out",+ tab.id,+ );+ notifyRestoreTimeout(triggerTabId).catch(() => {});+ setTimeout(() => {+ chrome.tabs.remove(tab.id).catch(() => {});+ }, 1000);+ resolve();+ }, 30000);+ function listener(tabId, info) {+ if (info.status === "complete" && tabId === tab.id) {+ if (settled) return;+ settled = true;+ clearTimeout(safetyId);+ chrome.tabs.onUpdated.removeListener(listener);+ setTimeout(() => {+ sendMessageTab(tab.id, { type: "restore-recording" });+ resolve();+ }, 2000);+ }+ }+ chrome.tabs.onUpdated.addListener(listener);+ });+ });+ return;+ }++ // IDB fallback: MediaRecorder + pre-4.4.0 WebCodecs.+ // Duration estimate routes between editor.html (short, ffmpeg) and viewer (long).+ // Priority: recordingDuration (clean stop) > lastChunkAt-firstChunkAt (survives SW death).const hasWebCodecs = Boolean(fastRecorderInUse);+ const {+ recordingDuration,+ firstChunkAt,+ lastChunkAt,+ } = await chrome.storage.local.get([+ "recordingDuration",+ "firstChunkAt",+ "lastChunkAt",+ ]);+ const chunkSpanMs =+ Number(firstChunkAt) > 0 && Number(lastChunkAt) > Number(firstChunkAt)+ ? Number(lastChunkAt) - Number(firstChunkAt)+ : 0;+ const durationMs = Math.max(Number(recordingDuration) || 0, chunkSpanMs);+ const FFMPEG_MAX_DURATION_MS = 7 * 60 * 1000;let editorUrl, messageType;-if (hasWebCodecs) {editorUrl = "editorwebcodecs.html?mode=recover";messageType = "restore-recording";+ } else if (durationMs > 0 && durationMs <= FFMPEG_MAX_DURATION_MS) {+ // ffmpeg-wasm cap: editLimit:600+ editorUrl = "editor.html?mode=recover";+ messageType = "fallback-recording";} else {+ // ffmpeg-wasm OOMs on >7min; viewer-onlyeditorUrl = "editorviewer.html?mode=recover";messageType = "viewer-recording";}const chunks = [];- await chunksStore.iterate((value) => {- chunks.push(value);- });-+ try {+ await chunksStore.iterate((value) => {+ chunks.push(value);+ });+ } catch (err) {+ console.warn("[Screenity][BG] restoreRecording chunksStore.iterate failed", err);+ }if (chunks.length === 0) {+ console.warn("[Screenity][BG] restoreRecording: no OPFS files and no IDB chunks");+ await notifyRestoreEmpty(triggerTabId);return;}+ // force IDB reader regardless of stale backendRef+ await chrome.storage.local.set({+ lastRecordingBackendRef: { backend: "idb" },+ });- // Create the editor tab- chrome.tabs.create(- {- url: editorUrl,- active: true,- },- async (tab) => {- // Save the tab ID in local storage- chrome.storage.local.set({ sandboxTab: tab.id });-- // Wait for the tab to load before sending messages- await new Promise((resolve) => {- chrome.tabs.onUpdated.addListener(function listener(tabId, info) {- if (info.status === "complete" && tabId === tab.id) {- chrome.tabs.onUpdated.removeListener(listener);-- setTimeout(() => {- sendMessageTab(tab.id, {- type: messageType,- });- resolve();- }, 2000);- }- });- });- }- );+ chrome.tabs.create({ url: editorUrl, active: true }, async (tab) => {+ chrome.storage.local.set({ sandboxTab: tab.id });+ await new Promise((resolve) => {+ let settled = false;+ const safetyId = setTimeout(() => {+ if (settled) return;+ settled = true;+ chrome.tabs.onUpdated.removeListener(listener);+ console.warn(+ "[Screenity][BG] restore-recording (idb) tab load timed out",+ tab.id,+ );+ notifyRestoreTimeout(triggerTabId).catch(() => {});+ setTimeout(() => {+ chrome.tabs.remove(tab.id).catch(() => {});+ }, 1000);+ resolve();+ }, 30000);+ function listener(tabId, info) {+ if (info.status === "complete" && tabId === tab.id) {+ if (settled) return;+ settled = true;+ clearTimeout(safetyId);+ chrome.tabs.onUpdated.removeListener(listener);+ setTimeout(() => {+ sendMessageTab(tab.id, { type: messageType });+ resolve();+ }, 2000);+ }+ }+ chrome.tabs.onUpdated.addListener(listener);+ });+ });};diff --git a/src/pages/Background/recording/resumePendingUploads.js b/src/pages/Background/recording/resumePendingUploads.jsindex 52a16fc..73b0259 100644--- a/src/pages/Background/recording/resumePendingUploads.js+++ b/src/pages/Background/recording/resumePendingUploads.js@@ -1,8 +1,6 @@-// Background retry queue for incomplete upload journals - resumed silently in an offscreen doc.-const JOURNAL_KEY_PREFIX = "uploadJournal-";const MAX_RESUME_ATTEMPTS = 5;-const RESUME_LOCK_TTL_MS = 10 * 60 * 1000; // 10 min - stale lock recovery.+const RESUME_LOCK_TTL_MS = 10 * 60 * 1000;const getAllStorage = () =>new Promise((resolve) => {@@ -21,7 +19,7 @@ const pickResumeCandidates = (storage) => {if (!value || typeof value !== "object") continue;if (value.trackType === "audio") continue; // audio is diagnostic, never uploadedif (value.status === "completed") continue;- if ((value.offset || 0) >= (value.totalBytes || 0)) continue;+ // status is source of truth; offset>=totalBytes still needs finalize()if ((value.resumeAttempts || 0) >= MAX_RESUME_ATTEMPTS) {abandonedKeys.push(key);continue;diff --git a/src/pages/Background/recording/sendChunks.js b/src/pages/Background/recording/sendChunks.jsindex 9c0343c..cb6fefb 100644--- a/src/pages/Background/recording/sendChunks.js+++ b/src/pages/Background/recording/sendChunks.js@@ -5,7 +5,6 @@ import { diagEvent } from "../../utils/diagnosticLog";export const sendChunks = async (override = false, target = null) => {const startedAt = Date.now();try {- // Wait briefly for chunks to be flushed to IndexedDBconst maxAttempts = 50;const delayMs = 200;let chunkCount = 0;@@ -40,7 +39,13 @@ export const sendChunks = async (override = false, target = null) => {targetTabId: target?.tabId ?? null,},});- } catch {}+ } catch (writeErr) {+ // diag-write failure means storage itself is broken (quota/corruption)+ diagEvent("storage-write-failed", {+ key: "lastChunkSendFailure",+ err: String(writeErr?.message || writeErr).slice(0, 200),+ });+ }diagEvent("chunks-fail", { why: "no-chunks-after-wait" });return { status: "empty", chunkCount: 0 };}@@ -52,7 +57,6 @@ export const sendChunks = async (override = false, target = null) => {console.debug("[Screenity][BG] sendChunks: collected chunks", {count: chunks.length,});- // Await handleChunks to ensure messaging completes before returningawait handleChunks(chunks, override, target);diagEvent("chunks-sent", { count: chunks.length });diagEvent("sw-sendchunks-done", {@@ -65,7 +69,11 @@ export const sendChunks = async (override = false, target = null) => {error: String(error?.message || error).slice(0, 200),elapsedMs: Date.now() - startedAt,});- console.error("Failed to send chunks. Reloading extension.", error);- chrome.runtime.reload();+ // never runtime.reload() here; caller retries on error status+ console.error("Failed to send chunks", error);+ return {+ status: "error",+ error: String(error?.message || error).slice(0, 200),+ };}};diff --git a/src/pages/Background/recording/sendMessageRecord.js b/src/pages/Background/recording/sendMessageRecord.jsindex 7e53587..516cf57 100644--- a/src/pages/Background/recording/sendMessageRecord.js+++ b/src/pages/Background/recording/sendMessageRecord.js@@ -34,21 +34,26 @@ export const sendMessageRecord = (message, responseCallback = null) => {reject(err);});} else {- // No recordingTab set - check if there's an active recorderSession- // This can happen if the service worker restarted and lost in-memory state+ // SW restart can lose recordingTab, fall back to recorderSession+ // but only if it's still live. completed/crashed/stopped sessions+ // point at a dead tab and would surface a misleading "No tab with+ // id" error instead of the real "no recorder tab" one.chrome.storage.local.get(["recorderSession"], (sessionResult) => {+ const session = sessionResult.recorderSession;const recorderTabId =- sessionResult.recorderSession?.recorderTabId ||- sessionResult.recorderSession?.tabId ||- null;- if (sessionResult.recorderSession && recorderTabId) {- // Try the tab from the persisted session+ session?.recorderTabId || session?.tabId || null;+ const sessionLive =+ session?.status === "recording" || session?.status === "starting";+ if (sessionLive && recorderTabId) {sendMessageTab(recorderTabId, message, responseCallback).then(resolve).catch(reject);} else {console.warn(- "sendMessageRecord: no recordingTab or recorderSession available"+ "sendMessageRecord: no recording tab available",+ session+ ? { sessionStatus: session.status, recorderTabId }+ : { session: null });reject(new Error("No recording tab available"));}diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.jsindex 3446d85..16ba666 100644--- a/src/pages/Background/recording/startRecording.js+++ b/src/pages/Background/recording/startRecording.js@@ -1,14 +1,162 @@import { sendMessageRecord } from "./sendMessageRecord";import { sendMessageTab } from "../tabManagement";+import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";import { initDiagSession, diagEvent } from "../../utils/diagnosticLog";import { makeRecordingAttemptId } from "../../utils/errorCodes";+import { lifecycle } from "../../utils/lifecycleLog";-export const startRecording = async () => {- // Correlation ID for this recording attempt+// `recording` flag isn't set until the recorder iframe inits (seconds later),+// so countdown-finished + 8s fallback can both fire and open two recorder tabs+let _startRecordingInFlight = false;+const STARTRECORDING_GUARD_TIMEOUT_MS = 30000;+let _startRecordingGuardTimer = null;+const releaseStartRecordingGuard = () => {+ _startRecordingInFlight = false;+ if (_startRecordingGuardTimer) {+ clearTimeout(_startRecordingGuardTimer);+ _startRecordingGuardTimer = null;+ }+ // mirrored to storage so listeners (onTabRemoved, sendMessageRecord)+ // can tell start-in-flight apart from idle+ chrome.storage.local.set({ recordingStartingAt: null }).catch(() => {});+};+try {+ chrome.storage.onChanged.addListener((changes, area) => {+ if (area !== "local") return;+ if (changes.recording && changes.recording.newValue === true) {+ releaseStartRecordingGuard();+ }+ if (+ changes.recording &&+ changes.recording.oldValue === true &&+ changes.recording.newValue === false+ ) {+ releaseStartRecordingGuard();+ }+ });+} catch {}++// matches STARTRECORDING_GUARD_TIMEOUT_MS so a crashed start eventually+// stops shielding cleanup+export const RECORDING_STARTING_GRACE_MS = 30000;+export const isRecordingStartInFlight = (flags) => {+ if (!flags) return false;+ if (flags.pendingRecording) return true;+ if (flags.restarting) return true;+ const at = flags.recordingStartingAt;+ if (typeof at === "number" && Date.now() - at < RECORDING_STARTING_GRACE_MS) {+ return true;+ }+ return false;+};++export const startRecording = async (caller = "unknown") => {+ if (_startRecordingInFlight) {+ diagEvent("warning", {+ note: "startRecording suppressed (in-flight)",+ caller,+ });+ return;+ }+ _startRecordingInFlight = true;+ _startRecordingGuardTimer = setTimeout(+ releaseStartRecordingGuard,+ STARTRECORDING_GUARD_TIMEOUT_MS,+ );+ try {+ return await _startRecordingInner(caller);+ } catch (err) {+ // sync failure before sendMessageRecord's deferred catch; release immediately+ releaseStartRecordingGuard();+ throw err;+ }+};++const _startRecordingInner = async (caller) => {const recordingAttemptId = makeRecordingAttemptId();+ // snapshot residual state to spot leaked flags from prior recordings+ try {+ const residual = await chrome.storage.local.get([+ "recordingTab",+ "recordingUiTabId",+ "tabRecordedID",+ "sandboxTab",+ "region",+ "customRegion",+ "recordingType",+ "recording",+ "pendingRecording",+ "restarting",+ "offscreen",+ "useWebCodecsRecorder",+ "fastRecorderInUse",+ "backup",+ "backupSetup",+ "backupTab",+ "memoryError",+ ]);+ lifecycle("BG.startRecording", "session-boundary", {+ caller,+ attemptId: recordingAttemptId,+ residual,+ });+ } catch {}+ let stack = null;+ try {+ stack = new Error().stack?.split("\n").slice(1, 6).join("\n") || null;+ } catch {}++ // set start-in-flight before any tab removal or message send below,+ // otherwise onTabRemoved/onTabUpdated fire with the flag still false+ // and tear down the recorder tab we're about to create+ await chrome.storage.local.set({+ recordingStartingAt: Date.now(),+ });++ // Close any prior editor tab. The OPFS writer wipes the previous+ // recording's file when a new one starts, so leaving the old editor+ // open with stale backing data is worse than closing it. The+ // editor-force-close message clears its beforeunload prompt first so+ // the user doesn't get a confirm dialog. The recordingStartingAt guard+ // above keeps the cascading cleanup off the new recorder tab.+ try {+ const { sandboxTab: priorSandboxTab } = await chrome.storage.local.get([+ "sandboxTab",+ ]);+ if (Number.isInteger(priorSandboxTab)) {+ try {+ await Promise.race([+ chrome.tabs.sendMessage(priorSandboxTab, {+ type: "editor-force-close",+ }),+ new Promise((r) => setTimeout(r, 250)),+ ]);+ } catch {}+ chrome.tabs.remove(priorSandboxTab).catch(() => {});+ }+ } catch {}+chrome.storage.local.set({restarting: false,recordingAttemptId,+ memoryError: false,+ cloudRecorderDegradedMode: null,+ editorRecordingError: null,+ // prior sandboxTab would route this attempt's errors to the wrong editor+ sandboxTab: null,+ // paused leak from a prior errored recording would mis-account duration+ paused: false,+ pausedAt: null,+ totalPausedMs: 0,+ // recorder writes a fresh ref on open; clear so a pre-writer failure+ // doesn't leave a later editor reading the prior recording's data+ lastRecordingBackendRef: null,+ // clear so the prior recording's "ready" signal can't trick the+ // editor into reading the new in-flight recording+ lastRecordingFinalizedFileName: null,+ lastRecordingError: null,+ lastChunkSendFailure: null,+ lastStartRecordingCaller: { caller, stack, ts: Date.now() },});const { activeTab, recordingUiTabId } = await chrome.storage.local.get([@@ -21,7 +169,6 @@ export const startRecording = async () => {chrome.storage.local.set({ recordingUiTabId: activeTab });}- // Check if customRegion is setconst { customRegion } = await chrome.storage.local.get(["customRegion"]);const { recordingType } = await chrome.storage.local.get(["recordingType"]);@@ -63,7 +210,6 @@ export const startRecording = async () => {chrome.storage.local.set({ lastRecordingType: recordingType || "screen" });- // Initialize diagnostic session for this recordingconst { quality, systemAudio, audioInput, backup, offscreen, alarm, alarmTime, countdown } =await chrome.storage.local.get(["quality",@@ -88,21 +234,16 @@ export const startRecording = async () => {alarmTime: alarm ? (alarmTime || null) : null,countdown: Boolean(countdown),});- // Log session-start immediately (not inside the async .then() callback) so- // the event is flushed to storage before the SW can be killed.- diagEvent("session-start", { region: Boolean(customRegion) });+ // sync log so the event flushes to storage before SW can be killed+ diagEvent("session-start", { region: Boolean(customRegion), caller });- // If recordingTab points to a dead tab left over from a previous recording,- // clear it so sendMessageRecord doesn't try to message it.const { recordingTab: prevRecTab } = await chrome.storage.local.get(["recordingTab",]);if (prevRecTab != null) {try {await chrome.tabs.get(prevRecTab);- // Tab is alive — this is the current recorder tab, leave it alone.} catch {- // Tab doesn't exist — stale reference from a previous recording.diagEvent("stale-recording-tab-cleared", { prevRecTab });chrome.storage.local.set({ recordingTab: null });}@@ -118,34 +259,57 @@ export const startRecording = async () => {errStr.includes("Receiving end does not exist") ||errStr.includes("No tab with id") ||errStr.includes("No recording tab available");- diagEvent("start-fail", {- region: Boolean(customRegion),- error: errStr,- staleTab: isStaleTab,- });- // Notify the user that the recording failed to start- chrome.storage.local.get(["activeTab"], ({ activeTab }) => {- if (activeTab) {- sendMessageTab(activeTab, {- type: "recording-error",- error: "start-failed",- why: isStaleTab- ? "stale-recorder-tab"- : "recorder-tab-unavailable",- }).catch(() => {});- }- });- chrome.action.setIcon({ path: "assets/icon-34.png" });+ // sendMessage can reject "message port closed" even on a healthy start; re-check+ setTimeout(async () => {+ let isReallyRecording = false;+ try {+ const snap = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ ]);+ isReallyRecording = Boolean(snap.recording);+ } catch {}+ if (isReallyRecording) return;+ diagEvent("start-fail", {+ region: Boolean(customRegion),+ error: errStr,+ staleTab: isStaleTab,+ });+ releaseStartRecordingGuard();+ chrome.storage.local.set({+ pendingRecording: false,+ restarting: false,+ recording: false,+ recordingTab: null,+ });+ chrome.storage.local.get(["activeTab"], ({ activeTab }) => {+ if (activeTab) {+ sendMessageTab(activeTab, {+ type: "recording-error",+ error: "start-failed",+ why: isStaleTab+ ? "stale-recorder-tab"+ : "recorder-tab-unavailable",+ }).catch(() => {});+ }+ });+ // releases the desktopCapture stream so Chrome's "Stop sharing" bar goes away+ discardOffscreenDocuments({ reason: "start-fail" }).catch(() => {});+ chrome.action.setIcon({ path: "assets/icon-34.png" });+ }, 2500);});chrome.action.setIcon({ path: "assets/recording-logo.png" });- // Set up alarm if set in storage+ // chrome.alarms 30s minimum in prod; sub-30s silently bumps or never firesif (alarm) {const seconds = parseFloat(alarmTime);- chrome.alarms.create("recording-alarm", { delayInMinutes: seconds / 60 });+ if (Number.isFinite(seconds) && seconds > 0) {+ const delayInMinutes = Math.max(seconds / 60, 0.5);+ chrome.alarms.create("recording-alarm", { delayInMinutes });+ }}};-export const startAfterCountdown = () => {+export const startAfterCountdown = (caller = "startAfterCountdown") => {chrome.storage.local.get(["recordingTab", "offscreen"], (result) => {if (chrome.runtime.lastError) {console.error(@@ -164,13 +328,12 @@ export const startAfterCountdown = () => {},});- // Some flows can start before recordingTab is persisted. Start anyway and- // let sendMessageRecord route via recorderSession/offscreen fallback.+ // sendMessageRecord routes via recorderSession/offscreen fallback if neededif (recordingTab === null && !offscreen) {console.warn("[Screenity] startAfterCountdown: no recordingTab/offscreen available, starting with fallback routing");}- startRecording();+ startRecording(caller);});};diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.jsindex ab4a6df..8a36faa 100644--- a/src/pages/Background/recording/stopRecording.js+++ b/src/pages/Background/recording/stopRecording.js@@ -4,6 +4,53 @@ import { sendMessageRecord } from "./sendMessageRecord";import { sendChunks } from "./sendChunks";import { waitForContentScript } from "../utils/waitForContentScript";import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";+import { perfMark, perfSpan } from "../../utils/perfMarks";++// resolves via onReady, onTimeout (30s), or onClosed+const onTabLoaded = (tabId, onReady, onTimeout = null, onClosed = null) => {+ let cleared = false;+ const cleanup = () => {+ if (cleared) return;+ cleared = true;+ chrome.tabs.onUpdated.removeListener(updateListener);+ chrome.tabs.onRemoved.removeListener(removeListener);+ if (safetyTimer) clearTimeout(safetyTimer);+ };+ const updateListener = (changedTabId, changeInfo) => {+ if (changedTabId === tabId && changeInfo.status === "complete") {+ cleanup();+ onReady();+ }+ };+ const removeListener = (removedTabId) => {+ if (removedTabId === tabId) {+ cleanup();+ if (typeof onClosed === "function") onClosed();+ }+ };+ const safetyTimer = setTimeout(() => {+ cleanup();+ if (typeof onTimeout === "function") onTimeout();+ }, 30000);+ chrome.tabs.onUpdated.addListener(updateListener);+ chrome.tabs.onRemoved.addListener(removeListener);+};++// persistent flag so an editor mounting AFTER the failure still picks it up+const markEditorStartFailed = async (tabId, errorCode, why) => {+ diagEvent("editor-start-failed", { tabId, errorCode, why });+ try {+ await chrome.storage.local.set({+ editorRecordingError: {+ ts: Date.now(),+ sandboxTab: Number.isInteger(tabId) ? tabId : null,+ error: "editor-start-failed",+ why: why || null,+ errorCode,+ },+ });+ } catch {}+};const acquirePostStopEditorLock = async (recordingId = null) => {const { postStopEditorOpening } = await chrome.storage.local.get([@@ -19,16 +66,13 @@ const acquirePostStopEditorLock = async (recordingId = null) => {};const releasePostStopEditorLock = async (overrides = {}) => {- // Only clear the "in-progress" flag. Keep postStopEditorOpened=true so- // stopRecording() (which runs later) still knows an editor was opened and- // won't open a duplicate. stopRecording() clears postStopEditorOpened itself.+ // keep postStopEditorOpened=true so later stopRecording() can detect the duplicateawait chrome.storage.local.set({postStopEditorOpening: false,...overrides,});};-/** Store a recovery URL and toast the user when the editor tab fails to open. */const handleEditorOpenFailed = async (editorUrl, lastError) => {diagEvent("editor-open-failed", {editorUrl,@@ -38,7 +82,6 @@ const handleEditorOpenFailed = async (editorUrl, lastError) => {editorRecoveryUrl: editorUrl,editorRecoveryAt: Date.now(),});- // Toast the active tabtry {const { activeTab } = await chrome.storage.local.get(["activeTab"]);if (activeTab) {@@ -48,14 +91,13 @@ const handleEditorOpenFailed = async (editorUrl, lastError) => {timeout: 12000,}).catch(() => {});}- } catch (_) {- // Recovery URL is still in storage either way- }+ } catch (_) {}};export const stopRecording = async () => {chrome.action.setIcon({ path: "assets/icon-34.png" });- chrome.storage.local.set({ restarting: false });+ // await the clear so a quick subsequent restart can't race startRecording's gate+ await chrome.storage.local.set({ restarting: false });const { recordingStartTime, isSubscribed, paused, pausedAt, totalPausedMs, recordingDuration: storedDuration } =await chrome.storage.local.get(["recordingStartTime",@@ -80,9 +122,8 @@ export const stopRecording = async () => {? Math.max(0, now - startTime - basePaused - extraPaused): 0;- // Recorder clears recordingStartTime before stopRecording() runs via- // videoReady(), so the computed duration can be 0 for valid recordings.- // Fall back to the previously stored recordingDuration if available.+ // recorder clears recordingStartTime before stopRecording runs via videoReady;+ // computed duration can be 0 for valid recordings, fall back to storedif (duration === 0 && Number(storedDuration) > 0) {duration = Number(storedDuration);}@@ -90,16 +131,18 @@ export const stopRecording = async () => {diagEvent("stop", { duration, isSubscribed: Boolean(isSubscribed) });- chrome.storage.local.set({+ // single batched write; splitting risks partial cleanup on storage failure+ await chrome.storage.local.set({recording: false,recordingDuration: duration,tabRecordedID: null,offscreen: false,+ region: false,+ customRegion: false,+ recordingUiTabId: null,+ pipForceClose: Date.now(),+ recordingStartTime: 0,});- chrome.storage.local.set({ recordingUiTabId: null });- chrome.storage.local.set({ pipForceClose: Date.now() });-- chrome.storage.local.set({ recordingStartTime: 0 });const {fastRecorderInUse,@@ -118,7 +161,6 @@ export const stopRecording = async () => {validation?.details?.recordingId &&validation.details.recordingId === fastRecorderActiveRecordingId;const hardFailForCurrent = Boolean(validationMatches && validation?.hardFail);- //const hasWebCodecs = supportsWebCodecs();const hasWebCodecs = Boolean(fastRecorderInUse) && !hardFailForCurrent;const {@@ -135,16 +177,19 @@ export const stopRecording = async () => {"recordingTab",]);+ // snapshot for handleRecordingComplete; live recordingTab may belong to a new session by then+ if (recordingTab) {+ chrome.storage.local.set({ completingRecordingTab: recordingTab });+ }+if (isSubscribed) {chrome.alarms.clear("recording-alarm");discardOffscreenDocuments();chrome.storage.local.remove(["recordingMeta"]);} else if (postStopEditorOpening || postStopEditorOpened) {- // Editor already opened by stop-recording-tab flow; avoid opening a second tab.- // That flow will trigger processing when the tab finishes loading.+ // editor already opened by stop-recording-tab flow; avoid duplicate} else if (hasWebCodecs) {diagEvent("editor-open", { type: "editorwebcodecs" });- // Use Mediabunny (editorwebcodecs.html) when WebCodecs is supportedconst query = postStopRecordingId? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`: "?mode=postStop";@@ -156,24 +201,39 @@ export const stopRecording = async () => {handleEditorOpenFailed(wcUrl, chrome.runtime.lastError?.message);return;}- chrome.tabs.onUpdated.addListener(function _(- tabId,- changeInfo,- updatedTab,- ) {- if (tabId === tab.id && changeInfo.status === "complete") {- chrome.tabs.onUpdated.removeListener(_);+ onTabLoaded(+ tab.id,+ async () => {chrome.storage.local.set({ sandboxTab: tab.id });- (async () => {- try {- await waitForContentScript(tab.id);- await sendMessageTab(tab.id, { type: "fallback-recording" });- } catch (err) {- console.error("❌ Failed to wait/send to content script:", err);- }- })();- }- });+ try {+ await waitForContentScript(tab.id);+ } catch (err) {+ console.error("❌ waitForContentScript timed out:", err);+ await markEditorStartFailed(+ tab.id,+ "EDITOR_CONTENT_SCRIPT_TIMEOUT",+ String(err?.message || err).slice(0, 200),+ );+ return;+ }+ try {+ await sendMessageTab(tab.id, { type: "fallback-recording" });+ } catch (err) {+ console.error("❌ Failed to send fallback-recording:", err);+ await markEditorStartFailed(+ tab.id,+ "EDITOR_MESSAGE_DELIVERY_FAILED",+ String(err?.message || err).slice(0, 200),+ );+ }+ },+ () =>+ markEditorStartFailed(+ tab.id,+ "EDITOR_TAB_LOAD_TIMEOUT",+ "editor tab never reached status=complete within 30s",+ ),+ );},);@@ -193,31 +253,45 @@ export const stopRecording = async () => {handleEditorOpenFailed(viewerUrl, chrome.runtime.lastError?.message);return;}- chrome.tabs.onUpdated.addListener(function _(- tabId,- changeInfo,- updatedTab,- ) {- if (tabId === tab.id && changeInfo.status === "complete") {- chrome.tabs.onUpdated.removeListener(_);+ onTabLoaded(+ tab.id,+ async () => {chrome.storage.local.set({ sandboxTab: tab.id });- (async () => {- try {- await waitForContentScript(tab.id);- await sendMessageTab(tab.id, { type: "viewer-recording" });- } catch (err) {- console.error("❌ Failed to wait/send to content script:", err);- }- })();- }- });+ try {+ await waitForContentScript(tab.id);+ } catch (err) {+ console.error("❌ waitForContentScript timed out:", err);+ await markEditorStartFailed(+ tab.id,+ "EDITOR_CONTENT_SCRIPT_TIMEOUT",+ String(err?.message || err).slice(0, 200),+ );+ return;+ }+ try {+ await sendMessageTab(tab.id, { type: "viewer-recording" });+ } catch (err) {+ console.error("❌ Failed to send viewer-recording:", err);+ await markEditorStartFailed(+ tab.id,+ "EDITOR_MESSAGE_DELIVERY_FAILED",+ String(err?.message || err).slice(0, 200),+ );+ }+ },+ () =>+ markEditorStartFailed(+ tab.id,+ "EDITOR_TAB_LOAD_TIMEOUT",+ "editor tab never reached status=complete within 30s",+ ),+ );},);chrome.runtime.sendMessage({ type: "turn-off-pip" });} else {diagEvent("editor-open", { type: "editor-ffmpeg" });- // Use FFmpeg (editor.html) for browsers without WebCodecsconst query = postStopRecordingId? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`: "?mode=postStop";@@ -227,40 +301,46 @@ export const stopRecording = async () => {handleEditorOpenFailed(ffmpegUrl, chrome.runtime.lastError?.message);return;}- chrome.tabs.onUpdated.addListener(function _(- tabId,- changeInfo,- updatedTab,- ) {- if (tabId === tab.id && changeInfo.status === "complete") {- chrome.tabs.onUpdated.removeListener(_);+ onTabLoaded(+ tab.id,+ async () => {chrome.storage.local.set({ sandboxTab: tab.id });- (async () => {- try {- await waitForContentScript(tab.id);- await sendMessageTab(tab.id, { type: "fallback-recording" });- } catch (err) {- console.error("❌ Failed to wait/send to content script:", err);- }- })();- }- });+ try {+ await waitForContentScript(tab.id);+ } catch (err) {+ console.error("❌ waitForContentScript timed out:", err);+ await markEditorStartFailed(+ tab.id,+ "EDITOR_CONTENT_SCRIPT_TIMEOUT",+ String(err?.message || err).slice(0, 200),+ );+ return;+ }+ try {+ await sendMessageTab(tab.id, { type: "fallback-recording" });+ } catch (err) {+ console.error("❌ Failed to send fallback-recording:", err);+ await markEditorStartFailed(+ tab.id,+ "EDITOR_MESSAGE_DELIVERY_FAILED",+ String(err?.message || err).slice(0, 200),+ );+ }+ },+ () =>+ markEditorStartFailed(+ tab.id,+ "EDITOR_TAB_LOAD_TIMEOUT",+ "editor tab never reached status=complete within 30s",+ ),+ );});chrome.runtime.sendMessage({ type: "turn-off-pip" });}- // NOTE: Do NOT clear recordingTab here. The pinned recorder tab may still- // be alive and is cleaned up by:- // - handleRecordingComplete() when the editor finishes processing- // - onTabRemoved when the user closes the editor (which closes the recorder tab)- // - openRecorderTab() as a safety net before creating a new recorder tab- // Clearing the reference here would orphan the tab because later cleanup- // relies on the reference to find and close it.-- // End the diagnostic session for all paths (subscriber, free webcodecs,- // free viewer, free ffmpeg, and already-opened-editor). Error/crash paths- // end the session separately via their own endDiagSession calls.+ // never clear recordingTab here; cleanup runs in handleRecordingComplete /+ // onTabRemoved / openRecorderTab safety netendDiagSession("ok");const { wasRegion } = await chrome.storage.local.get(["wasRegion"]);@@ -268,9 +348,7 @@ export const stopRecording = async () => {chrome.storage.local.set({ wasRegion: false, region: true });}- // Clear the "editor was opened" flag so it doesn't bleed into the next- // recording session. handleStopRecordingTab sets this; releasePostStopEditorLock- // intentionally preserves it so we can detect duplicates above.+ // releasePostStopEditorLock preserves this for duplicate detection; clear herechrome.storage.local.set({ postStopEditorOpened: false });chrome.alarms.clear("recording-alarm");@@ -278,6 +356,10 @@ export const stopRecording = async () => {};export const handleStopRecordingTab = async (request) => {+ perfMark("BG.stopRecording handleStopRecordingTab.enter", {+ reason: request?.reason || null,+ memoryError: Boolean(request?.memoryError),+ });chrome.action.setIcon({ path: "assets/icon-34.png" });if (request.memoryError) {diagEvent("error", {@@ -293,6 +375,8 @@ export const handleStopRecordingTab = async (request) => {});}+ // batched: each unbatched get adds ~1s when storage queue backs up during stop+ const endStorageGet1 = perfSpan("BG.stopRecording storage-get-batch");const {isSubscribed,recordingStartTime,@@ -300,6 +384,7 @@ export const handleStopRecordingTab = async (request) => {pausedAt,totalPausedMs,fastRecorderInUse,+ fastRecorderActiveRecordingId,} = await chrome.storage.local.get(["isSubscribed","recordingStartTime",@@ -307,7 +392,9 @@ export const handleStopRecordingTab = async (request) => {"pausedAt","totalPausedMs","fastRecorderInUse",+ "fastRecorderActiveRecordingId",]);+ endStorageGet1();const stopTabNow = Date.now();const stopTabStartTime = Number(recordingStartTime);const stopTabBasePaused = Number(totalPausedMs) || 0;@@ -326,10 +413,8 @@ export const handleStopRecordingTab = async (request) => {chrome.storage.local.set({ recordingDuration: stopTabDuration });}+ perfMark("BG.stopRecording pre-isSubscribed-branch", { isSubscribed: Boolean(isSubscribed) });if (!isSubscribed) {- const { fastRecorderActiveRecordingId } = await chrome.storage.local.get([- "fastRecorderActiveRecordingId",- ]);const recordingId =fastRecorderActiveRecordingId ||`${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;@@ -346,7 +431,9 @@ export const handleStopRecordingTab = async (request) => {? Math.max(0, now - startTime - basePaused - extraPaused): 0;const maxDuration = 7 * 60 * 1000;+ const endLock = perfSpan("BG.stopRecording acquireLock");const lockAcquired = await acquirePostStopEditorLock(recordingId);+ endLock({ lockAcquired });if (!lockAcquired) {console.warn("[Screenity][BG] Duplicate stop-recording-tab suppressed (editor opening)",@@ -382,6 +469,11 @@ export const handleStopRecordingTab = async (request) => {console.warn("[Screenity][BG] Editor tab load timed out — releasing lock");diagEvent("editor-open-timeout", { tabId: tab.id, type: "editorwebcodecs" });releasePostStopEditorLock();+ markEditorStartFailed(+ tab.id,+ "EDITOR_TAB_LOAD_TIMEOUT",+ "editor tab never reached status=complete within 15s",+ );}}, 15000);chrome.tabs.onUpdated.addListener(function _(@@ -402,6 +494,11 @@ export const handleStopRecordingTab = async (request) => {"❌ Failed to send message:",err?.message || err,);+ markEditorStartFailed(+ tab.id,+ "EDITOR_MESSAGE_DELIVERY_FAILED",+ String(err?.message || err).slice(0, 200),+ );},);}@@ -412,15 +509,18 @@ export const handleStopRecordingTab = async (request) => {const editorUrl =duration > maxDuration ? "editorviewer.html" : "editor.html";diagEvent("editor-open", { type: editorUrl.replace(".html", ""), via: "stop-tab", duration });- // MediaRecorder/FFmpeg path: open editor normally (no postStop gating)+ perfMark("BG.stopRecording editor-tab-create.start", { editorUrl });+ const endTabLoad = perfSpan("BG.stopRecording editor-tab-load");chrome.tabs.create({ url: editorUrl, active: true }, (tab) => {if (chrome.runtime.lastError || !tab?.id) {const errMsg = chrome.runtime.lastError?.message || "tab-create-failed";console.error("❌ Failed to open post-stop editor:", errMsg);+ endTabLoad({ result: "create-failed" });releasePostStopEditorLock({ postStopRecordingId: null });handleEditorOpenFailed(editorUrl, errMsg);return;}+ perfMark("BG.stopRecording editor-tab-create.done", { tabId: tab.id });let settled = false;const safetyTimer = setTimeout(() => {if (!settled) {@@ -428,6 +528,11 @@ export const handleStopRecordingTab = async (request) => {console.warn("[Screenity][BG] Editor tab load timed out — releasing lock");diagEvent("editor-open-timeout", { tabId: tab.id, type: editorUrl });releasePostStopEditorLock({ postStopRecordingId: null });+ markEditorStartFailed(+ tab.id,+ "EDITOR_TAB_LOAD_TIMEOUT",+ "editor tab never reached status=complete within 15s",+ );}}, 15000);chrome.tabs.onUpdated.addListener(function _(@@ -440,6 +545,7 @@ export const handleStopRecordingTab = async (request) => {if (settled) return;settled = true;clearTimeout(safetyTimer);+ endTabLoad({ result: "loaded" });chrome.storage.local.set({sandboxTab: tab.id,postStopRecordingId: null,@@ -452,25 +558,72 @@ export const handleStopRecordingTab = async (request) => {"❌ Failed to send message:",err?.message || err,);+ markEditorStartFailed(+ tab.id,+ "EDITOR_MESSAGE_DELIVERY_FAILED",+ String(err?.message || err).slice(0, 200),+ );},);} else {(async () => {+ // OPFS: sandbox reads the file directly; skip chunk relay+ const storage = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ if (storage.lastRecordingBackendRef?.backend === "opfs") {+ perfMark("BG.stopRecording opfs-direct-make-video-tab");+ sendMessageTab(tab.id, { type: "make-video-tab" }).catch(+ (err) => {+ console.warn(+ "[Screenity][BG] make-video-tab direct send failed",+ err,+ );+ },+ );+ return;+ }+ const endChunkLoop = perfSpan("BG.stopRecording sendChunks-loop");+ // hard cap; covers 6 attempts × ~1s but bails on a wedged sendChunks+ const SEND_CHUNKS_LOOP_TIMEOUT_MS = 15000;+ const loopStartedAt = Date.now();let sent = false;+ let timedOut = false;for (let i = 0; i < 6; i += 1) {+ if (Date.now() - loopStartedAt > SEND_CHUNKS_LOOP_TIMEOUT_MS) {+ timedOut = true;+ break;+ }+ perfMark("BG.stopRecording sendChunks.attempt", { attempt: i + 1 });// eslint-disable-next-line no-await-in-loop- const result = await sendChunks();+ const result = await Promise.race([+ sendChunks(),+ new Promise((resolve) =>+ setTimeout(+ () => resolve({ status: "timeout" }),+ SEND_CHUNKS_LOOP_TIMEOUT_MS -+ (Date.now() - loopStartedAt),+ ),+ ),+ ]);if (result?.status === "ok") {sent = true;+ perfMark("BG.stopRecording sendChunks.success", { attempt: i + 1 });+ break;+ }+ if (result?.status === "timeout") {+ timedOut = true;break;}// eslint-disable-next-line no-await-in-loopawait new Promise((resolve) => setTimeout(resolve, 1000));}+ endChunkLoop({ sent, timedOut });if (!sent) {console.warn("[Screenity][BG] editor opened but chunks are still unavailable",);+ // editor watches editorRecordingError via storage.onChangedtry {await chrome.storage.local.set({lastChunkSendFailure: {@@ -478,8 +631,20 @@ export const handleStopRecordingTab = async (request) => {why: "editor-opened-no-chunks",targetTabId: tab.id,},+ editorRecordingError: {+ ts: Date.now(),+ sandboxTab: tab.id,+ error: "chunks-unavailable",+ why: chrome.i18n.getMessage("opfsLoadErrorDescription"),+ errorCode: "REC_STOP_NO_CHUNKS",+ },});- } catch {}+ } catch (writeErr) {+ console.error(+ "[Screenity][BG] failed to write editorRecordingError",+ writeErr,+ );+ }}})();}@@ -489,9 +654,9 @@ export const handleStopRecordingTab = async (request) => {}}- // Send stop to recorder; toast if the recorder tab doesn't ack.(async () => {const STOP_ACK_TIMEOUT_MS = 3000;+ const endAck = perfSpan("BG.stopRecording stop-ack-wait");try {const ack = await Promise.race([sendMessageRecord({ type: "stop-recording-tab" }),@@ -500,7 +665,9 @@ export const handleStopRecordingTab = async (request) => {),]);if (!ack || ack.ok !== true) throw new Error("stop-no-ack");+ endAck({ result: "acked" });} catch (err) {+ endAck({ result: String(err?.message || err).slice(0, 60) });diagEvent("stop-ack-failed", { error: String(err).slice(0, 120) });try {const { activeTab } = await chrome.storage.local.get(["activeTab"]);@@ -508,22 +675,38 @@ export const handleStopRecordingTab = async (request) => {sendMessageTab(activeTab, {type: "show-toast",message: chrome.i18n.getMessage("stopAckTimeoutToast"),- timeout: 8000,- }).catch(() => {});+ // 12s matches editorRecoveryToast; text asks about data safety+ timeout: 12000,+ }).catch((sendErr) => {+ diagEvent("warning", {+ note: "stop-ack-toast undelivered",+ tabId: activeTab,+ err: String(sendErr).slice(0, 120),+ });+ });+ } else {+ diagEvent("warning", {+ note: "stop-ack-toast skipped: no activeTab in storage",+ });}- } catch (_) {- // Toast failed — non-fatal+ } catch (storeErr) {+ diagEvent("warning", {+ note: "stop-ack-toast skipped: storage.get threw",+ err: String(storeErr).slice(0, 120),+ });}}})();};export const handleStopRecordingTabBackup = async (request) => {+ // gated: unconditional flag would fire the modal on a clean backup-tab close+ const isMemoryError = Boolean(request?.memoryError);chrome.storage.local.set({recording: false,restarting: false,tabRecordedID: null,- memoryError: true,+ ...(isMemoryError ? { memoryError: true } : {}),});sendMessageRecord({ type: "stop-recording-tab" });diff --git a/src/pages/Background/tabManagement/resetActiveTab.js b/src/pages/Background/tabManagement/resetActiveTab.jsindex 818f172..8d8b779 100644--- a/src/pages/Background/tabManagement/resetActiveTab.js+++ b/src/pages/Background/tabManagement/resetActiveTab.js@@ -3,6 +3,8 @@ import { sendMessageTab } from "./sendMessageTab";import { startRecording } from "../recording/startRecording";import { getCurrentTab } from "./getCurrentTab";import { traceStep } from "../../utils/startFlowTrace";+import { perfMark, perfSpan } from "../../utils/perfMarks";+import { handleRecordingError } from "../recording/recordingHelpers";export const restartActiveTab = async (message = {}) => {try {@@ -18,9 +20,8 @@ export const restartActiveTab = async (message = {}) => {const { countdown } = await chrome.storage.local.get(["countdown"]);if (!countdown) {- startRecording();+ startRecording("restartActiveTab-no-countdown");}- // With countdown, content shows the UI and sends "countdown-finished".} else {console.error("No active tab found.");}@@ -30,6 +31,7 @@ export const restartActiveTab = async (message = {}) => {};export const resetActiveTab = async (forceRestart = false, message = {}) => {+ perfMark("BG.resetActiveTab.enter", { forceRestart });const { activeTab } = await chrome.storage.local.get(["activeTab"]);const { surface } = await chrome.storage.local.get(["surface"]);@@ -48,14 +50,30 @@ export const resetActiveTab = async (forceRestart = false, message = {}) => {if (activeTab) {try {- const tab = await chrome.tabs.get(activeTab);+ let tab = null;+ try {+ tab = await chrome.tabs.get(activeTab);+ } catch (err) {+ // source tab closed between picker-confirm and ready-to-record+ console.warn(+ "[Screenity][resetActiveTab] source tab gone, surfacing recording-error",+ { activeTab, err: String(err).slice(0, 120) },+ );+ // chrome.runtime.sendMessage from SW doesn't fire SW's own listeners+ await handleRecordingError({+ error: "stream-error",+ why: "source tab closed during stream acquisition",+ errorCode: "REC_START_SOURCE_TAB_GONE",+ });+ return;+ }if (!tab) {console.error("Active tab not found.");return;}- // Focus and update only if neededif (shouldFocusTab) {+ const endFocus = perfSpan("BG.resetActiveTab focus-back-to-tab");await chrome.windows.update(tab.windowId, { focused: true });await chrome.tabs.update(activeTab, {active: true,@@ -63,15 +81,13 @@ export const resetActiveTab = async (forceRestart = false, message = {}) => {highlighted: true,});await focusTab(activeTab);+ endFocus();}- // Always prefer the stored activeTab (the user's page, set before the- // recorder tab is created). Falling back to currentTab can target the- // pinned recorder tab when surface === "browser".+ // currentTab fallback would hit the pinned recorder tab when surface==="browser"const targetTabId = activeTab || currentTab?.id;- // Persist routing decision to the start-flow trace. Awaited so the- // write lands before sendMessageTab triggers the content-side write.+ // awaited so the write lands before sendMessageTab triggers the content-side writeawait traceStep("readyToRecordSent", {routing: {targetTabId,@@ -83,17 +99,14 @@ export const resetActiveTab = async (forceRestart = false, message = {}) => {});if (targetTabId) {+ perfMark("BG.resetActiveTab ready-to-record.sent", { targetTabId });sendMessageTab(targetTabId, { type: "ready-to-record" }).catch(() => {});const { countdown } = await chrome.storage.local.get(["countdown"]);if (!countdown) {- // No countdown — start immediately. The recorder's readiness gate- // will wait for the stream to be live before actually recording.- startRecording();+ startRecording("resetActiveTab-no-countdown", { storedCountdown: countdown });}- // With countdown: Content shows the countdown UI and sends- // "countdown-finished" when done, which triggers startAfterCountdown().} else {console.error("No valid tab to send message to.");}diff --git a/src/pages/Backup/Backup.jsx b/src/pages/Backup/Backup.jsxindex 49fd7e7..a12c5a9 100644--- a/src/pages/Backup/Backup.jsx+++ b/src/pages/Backup/Backup.jsx@@ -108,10 +108,9 @@ const Backup = () => {const directoryPicker = async (prompt = true) => {chrome.runtime.sendMessage({ type: "focus-this-tab" });- let directoryPicker = null;- // Request access to create a file in a user-selected directory+ let picked;try {- directoryPicker = await window.showDirectoryPicker({+ picked = await window.showDirectoryPicker({startIn: "videos",mode: "readwrite",});@@ -125,28 +124,13 @@ const Backup = () => {}return;}- // check if user cancelled the prompt- if (!directoryPicker) {- if (backupRef.current) {- chrome.runtime.sendMessage({- type: "recording-error",- error: "backup-error",- why: String(err),- });- }- return;- }-- let directoryHandle = directoryPicker;- if (directoryPicker.name === "Screenity Recordings") {- directoryHandle = directoryPicker;- } else {- directoryHandle = await directoryPicker.getDirectoryHandle(- "Screenity Recordings",- { create: true },- );- }+ const directoryHandle =+ picked.name === "Screenity Recordings"+ ? picked+ : await picked.getDirectoryHandle("Screenity Recordings", {+ create: true,+ });await localDirectoryStore.clear();await localDirectoryStore.setItem("directoryHandle", directoryHandle);@@ -171,13 +155,11 @@ const Backup = () => {localDirectoryStore.getItem("directoryHandle").then(async (directory) => {if (directory) {try {- const permissions = await verifyFilePermissions(- directory.directoryHandle,- );+ const permissions = await verifyFilePermissions(directory);if (!permissions) {directoryPicker(prompt);} else {- initLocalDirectory(directory.directoryHandle, prompt);+ initLocalDirectory(directory, prompt);}} catch (e) {localDirectoryStore.clear();@@ -248,23 +230,18 @@ const Backup = () => {}};- // Delete the latest file saved in the local backup folderconst deleteFile = async (restart = null) => {if (writingFile.current) {await writable.current.close();writingFile.current = false;const directory = await localDirectoryStore.getItem("directoryHandle");- if (directory && directory !== null) {- const permissions = await verifyFilePermissions(- directory.directoryHandle,- );+ if (directory) {+ const permissions = await verifyFilePermissions(directory);if (permissions) {- await directory.directoryHandle.removeEntry(titleRef.current);- if (restart) {- localSaving(false);- }- } else if (restart) {+ await directory.removeEntry(titleRef.current);+ }+ if (restart) {localSaving(false);}}@@ -313,7 +290,11 @@ const Backup = () => {writeFile(message.index);} else if (message.type === "close-writable") {if (!waitWrite.current) {- writable.current.close();+ if (writable.current) {+ try {+ writable.current.close();+ } catch (e) {}+ }} else {closeRequest.current = true;}diff --git a/src/pages/Camera/Camera.jsx b/src/pages/Camera/Camera.jsxindex 1607bdb..7ee085e 100644--- a/src/pages/Camera/Camera.jsx+++ b/src/pages/Camera/Camera.jsx@@ -34,22 +34,18 @@ const Camera = () => {setIsCameraMode,} = useCameraContext();- // Helper function to update loading statesconst updateLoadingState = (key, value) => {setLoadingStates((prev) => ({ ...prev, [key]: value }));};- // Calculate if anything is still loadingconst isLoading = Object.values(loadingStates).some((state) => state);- // Ensure the offScreenCanvas is created exactly onceuseEffect(() => {if (!offScreenCanvasRef.current) {offScreenCanvasRef.current = document.createElement("canvas");}}, []);- // Initialize message listeneruseEffect(() => {setupHandlers({setLoading: updateLoadingState,@@ -87,11 +83,28 @@ const Camera = () => {}}, [backgroundEffects, isModelLoaded]);+ // 30s ceiling on modelLoading; clears the spinner so the camera feed+ // shows even if CameraContext's inner GPU+CPU timeouts race past.useEffect(() => {- if (!videoRef.current || streamRef.current?.active) return;+ if (!loadingStates.modelLoading) return;+ const id = setTimeout(() => {+ console.warn(+ "[Screenity] modelLoading hard-capped at 30s; clearing spinner",+ );+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-camera-modelloading-hard-cap",+ });+ } catch {}+ updateLoadingState("modelLoading", false);+ }, 30000);+ return () => clearTimeout(id);+ }, [loadingStates.modelLoading]);+ const acquireStream = () => {+ if (!videoRef.current || streamRef.current?.active) return;updateLoadingState("videoElement", true);-chrome.storage.local.get(["defaultVideoInput"], (result) => {const constraints =result.defaultVideoInput !== "none"@@ -110,12 +123,75 @@ const Camera = () => {});});- }, [videoRef.current]); // Will run once when videoRef is set+ };++ useEffect(() => {+ // Acquire the stream only when camera is enabled AND a recording is+ // pending or active. Mounting alone must not trigger getUserMedia.+ chrome.storage.local.get(+ ["recording", "pendingRecording", "cameraActive"],+ (result) => {+ if (+ result.cameraActive &&+ (result.recording || result.pendingRecording)+ ) {+ acquireStream();+ }+ },+ );+ }, [videoRef.current]);++ // Release the camera light when no recording is active. The iframe stays+ // mounted to cache OS permissions, but holding getUserMedia keeps the+ // camera indicator on with no visible UI.+ useEffect(() => {+ let inflightAcquire = false;+ const evaluate = async () => {+ const { recording, pendingRecording, cameraActive } =+ await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ "cameraActive",+ ]);+ // Hold the stream only when cameraActive AND a recording is+ // active/pending. Without the gate, tab recordings without camera+ // would re-acquire and surface camera-denied errors.+ const wantStream = Boolean(+ cameraActive && (recording || pendingRecording),+ );+ const hasStream = Boolean(streamRef.current?.active);+ if (!wantStream && hasStream) {+ stopCameraStream(streamRef, videoRef);+ } else if (wantStream && !hasStream && !inflightAcquire) {+ inflightAcquire = true;+ try {+ acquireStream();+ } finally {+ // getCameraStream's onFinish flips loading off async; the+ // boolean flag here is just a re-entry guard, not a true lock.+ setTimeout(() => {+ inflightAcquire = false;+ }, 500);+ }+ }+ };+ const listener = (changes, area) => {+ if (area !== "local") return;+ if (+ "recording" in changes ||+ "pendingRecording" in changes ||+ "cameraActive" in changes+ ) {+ evaluate();+ }+ };+ chrome.storage.onChanged.addListener(listener);+ return () => chrome.storage.onChanged.removeListener(listener);+ }, []);- // After the camera stream is ready, check if we should re-enter PiP.- // This handles the case where the user navigated while recording a monitor —- // the old PiP was destroyed with the old page, so we need to re-enter it- // once the new camera iframe has a live stream.+ // re-enter PiP if needed after camera stream is ready. user navigated while+ // recording a monitor, old PiP was destroyed with old page, re-enter once the+ // new camera iframe has a live stream.useEffect(() => {if (!videoRef.current || !streamRef.current?.active) return;@@ -129,7 +205,6 @@ const Camera = () => {);}, [videoRef.current, streamRef.current?.active]);- // Handle PiP eventsconst handleEnterPip = () => {setPipMode(true);chrome.runtime.sendMessage({ type: "pip-started" });diff --git a/src/pages/Camera/components/Background.js b/src/pages/Camera/components/Background.jsindex 5a38a40..2777833 100644--- a/src/pages/Camera/components/Background.js+++ b/src/pages/Camera/components/Background.js@@ -6,6 +6,7 @@ import {renderBlurFromVideo,renderPersonCutoutFromVideo,renderEffectBackground,+ loadSegmentationModel,} from "../utils/backgroundUtils";const Background = () => {@@ -55,7 +56,6 @@ const Background = () => {return () => window.removeEventListener("resize", handleResize);}, []);- // Re-render background image on resize or effect changeuseEffect(() => {if (!effectRef.current || blurRef.current) return;@@ -82,13 +82,61 @@ const Background = () => {}}, [windowSize, effectRef.current, blurRef.current]);- // Self-contained render loop — segments video directly, no React state per frameuseEffect(() => {if (!backgroundEffects) return;let animFrameId;let running = true;let consecutiveErrors = 0;+ let lastSuccessAt = Date.now();+ let recreatingSegmenter = false;++ // Watchdog: if the segmenter goes silent (returns null masks for+ // 5s+ while video is delivering frames), the GPU context likely+ // crashed or the segmenter is wedged. Recreate it once. Without+ // this the user's blur/effect freezes mid-recording with no error+ // and no recovery.+ const STALE_MASK_THRESHOLD_MS = 5000;+ const recreateSegmenter = async () => {+ if (recreatingSegmenter) return;+ recreatingSegmenter = true;+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-recreate-attempt",+ data: { msSinceLastSuccess: Date.now() - lastSuccessAt },+ });+ } catch {}+ try {+ try { segmenterRef.current?.close?.(); } catch {}+ const fresh = await loadSegmentationModel();+ if (fresh && running) {+ segmenterRef.current = fresh;+ lastSuccessAt = Date.now();+ consecutiveErrors = 0;+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-recreate-ok",+ });+ } catch {}+ } else if (running) {+ // Recreate failed; disable effects so the camera feed isn't frozen.+ console.warn(+ "[Screenity] Segmenter recreate failed; disabling background effects",+ );+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-recreate-failed",+ });+ } catch {}+ setBackgroundEffects(false);+ }+ } finally {+ recreatingSegmenter = false;+ }+ };const tick = () => {if (!running) return;@@ -102,6 +150,7 @@ const Background = () => {if (result && result.categoryMask) {consecutiveErrors = 0;+ lastSuccessAt = Date.now();if (blurRef.current) {renderBlurFromVideo(video, result, canvasRef);} else if (effectRef.current) {@@ -117,6 +166,12 @@ const Background = () => {canvasContextRef,);}+ } else if (+ Date.now() - lastSuccessAt > STALE_MASK_THRESHOLD_MS &&+ !recreatingSegmenter+ ) {+ // Video frames flowing but segmenter silent: GPU context loss.+ recreateSegmenter();}}} catch (error) {@@ -124,6 +179,13 @@ const Background = () => {console.error("Background segmentation error:", error);if (consecutiveErrors >= 3) {console.warn("Disabling background effects after repeated failures");+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-disabled-after-errors",+ data: { error: String(error?.message || error).slice(0, 200) },+ });+ } catch {}setBackgroundEffects(false);return;}@@ -140,7 +202,6 @@ const Background = () => {};}, [backgroundEffects]);- // Listen for Chrome extension messagesuseEffect(() => {const handleMessage = (request) => {if (request.type === "set-background-effect") {diff --git a/src/pages/Camera/context/CameraContext.js b/src/pages/Camera/context/CameraContext.jsindex 97cc0e1..142361d 100644--- a/src/pages/Camera/context/CameraContext.js+++ b/src/pages/Camera/context/CameraContext.js@@ -5,6 +5,7 @@ import React, {useRef,useEffect,useCallback,+ useMemo,} from "react";import {loadSegmentationModel,@@ -128,7 +129,6 @@ export const CameraProvider = ({ children }) => {segmenterRef.current = model;setIsModelLoaded(true);} else {- // Model returned null — fall back to raw camera feedconsole.warn("Segmentation model unavailable, disabling background effects");handleSetBackgroundEffects(false);}@@ -244,31 +244,45 @@ export const CameraProvider = ({ children }) => {return true;};- const contextValue = {- width,- height,- backgroundEffects,- isModelLoaded,- pipMode,- isCameraMode,- videoRef,- streamRef,- recordingTypeRef,- offScreenCanvasRef,- offScreenCanvasContextRef,- segmenterRef,- blurRef,- effectRef,- setWidth: handleSetWidth,- setHeight: handleSetHeight,- setBackgroundEffects: handleSetBackgroundEffects,- setPipMode,- setIsCameraMode,- loadCustomEffect,- enableBlur,- setCustomEffect,- clearEffect,- };+ // Memoized so consumers (Camera, Background) only re-render when one+ // of the actual state values changes. Refs and setters are stable+ // identities anyway; without memoization a fresh object every render+ // forced every consumer to re-render on any provider re-render.+ const contextValue = useMemo(+ () => ({+ width,+ height,+ backgroundEffects,+ isModelLoaded,+ pipMode,+ isCameraMode,+ videoRef,+ streamRef,+ recordingTypeRef,+ offScreenCanvasRef,+ offScreenCanvasContextRef,+ segmenterRef,+ blurRef,+ effectRef,+ setWidth: handleSetWidth,+ setHeight: handleSetHeight,+ setBackgroundEffects: handleSetBackgroundEffects,+ setPipMode,+ setIsCameraMode,+ loadCustomEffect,+ enableBlur,+ setCustomEffect,+ clearEffect,+ }),+ [+ width,+ height,+ backgroundEffects,+ isModelLoaded,+ pipMode,+ isCameraMode,+ ],+ );return (<CameraContext.Provider value={contextValue}>diff --git a/src/pages/Camera/messaging/handlers.js b/src/pages/Camera/messaging/handlers.jsindex 9fbe468..e7fd964 100644--- a/src/pages/Camera/messaging/handlers.js+++ b/src/pages/Camera/messaging/handlers.js@@ -39,7 +39,10 @@ export const setupHandlers = ({ setLoading }) => {registerMessage("switch-camera", (message) => {if (message.id !== "none") {clearTimeout(cameraSwitchTimeout);- stopCameraStream();+ // stopCameraStream requires (streamRef, videoRef); a no-arg call+ // warns and returns, leaking the prior MediaStream.+ const refs = getContextRefs();+ stopCameraStream(refs.streamRef, refs.videoRef);cameraSwitchTimeout = setTimeout(() => {const {@@ -101,7 +104,7 @@ export const setupHandlers = ({ setLoading }) => {messageRouter();- // Fallback: if a runtime message is missed, close PiP when storage flag flips.+ // Fallback when a runtime message is missed: close PiP on storage flag flip.chrome.storage.local.get(["pipForceClose"], (res) => {if (res.pipForceClose && document.pictureInPictureElement) {document.exitPictureInPicture().catch(() => {});@@ -126,6 +129,15 @@ const handleStopRecording = async (request) => {setPipMode(false);chrome.runtime.sendMessage({ type: "pip-ended" });}+ // Stop tracks so the webcam light goes off; otherwise the iframe holds+ // the stream until the page is torn down (may be much later or never if+ // the user navigates away from the recorded tab).+ try {+ const { streamRef, videoRef } = getContextRefs();+ stopCameraStream(streamRef, videoRef);+ } catch (err) {+ console.warn("Failed to stop camera stream on recording end:", err);+ }};const safelyApplyFilter = (contextRef, filter) => {diff --git a/src/pages/Camera/utils/backgroundUtils.js b/src/pages/Camera/utils/backgroundUtils.jsindex 0980f03..966ca2a 100644--- a/src/pages/Camera/utils/backgroundUtils.js+++ b/src/pages/Camera/utils/backgroundUtils.js@@ -3,7 +3,7 @@ import {ImageSegmenter,} from "@mediapipe/tasks-vision";-// Pre-allocated canvases reused across frames to avoid GC pressure+// Reused across frames to avoid GC pressure.let _frameCanvas = null;let _frameCtx = null;let _blurCanvas = null;@@ -37,7 +37,6 @@ function getReusableCanvases() {};}-// Pre-allocated typed array for mask ImageData, reused across frameslet _maskImageDataCache = null;let _maskImageDataCacheSize = 0;@@ -51,31 +50,94 @@ function getOrCreateMaskImageData(ctx, width, height) {return _maskImageDataCache;}+// Bound the model load; MediaPipe's wasm/tflite fetch can hang on flaky+// networks, blocked CDNs, or corrupted bundles.+const MODEL_LOAD_TIMEOUT_MS = 12000;++const withTimeout = (promise, ms, label) =>+ Promise.race([+ promise,+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error(`${label}-timeout-${ms}ms`)), ms),+ ),+ ]);++const tryCreateSegmenter = async (vision, delegate) => {+ return ImageSegmenter.createFromOptions(vision, {+ baseOptions: {+ modelAssetPath: "./assets/mediapipeVision/selfie_segmenter.tflite",+ delegate,+ },+ outputCategoryMask: true,+ outputConfidenceMasks: false,+ runningMode: "VIDEO",+ });+};+export const loadSegmentationModel = async () => {try {- const vision = await FilesetResolver.forVisionTasks(- "./assets/mediapipeVision"+ const vision = await withTimeout(+ FilesetResolver.forVisionTasks("./assets/mediapipeVision"),+ MODEL_LOAD_TIMEOUT_MS,+ "fileset-resolver",);- const segmenter = await ImageSegmenter.createFromOptions(vision, {- baseOptions: {- modelAssetPath: "./assets/mediapipeVision/selfie_segmenter.tflite",- delegate: "GPU",- },- outputCategoryMask: true,- outputConfidenceMasks: false,- runningMode: "VIDEO",- });-- return segmenter;+ // GPU path; fall back to CPU on systems without WebGL2 or with bad+ // GPU drivers (old Intel iGPUs, Linux, some VMs).+ try {+ const gpu = await withTimeout(+ tryCreateSegmenter(vision, "GPU"),+ MODEL_LOAD_TIMEOUT_MS,+ "segmenter-gpu",+ );+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-loaded",+ data: { delegate: "GPU" },+ });+ } catch {}+ return gpu;+ } catch (gpuErr) {+ console.warn(+ "[Screenity] GPU segmenter failed, falling back to CPU:",+ gpuErr,+ );+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-gpu-fallback",+ data: { error: String(gpuErr?.message || gpuErr).slice(0, 200) },+ });+ } catch {}+ const cpu = await withTimeout(+ tryCreateSegmenter(vision, "CPU"),+ MODEL_LOAD_TIMEOUT_MS,+ "segmenter-cpu",+ );+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-loaded",+ data: { delegate: "CPU" },+ });+ } catch {}+ return cpu;+ }} catch (error) {console.error("Error loading segmentation model:", error);+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-segmenter-load-failed",+ data: { error: String(error?.message || error).slice(0, 200) },+ });+ } catch {}return null;}};-// Segment directly from a video element — avoids ImageData round-trips.-// The segmentForVideo callback fires synchronously, so this returns the result directly.+// segmentForVideo's callback fires synchronously, so the result can be returned directly.export const segmentFromVideo = (videoElement, segmenter) => {if (!videoElement || !segmenter) return null;if (videoElement.readyState < 2 || videoElement.videoWidth === 0) return null;@@ -96,8 +158,6 @@ export const segmentFromVideo = (videoElement, segmenter) => {}};-// Build a smoothed person mask from segmentation result onto reusable canvases.-// Shared by both blur and cutout render paths.function buildSmoothedMask(segmentationResult, edgeBlurAmount, personOpaque) {const mask = segmentationResult.categoryMask;const maskData = mask.getAsUint8Array();@@ -120,13 +180,12 @@ function buildSmoothedMask(segmentationResult, edgeBlurAmount, personOpaque) {const offset = i * 4;const isPerson = maskData[i] === 1;if (personOpaque) {- // Person = opaque white, background = transparent (for blur + cutout)maskPixels[offset] = 255;maskPixels[offset + 1] = 255;maskPixels[offset + 2] = 255;maskPixels[offset + 3] = isPerson ? 255 : 0;} else {- // Person = transparent, background = opaque black (for destination-out masking)+ // For destination-out masking.maskPixels[offset] = 0;maskPixels[offset + 1] = 0;maskPixels[offset + 2] = 0;@@ -143,7 +202,6 @@ function buildSmoothedMask(segmentationResult, edgeBlurAmount, personOpaque) {return { smoothMaskCanvas, maskW, maskH };}-// Render blur effect using the video element directly (no ImageData round-trip)export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef) => {if (!videoElement || !segmentationResult || !canvasRef.current) return false;@@ -157,7 +215,6 @@ export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef)const { frameCanvas, frameCtx, blurCanvas, blurCtx, personCanvas, personCtx } =getReusableCanvases();- // Resize reusable canvases only when dimensions changeif (frameCanvas.width !== vw || frameCanvas.height !== vh) {frameCanvas.width = vw;frameCanvas.height = vh;@@ -165,19 +222,15 @@ export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef)blurCanvas.height = vh;}- // Draw original frame from videoframeCtx.drawImage(videoElement, 0, 0);- // Draw blurred versionblurCtx.filter = `blur(${backgroundBlurAmount}px)`;blurCtx.drawImage(frameCanvas, 0, 0);blurCtx.filter = "none";- // Build smoothed person maskconst { smoothMaskCanvas, maskW, maskH } =buildSmoothedMask(segmentationResult, edgeBlurAmount, true);- // Size output canvasconst ratio = vw / vh;const outW = Math.round(window.innerHeight * ratio);const outH = window.innerHeight;@@ -194,17 +247,14 @@ export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef)const outputCtx = canvasRef.current.getContext("2d");- // Base layer: blurred frameoutputCtx.drawImage(blurCanvas, 0, 0, vw, vh, 0, 0, outW, outH);- // Person layer: mask → source-in with sharp framepersonCtx.clearRect(0, 0, outW, outH);personCtx.globalCompositeOperation = "source-over";personCtx.drawImage(smoothMaskCanvas, 0, 0, maskW, maskH, 0, 0, outW, outH);personCtx.globalCompositeOperation = "source-in";personCtx.drawImage(frameCanvas, 0, 0, vw, vh, 0, 0, outW, outH);- // Composite person on top of blurred backgroundoutputCtx.drawImage(personCanvas, 0, 0);return true;@@ -214,7 +264,6 @@ export const renderBlurFromVideo = (videoElement, segmentationResult, canvasRef)}};-// Render person cutout (transparent background) using the video element directlyexport const renderPersonCutoutFromVideo = (videoElement,segmentationResult,@@ -236,10 +285,8 @@ export const renderPersonCutoutFromVideo = (frameCanvas.height = vh;}- // Draw original frame from videoframeCtx.drawImage(videoElement, 0, 0);- // Build smoothed person maskconst { smoothMaskCanvas, maskW, maskH } =buildSmoothedMask(segmentationResult, edgeBlurAmount, true);@@ -251,7 +298,6 @@ export const renderPersonCutoutFromVideo = (personCanvas.height = canvas.height;}- // Composite: mask → source-in with frame = person-only with smooth edgespersonCtx.clearRect(0, 0, canvas.width, canvas.height);personCtx.globalCompositeOperation = "source-over";personCtx.drawImage(smoothMaskCanvas, 0, 0, maskW, maskH, 0, 0, canvas.width, canvas.height);@@ -285,7 +331,6 @@ export const loadEffect = (effectUrl) => {});};-// Render the background effect image to the bottom canvasexport const renderEffectBackground = (effectImg,bottomCanvasRef,@@ -301,7 +346,6 @@ export const renderEffectBackground = (canvas.width = window.innerWidth;canvas.height = window.innerHeight;- // Calculate dimensions to cover the canvas while maintaining aspect ratioconst imgRatio = effectImg.width / effectImg.height;const canvasRatio = canvas.width / canvas.height;let drawWidth = canvas.width;diff --git a/src/pages/Camera/utils/cameraUtils.js b/src/pages/Camera/utils/cameraUtils.jsindex 049fc9a..9f8715e 100644--- a/src/pages/Camera/utils/cameraUtils.js+++ b/src/pages/Camera/utils/cameraUtils.js@@ -89,6 +89,34 @@ export const getCameraStream = async (const videoTrack = stream.getVideoTracks()[0];const { width, height, deviceId, frameRate } = videoTrack.getSettings();+ // Camera track ends mid-recording (unplug, virtual cam crash, OS revoke).+ // Stop the stream and surface via camera-bubble-unavailable; don't tear+ // down the wrapping recording.+ try {+ videoTrack.addEventListener("ended", () => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "camera-bubble-track-ended",+ data: {+ trackLabel: String(videoTrack?.label || "").slice(0, 80),+ readyState: videoTrack?.readyState || null,+ },+ });+ } catch {}+ try {+ stopCameraStream(streamRef, videoRef);+ } catch {}+ try {+ chrome.runtime.sendMessage({+ type: "camera-bubble-unavailable",+ error: "camera-track-ended",+ why: "camera disconnected during recording",+ });+ } catch {}+ });+ } catch {}+if (setWidth && setHeight) {const isCamera = recordingTypeRef?.current === "camera";const w = isCamera || width / height < 1 ? "100%" : "auto";@@ -99,7 +127,6 @@ export const getCameraStream = async (console.warn("⚠️ setWidth or setHeight not available from context.");}- // VIDEO REF SETUPif (!videoRef.current) {console.warn("⏳ videoRef not ready yet. Will poll every 100ms.");const maxWaitTime = 5000;@@ -120,39 +147,166 @@ export const getCameraStream = async (const video = videoRef.current;video.srcObject = stream;+ // Virtual cameras (OBS Virtual Camera, mmhmm, Snap Camera, etc.)+ // trip up the naive `video.onloadedmetadata = ...` pattern in three+ // ways:+ // 1. Sync race: assigning srcObject can fire `loadedmetadata`+ // synchronously when the stream is already cached/active. By+ // the time we set `onloadedmetadata`, the event has already+ // fired and we hang forever.+ // 2. Track muted: virtual cams often start with the video track+ // `muted=true` (the source app hasn't focused yet); they fire+ // `unmute` on the track before metadata.+ // 3. Never fires: some virtual cams never fire `loadedmetadata`+ // until they receive their first real frame, which can take+ // arbitrarily long if the source app is paused.+ //+ // Check readyState, addEventListener (no clobber), listen on metadata+ // and unmute, cap the wait at 12s so virtual cams don't hang the spinner.+ const VIRTUAL_CAM_LOADED_TIMEOUT_MS = 12000;await new Promise((resolve) => {- video.onloadedmetadata = async () => {+ let settled = false;+ const finish = async () => {+ if (settled) return;+ settled = true;+ cleanup();await video.play().catch((err) => {console.error("❌ Error during video.play():", err);});-await new Promise((r) => setTimeout(r, 100));-const canvas = offScreenCanvasRef?.current;if (!canvas) {console.warn("⚠️ offScreenCanvasRef.current is null.");return resolve();}-canvas.width = video.videoWidth || 1280;canvas.height = video.videoHeight || 720;-const context = canvas.getContext("2d");if (!context) {console.error("❌ Failed to get 2D context from canvas.");return resolve();}-offScreenCanvasContextRef.current = context;-resolve();};++ const onMetadata = () => {+ finish();+ };+ const onUnmute = () => {+ // Track unmuted but readyState may still be 0; re-check in case+ // HAVE_METADATA was already reached.+ if (video.readyState >= 1) finish();+ };+ const cleanup = () => {+ try {+ video.removeEventListener("loadedmetadata", onMetadata);+ video.removeEventListener("loadeddata", onMetadata);+ } catch {}+ try {+ videoTrack?.removeEventListener?.("unmute", onUnmute);+ } catch {}+ if (timeoutId) clearTimeout(timeoutId);+ };++ // Sync race: already past metadata.+ if (video.readyState >= 1 && video.videoWidth > 0) {+ finish();+ return;+ }++ video.addEventListener("loadedmetadata", onMetadata, { once: true });+ video.addEventListener("loadeddata", onMetadata, { once: true });+ try {+ videoTrack?.addEventListener?.("unmute", onUnmute);+ } catch {}++ // Bounded fallback for virtual cams that never deliver metadata.+ // Proceed with default 1280x720; real frames are picked up later.+ const timeoutId = setTimeout(() => {+ if (settled) return;+ console.warn(+ "[Screenity] Camera loadedmetadata timeout (likely virtual camera); proceeding with defaults",+ {+ readyState: video.readyState,+ videoWidth: video.videoWidth,+ trackMuted: videoTrack?.muted,+ trackLabel: videoTrack?.label,+ },+ );+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-camera-metadata-timeout",+ data: {+ readyState: video.readyState,+ videoWidth: video.videoWidth,+ videoHeight: video.videoHeight,+ trackMuted: !!videoTrack?.muted,+ trackLabel: String(videoTrack?.label || "").slice(0, 80),+ },+ });+ } catch {}+ finish();+ }, VIRTUAL_CAM_LOADED_TIMEOUT_MS);});onFinish();} catch (err) {console.error("❌ Failed to get camera stream:", err);onFinish();+ // Surface to BG only during setup (pendingRecording=true):+ // 1. screen+camera with camera denied during setup; BG must clear+ // pendingRecording or the next record stalls.+ // 2. tab+camera with bubble failure mid-recording: stay silent;+ // propagating a recording-error tears down the live recording.+ try {+ const { recording, pendingRecording } = await chrome.storage.local.get([+ "recording",+ "pendingRecording",+ ]);+ const isPermissionDenial =+ err?.name === "NotAllowedError" ||+ err?.name === "PermissionDeniedError";+ // Diag fires regardless of fatality; "clicked record and got nothing"+ // reports need to distinguish permission denials from device-not-found+ // and getUserMedia hangs.+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-camera-acquire-failed",+ data: {+ errorName: err?.name || null,+ isPermissionDenial,+ duringSetup: pendingRecording === true && recording !== true,+ recordingActive: recording === true,+ message: String(err?.message || err).slice(0, 200),+ },+ });+ } catch {}+ if (pendingRecording === true && recording !== true) {+ // Setup-time failure: fatal. BG must clear pendingRecording.+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: isPermissionDenial+ ? "camera-permission-denied"+ : "camera-stream-error",+ why: String(err?.message || err),+ });+ } else if (recording === true) {+ // Recording is live: don't tear down for a cosmetic camera issue.+ // Surface a non-fatal toast via BG -> recorded tab's content script.+ chrome.runtime.sendMessage({+ type: "camera-bubble-unavailable",+ error: isPermissionDenial+ ? "camera-permission-denied"+ : "camera-stream-error",+ why: String(err?.message || err),+ });+ }+ } catch {+ // BG context might be gone (SW asleep).+ }}};@@ -233,15 +387,31 @@ export const surfaceHandler = async (request, videoRef) => {}};+let _cameraToggleReacquireTimer = null;export const cameraToggledToolbar = async (request) => {if (request.active) {- setTimeout(() => {- stopCameraStream();- getCameraStream({- video: {- deviceId: { exact: request.id },+ // Cancel any pending re-acquire so rapid toolbar toggles don't stack+ // up multiple getCameraStream calls fighting for the same device.+ if (_cameraToggleReacquireTimer) {+ clearTimeout(_cameraToggleReacquireTimer);+ }+ _cameraToggleReacquireTimer = setTimeout(() => {+ _cameraToggleReacquireTimer = null;+ // Pass refs so the prior camera stream actually stops; calling+ // stopCameraStream() with no args is a silent no-op (early return).+ const refs = getContextRefs();+ stopCameraStream(refs.streamRef, refs.videoRef);+ getCameraStream(+ {+ video: {+ deviceId: { exact: request.id },+ },},- });+ refs.streamRef,+ refs.videoRef,+ refs.offScreenCanvasRef,+ refs.offScreenCanvasContextRef,+ );}, 2000);setPipMode(false);}diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsxindex 777e179..fc91abc 100644--- a/src/pages/CloudRecorder/CloudRecorder.jsx+++ b/src/pages/CloudRecorder/CloudRecorder.jsx@@ -11,6 +11,18 @@ import { createVideoProject } from "./createVideoProject";import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";import { traceStep } from "../utils/startFlowTrace";import { IS_OFFSCREEN_HOST } from "../utils/recordingHost";+import { startPrewarm, stopPrewarm } from "../Recorder/streamWarmup";+import { preloadWebCodecsModules } from "../Recorder/webcodecs/WebCodecsRecorder";+import {+ chooseChunksStore,+ openExistingChunksStore,+} from "./recorderStorage/chooseChunksStore";+import { destroySessionDir } from "./recorderStorage/opfsKvStore";+import {+ chooseTrackEncoder,+ resetEncoderProbeCache,+ computeEncodedDimensions,+} from "./encoder/chooseEncoder";localforage.config({driver: localforage.INDEXEDDB,@@ -45,9 +57,32 @@ const RECOVERABLE_SESSION_STATUSES = new Set(["upload-stalled",]);-const chunksStore = localforage.createInstance({ name: "chunks" });-const audioChunksStore = localforage.createInstance({ name: "audioChunks" });-const cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });+// `let` (not `const`) so ensureChunkStoreReady() can swap each instance+// from the IDB default to an OPFS-backed adapter at session start. All+// callsites in this file see the new reference via closure.+let chunksStore = localforage.createInstance({ name: "chunks" });+let audioChunksStore = localforage.createInstance({ name: "audioChunks" });+let cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });+// Backend tag per track, written into recorderSession so restore /+// download / cloud-local-playback paths can route to the same backend+// the writer used.+let storageBackends = { screen: "idb", audio: "idb", camera: "idb" };+let storageOpfsSessionId = null;+// Encoder kind chosen per track ("webcodecs" | "mediarecorder"). Persisted+// into recorderSession so the resume / Download recovery paths know what+// container the chunks are in (mp4 vs webm).+let encoderKinds = {+ screen: "mediarecorder",+ audio: "mediarecorder",+ camera: "mediarecorder",+};+let trackContainers = {+ screen: "video/webm",+ audio: "video/webm",+ camera: "video/webm",+};+let trackCodecs = { screen: "vp9", audio: "opus", camera: "vp9" };+let encoderHwSlots = null;const urlParams = new URLSearchParams(window.location.search);const IS_INJECTED_IFRAME = urlParams.has("injected");@@ -57,8 +92,6 @@ const IS_IFRAME_CONTEXT =!document.referrer.startsWith("chrome-extension://"));const CloudRecorder = () => {- // Debug bundle removed; keep a no-op logger to preserve calls-const screenTimer = useRef({ start: null, total: 0, paused: false });const cameraTimer = useRef({ start: null, total: 0, paused: false });const [started, setStarted] = useState(false);@@ -72,7 +105,6 @@ const CloudRecorder = () => {const retryFinalize = async () => {setRetryingFinalize(true);try {- // Attempt to re-run finalize flow by calling stopRecording with shouldFinalize=trueawait stopRecording(true, "retry-finalize");} catch (err) {console.warn("Retry finalize failed:", err);@@ -83,10 +115,12 @@ const CloudRecorder = () => {const isTab = useRef(false);const tabID = useRef(null);+ const audioIntent = useRef({ micActive: false, systemAudio: false });const recordingTabId = useRef(null);const tabPreferred = useRef(false);const screenStream = useRef(null);+ const prewarmRef = useRef(null);const cameraStream = useRef(null);const micStream = useRef(null);const rawMicStream = useRef(null);@@ -97,6 +131,7 @@ const CloudRecorder = () => {const screenUploader = useRef(null);const cameraUploader = useRef(null);+ const audioUploader = useRef(null);const uploadMetaRef = useRef(null);const localScreenPlaybackOfferRef = useRef(null);const emptyCleanupRef = useRef(false);@@ -132,11 +167,20 @@ const CloudRecorder = () => {const consecutiveScreenFailures = useRef(0);const consecutiveCameraFailures = useRef(0);+ const consecutiveAudioFailures = useRef(0);const firstChunkTime = useRef(null);const firstChunkLoggedRef = useRef(false);const recorderSession = useRef(null);const recordingSessionId = useRef(null);+ // SW push + tab pull both deliver streaming-data by design (push at+ // openRecorderTab.js:163, pull from our "loaded" handler). Without this+ // guard, both fire startStreaming → two getDisplayMedia prompts and a+ // silent recorder close. Mirrors the same guard in legacy Recorder.jsx.+ const streamingDataReceivedAt = 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);const unloadGuardRef = useRef({pagehideSeen: false,beforeUnloadSeen: false,@@ -234,7 +278,6 @@ const CloudRecorder = () => {},});- // This checks if the recording was previously initializedconst isInit = useRef(false);const aCtx = useRef(null);@@ -246,9 +289,7 @@ const CloudRecorder = () => {const keepAliveLockAbort = useRef(null);const keepAliveMediaSessionActive = useRef(false);- const logDebugEvent = async () => {- // debug bundle feature removed; noop- };+ const logDebugEvent = async () => {};const setCloudRestartPhase = async (phase, details = {}) => {try {@@ -289,7 +330,6 @@ const CloudRecorder = () => {const attempt = pendingStartAttempts.current + 1;pendingStartAttempts.current = attempt;if (attempt > 75) {- // ~15s max with 200ms delayclearPendingStart();sendRecordingError("Recording is taking too long to start. Please try again.",@@ -354,7 +394,6 @@ const CloudRecorder = () => {const ensureRecordingSessionId = () => {if (!recordingSessionId.current) {recordingSessionId.current = crypto.randomUUID();- // Persist so telemetry correlation survives document death.try {chrome.storage.local.set({recordingSessionId: recordingSessionId.current,@@ -439,9 +478,7 @@ const CloudRecorder = () => {uploadTelemetryTokenRef.current = screenityToken;return screenityToken;}- } catch {- // ignore- }+ } catch {}try {const res = await fetch(`${API_BASE}/auth/get-extension-token`, {@@ -456,9 +493,7 @@ const CloudRecorder = () => {return token;}}- } catch {- // ignore- }+ } catch {}return null;};@@ -518,6 +553,18 @@ const CloudRecorder = () => {projectId: eventPayload.projectId || null,sceneId: eventPayload.sceneId || null,recordingSessionId: eventPayload.recordingSessionId || null,+ codec: eventPayload.codec || null,+ container: eventPayload.container || null,+ encoderKind: eventPayload.encoderKind || null,+ encoderHwSlots: eventPayload.encoderHwSlots || null,+ storageBackend: eventPayload.storageBackend || null,+ storageInitMs:+ typeof eventPayload.storageInitMs === "number"+ ? eventPayload.storageInitMs+ : null,+ screenStorageBackend: eventPayload.screenStorageBackend || null,+ cameraStorageBackend: eventPayload.cameraStorageBackend || null,+ audioStorageBackend: eventPayload.audioStorageBackend || null,},};};@@ -564,9 +611,7 @@ const CloudRecorder = () => {if (res.status === 404 || res.status === 405) {uploadTelemetryNetworkDisabledRef.current = true;}- } catch {- // best effort- }+ } catch {}};const emitUploadTelemetry = async (event, payload = {}) => {@@ -759,9 +804,7 @@ const CloudRecorder = () => {};try {await chrome.storage.local.set({ recorderPipelineState: state });- } catch {- // ignore- }+ } catch {}};const getOrCreateSceneId = async ({ forceNew = false } = {}) => {@@ -773,18 +816,14 @@ const CloudRecorder = () => {if (!forceNew && sceneId && sceneIdStatus === "recording") {return sceneId;}- } catch {- // ignore- }+ } catch {}const next = crypto.randomUUID();try {await chrome.storage.local.set({sceneId: next,sceneIdStatus: "recording",});- } catch {- // ignore- }+ } catch {}return next;};@@ -795,9 +834,7 @@ const CloudRecorder = () => {sceneIdStatus: "completed",lastCompletedSceneId: sceneId,});- } catch {- // ignore- }+ } catch {}};const upsertPendingScene = async (sceneId, payload) => {@@ -849,10 +886,13 @@ const CloudRecorder = () => {const linkMediaToScene = async (projectId, sceneId, mediaId) => {if (!projectId || !sceneId || !mediaId) return;- await fetch(`${API_BASE}/media/${mediaId}/scene`, {+ const { screenityToken } = await chrome.storage.local.get(["screenityToken"]);+ await fetch(`${API_BASE}/media/${mediaId}/scene/`, {method: "PATCH",- headers: { "Content-Type": "application/json" },- credentials: "include",+ headers: {+ "Content-Type": "application/json",+ ...(screenityToken ? { Authorization: `Bearer ${screenityToken}` } : {}),+ },body: JSON.stringify({ projectId, sceneId }),});};@@ -860,10 +900,13 @@ const CloudRecorder = () => {const confirmLinkedMedia = async (projectId, sceneId, mediaIds = []) => {const filtered = mediaIds.filter(Boolean);if (!projectId || !sceneId || filtered.length === 0) return;- await fetch(`${API_BASE}/media/confirm-linked`, {+ const { screenityToken } = await chrome.storage.local.get(["screenityToken"]);+ await fetch(`${API_BASE}/media/confirm-linked/`, {method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",+ headers: {+ "Content-Type": "application/json",+ ...(screenityToken ? { Authorization: `Bearer ${screenityToken}` } : {}),+ },body: JSON.stringify({ mediaIds: filtered, projectId, sceneId }),});};@@ -888,10 +931,13 @@ const CloudRecorder = () => {const mediaIds = [screenMediaId, cameraMediaId, audioMediaId].filter(Boolean,);- const res = await fetch(`${API_BASE}/videos/${projectId}/recover-scene`, {+ const { screenityToken } = await chrome.storage.local.get(["screenityToken"]);+ const res = await fetch(`${API_BASE}/videos/${projectId}/recover-scene/`, {method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",+ headers: {+ "Content-Type": "application/json",+ ...(screenityToken ? { Authorization: `Bearer ${screenityToken}` } : {}),+ },body: JSON.stringify({sceneId,mediaIds,@@ -907,23 +953,12 @@ const CloudRecorder = () => {return { ok: true };};- // exportDebugBundle removed-- // Note: We no longer try to "keep alive" the service worker with pings.- // Instead, we persist recording state to chrome.storage.local so the SW can- // recover context when it restarts. The CloudRecorder tab is the source of truth.- // However, we DO need to keep the tab itself alive using silent audio to prevent- // Chrome from freezing/discarding this background tab.-- /**- * Start silent audio playback to prevent Chrome from freezing this tab.- * Chrome throttles/freezes background tabs after ~5 minutes of inactivity,- * which would stop our recording. Playing silent audio keeps the tab active.- */+ // Tab keep-alive: Chrome throttles/freezes background tabs after ~5 minutes+ // of inactivity. Multi-layered signals (silent audio, web lock, mediaSession)+ // are needed because throttling stacks them.const startTabKeepAlive = () => {if (IS_OFFSCREEN_HOST) return;- // Multi-layered keepalive - Chrome's background-tab throttling stacks signals.try {if (!keepAliveAudioCtx.current) {const ctx = new (window.AudioContext || window.webkitAudioContext)();@@ -983,9 +1018,6 @@ const CloudRecorder = () => {.catch(() => {});};- /**- * Stop the silent audio playback when recording ends.- */const stopTabKeepAlive = () => {try {if (keepAliveOscillator.current) {@@ -1008,19 +1040,28 @@ const CloudRecorder = () => {keepAliveMediaSessionActive.current = false;}- // Allow Chrome to discard this tab again if neededchrome.runtime.sendMessage({type: "set-tab-auto-discardable",discardable: true,});chrome.runtime.sendMessage({ type: "stop-recorder-keepalive-alarm" })- .catch(() => {});+ .catch((err) => {+ // Surface failures: a leftover alarm can outlive the recording and re-wake the SW.+ console.warn(+ "[CloudRecorder] stop-recorder-keepalive-alarm failed",+ err,+ );+ });- // Cancel first-chunk watchdogchrome.runtime.sendMessage({ type: "cancel-first-chunk-watchdog" })- .catch(() => {});+ .catch((err) => {+ console.warn(+ "[CloudRecorder] cancel-first-chunk-watchdog failed",+ err,+ );+ });if (globalThis.SCREENITY_VERBOSE_LOGS) {if (DEBUG_START_FLOW) {@@ -1064,7 +1105,6 @@ const CloudRecorder = () => {logScreenTrackEvent("track-ended", track);const label = track?.label || null;- // Collect diagnostic info to understand WHY the track endedconst diagnosticInfo = {reason: "screen-track-ended",tabId: recordingTabId.current || null,@@ -1093,8 +1133,7 @@ const CloudRecorder = () => {lastTrackEnded: diagnosticInfo,});- // When screen track ends, we MUST stop the recording- // Otherwise we'd be recording black/frozen video with no way for user to know+ // Track end means we'd record frozen/black video silently; stop instead.if (!isFinishing.current && !sentLast.current) {console.warn("⚠️ Screen track ended - stopping recording");stopRecording(true, "screen-track-ended");@@ -1122,7 +1161,6 @@ const CloudRecorder = () => {screenTrackLostRef.current = true;logScreenTrackEvent("monitor-ended", track);- // Stop the recording when track diesif (!isFinishing.current && !sentLast.current) {console.warn("⚠️ Screen track monitor detected ended track - stopping recording",@@ -1135,22 +1173,34 @@ const CloudRecorder = () => {const ensureChunkStoreReady = async () => {if (idbReadyRef.current) return true;+ const sessionId = ensureRecordingSessionId();+ storageOpfsSessionId = sessionId;try {- await chunksStore.setItem("__probe", { ts: Date.now() });- await chunksStore.removeItem("__probe");+ const result = await chooseChunksStore({ sessionId, track: "screen" });+ chunksStore = result.store;+ storageBackends.screen = result.backend;+ if (result.backend === "idb") {+ // chooseChunksStore returned IDB without probing it; verify writability+ // here so the failure path matches the previous behaviour.+ await chunksStore.setItem("__probe", { ts: Date.now() });+ await chunksStore.removeItem("__probe");+ }idbReadyRef.current = true;void emitUploadTelemetry("upload_local_backup_enabled", {backupType: "screen",+ storageBackend: result.backend,+ storageInitMs: result.initMs,});return true;} catch (err) {fatalErrorRef.current = true;void emitUploadTelemetry("upload_local_backup_unavailable", {backupType: "screen",+ storageBackend: storageBackends.screen,error: err?.message || String(err),});sendRecordingError(- "Local storage is blocked (IndexedDB unavailable). Recording cannot start.",+ "Local storage is blocked. Recording cannot start.",);return false;}@@ -1158,18 +1208,28 @@ const CloudRecorder = () => {const ensureAudioChunkStoreReady = async () => {if (audioChunkStoreReadyRef.current) return true;+ const sessionId = ensureRecordingSessionId();+ storageOpfsSessionId = sessionId;try {- await audioChunksStore.setItem("__probe", { ts: Date.now() });- await audioChunksStore.removeItem("__probe");+ const result = await chooseChunksStore({ sessionId, track: "audio" });+ audioChunksStore = result.store;+ storageBackends.audio = result.backend;+ if (result.backend === "idb") {+ await audioChunksStore.setItem("__probe", { ts: Date.now() });+ await audioChunksStore.removeItem("__probe");+ }audioChunkStoreReadyRef.current = true;void emitUploadTelemetry("upload_local_backup_enabled", {backupType: "audio",+ storageBackend: result.backend,+ storageInitMs: result.initMs,});return true;} catch (err) {audioChunkStoreReadyRef.current = false;void emitUploadTelemetry("upload_local_backup_degraded", {backupType: "audio",+ storageBackend: storageBackends.audio,error: err?.message || String(err),});return false;@@ -1178,9 +1238,8 @@ const CloudRecorder = () => {const clearAudioChunkStore = async (reason = "unknown") => {audioChunkIndexRef.current = 0;- // Always attempt clear regardless of audioChunkStoreReadyRef state.- // If IDB degraded mid-session the flag is false, but partial chunks written- // before degradation must still be cleared to avoid stale data on next session.+ // Clear unconditionally: if IDB degraded mid-session the ready flag is false,+ // but partial chunks written before degradation must still be cleared.try {await audioChunksStore.clear();console.info("[CloudRecorder] clearAudioChunkStore:", reason);@@ -1191,18 +1250,28 @@ const CloudRecorder = () => {const ensureCameraChunkStoreReady = async () => {if (cameraChunkStoreReadyRef.current) return true;+ const sessionId = ensureRecordingSessionId();+ storageOpfsSessionId = sessionId;try {- await cameraChunksStore.setItem("__probe", { ts: Date.now() });- await cameraChunksStore.removeItem("__probe");+ const result = await chooseChunksStore({ sessionId, track: "camera" });+ cameraChunksStore = result.store;+ storageBackends.camera = result.backend;+ if (result.backend === "idb") {+ await cameraChunksStore.setItem("__probe", { ts: Date.now() });+ await cameraChunksStore.removeItem("__probe");+ }cameraChunkStoreReadyRef.current = true;void emitUploadTelemetry("upload_local_backup_enabled", {backupType: "camera",+ storageBackend: result.backend,+ storageInitMs: result.initMs,});return true;} catch (err) {cameraChunkStoreReadyRef.current = false;void emitUploadTelemetry("upload_local_backup_degraded", {backupType: "camera",+ storageBackend: storageBackends.camera,error: err?.message || String(err),});return false;@@ -1222,7 +1291,7 @@ const CloudRecorder = () => {}};- // Purge IDB chunks Bunny has confirmed. Keeps chunk_0 (webm init segment).+ // Purge IDB chunks Bunny has confirmed. chunk_0 (webm init segment) is preserved.const purgeConfirmedChunks = async (store,rangesRef,@@ -1366,6 +1435,15 @@ const CloudRecorder = () => {}const now = Date.now();+ const screenBackend = storageBackends.screen || "idb";+ const offerOpfsSessionId =+ screenBackend === "opfs"+ ? storageOpfsSessionId ||+ recorderSession.current?.opfsSessionId ||+ recorderSession.current?.id ||+ null+ : null;+ const screenContainer = trackContainers.screen || "video/webm";const nextOffer = {offerId: crypto.randomUUID(),projectId,@@ -1380,7 +1458,16 @@ const CloudRecorder = () => {createdAt: now,expiresAt: now + LOCAL_SCREEN_PLAYBACK_TTL_MS,status: "available",- source: "indexeddb-screen-chunks",+ source:+ screenBackend === "opfs"+ ? "opfs-screen-chunks"+ : "indexeddb-screen-chunks",+ storageBackend: screenBackend,+ opfsSessionId: offerOpfsSessionId,+ // Container drives the mimeType the editor uses for `<video>`. WebM+ // for the legacy MediaRecorder path, MP4 for the WebCodecs path.+ container: screenContainer,+ encoderKind: encoderKinds.screen || "mediarecorder",};try {@@ -1418,10 +1505,8 @@ const CloudRecorder = () => {};const buildAudioBlobFromDurableStore = async () => {- // Always attempt IDB read regardless of audioChunkStoreReadyRef state.- // The flag can be false if IDB degraded mid-session, but partial IDB data- // written before the failure is still more complete than the 8-chunk memory- // window. Falling back to memory prematurely silently drops early audio.+ // Try IDB even if audioChunkStoreReadyRef is false: partial pre-degradation+ // data is more complete than the 8-chunk memory window.try {const recovered = [];await audioChunksStore.iterate((value) => {@@ -1487,6 +1572,20 @@ const CloudRecorder = () => {lowSpace: storagePressureRef.current.lowSpace,critical: storagePressureRef.current.critical,},+ // Tracks which backend each track wrote to so restore / Download.jsx /+ // cloud-local-playback handlers can route reads to the same backend.+ // opfsSessionId is the directory key under cloud-chunks/ for OPFS+ // tracks; safe to keep null when all tracks are IDB.+ storageBackends: { ...storageBackends },+ opfsSessionId:+ storageOpfsSessionId || recorderSession.current?.id || null,+ // Encoder + container per track so Download.jsx writes the right+ // file extension on recovery and cloud-local-playback returns the+ // right mimeType to the editor.+ encoderKinds: { ...encoderKinds },+ trackContainers: { ...trackContainers },+ trackCodecs: { ...trackCodecs },+ encoderHwSlots,updatedAt: Date.now(),...overrides,};@@ -1536,6 +1635,12 @@ const CloudRecorder = () => {online: networkStateRef.current.online,offlineSince: networkStateRef.current.offlineSince,},+ storageBackends: { ...storageBackends },+ opfsSessionId: storageOpfsSessionId || sessionId || null,+ encoderKinds: { ...encoderKinds },+ trackContainers: { ...trackContainers },+ trackCodecs: { ...trackCodecs },+ encoderHwSlots,...meta,};recorderSession.current = session;@@ -1584,9 +1689,17 @@ const CloudRecorder = () => {return true;};- const finalizeRecorderSession = async (status = "completed") => {+ const finalizeRecorderSession = async (+ status = "completed",+ { keepOpfsSession = false } = {},+ ) => {if (!recorderSession.current) return;const sessionId = recorderSession.current.id;+ const opfsSessionId =+ recorderSession.current.opfsSessionId || storageOpfsSessionId || sessionId;+ const usedOpfs = Object.values(+ recorderSession.current.storageBackends || storageBackends || {},+ ).some((b) => b === "opfs");const sessionStateKey = getSessionStateKey(sessionId);logDebugEvent("recorder-session-finalize-start", {status,@@ -1621,6 +1734,47 @@ const CloudRecorder = () => {recordingSessionId.current = null;sessionStateIndexedRef.current = false;resetSessionTrackState();+ // Force the next recording on this component instance to re-probe and+ // re-bind chunksStore/audioChunksStore/cameraChunksStore so they don't+ // keep pointing at the previous session's OPFS directory.+ idbReadyRef.current = false;+ audioChunkStoreReadyRef.current = false;+ cameraChunkStoreReadyRef.current = false;+ chunksStore = localforage.createInstance({ name: "chunks" });+ audioChunksStore = localforage.createInstance({ name: "audioChunks" });+ cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });+ storageBackends = { screen: "idb", audio: "idb", camera: "idb" };+ storageOpfsSessionId = null;+ encoderKinds = {+ screen: "mediarecorder",+ audio: "mediarecorder",+ camera: "mediarecorder",+ };+ trackContainers = {+ screen: "video/webm",+ audio: "video/webm",+ camera: "video/webm",+ };+ trackCodecs = { screen: "vp9", audio: "opus", camera: "vp9" };+ encoderHwSlots = null;+ // Re-probe HW slots + sticky-disabled state on the next recording+ // (encoders chosen per session, not per component-mount).+ resetEncoderProbeCache();+ // Reap the OPFS session directory once chunks have been cleared by the+ // various callers' .clear() calls. Awaited because the success path+ // calls window.close() right after finalize, and a fire-and-forget+ // delete races with tab teardown, leaving half-deleted dirs across+ // sessions and confuse the orphan reaper.+ //+ // Skipped when a local-playback offer is still holding the screen+ // chunks: the editor reads them via cloud-local-playback-read-chunk+ // and clears+destroys via cloud-local-playback-clear when done. The+ // offer's TTL alarm cleans up if the editor never gets to it.+ if (usedOpfs && opfsSessionId && !keepOpfsSession) {+ try {+ await destroySessionDir(opfsSessionId);+ } catch {}+ }logDebugEvent("recorder-session-finalized", { status });}};@@ -1803,9 +1957,7 @@ const CloudRecorder = () => {});try {await chrome.storage.local.set({ sceneIdStatus: "failed" });- } catch {- // ignore- }+ } catch {}};const exportLocalRecovery = async (reason = "upload failed") => {try {@@ -1846,12 +1998,10 @@ const CloudRecorder = () => {}};- // Called inside tryRecoverPreviousSession after IDB chunks are cleared.- // Removes stale TUS upload journals, lookup keys, and Bunny video-map entries- // that survive a process crash. Without this cleanup the next recording attempt- // can pick up the old journal, "resume" from the wrong server offset, and- // append fresh MediaRecorder chunks to the old partial Bunny upload — producing- // a garbled video. Also resets sceneId so the next session gets a fresh scene.+ // Removes stale TUS journals, lookup keys, and Bunny video-map entries that+ // survive a process crash. Without this, the next session can resume the old+ // partial Bunny upload and append fresh chunks, producing a garbled video.+ // Also resets sceneId so the next session gets a fresh scene.const clearStaleUploadJournals = async (storedSession) => {const keysToRemove = [];const tracks = storedSession?.tracks || {};@@ -1863,7 +2013,6 @@ const CloudRecorder = () => {if (upl.journalKey) keysToRemove.push(upl.journalKey);if (upl.journalLookupKey) keysToRemove.push(upl.journalLookupKey);- // Also clear the Bunny video-map fallback entryconst pid = upl.projectId || storedSession?.projectId || null;const sid = upl.sceneId || null;const t = upl.type || upl.trackType || null;@@ -1874,8 +2023,7 @@ const CloudRecorder = () => {}}- // Force a fresh sceneId on the next recording so getOrCreateSceneId doesn't- // reuse the stale scene that is tied to the now-cleared journals.+ // Reset sceneId so getOrCreateSceneId doesn't reuse a scene tied to cleared journals.keysToRemove.push("sceneId", "sceneIdStatus");const uniqKeys = [...new Set(keysToRemove)];@@ -1937,10 +2085,37 @@ const CloudRecorder = () => {["recorderSession"],);+ // Recovery reads from whatever backend the previous session wrote to.+ // Sessions before the OPFS migration have no storageBackends field; fall+ // back to IDB across the board, matching pre-migration behaviour.+ const prevBackends =+ storedSession?.storageBackends || {+ screen: "idb",+ audio: "idb",+ camera: "idb",+ };+ const prevOpfsSessionId =+ storedSession?.opfsSessionId || storedSession?.id || null;+ const recoveryScreenStore = openExistingChunksStore({+ sessionId: prevOpfsSessionId,+ track: "screen",+ backend: prevBackends.screen || "idb",+ }).store;+ const recoveryCameraStore = openExistingChunksStore({+ sessionId: prevOpfsSessionId,+ track: "camera",+ backend: prevBackends.camera || "idb",+ }).store;+ const recoveryAudioStore = openExistingChunksStore({+ sessionId: prevOpfsSessionId,+ track: "audio",+ backend: prevBackends.audio || "idb",+ }).store;+const [chunkCount, cameraChunkCount, audioChunkCount] = await Promise.all([- chunksStore.length().catch(() => 0),- cameraChunksStore.length().catch(() => 0),- audioChunksStore.length().catch(() => 0),+ recoveryScreenStore.length().catch(() => 0),+ recoveryCameraStore.length().catch(() => 0),+ recoveryAudioStore.length().catch(() => 0),]);const isRecoverable = RECOVERABLE_SESSION_STATUSES.has(storedSession?.status,@@ -1955,12 +2130,15 @@ const CloudRecorder = () => {recoveredAudioChunkCount: audioChunkCount,recordingSessionId: storedSession?.id || null,projectId: storedSession?.projectId || null,+ screenStorageBackend: prevBackends.screen || "idb",+ cameraStorageBackend: prevBackends.camera || "idb",+ audioStorageBackend: prevBackends.audio || "idb",});const ts = new Date().toISOString();if (chunkCount > 0) {const recovered = [];- await chunksStore.iterate((value) => {+ await recoveryScreenStore.iterate((value) => {recovered.push(value);});recovered.sort((a, b) => a.index - b.index);@@ -1977,14 +2155,19 @@ const CloudRecorder = () => {saveAs: false,});} finally {- URL.revokeObjectURL(objectUrl);+ // download() resolves before the blob fetch; delay revoke.+ setTimeout(() => {+ try {+ URL.revokeObjectURL(objectUrl);+ } catch {}+ }, 2000);}}}if (cameraChunkCount > 0) {const cameraRecovered = [];- await cameraChunksStore.iterate((value) => {+ await recoveryCameraStore.iterate((value) => {cameraRecovered.push(value);});cameraRecovered.sort((a, b) => (a.index || 0) - (b.index || 0));@@ -2001,7 +2184,11 @@ const CloudRecorder = () => {saveAs: false,});} finally {- URL.revokeObjectURL(cameraObjectUrl);+ setTimeout(() => {+ try {+ URL.revokeObjectURL(cameraObjectUrl);+ } catch {}+ }, 2000);}}}@@ -2011,11 +2198,17 @@ const CloudRecorder = () => {message: chrome.i18n.getMessage("toastRecoveredSession"),});- await chunksStore.clear();- await clearAudioChunkStore("recovery");- await clearCameraChunkStore("recovery");- // Clear stale journals and sceneId so the next recording can't accidentally- // resume the old partial Bunny upload and produce a garbled video.+ await recoveryScreenStore.clear().catch(() => {});+ await recoveryAudioStore.clear().catch(() => {});+ await recoveryCameraStore.clear().catch(() => {});+ // If the previous session wrote anything to OPFS, drop the whole+ // session directory so the parent doesn't accumulate empty subdirs.+ const prevUsedOpfs = Object.values(prevBackends).some(+ (b) => b === "opfs",+ );+ if (prevUsedOpfs && prevOpfsSessionId) {+ destroySessionDir(prevOpfsSessionId).catch(() => {});+ }await clearStaleUploadJournals(storedSession);await chrome.storage.local.set({recorderSession: {@@ -2033,8 +2226,7 @@ const CloudRecorder = () => {recordingSessionId: storedSession?.id || null,projectId: storedSession?.projectId || null,});- // Even with no durable chunks, stale journals must be cleared — the video- // map and lookup keys are enough to cause a garbled resume on next start.+ // Even without durable chunks, video-map/lookup keys alone can cause a garbled resume.await clearStaleUploadJournals(storedSession);await chrome.storage.local.set({recorderSession: {@@ -2132,6 +2324,24 @@ const CloudRecorder = () => {]);};+ // trackCodecs at start is the requested codec. HW encoders re-derive+ // profile/level from the SPS (e.g. requested High L4.2 yields High L4.0+ // at 1080p), so sync to the actual codec from the first encoded chunk's+ // decoderConfig.+ const syncActualVideoCodec = (track, recorder) => {+ const actual = recorder?.actualVideoCodec;+ if (!actual || trackCodecs[track] === actual) return;+ trackCodecs[track] = actual;+ const uploader =+ track === "screen"+ ? screenUploader.current+ : track === "camera"+ ? cameraUploader.current+ : null;+ uploader?.updateEncoderInfo?.({ codec: actual });+ persistSessionState({});+ };+const checkMaxMemory = () => {const now = Date.now();if (now - storagePressureRef.current.lastEstimateAt < STORAGE_CHECK_INTERVAL_MS) {@@ -2230,10 +2440,8 @@ const CloudRecorder = () => {const setMic = async (result) => {if (micStream.current && audioInputGain.current) {- // Mute merged audio in the main streamaudioInputGain.current.gain.value = result.active ? 1 : 0;- // Mute transcription-only mic stream tooif (rawMicStream.current) {rawMicStream.current.getAudioTracks().forEach((track) => {track.enabled = result.active;@@ -2295,19 +2503,20 @@ const CloudRecorder = () => {});}- if (uploadMeta?.audio?.mediaId && uploadMeta?.audio?.path) {+ if (uploadMeta?.audio?.mediaId && uploadMeta?.audio?.videoId) {mediaToDelete.push({+ videoId: uploadMeta.audio.videoId,mediaId: uploadMeta.audio.mediaId,- path: uploadMeta.audio.path,type: "audio",});}- await fetch(`${API_BASE}/videos/${projectId}/delete`, {+ const { screenityToken } = await chrome.storage.local.get(["screenityToken"]);+ await fetch(`${API_BASE}/videos/${projectId}/delete/`, {method: "POST",- credentials: "include",headers: {"Content-Type": "application/json",+ ...(screenityToken ? { Authorization: `Bearer ${screenityToken}` } : {}),},body: JSON.stringify({mediaToDelete,@@ -2337,15 +2546,14 @@ const CloudRecorder = () => {emptyCleanupRef.current = true;- console.warn("[Screenity] empty upload cleanup", {- reason,- screenOffset,- cameraOffset,- });+ console.warn(+ `[Screenity] empty upload cleanup reason=${reason} screenOffset=${screenOffset} cameraOffset=${cameraOffset}`,+ );await Promise.allSettled([screenUploader.current?.abort?.(),cameraUploader.current?.abort?.(),+ audioUploader.current?.abort?.(),]);try {@@ -2372,6 +2580,9 @@ const CloudRecorder = () => {};const sendRecordingError = (why, cancel = false) => {+ console.error(+ `[Screenity][CloudRecorder] sendRecordingError why=${typeof why === "string" ? why : JSON.stringify(why)} cancel=${cancel}`,+ );void cleanupIfEmptyUploads("error");sendRecordingErrorBase(why, cancel);};@@ -2381,7 +2592,6 @@ const CloudRecorder = () => {setInitProject(false);await cleanupIfEmptyUploads(restarting ? "restart" : "dismiss");- // Stop keepalive (also cancels first-chunk watchdog)stopTabKeepAlive();await setRecordingTimingState({recording: false,@@ -2409,6 +2619,7 @@ const CloudRecorder = () => {await Promise.allSettled([screenUploader.current?.abort?.(),cameraUploader.current?.abort?.(),+ audioUploader.current?.abort?.(),]);if (!recordingToScene) {try {@@ -2423,13 +2634,12 @@ const CloudRecorder = () => {}try {await finalizeRecorderSession("restarting");- } catch {- // best effort- }+ } catch {}uploadMetaRef.current = null;sentLast.current = false;screenUploader.current = null;cameraUploader.current = null;+ audioUploader.current = null;uploadersInitialized.current = false;cleanupTimers();return;@@ -2443,6 +2653,7 @@ const CloudRecorder = () => {await Promise.allSettled([screenUploader.current?.abort?.(),cameraUploader.current?.abort?.(),+ audioUploader.current?.abort?.(),]);await stopRecording(false);@@ -2456,7 +2667,6 @@ const CloudRecorder = () => {if (multiMode) {if (multiSceneCount === 0) {if (!recordingToScene) {- // Only delete if new projectif (projectId) {try {await deleteProject(projectId, uploadMeta);@@ -2474,21 +2684,16 @@ const CloudRecorder = () => {uploadMetaRef.current = null;- // FLAG: decide whether to close or not- // window.close();return;}- // Not multi-mode: original logicif (projectId && !recordingToScene) {- // Only delete if new projecttry {await deleteProject(projectId, uploadMeta);} catch (err) {console.warn("❌ Failed to delete project:", err);}} else if (projectId) {- // Only delete media, not projecttry {await deleteProject(projectId, uploadMeta, false);} catch (err) {@@ -2502,18 +2707,15 @@ const CloudRecorder = () => {uploadMetaRef.current = null;isInit.current = false;- // FLAG: decide whether to close or notif (!IS_IFRAME_CONTEXT) {try {window.close();} catch {}return;}- // iframe contexttry {window.parent.postMessage({ type: "screenity-exit", mode }, "*");} catch {}- // fallbackwindow.location.reload();};@@ -2525,7 +2727,7 @@ const CloudRecorder = () => {isRestarting.current = true;await dismissRecording(true);await setCloudRestartPhase("restart-dismissed");- // Restart keeps existing capture streams; only recorder instances should stop.+ // Keep capture streams; only stop recorder instances.await stopAllRecorders({ stopStreams: false });await setCloudRestartPhase("restart-recorders-stopped");screenChunks.current = [];@@ -2622,6 +2824,48 @@ const CloudRecorder = () => {}};+ // Decide encoder kind (and therefore container) per track BEFORE+ // constructing the uploaders. The TUS Upload-Metadata `filetype` is+ // set at upload-create time and isn't re-declarable on PATCH, so the+ // uploader needs to know the right container up front. The plan is+ // cached; chooseTrackEncoder during startRecording reads the same+ // probe result and returns the same kind.+ const screenSettings = screenStream.current?.getVideoTracks?.()?.[0]+ ?.getSettings?.() || {};+ const cameraSettings = cameraStream.current?.getVideoTracks?.()?.[0]+ ?.getSettings?.() || {};+ const probeOptions = {+ screenWidth: Number(screenSettings.width) || 1920,+ screenHeight: Number(screenSettings.height) || 1080,+ cameraWidth: Number(cameraSettings.width) || 1280,+ cameraHeight: Number(cameraSettings.height) || 720,+ framerate:+ Number(screenSettings.frameRate) ||+ Number(cameraSettings.frameRate) ||+ 30,+ };+ const { inspectTrackPlan } = await import(+ "./encoder/chooseEncoder"+ );+ const screenPlan = await inspectTrackPlan({ track: "screen", probeOptions });+ const cameraPlan = await inspectTrackPlan({ track: "camera", probeOptions });+ const audioPlan = await inspectTrackPlan({ track: "audio" });+ encoderKinds.screen = screenPlan.kind;+ encoderKinds.camera = cameraPlan.kind;+ encoderKinds.audio = audioPlan.kind;+ trackContainers.screen = screenPlan.container;+ trackContainers.camera = cameraPlan.container;+ trackContainers.audio = audioPlan.container;+ trackCodecs.screen = screenPlan.codec;+ trackCodecs.camera = cameraPlan.codec;+ trackCodecs.audio = audioPlan.codec;+ encoderHwSlots = screenPlan.hwSlots || cameraPlan.hwSlots || encoderHwSlots;+ logDebugEvent("encoder-plan", {+ screen: screenPlan,+ camera: cameraPlan,+ audio: audioPlan,+ });+const onStall = (trackType) => (payload) => {stallNotified.current = true;persistSessionState({@@ -2655,6 +2899,9 @@ const CloudRecorder = () => {screenUploader.current = new BunnyTusUploader({sessionId,trackType: "screen",+ container: trackContainers.screen,+ codec: trackCodecs.screen,+ encoderKind: encoderKinds.screen,onProgress: ({ offset }) => {const now = Date.now();lastUploadProgress.current = {@@ -2685,6 +2932,17 @@ const CloudRecorder = () => {width = settings.width;height = settings.height;}+ // WebCodecs caps encoded resolution at 1080p via the resize canvas;+ // record the post-downscale dims on the Media doc + scene so any+ // pixel-math against the encoded video is consistent. MediaRecorder+ // path records at native, so dims pass through unchanged.+ if (encoderKinds.screen === "webcodecs") {+ const downscaled = computeEncodedDimensions({ width, height });+ if (downscaled.width > 0 && downscaled.height > 0) {+ width = downscaled.width;+ height = downscaled.height;+ }+ }await screenUploader.current.initialize(projectId, {title: "Screen Recording",type: "screen",@@ -2706,6 +2964,9 @@ const CloudRecorder = () => {cameraUploader.current = new BunnyTusUploader({sessionId,trackType: "camera",+ container: trackContainers.camera,+ codec: trackCodecs.camera,+ encoderKind: encoderKinds.camera,onProgress: ({ offset }) => {const now = Date.now();lastUploadProgress.current = {@@ -2730,7 +2991,14 @@ const CloudRecorder = () => {if (track?.readyState === "ended") {throw new Error("Camera track has ended");}- const { width, height } = track.getSettings();+ let { width, height } = track.getSettings();+ if (encoderKinds.camera === "webcodecs") {+ const downscaled = computeEncodedDimensions({ width, height });+ if (downscaled.width > 0 && downscaled.height > 0) {+ width = downscaled.width;+ height = downscaled.height;+ }+ }await cameraUploader.current.initialize(projectId, {title: "Camera Recording",type: "camera",@@ -2749,6 +3017,62 @@ const CloudRecorder = () => {});}+ const { micActive } = await chrome.storage.local.get(["micActive"]);+ // Only spin up the audio TUS uploader when the user actually has+ // mic on. The cloudrecorder always attaches a mic stream (then+ // gain-mutes it when micActive=false) for system-audio mixing+ // routing, so a non-empty getAudioTracks() isn't a strong signal+ // on its own.+ if (micActive === true && rawMicStream.current?.getAudioTracks?.().length) {+ // Audio uploader failures are non-fatal; recording proceeds+ // without an audio track if init fails (mic supplementary).+ try {+ audioUploader.current = new BunnyTusUploader({+ sessionId,+ trackType: "audio",+ container: trackContainers.audio,+ codec: trackCodecs.audio,+ encoderKind: encoderKinds.audio,+ onProgress: ({ offset }) => {+ const now = Date.now();+ patchTrackState("audio", {+ lastUploadOffset: offset,+ uploaderUpdatedAt: now,+ });+ },+ onStall: onStall("audio"),+ onTelemetry: onUploaderTelemetry("audio"),+ onStateChange: onUploaderStateChange("audio"),+ });+ await audioUploader.current.initialize(projectId, {+ title: "Audio Recording",+ type: "audio",+ linkedMediaId:+ screenUploader.current?.getMeta()?.mediaId ||+ cameraUploader.current?.getMeta()?.mediaId ||+ null,+ sceneId,+ sessionId,+ });+ logDebugEvent("uploader-ready", {+ type: "audio",+ projectId,+ sceneId,+ mediaId: audioUploader.current?.getMeta()?.mediaId || null,+ videoId: audioUploader.current?.getMeta()?.videoId || null,+ });+ } catch (audioErr) {+ console.warn(+ "⚠️ Audio uploader init failed; recording will continue without an audio track:",+ audioErr,+ );+ logDebugEvent("audio-uploader-init-failed", {+ error: audioErr?.message || String(audioErr),+ });+ audioUploader.current = null;+ }+ }+await setPipelineState("uploaders-ready", {projectId,sceneId,@@ -2775,13 +3099,22 @@ const CloudRecorder = () => {const createMediaRecorder = (stream, options, onDataAvailable) => {try {const recorder = new MediaRecorder(stream, options);+ // Track in-flight write() promises so stopAllRecorders can drain them+ // before finalize() runs. Without this, a late ondataavailable that+ // fires after onstop (or whose write() promise hasn't resolved yet)+ // can race finalize and get rejected by the isFinalizing guard,+ // silently truncating the upload.+ recorder._pendingWrites = new Set();recorder.ondataavailable = (event) => {if (event.data && event.data.size > 0) {try {const maybePromise = onDataAvailable(event.data);- if (maybePromise && typeof maybePromise.catch === "function") {- maybePromise.catch((err) => {+ if (maybePromise && typeof maybePromise.then === "function") {+ recorder._pendingWrites.add(maybePromise);+ const settle = () => recorder._pendingWrites.delete(maybePromise);+ maybePromise.then(settle, (err) => {+ settle();console.warn("onDataAvailable failed:", err);});}@@ -2806,9 +3139,12 @@ const CloudRecorder = () => {const startRecording = async () => {setInitProject(false);await clearLocalScreenPlaybackOffer("start-recording");- // Ensure keepalive is runningstartTabKeepAlive();+ // Release the prewarm reader so the recorder can claim the track.+ await stopPrewarm(prewarmRef.current);+ prewarmRef.current = null;+const storageReady = await ensureChunkStoreReady();if (!storageReady) return;await ensureAudioChunkStoreReady();@@ -2830,7 +3166,49 @@ const CloudRecorder = () => {const { projectId } = await chrome.storage.local.get(["projectId"]);if (!projectId) {- sendRecordingError("No project ID found. Please restart recording.");+ // Diagnostic: capture co-resident state so we can see how the cloudrecorder+ // reached startRecording without a project. The most common path is a BG+ // recording-error firing during attempt N (which clears projectId) followed+ // by a retry that reaches us via `start-recording-tab` without going back+ // through openRecorderTab → createVideoProject.+ let danglingState = null;+ try {+ danglingState = await chrome.storage.local.get([+ "sceneId",+ "sceneIdStatus",+ "multiProjectId",+ "multiMode",+ "multiSceneCount",+ "recordingAttemptId",+ ]);+ } catch {}+ void emitUploadTelemetry("project_state_change", {+ source: "startRecording-missing",+ from: null,+ to: null,+ sceneId: danglingState?.sceneId || null,+ sceneIdStatus: danglingState?.sceneIdStatus || null,+ multiProjectId: danglingState?.multiProjectId || null,+ multiMode: Boolean(danglingState?.multiMode),+ multiSceneCount: danglingState?.multiSceneCount || 0,+ recordingAttemptId: danglingState?.recordingAttemptId || null,+ uploadersInitialized: Boolean(uploadersInitialized.current),+ hasScreenUploader: Boolean(screenUploader.current),+ hasCameraUploader: Boolean(cameraUploader.current),+ });+ // Clear dangling scene state so a retry doesn't inherit broken sceneId/status+ // tied to a project that no longer exists. (BG recordingHelpers does the same+ // on its side; this is the cloudrecorder-side backup clear.)+ try {+ await chrome.storage.local.remove([+ "sceneId",+ "sceneIdStatus",+ "pendingSceneIndex",+ ]);+ } catch {}+ sendRecordingError(+ "No project ID found. Please close this tab and start a new recording.",+ );return;}@@ -2861,6 +3239,7 @@ const CloudRecorder = () => {await Promise.allSettled([screenUploader.current?.setSessionId?.(recorderSession.current?.id || null),cameraUploader.current?.setSessionId?.(recorderSession.current?.id || null),+ audioUploader.current?.setSessionId?.(recorderSession.current?.id || null),]);if (!screenUploader.current && !cameraUploader.current) {@@ -2901,7 +3280,6 @@ const CloudRecorder = () => {audioCaptureDegradedRef.current = false;resetSessionTrackState();- // Clear blob storage arraysscreenChunks.current = [];cameraChunks.current = [];audioChunks.current = [];@@ -2932,26 +3310,40 @@ const CloudRecorder = () => {hasCamera: Boolean(cameraStream.current),hasMic: Boolean(micStream.current),});- // Screen recorder setupif (screenStream.current) {- const stream = attachMicToStream(- screenStream.current,- micStream.current,- );+ // micStream is always attached when a mic device exists (it's the+ // AudioContext mix point for system audio too) and gain-muted to 0+ // when micActive=false, so stream-track presence isn't reliable.+ // audioIntent comes from BG's getStreamingData payload, which reads+ // before the content-script ContentState's fresh-state auto-default+ // can race-flip micActive false back to true.+ const { micActive, systemAudio } = audioIntent.current;+ const screenHasAudio = micActive === true || systemAudio === true;+ const stream = screenHasAudio+ ? attachMicToStream(screenStream.current, micStream.current)+ : // Strip incidental audio tracks (e.g. residual tab-capture+ // audio). Any audio track in the input causes the muxer to+ // emit a silent AAC stream into /original.+ new MediaStream(screenStream.current.getVideoTracks());const screenOptions = {mimeType: "video/webm;codecs=vp9,opus",- videoBitsPerSecond: 16000000, // 16 Mbps- audioBitsPerSecond: 128000, // 128 Kbps+ videoBitsPerSecond: 16000000,+ audioBitsPerSecond: 128000,};- screenRecorder.current = createMediaRecorder(+ const screenSettings = screenTrack?.getSettings?.() || {};+ const screenSelection = await chooseTrackEncoder({+ track: "screen",stream,- screenOptions,- async (blob) => {+ mimeType: screenOptions.mimeType,+ videoBitsPerSecond: screenOptions.videoBitsPerSecond,+ audioBitsPerSecond: screenOptions.audioBitsPerSecond,+ enableAudio: screenHasAudio,+ createMediaRecorder,+ onDataAvailable: async (blob) => {checkMaxMemory();- // Detect empty chunks which indicate recording failureif (!blob || blob.size === 0) {console.error("❌ MediaRecorder produced empty chunk!");consecutiveScreenFailures.current++;@@ -2964,7 +3356,6 @@ const CloudRecorder = () => {return;}- // Store for final blob creationscreenChunks.current.push(blob);const screenDropped = trimChunkBuffer(screenChunks,@@ -2979,11 +3370,13 @@ const CloudRecorder = () => {const timestamp = Date.now();+ // No-ops after the codec matches; called outside the hasChunks+ // gate so it still runs if hasChunks was set elsewhere.+ syncActualVideoCodec("screen", screenRecorder.current);if (!hasChunks.current) {hasChunks.current = true;lastTimecode.current = timestamp;firstChunkTime.current = timestamp;- // Cancel first-chunk watchdogchrome.runtime.sendMessage({ type: "cancel-first-chunk-watchdog" }).catch(() => {});@@ -2996,7 +3389,7 @@ const CloudRecorder = () => {.catch(() => {});}} else if (timestamp < lastTimecode.current) {- return; // Skip duplicate+ return;} else {lastTimecode.current = timestamp;}@@ -3037,7 +3430,7 @@ const CloudRecorder = () => {.catch(() => {});}await screenUploader.current.write(blob);- consecutiveScreenFailures.current = 0; // Reset on success+ consecutiveScreenFailures.current = 0;const endByte =Number(screenUploader.current?.totalBytes) || 0;screenChunkByteRangesRef.current.push({@@ -3074,12 +3467,29 @@ const CloudRecorder = () => {index.current++;},- );+ probeOptions: {+ screenWidth: Number(screenSettings.width) || 1920,+ screenHeight: Number(screenSettings.height) || 1080,+ framerate: Number(screenSettings.frameRate) || 30,+ },+ });+ screenRecorder.current = screenSelection.recorder;+ encoderKinds.screen = screenSelection.kind;+ trackContainers.screen = screenSelection.container;+ trackCodecs.screen = screenSelection.codec;+ encoderHwSlots = screenSelection.hwSlots || encoderHwSlots;+ logDebugEvent("encoder-selected", {+ track: "screen",+ kind: screenSelection.kind,+ reason: screenSelection.reason,+ container: screenSelection.container,+ codec: screenSelection.codec,+ hwSlots: screenSelection.hwSlots,+ });- // Start recording with 2-second time slicesscreenRecorder.current.start(2000);- // Start first-chunk watchdog (8s, via chrome.alarms)+ // First-chunk watchdog (8s, chrome.alarms-backed).chrome.runtime.sendMessage({ type: "start-first-chunk-watchdog" }).catch(() => {});@@ -3089,19 +3499,23 @@ const CloudRecorder = () => {}}- // Audio recorder setup (for transcription)+ // Audio recorder for transcription. webm > wav for browser support.if (rawMicStream.current?.getAudioTracks?.().length) {const audioOptions = {- mimeType: "audio/webm", // Using webm instead of wav for better browser support+ mimeType: "audio/webm",audioBitsPerSecond: 128000,};- audioRecorder.current = createMediaRecorder(- rawMicStream.current,- audioOptions,- async (blob) => {+ const audioSelection = await chooseTrackEncoder({+ track: "audio",+ stream: rawMicStream.current,+ mimeType: audioOptions.mimeType,+ audioBitsPerSecond: audioOptions.audioBitsPerSecond,+ enableAudio: true,+ createMediaRecorder,+ onDataAvailable: async (blob) => {const timestamp = Date.now();- // Keep a small in-memory window for UI/quick fallback only.+ // Small in-memory window for UI/quick fallback only.audioChunks.current.push(blob);const droppedAudio = trimChunkBuffer(audioChunks,@@ -3165,30 +3579,66 @@ const CloudRecorder = () => {}return;}+ if (uploadersInitialized.current && audioUploader.current) {+ try {+ if (audioUploader.current?.isPaused) return;+ if (audioUploader.current.queuedBytes > 5 * 1024 * 1024) {+ await audioUploader.current+ .waitForPendingUploads?.()+ .catch(() => {});+ }+ await audioUploader.current.write(blob);+ consecutiveAudioFailures.current = 0;+ } catch (uploadErr) {+ console.warn("Failed to upload audio chunk to Bunny:", uploadErr);+ consecutiveAudioFailures.current++;+ if (consecutiveAudioFailures.current > 3) {+ // Audio is supplementary; pause uploader, keep recording.+ audioUploader.current?.pause?.();+ }+ }+ }if (!firstChunkLoggedRef.current) {firstChunkLoggedRef.current = true;logStartFlow("first_chunk", { type: "audio" });assertCountdownBeforeFirstChunk(Date.now());}},- );+ });+ audioRecorder.current = audioSelection.recorder;+ encoderKinds.audio = audioSelection.kind;+ trackContainers.audio = audioSelection.container;+ trackCodecs.audio = audioSelection.codec;+ logDebugEvent("encoder-selected", {+ track: "audio",+ kind: audioSelection.kind,+ reason: audioSelection.reason,+ container: audioSelection.container,+ codec: audioSelection.codec,+ });audioRecorder.current.start(2000);}- // Camera recorder setupif (cameraStream.current) {let streamToRecord = cameraStream.current;- if (recordingType.current === "camera") {- if (micStream.current) {- streamToRecord = attachMicToStream(- cameraStream.current,- micStream.current,- );- } else {- console.warn("⚠️ Camera-only recording: microphone not available");- }+ // Camera-only carries the mic in-stream; screen+camera routes audio+ // through the audio uploader so the camera track stays video-only.+ // audioIntent is the BG snapshot (see screen branch above for why).+ if (+ recordingType.current === "camera" &&+ audioIntent.current.micActive &&+ micStream.current+ ) {+ streamToRecord = attachMicToStream(+ cameraStream.current,+ micStream.current,+ );+ } else {+ // Drop incidental audio tracks; otherwise the muxer emits a+ // silent AAC stream into the camera MP4.+ streamToRecord = new MediaStream(cameraStream.current.getVideoTracks());}const cameraOptions = {@@ -3196,22 +3646,34 @@ const CloudRecorder = () => {recordingType.current === "camera"? "video/webm;codecs=vp9,opus": "video/webm;codecs=vp9",- videoBitsPerSecond: 16000000, // 16 Mbps- audioBitsPerSecond: 128000, // 128 Kbps+ videoBitsPerSecond: 16000000,+ audioBitsPerSecond: 128000,};- cameraRecorder.current = createMediaRecorder(- streamToRecord,- cameraOptions,- async (blob) => {- // Detect empty chunks+ const cameraSettings = cameraTrack?.getSettings?.() || {};+ const cameraHasAudio =+ recordingType.current === "camera" &&+ (streamToRecord?.getAudioTracks?.()?.length ?? 0) > 0;+ const cameraSelection = await chooseTrackEncoder({+ track: "camera",+ stream: streamToRecord,+ mimeType: cameraOptions.mimeType,+ videoBitsPerSecond: cameraOptions.videoBitsPerSecond,+ audioBitsPerSecond: cameraOptions.audioBitsPerSecond,+ enableAudio: cameraHasAudio,+ createMediaRecorder,+ probeOptions: {+ cameraWidth: Number(cameraSettings.width) || 1280,+ cameraHeight: Number(cameraSettings.height) || 720,+ framerate: Number(cameraSettings.frameRate) || 30,+ },+ onDataAvailable: async (blob) => {if (!blob || blob.size === 0) {console.warn("⚠️ Camera MediaRecorder produced empty chunk");consecutiveCameraFailures.current++;return;}- // Store for final blob creationcameraChunks.current.push(blob);const cameraDropped = trimChunkBuffer(cameraChunks,@@ -3223,6 +3685,9 @@ const CloudRecorder = () => {(sessionTrackState.current.camera?.droppedInMemoryChunks || 0) +cameraDropped,});+ // firstChunkLoggedRef fires once across screen+camera, so this+ // sits outside that gate. No-ops after the codec matches.+ syncActualVideoCodec("camera", cameraRecorder.current);if (!firstChunkLoggedRef.current) {firstChunkLoggedRef.current = true;logStartFlow("first_chunk", { type: "camera" });@@ -3263,7 +3728,7 @@ const CloudRecorder = () => {try {if (cameraUploader.current?.isPaused) return;await cameraUploader.current.write(blob);- consecutiveCameraFailures.current = 0; // Reset on success+ consecutiveCameraFailures.current = 0;if (cameraPersistedIndex !== null) {const endByte =Number(cameraUploader.current?.totalBytes) || 0;@@ -3295,7 +3760,20 @@ const CloudRecorder = () => {}}},- );+ });+ cameraRecorder.current = cameraSelection.recorder;+ encoderKinds.camera = cameraSelection.kind;+ trackContainers.camera = cameraSelection.container;+ trackCodecs.camera = cameraSelection.codec;+ encoderHwSlots = cameraSelection.hwSlots || encoderHwSlots;+ logDebugEvent("encoder-selected", {+ track: "camera",+ kind: cameraSelection.kind,+ reason: cameraSelection.reason,+ container: cameraSelection.container,+ codec: cameraSelection.codec,+ hwSlots: cameraSelection.hwSlots,+ });cameraRecorder.current.start(2000);}@@ -3310,7 +3788,6 @@ const CloudRecorder = () => {clearInterval(screenTimer.current.notificationInterval);const timerInterval = setInterval(() => {- // stop if not recording anymoreif (!screenStream.current && !cameraStream.current) {clearInterval(timerInterval);cleanupTimers();@@ -3337,7 +3814,6 @@ const CloudRecorder = () => {}}, 1000);- // Save to clear laterscreenTimer.current.notificationInterval = timerInterval;screenTimer.current.warned = warned;@@ -3398,30 +3874,24 @@ const CloudRecorder = () => {if (interval) clearInterval(interval);screenTimer.current.notificationInterval = null;screenTimer.current.warned = false;+ // Roll unaccumulated elapsed into `total` before nulling `start`.+ // Without this, paused recordings end up with a truncated+ // screenDuration that bypasses the lastChunk-firstChunk fallback.+ const now = Date.now();+ if (!screenTimer.current.paused && screenTimer.current.start) {+ screenTimer.current.total =+ (screenTimer.current.total || 0) + (now - screenTimer.current.start);+ }screenTimer.current.start = null;screenTimer.current.paused = false;+ if (!cameraTimer.current.paused && cameraTimer.current.start) {+ cameraTimer.current.total =+ (cameraTimer.current.total || 0) + (now - cameraTimer.current.start);+ }cameraTimer.current.start = null;cameraTimer.current.paused = false;}- async function uploadAudioToBunny(audioFile, projectId) {- const formData = new FormData();- formData.append("file", audioFile);- formData.append("projectId", projectId);- formData.append("type", "audio");-- const res = await fetch(`${API_BASE}/bunny/upload`, {- method: "POST",- body: formData,- credentials: "include",- });-- const result = await res.json();- if (!res.ok) throw new Error(result?.error || "Audio upload failed");-- return result;- }-const stopAllRecorders = async ({ stopStreams = true } = {}) => {const stopRecorder = async (recorderRef) => {if (recorderRef.current && recorderRef.current.state !== "inactive") {@@ -3437,7 +3907,22 @@ const CloudRecorder = () => {]);} catch (err) {console.error("Error stopping recorder:", err);- // Force resolve to prevent hanging+ }+ // Drain any write() promises started by ondataavailable. Without+ // this, finalize() can race the final chunk and reject it with+ // "Cannot write during finalization", silently truncating.+ const pending = recorderRef.current?._pendingWrites;+ if (pending && pending.size > 0) {+ try {+ await Promise.race([+ Promise.allSettled(Array.from(pending)),+ new Promise((_, reject) =>+ setTimeout(() => reject(new Error("Drain timeout")), 5000),+ ),+ ]);+ } catch (err) {+ console.warn("Pending writes drain timed out:", err);+ }}}};@@ -3470,7 +3955,6 @@ const CloudRecorder = () => {const total = (timer.total || 0) + elapsed;const duration = total / 1000;- // If timer ever started but duration is zero, use min durationif (timer.start && duration < MIN_DURATION_SECONDS) {return MIN_DURATION_SECONDS;}@@ -3488,52 +3972,30 @@ const CloudRecorder = () => {};};- const handleAudioUpload = async (audioBlob, projectId, uploadMeta) => {- if (!audioBlob) return;-- try {- const audioFile = new File([audioBlob], "audio-recording.webm", {- type: "audio/webm",- });- logDebugEvent("audio-upload-start", {- projectId,- sceneId: uploadMeta?.sceneId || null,- });- const result = await uploadAudioToBunny(audioFile, projectId);-- logDebugEvent("audio-upload-complete", {- projectId,- sceneId: uploadMeta?.sceneId || null,- mediaId: result?.mediaId || null,- });- return result;- } catch (err) {- console.warn("❌ Audio upload/transcription failed:", err);- logDebugEvent("audio-upload-failed", {- projectId,- sceneId: uploadMeta?.sceneId || null,- error: err?.message || String(err),- });- }- };-const handleTranscription = async (uploadMeta, projectId) => {if (!uploadMeta.audio || !uploadMeta.audio.mediaId) return;try {const transcriptionTarget =uploadMeta.screen?.mediaId || uploadMeta.camera?.mediaId;- if (transcriptionTarget && uploadMeta.audio?.url) {+ if (transcriptionTarget) {const dedupeKey = `transcriptionQueued:${uploadMeta.sceneId}:${uploadMeta.audio.mediaId}`;const dedupe = await chrome.storage.local.get([dedupeKey]);if (dedupe?.[dedupeKey]) return;+ const { screenityToken } = await chrome.storage.local.get([+ "screenityToken",+ ]);await fetch(`${API_BASE}/transcription/queue`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: {+ "Content-Type": "application/json",+ ...(screenityToken+ ? { Authorization: `Bearer ${screenityToken}` }+ : {}),+ },credentials: "include",body: JSON.stringify({- input: uploadMeta.audio.url,output: `transcriptions/${uploadMeta.audio.mediaId}.json`,videoId: projectId,sceneId: uploadMeta.sceneId,@@ -3563,12 +4025,9 @@ const CloudRecorder = () => {useEffect(() => {const onHide = (event) => {- // Only finalize if the page is actually being unloaded (persisted = false)- // Don't finalize just because the tab went to background- // event.persisted indicates if the page might be restored from bfcache+ // event.persisted means the page may come back via bfcache; don't finalize then.const isActualUnload = !event.persisted;- // Only finalize if an active recording really existsconst hasActiveRecorder =screenRecorder.current?.state === "recording" ||cameraRecorder.current?.state === "recording" ||@@ -3592,7 +4051,6 @@ const CloudRecorder = () => {unloadGuardRef.current.stopTriggeredFromUnload = true;emitAbandonedOnUnloadOnce("pagehide");console.warn("⚠️ Recorder page unloading — finalizing");- // Use sendBeacon or sync storage write for reliabilitynavigator.sendBeacon?.(`${API_BASE}/log/recorder-unload`,JSON.stringify({ reason: "pagehide", ts: Date.now() }),@@ -3615,7 +4073,7 @@ const CloudRecorder = () => {visibilityChangedAt: Date.now(),});} else if (document.visibilityState === "visible") {- // Force stall-recovery on uploaders - in-tab heartbeat may have been throttled while hidden.+ // In-tab heartbeat may have been throttled while hidden; force stall-recovery.try {const now = Date.now();const staleThreshold = 10_000;@@ -3668,6 +4126,7 @@ const CloudRecorder = () => {};screenUploader.current?.pause?.();cameraUploader.current?.pause?.();+ audioUploader.current?.pause?.();void emitUploadTelemetry("upload_stalled", {reason: "network-offline",uploaderType: "cloud_recorder",@@ -3706,6 +4165,12 @@ const CloudRecorder = () => {) {cameraUploader.current.resume();}+ if (+ audioUploader.current &&+ RESUMABLE_UPLOADER_STATUSES.has(audioUploader.current.status)+ ) {+ audioUploader.current.resume();+ }void emitUploadTelemetry("upload_resumed", {reason: "network-online",uploaderType: "cloud_recorder",@@ -3738,7 +4203,7 @@ const CloudRecorder = () => {useEffect(() => {return () => {stopAllIntervals();- stopTabKeepAlive(); // Clean up keep-alive on unmount+ stopTabKeepAlive();};}, []);@@ -3845,7 +4310,6 @@ const CloudRecorder = () => {"recordingType",]);- // Check if cameraFlipped is set in storage, then pass it in payloadconst { cameraFlipped } = await chrome.storage.local.get(["cameraFlipped"]);let insertAfterSceneId = null;@@ -3855,7 +4319,6 @@ const CloudRecorder = () => {insertAfterSceneId = activeSceneId;}- // Validate uploadMeta has required dataif (!uploadMeta.sceneId) {throw new Error("Missing sceneId in uploadMeta");}@@ -3876,15 +4339,10 @@ const CloudRecorder = () => {projectId,sceneId,});- await ensureMediaLinked({- projectId,- sceneId,- mediaIds: [- uploadMeta.screen?.mediaId,- uploadMeta.camera?.mediaId,- uploadMeta.audio?.mediaId,- ],- });+ // No ensureMediaLinked call here: /api/bunny/videos already+ // stamped each media's `usedIn` at TUS init time, and the prior+ // /scenes/ POST already cleared `recoveryState`. PATCH was a+ // no-op + a post-stop hang risk in the dying cloudrecorder tab.await removePendingScene(sceneId);await markSceneComplete(sceneId);await setPipelineState("scene-reused", {@@ -3941,15 +4399,30 @@ const CloudRecorder = () => {domain: recordedTabDomain || null,};- const res = await fetch(`${API_BASE}/videos/${projectId}/scenes`, {- method: "POST",- headers: { "Content-Type": "application/json" },- credentials: "include",- body: JSON.stringify(payload),- });+ // Forward to the editor tab via BG; editor performs the POST itself+ // (same-origin cookie auth, no CORS, no SW lifecycle race). MV3 SW+ // fetches hang indefinitely when dispatched from the cloud recorder+ // during its post-stop teardown; the editor's tab outlives it.+ let swRes;+ try {+ swRes = await chrome.runtime.sendMessage({+ type: "forward-create-scene",+ projectId,+ payload,+ });+ } catch (err) {+ swRes = { ok: false, error: err?.message || String(err) };+ }+ if (!swRes) swRes = { ok: false, error: "no-bg-response" };+ const res = {+ ok: !!swRes?.ok,+ status: swRes?.status ?? 0,+ text: async () => swRes?.text || swRes?.error || "",+ json: async () => swRes?.body ?? null,+ };if (!res.ok) {- const errorText = await res.text();+ const errorText = swRes?.text || swRes?.error || "";const recoverResult = await recoverScene({projectId,sceneId,@@ -3996,15 +4469,11 @@ const CloudRecorder = () => {}} else {await setSceneCreateStatus(sceneId, "created");- await ensureMediaLinked({- projectId,- sceneId,- mediaIds: [- uploadMeta.screen?.mediaId,- uploadMeta.camera?.mediaId,- uploadMeta.audio?.mediaId,- ],- });+ // No ensureMediaLinked call here: /api/bunny/videos already+ // stamped each media's `usedIn` at TUS init time, and the+ // /scenes/ POST that just succeeded already cleared+ // `recoveryState`. PATCH was a no-op + a post-stop hang risk+ // in the dying cloudrecorder tab.await removePendingScene(sceneId);await markSceneComplete(sceneId);await setPipelineState("scene-created", {@@ -4041,10 +4510,9 @@ const CloudRecorder = () => {return { [sceneOutcome || "created"]: true };};- // Check if audio is silent to skip transcriptionconst isAudioSilent = async (audioBlob, silenceThreshold = 0.01) => {const arrayBuffer = await audioBlob.arrayBuffer();- const audioCtx = new OfflineAudioContext(1, 44100 * 40, 44100); // up to 40s+ const audioCtx = new OfflineAudioContext(1, 44100 * 40, 44100);const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);const channelData = audioBuffer.getChannelData(0);@@ -4055,12 +4523,12 @@ const CloudRecorder = () => {}const avg = total / channelData.length;- return avg < silenceThreshold; // true if basically silent+ return avg < silenceThreshold;};const stopRecording = async (shouldFinalize = true, reason = "unknown") => {if (isFinishing.current || sentLast.current) return;- // Lock immediately to prevent duplicate stop/finalize races under unload pressure.+ // Lock immediately: prevents duplicate stop/finalize races under unload pressure.isFinishing.current = true;clearPendingStart();@@ -4097,7 +4565,6 @@ const CloudRecorder = () => {keepAliveInterval.current = null;}- // Stop the silent audio keep-alive since we're done recordingstopTabKeepAlive();const { projectId, recordingToScene, multiMode } =@@ -4110,15 +4577,15 @@ const CloudRecorder = () => {await persistSessionState({ status: "stopping" });if (shouldFinalize && reason !== "retry-finalize") {- // Skip on retry-finalize: editor tab is already open from the first attempt.- // Re-sending would open a duplicate tab or reload the editor mid-session.+ // retry-finalize: editor tab is already open from the first attempt; resending+ // would open a duplicate or reload it mid-session.if (recordingToScene) {chrome.runtime.sendMessage({type: "prepare-editor-existing",multiMode: multiMode,});} else if (!multiMode && !recordingToScene && projectId) {- // Opening /editor/null on cancelled-before-create yields a broken page.+ // /editor/null on cancelled-before-create yields a broken page.chrome.runtime.sendMessage({type: "prepare-open-editor",projectId,@@ -4146,11 +4613,11 @@ const CloudRecorder = () => {const uploadMeta = {screen: screenUploader.current?.getMeta() || null,camera: cameraUploader.current?.getMeta() || null,- audio: null,- // use sceneId as per the metadata in screenUploader or cameraUploader, whichever exists+ audio: audioUploader.current?.getMeta() || null,sceneId:screenUploader.current?.getMeta()?.sceneId ||cameraUploader.current?.getMeta()?.sceneId ||+ audioUploader.current?.getMeta()?.sceneId ||sceneId,};uploadMetaRef.current = uploadMeta;@@ -4172,9 +4639,7 @@ const CloudRecorder = () => {});try {await chrome.storage.local.set({ sceneIdStatus: "cancelled" });- } catch {- // ignore- }+ } catch {}await finalizeRecorderSession("cancelled");await chunksStore.clear().catch((e) =>console.warn("[CloudRecorder] chunksStore.clear failed (cancelled-stop):", e),@@ -4210,6 +4675,30 @@ const CloudRecorder = () => {(result) => result.status === "rejected",);+ // Audio is supplementary: a dead mic mid-recording shouldn't block+ // scene creation. Finalize separately, never feed into+ // incompleteUploaders. On failure, clear uploadMeta.audio so the+ // scene isn't wired to a half-uploaded audio doc (which would+ // break playback and 400 the transcription queue precondition).+ if (audioUploader.current) {+ let audioFinalizeOk = true;+ try {+ await audioUploader.current.finalize?.();+ } catch (audioFinalizeErr) {+ audioFinalizeOk = false;+ console.warn(+ "⚠️ Audio uploader finalize failed; scene will be created without audio:",+ audioFinalizeErr,+ );+ logDebugEvent("audio-finalize-failed", {+ error: audioFinalizeErr?.message || String(audioFinalizeErr),+ });+ }+ const audioMeta = audioUploader.current?.getMeta?.() || null;+ uploadMeta.audio =+ audioFinalizeOk && audioMeta?.status === "completed" ? audioMeta : null;+ }+const screenMeta = screenUploader.current?.getMeta?.() || null;const cameraMeta = cameraUploader.current?.getMeta?.() || null;const incompleteUploaders = [];@@ -4287,7 +4776,6 @@ const CloudRecorder = () => {return;}- // Validate that at least one media source was successfully uploadedconst hasAnyScreenData = (uploadMeta.screen?.offset || 0) > 0;const hasAnyCameraData = (uploadMeta.camera?.offset || 0) > 0;const hasValidScreen =@@ -4299,7 +4787,6 @@ const CloudRecorder = () => {uploadMeta.camera?.mediaId &&uploadMeta.camera?.videoId;- // Warn if upload size seems suspiciously small for recording durationconst screenDuration = durations.screen || 0;const cameraDuration = durations.camera || 0;const fallbackSeconds = durations.fallbackMs@@ -4320,7 +4807,7 @@ const CloudRecorder = () => {};if (hasValidScreen && effectiveScreenDuration > 5) {const screenOffset = uploadMeta.screen?.offset || 0;- const minExpectedSize = effectiveScreenDuration * 50000; // ~50KB/sec minimum+ const minExpectedSize = effectiveScreenDuration * 50000;if (screenOffset < minExpectedSize) {console.warn(`⚠️ Screen upload size (${screenOffset} bytes) seems small for ${effectiveScreenDuration}s recording. Expected at least ${minExpectedSize} bytes.`,@@ -4335,7 +4822,7 @@ const CloudRecorder = () => {const cameraOffset = uploadMeta.camera?.offset || 0;const screenError = uploadMeta.screen?.error || "none";const cameraError = uploadMeta.camera?.error || "none";- // If we see bytes on Bunny (offset > 0) but status is not completed, treat as success with a warning.+ // Bytes on Bunny but not "completed" status: proceed with a warning.if (hasAnyScreenData || hasAnyCameraData) {console.warn("Uploads have data but were not marked completed. Proceeding with scene creation.",@@ -4359,7 +4846,6 @@ const CloudRecorder = () => {}}- // Create final audio blob from durable store when available.const audioBlob = await buildAudioBlobFromDurableStore();const silent = audioBlob ? await isAudioSilent(audioBlob) : true;@@ -4403,27 +4889,17 @@ const CloudRecorder = () => {if (!sentLast.current) {sentLast.current = true;try {- await createSceneOrHandleMultiMode(uploadMeta, usedDurations, silent);-- const result = await handleAudioUpload(- audioBlob,- projectId,- uploadMeta,- );- uploadMeta.audio = result;- chrome.storage.local.set({ uploadMeta });-- if (result?.mediaId) {- await ensureMediaLinked({- projectId,- sceneId: uploadMeta.sceneId,- mediaIds: [uploadMeta.audio?.mediaId],- });+ // Fire-and-forget transcription queue: not awaited so it doesn't+ // extend the cloudrecorder's post-stop tail. The fetch dispatches+ // synchronously into Chrome's network stack, so the request leaves+ // the page even if window.close fires shortly after.+ if (!silent && uploadMeta.audio?.mediaId) {+ handleTranscription(uploadMeta, projectId).catch((err) =>+ console.warn("[CloudRecorder] handleTranscription failed:", err),+ );}- if (!silent && audioBlob) {- await handleTranscription(uploadMeta, projectId);- }+ await createSceneOrHandleMultiMode(uploadMeta, usedDurations, silent);chrome.runtime.sendMessage({ type: "video-ready", uploadMeta });if (localScreenPlaybackOfferRef.current?.offerId) {@@ -4450,7 +4926,9 @@ const CloudRecorder = () => {sceneId: uploadMeta.sceneId,mediaId: uploadMeta.screen?.mediaId || uploadMeta.camera?.mediaId || null,});- await finalizeRecorderSession("completed");+ await finalizeRecorderSession("completed", {+ keepOpfsSession: Boolean(localScreenPlaybackOfferRef.current?.offerId),+ });void emitUploadTelemetry("upload_complete_client", {projectId,sceneId: uploadMeta.sceneId,@@ -4468,7 +4946,6 @@ const CloudRecorder = () => {} catch (err) {console.error("❌ Failed to create scene:", err);- // Provide user-friendly error message based on the error typelet userMessage = "Failed to save recording: ";if (err.message.includes("No data uploaded") ||@@ -4513,8 +4990,7 @@ const CloudRecorder = () => {status: err.message,});- // Still close the window even on error to prevent stuck tabs- // Give user time to see the error message+ // Close anyway to prevent stuck tabs; delay so user sees the error.setTimeout(() => {if (!IS_IFRAME_CONTEXT) {try {@@ -4530,9 +5006,7 @@ const CloudRecorder = () => {);try {await chrome.storage.local.set({ sceneIdStatus: "failed" });- } catch {- // ignore- }+ } catch {}await finalizeRecorderSession("failed");await clearAudioChunkStore("scene-error");await clearCameraChunkStore("scene-error");@@ -4590,7 +5064,6 @@ const CloudRecorder = () => {err2,);- // Optional: small non-fatal UI signalchrome.runtime.sendMessage({type: "show-toast",message:@@ -4650,8 +5123,6 @@ const CloudRecorder = () => {streamOpts.canRequestAudioTrack !== false;const useDisplayMedia = !!streamOpts.useDisplayMedia;const prewarmedStream = streamOpts.prewarmedStream || null;- // Defaulting quality for now- //const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);const { width = 1920, height = 1080 } = getResolutionForQuality() || {};const { fpsValue } = await chrome.storage.local.get(["fpsValue"]);@@ -4672,6 +5143,14 @@ const CloudRecorder = () => {};recordingType.current = data.recordingType || "screen";+ // Snapshot audio intent from BG's startStreaming payload. Reading+ // micActive from storage later races with ContentState's fresh-state+ // auto-default in the content script, which can flip an explicit+ // false back to true. BG reads these before that race window.+ audioIntent.current = {+ micActive: data.micActive === true,+ systemAudio: data.systemAudio === true,+ };try {const { cameraActive } = await chrome.storage.local.get(["cameraActive"]);@@ -4690,8 +5169,10 @@ const CloudRecorder = () => {try {const constraints = {preferCurrentTab: true,+ // Crop target is tied to this tab's DOM; surface switching breaks it.+ surfaceSwitching: "exclude",video: {- width: { max: 2560 }, // or use getResolutionForQuality()+ width: { max: 2560 },height: { max: 1440 },frameRate: { ideal: 30, max: 60 },},@@ -4754,10 +5235,8 @@ const CloudRecorder = () => {);cameraStream.current = null;- // keep UI consistent (optional)await chrome.storage.local.set({ cameraActive: false });- // only fatal if the user is doing camera-only recordingif (data.recordingType === "camera") {sendRecordingError("Camera permission is blocked. Please allow camera access to record.",@@ -4782,41 +5261,66 @@ const CloudRecorder = () => {return;}} else {- // Offscreen has no viewport - window.innerWidth/Height are 0, so fall back to quality dimensions.- const safeInnerWidth =- typeof window !== "undefined" && window.innerWidth- ? window.innerWidth- : width;- const safeInnerHeight =- typeof window !== "undefined" && window.innerHeight- ? window.innerHeight- : height;- const tabWidth = isTab.current ? safeInnerWidth : width;- const tabHeight = isTab.current ? safeInnerHeight : height;-- const videoConstraints = isTab.current- ? IS_OFFSCREEN_HOST- ? {- // Offscreen can't measure the tab - let Chrome pick sizing or it throws OverconstrainedError.- chromeMediaSource: "tab",- chromeMediaSourceId: id,- maxFrameRate: fps,+ // tab capture defaults to 1920x1080 and pillarboxes narrower tabs,+ // so probe the tab's real viewport and lock min/max to its aspect+ // (offscreen host has to proxy via "get-tab-viewport" since it+ // can't call chrome.scripting directly)+ let videoMaxW = null;+ let videoMaxH = null;+ if (isTab.current && recordingTabId.current) {+ let viewport = null;+ try {+ if (IS_OFFSCREEN_HOST) {+ const response = await chrome.runtime+ .sendMessage({+ type: "get-tab-viewport",+ tabId: recordingTabId.current,+ })+ .catch(() => null);+ if (response?.ok && response.width > 0 && response.height > 0) {+ viewport = { width: response.width, height: response.height };}- : {- chromeMediaSource: "tab",- chromeMediaSourceId: id,- maxFrameRate: fps,- maxWidth: tabWidth,- maxHeight: tabHeight,+ } else {+ const results = await chrome.scripting.executeScript({+ target: { tabId: recordingTabId.current },+ func: () => ({+ w: Math.round(window.innerWidth * (window.devicePixelRatio || 1)),+ h: Math.round(window.innerHeight * (window.devicePixelRatio || 1)),+ }),+ });+ const r = results?.[0]?.result;+ if (r && r.w > 0 && r.h > 0) {+ viewport = { width: r.w, height: r.h };}- : {- // Desktop/window recording - use quality settings as max bounds- chromeMediaSource: "desktop",- chromeMediaSourceId: id,- maxWidth: width,- maxHeight: height,- maxFrameRate: fps,- };+ }+ } catch {}+ if (viewport) {+ const tabW = viewport.width;+ const tabH = viewport.height;+ // cap to the quality limit while keeping the tab's aspect ratio.+ // chrome won't upscale, so smaller tabs resolve to native size.+ const fitScale = Math.min(width / tabW, height / tabH, 1);+ videoMaxW = Math.max(2, Math.round(tabW * fitScale));+ videoMaxH = Math.max(2, Math.round(tabH * fitScale));+ if (videoMaxW % 2) videoMaxW -= 1;+ if (videoMaxH % 2) videoMaxH -= 1;+ }+ }++ const videoConstraints = {+ chromeMediaSource: isTab.current ? "tab" : "desktop",+ chromeMediaSourceId: id,+ maxFrameRate: fps,+ };+ if (videoMaxW && videoMaxH) {+ videoConstraints.maxWidth = videoMaxW;+ videoConstraints.maxHeight = videoMaxH;+ videoConstraints.minWidth = videoMaxW;+ videoConstraints.minHeight = videoMaxH;+ } else if (!isTab.current) {+ videoConstraints.maxWidth = width;+ videoConstraints.maxHeight = height;+ }const desktopConstraints = {audio: canCaptureSourceAudio@@ -4846,7 +5350,7 @@ const CloudRecorder = () => {window.__screenityPrewarmedTabStream = null;}} else if (useDisplayMedia) {- // Aliases to avoid TDZ with the later `const {width, height}` destructuring.+ // Alias to avoid TDZ with the later `const {width, height}` destructuring.const targetFps = fps;const targetWidth = width;const targetHeight = height;@@ -4909,7 +5413,7 @@ const CloudRecorder = () => {width: _actualStreamWidth,height: _actualStreamHeight,displaySurface: surface,- } = track.getSettings(); // Always use displaySurface from track+ } = track.getSettings();const settings = screenStream.current.getVideoTracks()[0]@@ -4917,7 +5421,6 @@ const CloudRecorder = () => {traceStep("streamAcquired", { surface: surface || null });- // Show "Preparing..." on the user's page while API calls run.setTimeout(() => {traceStep("preparingSent");chrome.runtime.sendMessage({ type: "preparing-recording" });@@ -4978,7 +5481,7 @@ const CloudRecorder = () => {stack: err?.stack || null,},}).catch(() => {});- // Offscreen tab-mode fallback: pre-acquired streamId failed - retry with getDisplayMedia.+ // Offscreen tab-mode: pre-acquired streamId failed; retry with getDisplayMedia.if (IS_OFFSCREEN_HOST &&isTab.current &&@@ -5053,10 +5556,8 @@ const CloudRecorder = () => {);cameraStream.current = null;- // keep UI consistent (optional)await chrome.storage.local.set({ cameraActive: false });- // only fatal if the user is doing camera-only recordingif (data.recordingType === "camera") {sendRecordingError("Camera permission is blocked. Please allow camera access to record.",@@ -5069,11 +5570,36 @@ const CloudRecorder = () => {setInitProject(true);- // Try to get microphone accessmicStream.current = await startAudioStream(data.defaultAudioInput);rawMicStream.current = micStream.current;- // Setup audio context and routing+ // Mic track death mid-recording (unplug, OS revoke, BT disconnect): toast only,+ // since Pro recordings often have system audio worth keeping.+ try {+ const rawTrack = rawMicStream.current?.getAudioTracks?.()[0];+ if (rawTrack) {+ rawTrack.addEventListener("ended", () => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "cloudrecorder-mic-track-ended",+ data: {+ trackLabel: String(rawTrack?.label || "").slice(0, 80),+ readyState: rawTrack?.readyState || null,+ },+ });+ } catch {}+ try {+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "stream-ended",+ why: chrome.i18n.getMessage("audioTrackEndedToast"),+ });+ } catch {}+ });+ }+ } catch {}+aCtx.current = new AudioContext();destination.current = aCtx.current.createMediaStreamDestination();@@ -5100,7 +5626,6 @@ const CloudRecorder = () => {.connect(audioOutputGain.current).connect(destination.current);- // Set initial system audio volume based on preferencesconst { systemAudioVolume } = await chrome.storage.local.get(["systemAudioVolume",]);@@ -5110,7 +5635,6 @@ const CloudRecorder = () => {}try {- // Try to get projectId from storage - this may have been set externallyconst { projectId, multiMode, multiProjectId, multiSceneCount } =await chrome.storage.local.get(["projectId",@@ -5120,6 +5644,7 @@ const CloudRecorder = () => {]);let videoId = projectId || multiProjectId;+ const reusedProject = Boolean(videoId);if (videoId) {if (multiMode) {@@ -5151,6 +5676,14 @@ const CloudRecorder = () => {await chrome.storage.local.set({ projectId: videoId });traceStep("apiProjectCreated");+ void emitUploadTelemetry("project_state_change", {+ source: reusedProject+ ? "cloudrecorder-reused"+ : "cloudrecorder-created",+ from: projectId || null,+ to: videoId,+ multiMode: Boolean(multiMode),+ });await setPipelineState("project-ready", {projectId: videoId,status: multiMode ? "multi" : "single",@@ -5168,6 +5701,11 @@ const CloudRecorder = () => {setStarted(true);setInitProject(false);+ if (screenStream.current) {+ await stopPrewarm(prewarmRef.current);+ prewarmRef.current = startPrewarm(screenStream.current);+ preloadWebCodecsModules();+ }traceStep("resetActiveTabSent");chrome.runtime.sendMessage({ type: "reset-active-tab" });if (pendingStartRef.current) {@@ -5183,6 +5721,11 @@ const CloudRecorder = () => {};const startStreaming = async (data) => {+ if (startStreamingInFlight.current) {+ console.warn("[CloudRecorder] startStreaming already in flight, ignoring duplicate");+ return;+ }+ startStreamingInFlight.current = true;startTabKeepAlive();if (document.visibilityState === "hidden") {@@ -5201,13 +5744,10 @@ const CloudRecorder = () => {});if (isTab.current) {- // Wait for getStreamID to resolve regardless of recordingType — the- // previous guard (data.recordingType !== "region") caused startStream- // to be called with tabID.current = null for region tab-captures when- // getStreamID hadn't resolved yet.+ // Wait for getStreamID across all recordingTypes: an earlier guard skipped+ // region tab-captures and started with tabID.current = null.let attempts = 0;while (!tabID.current && attempts < 20) {- // wait for tab stream id to resolve// eslint-disable-next-line no-await-in-loopawait new Promise((resolve) => setTimeout(resolve, 50));attempts += 1;@@ -5221,7 +5761,7 @@ const CloudRecorder = () => {if (data.recordingType === "camera") {startStream(data, null, permissions, permissions2);} else if (IS_OFFSCREEN_HOST && isTab.current && tabID.current) {- // Pre-acquired tab streamId from action-icon click - frictionless path; picker fallback in catch.+ // Pre-acquired tab streamId from action-icon click; picker fallback in catch.console.log("[CloudRecorder][offscreen] using pre-acquired tab streamId");startStream(data, tabID.current, permissions, permissions2);} else if (IS_OFFSCREEN_HOST) {@@ -5229,11 +5769,8 @@ const CloudRecorder = () => {useDisplayMedia: true,});} else if (!isTab.current && (data.recordingType != "region" || tabPreferred.current)) {- // Show the desktop picker when:- // - not tab-capture mode AND not region recording, OR- // - tabPreferred=true (playground) forced isTab=false even for a region- // recording — in that case we still need the picker because there is- // no pre-obtained stream ID to pass to startStream.+ // Desktop picker path: non-tab mode without region, or tabPreferred forced+ // isTab=false (playground) so there's no pre-obtained streamId.{chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab", "audio"],@@ -5259,7 +5796,7 @@ const CloudRecorder = () => {try {let streamId;if (IS_OFFSCREEN_HOST) {- // chrome.tabCapture is not callable from offscreen - delegate to SW.+ // chrome.tabCapture is not callable from offscreen; delegate to SW.const response = await chrome.runtime.sendMessage({type: "offscreen-request-stream",@@ -5285,7 +5822,6 @@ const CloudRecorder = () => {useEffect(() => {if (!IS_IFRAME_CONTEXT) return;- // Notify parent that the region capture iframe has loadedconst sendReady = () => {window.parent.postMessage({ type: "screenity-region-capture-loaded" },@@ -5306,7 +5842,7 @@ const CloudRecorder = () => {regionWidth.current = event.data.width;regionHeight.current = event.data.height;} else if (event.data.type === "restart-recording") {- // Legacy path: restart is now orchestrated via runtime message.+ // Legacy: restart is now orchestrated via runtime message.void setCloudRestartPhase("restart-postmessage-ignored");}};@@ -5319,7 +5855,6 @@ const CloudRecorder = () => {function getActiveVideoTime() {const now = Date.now();- // Choose whichever timer is runningconst timer = screenTimer.current.start? screenTimer: cameraTimer.current.start@@ -5337,17 +5872,14 @@ const CloudRecorder = () => {setInitProject(false);backupRef.current = request.backup;if (IS_IFRAME_CONTEXT) {- // Skip payloads targeted at offscreen - otherwise both contexts race to acquire the stream.+ // 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" });}} else if (!request.region || (IS_OFFSCREEN_HOST && request.isTab)) {- // If the background included tabPreferred in the message, apply it- // synchronously before we use it — this eliminates a race where- // chrome.storage.local.get(["tabPreferred"]) hasn't completed yet when- // "loaded" arrives, causing isTab.current to be set incorrectly on the- // first attempt from playground.html.+ // Apply tabPreferred synchronously: chrome.storage.local.get races against+ // "loaded" and would set isTab.current incorrectly on the first playground attempt.if (typeof request.tabPreferred === "boolean") {tabPreferred.current = request.tabPreferred;console.info(@@ -5371,13 +5903,17 @@ const CloudRecorder = () => {}} else if (request.type === "streaming-data") {if (!isInit.current) return;- if (IS_IFRAME_CONTEXT) {- if (regionRef.current) {- startStreaming(JSON.parse(request.data));- }- } else if (!regionRef.current || (IS_OFFSCREEN_HOST && isTab.current)) {- startStreaming(JSON.parse(request.data));- }+ // Dedup: SW push + tab pull both deliver this by design.+ // Only mark received once we actually take the call, otherwise an+ // ignored delivery in the wrong context blocks the right one.+ const willHandle =+ (IS_IFRAME_CONTEXT && regionRef.current) ||+ (!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));} else if (request.type === "start-recording-tab") {if (!isInit.current) return;@@ -5443,6 +5979,8 @@ const CloudRecorder = () => {Promise.resolve(),cameraUploader.current?.waitForPendingUploads?.() ??Promise.resolve(),+ audioUploader.current?.waitForPendingUploads?.() ??+ Promise.resolve(),]);await Promise.race([drainPromise,@@ -5466,14 +6004,13 @@ const CloudRecorder = () => {setAudioOutputVolume(request.volume);} else if (request.type === "get-video-time") {if (!isInit.current) return;- const videoTime = getActiveVideoTime() / 1000; // in seconds+ const videoTime = getActiveVideoTime() / 1000;sendResponse({ videoTime });return true;} else if (request.type === "pause-recording-tab") {if (!isInit.current) return;if (pausedStateRef.current) return;- // Pause all active recordersif (screenRecorder.current &&screenRecorder.current.state === "recording"@@ -5515,7 +6052,6 @@ const CloudRecorder = () => {if (!isInit.current) return;if (!pausedStateRef.current) return;- // Resume all paused recordersif (screenRecorder.current && screenRecorder.current.state === "paused") {screenRecorder.current.resume();}diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.jsindex 7d1878c..63cd67c 100644--- a/src/pages/CloudRecorder/bunnyTusUploader.js+++ b/src/pages/CloudRecorder/bunnyTusUploader.js@@ -56,7 +56,7 @@ export async function getThumbnailFromBlob(blob, seekTo = 0.1) {export default class BunnyTusUploader {constructor(options = {}) {- this.CHUNK_SIZE = options.chunkSize || 512 * 1024; // 512KB default+ this.CHUNK_SIZE = options.chunkSize || 512 * 1024;this.MAX_RETRIES = options.maxRetries || 5;this.RETRY_DELAY = options.retryDelay || 1000;this.UPLOAD_TIMEOUT_MS = options.uploadTimeoutMs || 20000;@@ -69,6 +69,13 @@ export default class BunnyTusUploader {this.onTelemetry = options.onTelemetry || null;this.onStateChange = options.onStateChange || null;this.trackType = options.trackType || 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+ // stays on webm.+ this.container = options.container || "video/webm";+ this.codec = options.codec || null;+ this.encoderKind = options.encoderKind || null;this.totalBytes = 0;this.uploadUrl = null;@@ -94,7 +101,7 @@ export default class BunnyTusUploader {this.isProcessingQueue = false;this.queueProcessingPromise = null;this.queuedBytes = 0;- this._hasExtractedMeta = true; // Skip in-flight thumbnail extraction to avoid timeouts/noise+ this._hasExtractedMeta = true;this.sessionId = options.sessionId || null;this.journalKey = null;this.journalLookupKey = null;@@ -120,6 +127,11 @@ export default class BunnyTusUploader {this.hasEmittedFirstByte = false;this.lastProgressEventAt = 0;this.initializedFromResume = false;+ // Bytes from write() calls that arrived after finalize() locked us+ // out. Tracked so finalize() can refuse to mark the upload completed+ // instead of silently truncating; the throw inside write() is+ // unobserved because MediaRecorder.ondataavailable is fire-and-forget.+ this.bytesLostAfterFinalize = 0;}debugLog(message, payload = null) {@@ -138,7 +150,7 @@ export default class BunnyTusUploader {emitTelemetry(event, payload = {}) {if (typeof this.onTelemetry !== "function") return;try {- this.onTelemetry(event, {+ const body = {projectId: this.projectId || null,sceneId: this.sceneId || null,recordingSessionId: this.sessionId || null,@@ -150,13 +162,27 @@ export default class BunnyTusUploader {offset: this.offset || 0,totalBytes: this.totalBytes || 0,queuedBytes: this.queuedBytes || 0,+ codec: this.codec || null,+ container: this.container || null,+ encoderKind: this.encoderKind || null,...payload,- });+ };+ this.onTelemetry(event, body);} catch (err) {console.warn("Upload telemetry callback failed:", err);}}+ // The encoder's emitted codec can differ from what was requested at+ // construction (HW encoders re-derive profile/level from the SPS).+ // Call after the first chunk so telemetry and /bunny/save-upload-meta+ // carry the actual values.+ updateEncoderInfo({ codec, container, encoderKind } = {}) {+ if (typeof codec === "string" && codec) this.codec = codec;+ if (typeof container === "string" && container) this.container = container;+ if (typeof encoderKind === "string" && encoderKind) this.encoderKind = encoderKind;+ }+notifyStateChange(reason = null, extra = {}) {if (typeof this.onStateChange !== "function") return;try {@@ -175,6 +201,8 @@ export default class BunnyTusUploader {this.error = errorCode || err?.message || "upload-error";this.lastErrorAt = Date.now();this.lastErrorCode = errorCode || null;+ // resume() restarts.+ this.stopHeartbeat();this.emitTelemetry("upload_error", {errorCode: errorCode || null,message: err?.message || this.error || "upload-error",@@ -415,6 +443,18 @@ export default class BunnyTusUploader {error: err?.message || err,mediaId: this.mediaId,});+ // Journal write failure (quota, transient I/O). Halt the uploader so+ // a crash+resume doesn't replay bytes from the stale on-disk offset.+ this.stalled = true;+ this.lastErrorAt = Date.now();+ this.lastErrorCode = "JOURNAL_PERSIST_FAILED";+ this.error = String(err?.message || err).slice(0, 200);+ try {+ this.notifyStateChange("journal-persist-failed");+ } catch {+ // notifyStateChange itself shouldn't fail, but if it does the+ // stalled flag above is the load-bearing signal.+ }}}@@ -613,7 +653,6 @@ export default class BunnyTusUploader {this.lastErrorCode = null;this.initializedFromResume = false;- // Build fingerprint for resume journal matchingconst fingerprint = this.buildFingerprint({projectId,sceneId,@@ -623,7 +662,6 @@ export default class BunnyTusUploader {});this.fingerprint = fingerprint;- // Attempt to locate a resume journal candidate from storageconst resumeJournal = await this.getResumeJournal({projectId,sceneId,@@ -632,7 +670,6 @@ export default class BunnyTusUploader {reuse,});- // Validate reuse object if providedif (reuse) {if (!reuse.videoId || !reuse.mediaId) {throw new Error(@@ -785,14 +822,13 @@ export default class BunnyTusUploader {}async refreshTusAuth() {- // Prefer stored screenityToken for authconst token = this.userToken || (await chrome.storage.local.get(["screenityToken"]).then(r => r.screenityToken));const headers = token ? { Authorization: `Bearer ${token}` } : {};const url = `${API_BASE}/bunny/videos/tus-auth?videoId=${this.videoId}`;// Internal retry absorbs short backend blips (5xx/408/429/network) so they// don't burn the outer uploadChunk retry budget. Fatal auth errors- // (400/401/403) are surfaced immediately — no recovery possible.+ // (400/401/403) are surfaced immediately, no recovery possible.const MAX_ATTEMPTS = 4;let lastStatus = null;let lastErr = null;@@ -863,7 +899,7 @@ export default class BunnyTusUploader {AuthorizationExpire: String(this.expires),LibraryId: String(this.libraryId),VideoId: this.videoId,- "Upload-Metadata": `filetype ${btoa("video/webm")},title ${btoa(+ "Upload-Metadata": `filetype ${btoa(this.container || "video/webm")},title ${btoa(this.metadata.title,)}`,},@@ -871,9 +907,25 @@ export default class BunnyTusUploader {if (!res.ok) throw new Error("Failed to start TUS upload session");const location = res.headers.get("location");- this.uploadUrl = location.startsWith("/")+ const resolved = location.startsWith("/")? `https://video.bunnycdn.com${location}`: location;+ // Defense-in-depth: TUS Location header must stay on Bunny's host. Without+ // this, a redirect to attacker.com would receive subsequent PATCHes+ // carrying recording chunks plus the AuthorizationSignature header.+ try {+ const parsed = new URL(resolved);+ if (parsed.host !== "video.bunnycdn.com") {+ throw new Error(`Untrusted TUS location host: ${parsed.host}`);+ }+ } catch (err) {+ throw new Error(`Invalid TUS location: ${err?.message || err}`);+ }+ this.uploadUrl = resolved;++ // Persist BEFORE save-upload-meta: the local journal is the only recovery+ // path if the extension crashes before the backend records the URL.+ await this.persistUploadJournal({ force: true });if (this.userToken) {fetch(`${API_BASE}/bunny/videos/save-upload-meta`, {@@ -903,15 +955,17 @@ export default class BunnyTusUploader {expires: this.expires,});}- await this.persistUploadJournal({ force: true });}async write(chunk) {- if (this.isFinalizing) throw new Error("Cannot write during finalization");+ if (this.isFinalizing) {+ this.bytesLostAfterFinalize += chunk?.size || 0;+ this.setUploaderError("write-after-finalize");+ throw new Error("Cannot write during finalization");+ }if (this.isPaused) throw new Error("Uploader paused");if (!this.uploadUrl) throw new Error("Uploader not initialized");- // Check if we're in error stateif (this.status === "error") {throw new Error(`Uploader in error state: ${this.error}`);}@@ -932,17 +986,14 @@ export default class BunnyTusUploader {this.lastChunkQueuedAt = Date.now();this.scheduleJournalPersist();- // Always ensure queue is processingif (!this.isProcessingQueue) {this.queueProcessingPromise = this.processQueue();}- // Wait for current queue to finish processing these chunksif (this.queuedBytes > 10 * 1024 * 1024) {await this.waitForPendingUploads();}- // Thumbnail extraction disabled in-flight to reduce timeouts/noise.this._hasExtractedMeta = true;}@@ -995,14 +1046,34 @@ export default class BunnyTusUploader {this.currentPatchAbort = null;if (res.ok || res.status === 204) {- // Server is the source of truthconst serverOffsetHeader = res.headers.get("Upload-Offset");+ let nextOffset;if (serverOffsetHeader) {- this.offset = parseInt(serverOffsetHeader, 10);+ 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;+ if (+ !Number.isFinite(parsed) ||+ parsed < currentOffset ||+ parsed > expectedMin+ ) {+ this.setUploaderError("invalid-server-offset", {+ serverOffsetHeader,+ parsed,+ currentOffset,+ expectedMin,+ });+ throw new Error(+ `Invalid Upload-Offset from server: "${serverOffsetHeader}"`,+ );+ }+ nextOffset = parsed;} else {- // Fallback if Bunny doesn't return it for some reason- this.offset = currentOffset + data.length;+ nextOffset = currentOffset + data.length;}+ this.offset = nextOffset;this.lastServerOffset = this.offset;this.recordProgress(data.length);@@ -1010,7 +1081,7 @@ export default class BunnyTusUploader {} else {const errorText = await res.text();- // If the TUS session was invalidated (404), flag as fatal so callers can fall back.+ // Session invalidated; fatal so callers can fall back.if (res.status === 404) {this.status = "error";this.error = "tus-session-missing";@@ -1034,7 +1105,6 @@ export default class BunnyTusUploader {throw new Error("TUS session missing (404).");}- // Handle offset mismatch errors (409 Conflict)if (res.status === 409 ||errorText.toLowerCase().includes("offset")@@ -1043,10 +1113,23 @@ export default class BunnyTusUploader {`⚠️ Offset conflict detected (status ${res.status}), fetching current offset from server`,);- // Query server for current offset using HEAD request+ // Query server offset via HEAD. If it fails or returns garbage,+ // mark fatal: retrying with a stale offset loops on 409.try {const serverOffset = await this.getServerOffset();if (Number.isFinite(serverOffset) && serverOffset >= 0) {+ // Server offset must not be lower than what was sent;+ // if it is, server state is corrupted. Fail loudly.+ const priorOffset = this.offset;+ if (serverOffset < priorOffset - data.length) {+ this.setUploaderError("server-offset-regressed", {+ serverOffset,+ priorOffset,+ });+ throw new Error(+ `Server offset regressed (${serverOffset} < ${priorOffset})`,+ );+ }this.lastServerOffset = serverOffset;this.offset = serverOffset;this.totalBytes = Math.max(this.totalBytes || 0, serverOffset);@@ -1056,11 +1139,22 @@ export default class BunnyTusUploader {});this.scheduleJournalPersist({ force: true });- // Retry with corrected offsetcontinue;}+ // serverOffset null/NaN: HEAD response unparseable.+ this.setUploaderError("offset-conflict-head-unparseable", {+ priorOffset: this.offset,+ });+ throw new Error(+ "409 offset conflict but HEAD returned unparseable offset",+ );} catch (headErr) {- console.error("Failed to fetch server offset:", headErr);+ console.error(+ "Failed to fetch server offset during 409 recovery:",+ headErr,+ );+ this.setUploaderError("offset-conflict-head-failed", headErr);+ throw headErr;}}@@ -1068,7 +1162,7 @@ export default class BunnyTusUploader {}} catch (err) {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/429) retry forever with capped backoff.const isExplicitAbort =this.status === "aborted" || this.isPaused === true;if (isExplicitAbort) {@@ -1077,8 +1171,8 @@ export default class BunnyTusUploader {const msg = String(err?.message || "");const status = typeof err?.status === "number" ? err.status : null;const isTransient =- err?.name === "AbortError" || // timeout / stall-recovery- err?.name === "TypeError" || // fetch network failure+ err?.name === "AbortError" ||+ err?.name === "TypeError" ||(status !== null && (status >= 500 || status === 408 || status === 429)) ||/Upload failed \((?:5\d\d|408|429)\b/.test(msg) ||/network|Failed to fetch|timeout/i.test(msg);@@ -1097,14 +1191,50 @@ export default class BunnyTusUploader {? `transient retry #${attempt + 1}`: `attempt ${attempt + 1}/${this.MAX_RETRIES + 1}`;console.warn(`⚠️ Upload ${attemptLabel} failed, retrying...`, err.message);+ // Wait for online event before retrying so we don't burn retries+ // during the offline window. 5min cap ensures permanently+ // disconnected machines still surface a stall.+ if (typeof navigator !== "undefined" && navigator.onLine === false) {+ this.emitTelemetry("upload_offline_wait", {+ attempt,+ errorCode: msg.slice(0, 100),+ });+ await new Promise((resolve) => {+ const ONLINE_WAIT_CAP_MS = 5 * 60 * 1000;+ const onOnline = () => {+ cleanup();+ resolve();+ };+ const cap = setTimeout(() => {+ cleanup();+ resolve();+ }, ONLINE_WAIT_CAP_MS);+ const cleanup = () => {+ clearTimeout(cap);+ try {+ window.removeEventListener("online", onOnline);+ } catch {}+ };+ try {+ window.addEventListener("online", onOnline, { once: true });+ } catch {+ // Worker context: fall through to backoff.+ cleanup();+ resolve();+ }+ });+ if (typeof navigator !== "undefined" && navigator.onLine) {+ this.emitTelemetry("upload_back_online", { attempt });+ }+ }const jitter = Math.random() * 300;- // Cap backoff at 60s so offline→online reconnects retry within a minute.+ // 60s cap so offline→online reconnects retry within a minute.const baseDelay = Math.min(this.RETRY_DELAY * Math.pow(2, Math.min(attempt, 7)),60_000,);await new Promise((r) => setTimeout(r, baseDelay + jitter));- // Never trip the permanent-failure branch for transient errors.+ // Never let transient errors trip the permanent-failure branch.if (isTransient && attempt >= this.MAX_RETRIES) {attempt = this.MAX_RETRIES - 1;}@@ -1121,20 +1251,26 @@ export default class BunnyTusUploader {const chunk = this.chunkQueue.shift();this.queuedBytes -= chunk.size;- // Serialize uploads: wait for each chunk to complete before starting nexttry {await this.uploadChunk(chunk);} catch (err) {console.error("❌ Chunk upload failed in queue:", err);- // Put chunk back at front of queue for potential retrythis.chunkQueue.unshift(chunk);this.queuedBytes += chunk.size;- // Set error state- this.setUploaderError("queue-upload-failed", err);+ // Don't clobber a non-recoverable code that uploadChunk already+ // set (e.g. "offset-conflict-head-failed", "invalid-server-offset"),+ // otherwise resume() sees the recoverable "queue-upload-failed"+ // and loops forever.+ const nonRecoverableInner =+ this.lastErrorCode &&+ this.lastErrorCode !== "queue-upload-failed" &&+ this.lastErrorCode !== "chunk-upload-retries-exhausted";+ if (!nonRecoverableInner) {+ this.setUploaderError("queue-upload-failed", err);+ }- // Stop processing queue on errorbreak;}}@@ -1145,7 +1281,6 @@ export default class BunnyTusUploader {}async waitForPendingUploads() {- // Temporarily unpause to ensure all chunks are processedconst wasPaused = this.isPaused;if (wasPaused) {this.isPaused = false;@@ -1171,11 +1306,9 @@ export default class BunnyTusUploader {if (this.pendingUploads.length) {await Promise.all(this.pendingUploads);}- // Small delay to catch any race conditionsawait new Promise((r) => setTimeout(r, 100));}- // Restore pause state if it was pausedif (wasPaused) {this.isPaused = true;}@@ -1190,9 +1323,26 @@ export default class BunnyTusUploader {this.scheduleJournalPersist({ force: true });try {await this.waitForPendingUploads();++ if (this.bytesLostAfterFinalize > 0) {+ this.status = "error";+ this.error = `bytes-lost-during-finalize=${this.bytesLostAfterFinalize}`;+ this.lastErrorAt = Date.now();+ this.lastErrorCode = "finalize-bytes-lost";+ this.emitTelemetry("upload_error", {+ errorCode: "finalize-bytes-lost",+ bytesLost: this.bytesLostAfterFinalize,+ totalBytes: this.totalBytes,+ });+ this.scheduleJournalPersist({ force: true });+ throw new Error(+ `Finalize blocked: ${this.bytesLostAfterFinalize} bytes lost after finalize started.`,+ );+ }+await this.checkAuthExpiration();- // Re-validate offset with server to avoid partial finalization+ // Re-validate offset to avoid partial finalization.let serverOffset = null;try {const headRes = await fetch(this.uploadUrl, {@@ -1217,7 +1367,7 @@ export default class BunnyTusUploader {console.warn("⚠️ Failed HEAD before finalize:", err);}- // If server didn't receive everything, don't "finalize" into a ghost upload.+ // Don't finalize into a ghost upload if the server is short.if (serverOffset === null) {this.setUploaderError("finalize-offset-unverified");throw new Error("Finalize failed: could not verify server offset.");@@ -1267,7 +1417,7 @@ export default class BunnyTusUploader {);}- // Now we can safely complete the tus upload by declaring the final length+ // Complete the tus upload by declaring final length.const res = await fetch(this.uploadUrl, {method: "PATCH",headers: {@@ -1298,11 +1448,10 @@ export default class BunnyTusUploader {await this.clearUploadJournal();this.notifyStateChange("finalize-completed");} catch (err) {- // Reset the lock so a subsequent retry call can attempt finalize again.- // Without this reset, isFinalizing stays true permanently after any error,- // and every retry immediately throws "Already finalizing".+ // Reset the lock so retries can attempt finalize again. Without+ // this, every retry immediately throws "Already finalizing".this.isFinalizing = false;- console.warn("[BunnyTusUploader] finalize failed — isFinalizing reset for retry", {+ console.warn("[BunnyTusUploader] finalize failed, isFinalizing reset for retry", {trackType: this.trackType,error: err?.message || String(err),offset: this.offset,@@ -1343,23 +1492,39 @@ export default class BunnyTusUploader {}resume() {- if (this.isPaused) {- this.isPaused = false;- if (- this.status !== "completed" &&- this.status !== "error" &&- this.status !== "finalizing"- ) {- this.status = "uploading";- }- if (!this.isProcessingQueue && this.chunkQueue.length > 0) {- this.queueProcessingPromise = this.processQueue();- }- this.emitTelemetry("upload_resumed", {- reason: "client-resume",- });- this.scheduleJournalPersist();+ // Excludes codes that need re-init (tus-session-missing, finalize-*,+ // server-offset-0); those don't recover from a plain resume.+ const RECOVERABLE_ERROR_CODES = new Set([+ "queue-upload-failed",+ "chunk-upload-retries-exhausted",+ ]);+ const canRecoverFromError =+ this.status === "error" &&+ RECOVERABLE_ERROR_CODES.has(this.lastErrorCode);+ if (!this.isPaused && !canRecoverFromError) return;++ if (canRecoverFromError) {+ this.error = null;+ this.stalled = false;+ // Restart heartbeat (stopped by setUploaderError); idempotent.+ this.startHeartbeat();}+ this.isPaused = false;+ // Don't mask a non-recoverable error when isPaused + status="error" coexist.+ if (+ this.status !== "completed" &&+ this.status !== "finalizing" &&+ (this.status !== "error" || canRecoverFromError)+ ) {+ this.status = "uploading";+ }+ if (!this.isProcessingQueue && this.chunkQueue.length > 0) {+ this.queueProcessingPromise = this.processQueue();+ }+ this.emitTelemetry("upload_resumed", {+ reason: canRecoverFromError ? "error-recovery" : "client-resume",+ });+ this.scheduleJournalPersist();}async abort() {@@ -1383,10 +1548,42 @@ export default class BunnyTusUploader {startHeartbeat() {this.stopHeartbeat();this.lastProgressAt = Date.now();+ this.lastHeartbeatTickAt = Date.now();this.stalled = false;this.stallRecoveryInFlight = false;this.heartbeatTimer = setInterval(() => {const now = Date.now();+ // Sleep/wake: timers don't fire while asleep, but on wake fire+ // missed ticks back-to-back. Skip ticks whose wall-clock gap is+ // much shorter than HEARTBEAT_INTERVAL_MS, otherwise an 8hr sleep+ // stacks ~2880 ticks and each runs stall recovery, flooding+ // the network on wake.+ const sinceLastTick = now - (this.lastHeartbeatTickAt || 0);+ this.lastHeartbeatTickAt = now;+ if (sinceLastTick < Math.floor(this.HEARTBEAT_INTERVAL_MS * 0.5)) {+ return;+ }+ // Wake-jump: if tick-to-tick gap is dramatically larger than+ // expected, abort any in-flight PATCH hanging on a dead connection.+ // Without this, PATCH stays pending until UPLOAD_TIMEOUT_MS, delaying+ // recovery.+ if (+ sinceLastTick >+ Math.max(this.HEARTBEAT_INTERVAL_MS * 6, 60_000)+ ) {+ try {+ this.emitTelemetry("upload_wake_detected", {+ sinceLastTickMs: sinceLastTick,+ });+ } catch {}+ if (this.currentPatchAbort) {+ try {+ this.currentPatchAbort.abort("wake-jump");+ } catch {}+ this.currentPatchAbort = null;+ }+ }+const diff = now - this.lastProgressAt;if (diff > this.HEARTBEAT_LAG_MS) {this.stalled = true;@@ -1419,7 +1616,7 @@ export default class BunnyTusUploader {} catch {}this.currentPatchAbort = null;}- // Resync offset from server via HEAD so a partially-applied PATCH doesn't cause duplicate bytes.+ // Resync via HEAD so a partially-applied PATCH doesn't dup bytes.try {const res = await fetch(this.uploadUrl, {method: "HEAD",diff --git a/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.js b/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.jsnew file mode 100644index 0000000..1c5c3ec--- /dev/null+++ b/src/pages/CloudRecorder/encoder/WebCodecsTrackRecorder.js@@ -0,0 +1,189 @@+// MediaRecorder-shaped wrapper around WebCodecsRecorder so Cloud's+// existing recorder lifecycle (start/stop/pause/resume, ondataavailable,+// _pendingWrites drain) drives WebCodecs without a refactor. Muxer+// fragments come out as fMP4 Blobs through ondataavailable; uploader+// just sees Blobs. `state` mirrors the MediaRecorder string so existing+// comparisons in CloudRecorder.jsx still work.++import { WebCodecsRecorder } from "../../Recorder/webcodecs/WebCodecsRecorder";++const dispatchError = (cb, err) => {+ if (typeof cb !== "function") return;+ try {+ // Mirror MediaRecorder's onerror event shape just enough for callers+ // that read event.error.+ cb({ error: err instanceof Error ? err : new Error(String(err)) });+ } catch {}+};++export class WebCodecsTrackRecorder {+ constructor(stream, options = {}) {+ this.stream = stream;+ this.mimeType = options.mimeType || "video/mp4";+ this.videoBitsPerSecond =+ options.videoBitsPerSecond || 16_000_000;+ this.audioBitsPerSecond = options.audioBitsPerSecond || 128_000;+ this.enableAudio = options.enableAudio !== false; // default true+ // MediaRecorder-shape fields used by callers.+ this._state = "inactive";+ this.ondataavailable = null;+ this.onerror = null;+ this.onstop = null;+ // Cloud's stopAllRecorders awaits this set before finalize, so+ // late ondataavailable handlers can't race the upload finalize.+ this._pendingWrites = new Set();++ this._recorder = null;+ this._stopPromise = null;+ this._finalizedResolved = false;+ // Set when the recorder fully finalizes (all bytes flushed). stop()+ // resolves on this and then fires onstop.+ this._onFinalizedResolve = null;+ this._onFinalizedPromise = new Promise((resolve) => {+ this._onFinalizedResolve = resolve;+ });+ }++ get state() {+ return this._state;+ }++ // Codec string (e.g. "avc1.640028") parsed from the first encoded chunk's+ // decoderConfig. Can differ from the requested codec when HW encoders+ // re-derive profile/level. Null until the first chunk emits.+ get actualVideoCodec() {+ return this._recorder?.actualVideoCodec || null;+ }++ start(_timeslice) {+ // The timeslice arg is a no-op here; Mp4MuxerWrapper emits fragments+ // on its own ~1s cadence, which is comparable to the 2000ms timeslice+ // cloud uses with MediaRecorder. Timing differs slightly but the+ // chunk-write contract (Blob events) is the same.+ if (this._state !== "inactive") {+ throw new Error(+ `WebCodecsTrackRecorder: cannot start in state ${this._state}`,+ );+ }++ const handleChunk = (uint8) => {+ if (!uint8 || uint8.byteLength === 0) return;+ const blob = new Blob([uint8], { type: this.mimeType });+ if (typeof this.ondataavailable !== "function") return;+ try {+ const maybe = this.ondataavailable({ data: blob });+ if (maybe && typeof maybe.then === "function") {+ this._pendingWrites.add(maybe);+ const settle = () => this._pendingWrites.delete(maybe);+ maybe.then(settle, (err) => {+ settle();+ console.warn("[WCTrackRecorder] ondataavailable failed:", err);+ });+ }+ } catch (err) {+ console.warn("[WCTrackRecorder] ondataavailable threw:", err);+ }+ };++ const handleFinalized = () => {+ if (this._finalizedResolved) return;+ this._finalizedResolved = true;+ this._state = "inactive";+ this._onFinalizedResolve?.();+ try {+ this.onstop?.();+ } catch {}+ };++ const handleError = (err) => {+ // Sticky-disable handling for non-transient WebCodecs failures lives+ // outside this class (see chooseEncoder.js + CloudRecorder.jsx).+ // Surface to the caller via the MediaRecorder-shape onerror.+ dispatchError(this.onerror, err);+ };++ this._recorder = new WebCodecsRecorder(this.stream, {+ onChunk: handleChunk,+ onFinalized: handleFinalized,+ onError: handleError,+ enableAudio: this.enableAudio,+ videoBitrate: this.videoBitsPerSecond,+ audioBitrate: this.audioBitsPerSecond,+ // Cap encoded resolution at 1080p. Without this, retina screen+ // captures (often 2200x1440 or higher) exceed the AVC Level 4.2+ // max coded area (~2.2 MP) and the encoder throws NotSupportedError+ // on the first frame, leaving Bunny with only the 28-byte ftyp init.+ // 1080p matches Bunny Stream's tier ceiling, so users can't play+ // back at higher than 1080p anyway. WebCodecsRecorder downscales+ // via its resize canvas; aspect ratio is preserved.+ width: 1920,+ height: 1080,+ });+ this._state = "recording";++ // underlying recorder.start() is async; dispatch and don't block,+ // since MediaRecorder.start() is sync to the caller and startup+ // errors flow through onerror.+ Promise.resolve(this._recorder.start()).catch((err) => {+ handleError(err);+ });+ }++ pause() {+ if (this._state !== "recording") return;+ try {+ this._recorder?.pause?.();+ } catch (err) {+ dispatchError(this.onerror, err);+ return;+ }+ this._state = "paused";+ }++ resume() {+ if (this._state !== "paused") return;+ try {+ this._recorder?.resume?.();+ } catch (err) {+ dispatchError(this.onerror, err);+ return;+ }+ this._state = "recording";+ }++ // MediaRecorder.stop() is sync and queues a finalize that fires onstop+ // on completion. mirror that shape: return undefined, callers await+ // onstop. WebCodecsRecorder.stop() is async and resolves after finalize;+ // we hook onFinalized to fire onstop at the right time.+ stop() {+ if (this._state === "inactive") return;+ this._state = "inactive";+ if (!this._stopPromise) {+ this._stopPromise = (async () => {+ try {+ await this._recorder?.stop?.();+ } catch (err) {+ dispatchError(this.onerror, err);+ }+ // if onFinalized never fires (rare: muxer hung past internal+ // timeout), force the stop callback so the caller's drain doesn't+ // deadlock. WebCodecsRecorder already has a 5s finalize timeout ++ // flushPending fallback that emits chunks.+ if (!this._finalizedResolved) {+ this._finalizedResolved = true;+ this._onFinalizedResolve?.();+ try {+ this.onstop?.();+ } catch {}+ }+ })();+ }+ }++ // Used by CloudRecorder when the underlying stream's display track ends+ // (e.g. user clicked the OS-level "Stop sharing" chip). Same teardown+ // path as stop(), exposed for clarity.+ destroy() {+ if (this._state !== "inactive") this.stop();+ }+}diff --git a/src/pages/CloudRecorder/encoder/chooseEncoder.js b/src/pages/CloudRecorder/encoder/chooseEncoder.jsnew file mode 100644index 0000000..cb4fba7--- /dev/null+++ b/src/pages/CloudRecorder/encoder/chooseEncoder.js@@ -0,0 +1,197 @@+// picks WebCodecs (H.264 fMP4) when the HW probe + fastRecorderGate+// sticky state allow, otherwise falls back to MediaRecorder (VP9-WebM).+// chooseTrackEncoder returns either a real MediaRecorder (built by the+// caller's factory) or a WebCodecsTrackRecorder; both expose the same+// MediaRecorder-shaped surface CloudRecorder uses.++import {+ getFastRecorderStickyState,+ markFastRecorderFailure,+} from "../../../media/fastRecorderGate";+import { WebCodecsTrackRecorder } from "./WebCodecsTrackRecorder";+import { probeHwSlots } from "./hwSlotProbe";++// Mirrors WebCodecsRecorder's resize-canvas dimension math (Recorder/+// webcodecs/WebCodecsRecorder.js ~line 199-209). Cloud calls this so+// the per-track uploader + persisted scene.{screen,camera} record the+// actual encoded dimensions instead of the source track's native+// dimensions, which can be retina-scale (e.g. 2200x1440) on macOS+// while the encoded video is capped at 1080p.+//+// MediaRecorder paths don't downscale (they record at native), so+// callers must skip this when kind === "mediarecorder".+export const WEBCODECS_CAP_WIDTH = 1920;+export const WEBCODECS_CAP_HEIGHT = 1080;+const HARD_CAP = 3840;++export const computeEncodedDimensions = ({+ width,+ height,+ capWidth = WEBCODECS_CAP_WIDTH,+ capHeight = WEBCODECS_CAP_HEIGHT,+}) => {+ if (+ !Number.isFinite(width) ||+ !Number.isFinite(height) ||+ width <= 0 ||+ height <= 0+ ) {+ return { width: 0, height: 0 };+ }+ const effectiveCapWidth = Math.min(capWidth, HARD_CAP);+ const effectiveCapHeight = Math.min(capHeight, HARD_CAP);+ let targetWidth = Math.min(width, effectiveCapWidth);+ let targetHeight = Math.round((height / width) * targetWidth);+ if (targetHeight > effectiveCapHeight) {+ targetHeight = effectiveCapHeight;+ targetWidth = Math.round((width / height) * targetHeight);+ }+ // H.264 requires even dimensions; min 32 for tiny regions.+ targetWidth = Math.max(32, targetWidth - (targetWidth % 2));+ targetHeight = Math.max(32, targetHeight - (targetHeight % 2));+ return { width: targetWidth, height: targetHeight };+};++// memoize per-session: chooseTrackEncoder() runs once per track during+// start, so the probe fires three times back-to-back without this cache.+let _hwSlotsPromise = null;+let _stickyStatePromise = null;++export const resetEncoderProbeCache = () => {+ _hwSlotsPromise = null;+ _stickyStatePromise = null;+};++const ensureProbes = async (probeOptions) => {+ if (!_hwSlotsPromise) {+ _hwSlotsPromise = probeHwSlots(probeOptions);+ }+ if (!_stickyStatePromise) {+ _stickyStatePromise = getFastRecorderStickyState();+ }+ return Promise.all([_hwSlotsPromise, _stickyStatePromise]);+};++const TRACK_TO_PROBE = {+ screen: "screen",+ camera: "camera",+ // Audio always uses MediaRecorder; chooseTrackEncoder short-circuits+ // before consulting probes.+};++// Returns the encoder decision (kind / container / codec) without+// constructing a recorder. Used by initializeUploaders so the+// 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 }) => {+ if (track === "audio") {+ return {+ kind: "mediarecorder",+ container: "video/webm",+ codec: "opus",+ hwSlots: null,+ reason: "audio-track-fixed",+ };+ }+ const [hwSlots, sticky] = await ensureProbes(probeOptions || {});+ if (sticky?.disabled) {+ return {+ kind: "mediarecorder",+ container: "video/webm",+ codec: "vp9",+ hwSlots: hwSlots.summary,+ reason: "fastRecorderGate-sticky-disabled",+ };+ }+ const trackHw = hwSlots[TRACK_TO_PROBE[track]];+ if (!trackHw?.supported) {+ return {+ kind: "mediarecorder",+ container: "video/webm",+ codec: "vp9",+ hwSlots: hwSlots.summary,+ reason: `hw-probe-${track}-unsupported`,+ };+ }+ if (track === "camera" && hwSlots.summary.mode === "screen-hw-camera-mr") {+ return {+ kind: "mediarecorder",+ container: "video/webm",+ codec: "vp9",+ hwSlots: hwSlots.summary,+ reason: "screen-hw-camera-mr-mode",+ };+ }+ return {+ kind: "webcodecs",+ container: "video/mp4",+ codec: "avc1.4D0028",+ hwSlots: hwSlots.summary,+ reason: "ok",+ };+};++export const chooseTrackEncoder = async ({+ track,+ stream,+ mimeType,+ videoBitsPerSecond,+ audioBitsPerSecond,+ enableAudio,+ createMediaRecorder,+ onDataAvailable,+ probeOptions,+}) => {+ const plan = await inspectTrackPlan({ track, probeOptions });++ if (plan.kind === "mediarecorder") {+ return {+ ...plan,+ recorder: createMediaRecorder(stream, { mimeType }, onDataAvailable),+ };+ }++ // WebCodecs path. The MP4 mime type is always video/mp4, regardless of+ // whether audio is included (AAC fits inside MP4 alongside H.264).+ const recorder = new WebCodecsTrackRecorder(stream, {+ mimeType: "video/mp4",+ videoBitsPerSecond,+ audioBitsPerSecond,+ enableAudio,+ });+ recorder.ondataavailable = (event) => {+ if (event.data && event.data.size > 0) {+ const maybe = onDataAvailable(event.data);+ if (maybe && typeof maybe.then === "function") {+ recorder._pendingWrites.add(maybe);+ const settle = () => recorder._pendingWrites.delete(maybe);+ maybe.then(settle, (err) => {+ settle();+ console.warn(+ "[chooseEncoder] WebCodecs ondataavailable failed:",+ err,+ );+ });+ }+ }+ };+ recorder.onerror = (event) => {+ const err = event?.error;+ console.error(+ `[chooseEncoder] WebCodecs ${track} runtime error:`,+ err,+ );+ // Sticky-disable on hard failures, leave transient ones alone. The+ // gate's marker function distinguishes via its own pattern list.+ void markFastRecorderFailure(`cloud-${track}-runtime`, {+ error: String(err?.message || err),+ track,+ });+ };++ return {+ ...plan,+ recorder,+ };+};diff --git a/src/pages/CloudRecorder/encoder/hwSlotProbe.js b/src/pages/CloudRecorder/encoder/hwSlotProbe.jsnew file mode 100644index 0000000..331359a--- /dev/null+++ b/src/pages/CloudRecorder/encoder/hwSlotProbe.js@@ -0,0 +1,124 @@+// probes HW H.264 slot availability via VideoEncoder.isConfigSupported.+// screen + camera each want a slot. Intel Quick Sync usually has 2,+// Apple Silicon many more, Linux often 0-1, VMs often 0.+// returned separately so chooseEncoder can fall the camera back to+// MediaRecorder/VP9 when only the screen slot is free (mixing HW H.264+// for screen + SW H.264 for camera trashes the main thread).++// Probe at a conservative bitrate baseline (4 Mbps). The real encoder+// runs later at the desired bitrate; isConfigSupported gates codec /+// profile / dimensions / HW availability, and some HW reports false on+// aggressive bitrates that it actually handles fine in practice.+const PROBE_BITRATE = 4_000_000;++// Codec candidates ordered by preference. Trying multiple lets the probe+// succeed on machines where the highest profile isn't supported but a+// lower one (e.g. Baseline L3.0) is. Mirrors fastRecorderGate's approach.+// avc1.64002A = High Profile L4.2 (up to 1080p high bitrate)+// avc1.4D0028 = Main L4.0 (up to 1080p)+// avc1.4D401F = Main L3.1 (up to 720p high bitrate)+// avc1.42E01E = Baseline L3.0 (universal compatibility)+const CODEC_CANDIDATES = [+ "avc1.64002A",+ "avc1.4D0028",+ "avc1.4D401F",+ "avc1.42E01E",+];++const HW_OPTIONS = ["prefer-hardware", "no-preference"];++const buildVideoConfig = ({ codec, width, height, framerate, hwOption }) => ({+ codec,+ width,+ height,+ bitrate: PROBE_BITRATE,+ framerate,+ bitrateMode: "constant",+ latencyMode: "realtime",+ hardwareAcceleration: hwOption,+});++// Try (codec × hw-option) combinations until one reports supported. A+// machine that supports plain H.264 software but not hardware still gets+// WebCodecs (better encoder reliability than MediaRecorder VP9, which is+// also software). The "all-mr" fallback only triggers when every codec+// + hw option fails.+const probeOne = async (label, { width, height, framerate }) => {+ if (typeof VideoEncoder === "undefined") {+ return { label, supported: false, reason: "VideoEncoder unavailable" };+ }+ const attempts = [];+ for (const codec of CODEC_CANDIDATES) {+ for (const hwOption of HW_OPTIONS) {+ const config = buildVideoConfig({+ codec,+ width,+ height,+ framerate,+ hwOption,+ });+ try {+ const result = await VideoEncoder.isConfigSupported(config);+ attempts.push({+ codec,+ hwOption,+ supported: Boolean(result?.supported),+ });+ if (result?.supported) {+ return {+ label,+ supported: true,+ configResolved: result.config || config,+ attempts,+ };+ }+ } catch (err) {+ attempts.push({+ codec,+ hwOption,+ supported: false,+ error: String(err?.message || err),+ });+ }+ }+ }+ return { label, supported: false, attempts };+};++export const probeHwSlots = async ({+ framerate = 30,+} = {}) => {+ // Probe at a universal 720p baseline regardless of the actual stream+ // dimensions. isConfigSupported is a feasibility check for this codec+ // family on this hardware. modern HW that can encode 720p H.264+ // can encode any resolution we'd realistically capture (Bunny caps at+ // 1080p tier anyway). Probing at the actual resolution is risky:+ // getSettings() can return inaccurate values during track warmup, and+ // some Chromium builds (Playwright's headless variant) reject 1080p+ // configs even though the real encoder handles them once started.+ const screenProbe = await probeOne("screen", {+ width: 1280,+ height: 720,+ framerate,+ });+ const cameraProbe = await probeOne("camera", {+ width: 1280,+ height: 720,+ framerate,+ });+ return {+ screen: screenProbe,+ camera: cameraProbe,+ summary: {+ screenHw: screenProbe.supported,+ cameraHw: cameraProbe.supported,+ // Both supported = dual-hw. Only screen = degrade camera. Neither+ // (or only camera, which we don't optimize for) = all-mr.+ mode: screenProbe.supported+ ? cameraProbe.supported+ ? "dual-hw"+ : "screen-hw-camera-mr"+ : "all-mr",+ },+ };+};diff --git a/src/pages/CloudRecorder/recorderStorage/chooseChunksStore.js b/src/pages/CloudRecorder/recorderStorage/chooseChunksStore.jsnew file mode 100644index 0000000..e7f831d--- /dev/null+++ b/src/pages/CloudRecorder/recorderStorage/chooseChunksStore.js@@ -0,0 +1,96 @@+// picks OPFS or localforage IDB for chunk storage. OPFS by default,+// IDB fallback when OPFS APIs are missing or the probe write fails.+// track is "screen" | "audio" | "camera"; the prefix is what the rest+// of the codebase already uses, so OpfsKvStore.iterate() returns keys+// in the same shape as localforage did.+import localforage from "localforage";+import { OpfsKvStore, isOpfsSupported } from "./opfsKvStore";++export const TRACK_KEY_PREFIX = {+ screen: "chunk_",+ audio: "audio_chunk_",+ camera: "camera_chunk_",+};++export const TRACK_IDB_INSTANCE = {+ screen: "chunks",+ audio: "audioChunks",+ camera: "cameraChunks",+};++const opfsDiag = (event, data = {}) => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: `opfs-cloud-${event}`,+ data,+ });+ } catch {}+};++const idbInstance = (track) =>+ localforage.createInstance({ name: TRACK_IDB_INSTANCE[track] });++// Probe writes a tiny 1-byte chunk under "__probe" then removes it. Detects+// quota / API-disabled / cross-origin-isolation issues before any real+// chunk is written.+const probeOpfs = async (store) => {+ const probeBlob = new Blob([new Uint8Array([1])], {+ type: "application/octet-stream",+ });+ await store.setItem("__probe", { chunk: probeBlob });+ await store.removeItem("__probe");+};++export const chooseChunksStore = async ({+ sessionId,+ track,+ preferOpfs = true,+}) => {+ const prefix = TRACK_KEY_PREFIX[track];+ if (!prefix) throw new Error(`chooseChunksStore: unknown track ${track}`);++ if (preferOpfs && sessionId && isOpfsSupported()) {+ const startedAt = Date.now();+ const store = new OpfsKvStore({ sessionId, track, prefix });+ try {+ await probeOpfs(store);+ opfsDiag("probe-ok", {+ sessionId,+ track,+ durationMs: Date.now() - startedAt,+ });+ return { store, backend: "opfs", initMs: Date.now() - startedAt };+ } catch (err) {+ opfsDiag("probe-failed", {+ sessionId,+ track,+ error: String(err?.message || err),+ errorName: err?.name || "Error",+ });+ // Probe may have created the track dir before failing; reap it so we+ // don't leave empty dirs behind when we fall back to IDB.+ store.destroyTrackDir().catch(() => {});+ }+ }++ return { store: idbInstance(track), backend: "idb", initMs: 0 };+};++// reconstructs a store for a recording that's already on disk (resume/+// restore). backend is fixed by what was written, not by current pref.+export const openExistingChunksStore = ({ sessionId, track, backend }) => {+ const prefix = TRACK_KEY_PREFIX[track];+ if (!prefix) throw new Error(`openExistingChunksStore: unknown track ${track}`);++ if (backend === "opfs") {+ if (!sessionId) {+ throw new Error("openExistingChunksStore: opfs backend requires sessionId");+ }+ return {+ store: new OpfsKvStore({ sessionId, track, prefix }),+ backend: "opfs",+ };+ }+ return { store: idbInstance(track), backend: "idb" };+};diff --git a/src/pages/CloudRecorder/recorderStorage/opfsKvStore.js b/src/pages/CloudRecorder/recorderStorage/opfsKvStore.jsnew file mode 100644index 0000000..54a86bc--- /dev/null+++ b/src/pages/CloudRecorder/recorderStorage/opfsKvStore.js@@ -0,0 +1,304 @@+// OPFS-backed kv store shaped like localforage, one file per chunk at+// cloud-chunks/<sessionId>/<track>/<index>.bin. Async writes via+// createWritable() so it works from tab and SW contexts. Probe values+// are JSON; chunk values write the Blob directly. Keys keep their+// track prefix on iterate() to match what callers got from localforage.++const ROOT_DIR_NAME = "cloud-chunks";+const PROBE_FILE = "__probe.bin";+const CHUNK_FILE_RE = /^(\d+)\.bin$/;++const opfsDiag = (event, data = {}) => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: `opfs-cloud-${event}`,+ data,+ });+ } catch {}+};++const safeRemove = async (parent, name) => {+ try {+ await parent.removeEntry(name);+ } catch (err) {+ if (err?.name !== "NotFoundError") throw err;+ }+};++export class OpfsKvStore {+ constructor({ sessionId, track, prefix }) {+ if (!sessionId) throw new Error("OpfsKvStore: sessionId required");+ if (!track) throw new Error("OpfsKvStore: track required");+ if (!prefix) throw new Error("OpfsKvStore: prefix required");+ this.sessionId = sessionId;+ this.track = track;+ this.prefix = prefix;+ this._dirPromise = null;+ }++ async _dir({ create = true } = {}) {+ if (this._dirPromise && create) return this._dirPromise;+ if (!create) {+ // read-only path. returns null if the tree doesn't exist so callers+ // can treat missing dirs as "no chunks".+ const root = await navigator.storage.getDirectory();+ const cloud = await root+ .getDirectoryHandle(ROOT_DIR_NAME)+ .catch(() => null);+ if (!cloud) return null;+ const session = await cloud+ .getDirectoryHandle(this.sessionId)+ .catch(() => null);+ if (!session) return null;+ return session.getDirectoryHandle(this.track).catch(() => null);+ }+ if (!this._dirPromise) {+ this._dirPromise = (async () => {+ const root = await navigator.storage.getDirectory();+ const cloud = await root.getDirectoryHandle(ROOT_DIR_NAME, {+ create: true,+ });+ const session = await cloud.getDirectoryHandle(this.sessionId, {+ create: true,+ });+ return session.getDirectoryHandle(this.track, { create: true });+ })().catch((err) => {+ // Reset so retries can re-attempt; otherwise a transient init failure+ // poisons the instance permanently.+ this._dirPromise = null;+ throw err;+ });+ }+ return this._dirPromise;+ }++ _keyToFile(key) {+ if (key === "__probe") return PROBE_FILE;+ if (this.prefix && typeof key === "string" && key.startsWith(this.prefix)) {+ const tail = key.slice(this.prefix.length);+ if (/^\d+$/.test(tail)) return `${tail}.bin`;+ }+ // Fall back to a sanitized key for any non-numeric writes (e.g. probes+ // with custom keys); never used in steady state but keeps the adapter+ // permissive.+ const safe = String(key).replace(/[^A-Za-z0-9_-]/g, "_");+ return `${safe}.bin`;+ }++ _fileToKey(name) {+ if (name === PROBE_FILE) return "__probe";+ const m = name.match(CHUNK_FILE_RE);+ if (!m) return null;+ return `${this.prefix}${m[1]}`;+ }++ async setItem(key, value) {+ const fileName = this._keyToFile(key);+ const dir = await this._dir();+ const handle = await dir.getFileHandle(fileName, { create: true });+ const writable = await handle.createWritable();+ try {+ if (value && value.chunk instanceof Blob) {+ await writable.write(value.chunk);+ } else if (value instanceof Blob) {+ await writable.write(value);+ } else if (value !== undefined && value !== null) {+ // Probe path: just serialize whatever scalar/object the caller gave.+ await writable.write(JSON.stringify(value));+ }+ } finally {+ await writable.close();+ }+ return value;+ }++ async getItem(key) {+ const fileName = this._keyToFile(key);+ const dir = await this._dir({ create: false });+ if (!dir) return null;+ let handle;+ try {+ handle = await dir.getFileHandle(fileName);+ } catch (err) {+ if (err?.name === "NotFoundError") return null;+ throw err;+ }+ const file = await handle.getFile();+ if (key === "__probe") {+ // Probe reads aren't load-bearing; return a placeholder.+ return { ts: 0 };+ }+ const m = fileName.match(CHUNK_FILE_RE);+ const index = m ? Number(m[1]) : 0;+ // File is itself a Blob; wrap so callers always get a stable Blob shape.+ const blob = file instanceof Blob ? file : new Blob([file]);+ return { index, chunk: blob, timestamp: null };+ }++ async removeItem(key) {+ const fileName = this._keyToFile(key);+ const dir = await this._dir({ create: false });+ if (!dir) return;+ await safeRemove(dir, fileName);+ }++ async iterate(callback) {+ const dir = await this._dir({ create: false });+ if (!dir) return undefined;+ const entries = [];+ for await (const [name, handle] of dir.entries()) {+ if (name === PROBE_FILE) continue;+ const m = name.match(CHUNK_FILE_RE);+ if (!m) continue;+ entries.push({+ name,+ index: Number(m[1]),+ key: `${this.prefix}${m[1]}`,+ handle,+ });+ }+ entries.sort((a, b) => a.index - b.index);+ let i = 0;+ for (const entry of entries) {+ const file = await entry.handle.getFile();+ const blob = file instanceof Blob ? file : new Blob([file]);+ const value = { index: entry.index, chunk: blob, timestamp: null };+ const result = callback(value, entry.key, ++i);+ if (result !== undefined) return result;+ }+ return undefined;+ }++ async length() {+ const dir = await this._dir({ create: false });+ if (!dir) return 0;+ let count = 0;+ for await (const [name] of dir.entries()) {+ if (name === PROBE_FILE) continue;+ if (!CHUNK_FILE_RE.test(name)) continue;+ count++;+ }+ return count;+ }++ async clear() {+ const dir = await this._dir({ create: false });+ if (!dir) return;+ const names = [];+ for await (const [name] of dir.entries()) names.push(name);+ await Promise.all(names.map((n) => safeRemove(dir, n)));+ }++ // Cloud-only helper: removes the track subdirectory. Call after a session+ // is fully torn down so the parent session dir can also be reaped by+ // destroySessionDir() once all tracks are gone.+ async destroyTrackDir() {+ try {+ const root = await navigator.storage.getDirectory();+ const cloud = await root.getDirectoryHandle(ROOT_DIR_NAME).catch(() => null);+ if (!cloud) return;+ const session = await cloud+ .getDirectoryHandle(this.sessionId)+ .catch(() => null);+ if (!session) return;+ await removeDirRecursive(session, this.track);+ this._dirPromise = null;+ } catch (err) {+ opfsDiag("destroy-track-failed", {+ sessionId: this.sessionId,+ track: this.track,+ error: String(err?.message || err),+ });+ }+ }+}++// Manual recursive remove. Chrome's removeEntry({recursive: true}) is+// supposed to delete non-empty directories but in practice silently+// fails on some Chromium builds when subdirectories aren't fully empty+// (e.g. lingering __probe.bin or pending write handles). Walking the+// tree explicitly is slower but reliable.+const removeDirRecursive = async (parent, name) => {+ let handle;+ try {+ handle = await parent.getDirectoryHandle(name);+ } catch (err) {+ if (err?.name === "NotFoundError") return;+ throw err;+ }+ const childNames = [];+ for await (const [childName] of handle.entries()) childNames.push(childName);+ for (const childName of childNames) {+ let isDir = false;+ try {+ await handle.getDirectoryHandle(childName);+ isDir = true;+ } catch {}+ if (isDir) {+ await removeDirRecursive(handle, childName);+ } else {+ await handle.removeEntry(childName).catch(() => {});+ }+ }+ await parent.removeEntry(name).catch((err) => {+ opfsDiag("remove-entry-failed", {+ name,+ error: String(err?.message || err),+ });+ });+};++// Best-effort whole-session cleanup. Call once after all per-track+// destroyTrackDir() complete (or independently for orphan reaping).+export const destroySessionDir = async (sessionId) => {+ if (!sessionId) return;+ try {+ const root = await navigator.storage.getDirectory();+ const cloud = await root.getDirectoryHandle(ROOT_DIR_NAME).catch(() => null);+ if (!cloud) return;+ await removeDirRecursive(cloud, sessionId);+ } catch (err) {+ opfsDiag("destroy-session-failed", {+ sessionId,+ error: String(err?.message || err),+ });+ }+};++// Lists session subdirectories under cloud-chunks/. Used by the background+// startup pass to find orphan sessions whose recorderSession is gone.+export const listSessionDirs = async () => {+ try {+ const root = await navigator.storage.getDirectory();+ const cloud = await root+ .getDirectoryHandle(ROOT_DIR_NAME)+ .catch(() => null);+ if (!cloud) return [];+ const names = [];+ for await (const [name, handle] of cloud.entries()) {+ if (handle.kind === "directory") names.push(name);+ }+ return names;+ } catch {+ return [];+ }+};++export const isOpfsSupported = () => {+ try {+ if (typeof navigator === "undefined") return false;+ if (!navigator.storage || typeof navigator.storage.getDirectory !== "function") {+ return false;+ }+ if (typeof FileSystemFileHandle === "undefined") return false;+ if (+ typeof FileSystemFileHandle.prototype?.createWritable !== "function"+ ) {+ return false;+ }+ return true;+ } catch {+ return false;+ }+};diff --git a/src/pages/Content/DevHUD.jsx b/src/pages/Content/DevHUD.jsxindex 6058b44..bd7d58b 100644--- a/src/pages/Content/DevHUD.jsx+++ b/src/pages/Content/DevHUD.jsx@@ -24,8 +24,8 @@ const DevHUD = ({ contentStateRef, setContentState }) => {useEffect(() => {const el = document.createElement("div");el.id = "screenity-dev-hud-portal";- // Make the container itself invisible/non-interfering but ensure its- // children (position:fixed) are not clipped by host-page CSS.+ // Container invisible but children (position:fixed) must not be+ // clipped by host-page CSS.el.style.cssText = ["position:fixed !important","top:0 !important",@@ -131,8 +131,7 @@ const DevHUD = ({ contentStateRef, setContentState }) => {if (!portalEl) return null;- // Shared wrapper style — lives inside the zero-size fixed container,- // so it needs its own position:fixed to escape.+ // Lives inside the zero-size fixed container so needs its own position:fixed.const wrapBase = {position: "fixed",bottom: 6,diff --git a/src/pages/Content/camera/layout/CameraWrap.jsx b/src/pages/Content/camera/layout/CameraWrap.jsxindex 829bc74..90735ad 100644--- a/src/pages/Content/camera/layout/CameraWrap.jsx+++ b/src/pages/Content/camera/layout/CameraWrap.jsx@@ -24,15 +24,13 @@ const CameraWrap = (props) => {const updateUIPosition = () => {const ref =props.shadowRef.current.shadowRoot.querySelector(".camera-draggable");- const circleCenterX =- ref.getBoundingClientRect().left + ref.getBoundingClientRect().width / 2;- const circleCenterY =- ref.getBoundingClientRect().top + ref.getBoundingClientRect().height / 2;- const circleRadius = ref.getBoundingClientRect().width / 2;- const squareBottomRightX =- ref.getBoundingClientRect().left + ref.getBoundingClientRect().width;- const squareBottomRightY =- ref.getBoundingClientRect().top + ref.getBoundingClientRect().height;+ // Cached: fires at ~60Hz during resize, was 12 reflows/call.+ const refRect = ref.getBoundingClientRect();+ const circleCenterX = refRect.left + refRect.width / 2;+ const circleCenterY = refRect.top + refRect.height / 2;+ const circleRadius = refRect.width / 2;+ const squareBottomRightX = refRect.left + refRect.width;+ const squareBottomRightY = refRect.top + refRect.height;const handle =props.shadowRef.current.shadowRoot.querySelector(".camera-resize");const toolbar =@@ -48,31 +46,25 @@ const CameraWrap = (props) => {const x = r - r / Math.sqrt(2);const y = r - r / Math.sqrt(2);- handle.style.bottom = `${y - handle.getBoundingClientRect().width / 2}px`;- handle.style.right = `${x - handle.getBoundingClientRect().height / 2}px`;- toolbar.style.top = `${y - toolbar.getBoundingClientRect().width / 2}px`;- toolbar.style.left = `${x - toolbar.getBoundingClientRect().height / 2}px`;+ const handleRect = handle.getBoundingClientRect();+ const toolbarRect = toolbar.getBoundingClientRect();+ handle.style.bottom = `${y - handleRect.width / 2}px`;+ handle.style.right = `${x - handleRect.height / 2}px`;+ toolbar.style.top = `${y - toolbarRect.width / 2}px`;+ toolbar.style.left = `${x - toolbarRect.height / 2}px`;};const saveDimensions = () => {const ref =props.shadowRef.current.shadowRoot.querySelector(".camera-draggable");+ const rect = ref.getBoundingClientRect();+ const dims = { size: rect.width, x: rect.x, y: rect.y };setContentState((prevContentState) => ({...prevContentState,- cameraDimensions: {- size: ref.getBoundingClientRect().width,- x: ref.getBoundingClientRect().x,- y: ref.getBoundingClientRect().y,- },+ cameraDimensions: dims,}));- chrome.storage.local.set({- cameraDimensions: {- size: ref.getBoundingClientRect().width,- x: ref.getBoundingClientRect().x,- y: ref.getBoundingClientRect().y,- },- });+ chrome.storage.local.set({ cameraDimensions: dims });};useEffect(() => {@@ -85,7 +77,7 @@ const CameraWrap = (props) => {updateUIPosition();}, [cameraRef.current]);- // I need to make sure the camera is never offscreen (if the user resizes the window)+ // Keep the camera onscreen when the window is resized.useLayoutEffect(() => {const updateCameraPosition = () => {if (@@ -97,19 +89,24 @@ const CameraWrap = (props) => {let xpos = cameraRef.current.getDraggablePosition().x;let ypos = cameraRef.current.getDraggablePosition().y;- // Width and height of camera- const width = ref.getBoundingClientRect().width;- const height = ref.getBoundingClientRect().height;+ const cameraRect = ref.getBoundingClientRect();+ const width = cameraRect.width;+ const height = cameraRect.height;const { innerWidth, innerHeight } = window;- // Keep camera positioned relative to the bottom and right of the screen, proportionallyif (xpos + width > innerWidth) {xpos = innerWidth - width;}if (ypos + height > innerHeight) {ypos = innerHeight - height;}+ // Clamp top/left too: the right/bottom clamp can go negative if the+ // viewport is smaller than the saved bubble (external monitor saved,+ // built-in restored). Rnd's bounds="window" only constrains drag,+ // not initial render.+ if (xpos < 0) xpos = 0;+ if (ypos < 0) ypos = 0;cameraRef.current.updatePosition({ x: xpos, y: ypos });diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsxindex 263113b..7e1487a 100644--- a/src/pages/Content/context/ContentState.jsx+++ b/src/pages/Content/context/ContentState.jsx@@ -3,16 +3,17 @@ import React, {useState,useEffect,useCallback,+ useMemo,useRef,} from "react";import { updateFromStorage } from "./utils/updateFromStorage";+import { lifecycle } from "../../utils/lifecycleLog";+import { perfMark, perfReset } from "../../utils/perfMarks";-// Shortcutsimport Shortcuts from "../shortcuts/Shortcuts";import DevHUD from "../DevHUD";-// import { initializeContentMessageListener } from "./messaging/messageListener";import { setupHandlers } from "./messaging/handlers";import { checkAuthStatus } from "./utils/checkAuthStatus";@@ -22,7 +23,6 @@ import {setStartFlowOutcome,} from "../../utils/startFlowTrace";-//create a context, with createContext apiexport const contentStateContext = createContext();export const contentStateRef = { current: null };export let setContentState = () => {};@@ -87,7 +87,6 @@ const ContentState = (props) => {return true;}, []);- // Check if the user is logged inconst verifyUser = useCallback(async () => {if (!CLOUD_FEATURES_ENABLED) return;const result = await checkAuthStatus();@@ -103,7 +102,7 @@ const ContentState = (props) => {}));if (result.authenticated) {- // Client-side zoom is not available for authenticated users.+ // Client-side zoom is unavailable for authenticated users.setContentState((prev) => ({...prev,zoomEnabled: false,@@ -145,13 +144,9 @@ const ContentState = (props) => {);}, []);- // Detect Permissions-Policy camera/microphone blocks on the hosting page.- // Some sites (banking, enterprise SaaS, admin panels) set headers like- // `Permissions-Policy: camera=(), microphone=()` which disable those APIs- // for every iframe on the page, including extension iframes. When this is- // set, Screenity's camera/mic iframes fail with a NotAllowedError and the- // generic "check your permissions" modal is misleading because the browser- // setting is fine, the site is the blocker.+ // Permissions-Policy: camera=(), microphone=() on the host page disables+ // those APIs in every iframe including ours, surfacing as NotAllowedError;+ // distinguish from a real permission issue.useEffect(() => {try {const pp = document.permissionsPolicy || document.featurePolicy;@@ -164,9 +159,7 @@ const ContentState = (props) => {sitePermissionsBlocked: true,}));}- } catch {- // allowsFeature can throw on detached documents; treat as not blocked.- }+ } catch {}}, []);useEffect(() => {@@ -225,14 +218,10 @@ const ContentState = (props) => {chrome.storage.local.set({ restarting: false });traceStep("recordingStarted");setStartFlowOutcome("ok");-- // This cannot be triggered from here because the user might not have the page focused- //chrome.runtime.sendMessage({ type: "start-recording" });}, []);const restartRecording = useCallback(() => {- // Restart transitions recording true -> false briefly; suppress the normal- // "stop" beep because this is not a final stop/save action.+ // Suppress the stop beep: restart transitions recording true→false briefly.suppressStopBeepRef.current = true;const sourceTabId = tabIdRef.current ?? activeTabRef.current ?? null;chrome.storage.local.set({ restarting: true });@@ -303,12 +292,12 @@ const ContentState = (props) => {cursorMode: "none",cursorEffects: [],}));- // Remove blur from all elementsconst elements = document.querySelectorAll(".screenity-blur");elements.forEach((element) => {element.classList.remove("screenity-blur");});setTimer(0);+ perfMark("Content stop-click", { reason: "content-toolbar-stop" });chrome.runtime.sendMessage({ type: "stop-recording-tab", reason: "content-toolbar-stop" },(res) => {@@ -356,7 +345,15 @@ const ContentState = (props) => {const dismissRecording = useCallback(() => {setStartFlowOutcome("cancelled");suppressStopBeepRef.current = true;- chrome.storage.local.set({ restarting: false });+ chrome.runtime.sendMessage({ type: "clear-recording-alarm" });+ chrome.storage.local.set({+ restarting: false,+ tabRecordedID: null,+ drawingMode: false,+ blurMode: false,+ cursorMode: "none",+ cursorEffects: [],+ });chrome.runtime.sendMessage({ type: "dismiss-recording-tab" });setContentState((prevContentState) => ({...prevContentState,@@ -373,8 +370,11 @@ const ContentState = (props) => {pipEnded: false,blurMode: false,drawingMode: false,+ // Mirror the storage write to avoid a frame where the cursor overlay+ // renders on top of a "dismissed" UI while onChanged propagates.+ cursorMode: "none",+ cursorEffects: [],}));- // Remove blur from all elementsconst elements = document.querySelectorAll(".screenity-blur");elements.forEach((element) => {element.classList.remove("screenity-blur");@@ -385,7 +385,6 @@ const ContentState = (props) => {const checkChromeCapturePermissions = useCallback(async () => {const permissions = ["desktopCapture", "alarms", "offscreen"];- // Only request clipboardWrite if the user is logged in and subscribedif (contentStateRef.current?.isLoggedIn &&contentStateRef.current?.isSubscribed@@ -421,9 +420,9 @@ const ContentState = (props) => {}}, []);- // Must be called synchronously from a user-gesture handler so the- // activation propagates to the SW via sendMessage. Awaiting the returned- // Promise is fine; awaiting anything before invoking this is not.+ // Must be invoked synchronously from a user-gesture handler so the+ // activation propagates through sendMessage. Awaiting the returned Promise+ // is fine; awaiting anything before invoking is not.const checkChromeCapturePermissionsSW = useCallback(() => {const { isLoggedIn, isSubscribed } = contentStateRef.current || {};return new Promise((resolve) => {@@ -437,15 +436,24 @@ const ContentState = (props) => {}, []);const startStreaming = useCallback(async () => {- // Kick off synchronously so the click's user-gesture propagates through- // sendMessage into chrome.permissions.request in the SW. Later awaits- // (initStartFlowTrace, check-storage-quota for Pro) would consume it.+ // Double-click guard: a previous start may still be in flight.+ const snap = await chrome.storage.local.get([+ "pendingRecording",+ "recording",+ "restarting",+ ]);+ if (snap.pendingRecording || snap.recording || snap.restarting) {+ return;+ }++ // Kick off synchronously: later awaits (initStartFlowTrace, Pro storage+ // quota) would consume the click's user-gesture before it reaches+ // chrome.permissions.request in the SW.const isExtensionPage = window.location.href.includes("chrome-extension://");const permissionPromise = isExtensionPage? null: checkChromeCapturePermissionsSW();- // Init start-flow trace for this attemptconst attemptId = `ra-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;await initStartFlowTrace(attemptId, {recordingType: contentStateRef.current.recordingType,@@ -457,12 +465,14 @@ const ContentState = (props) => {countdown: Boolean(contentStateRef.current.countdown),});traceStep("startStreaming");+ perfReset();+ perfMark("Content startStreaming.click", {+ recordingType: contentStateRef.current.recordingType,+ });- // Overlay becomes non-blocking while pending. Popup stays open until the- // recorder tab takes focus. Also clear countdownCancelled so a stale- // cancellation from a previous attempt can't block this one.- // Write to storage immediately (not via useEffect) so the tab activation- // listener sees pendingRecording=true before the recorder tab opens.+ // Overlay non-blocking while pending; popup stays open until recorder tab+ // takes focus. Clear countdownCancelled to avoid stale block. Storage+ // write must precede recorder-tab open so the activation listener sees it.chrome.storage.local.set({ pendingRecording: true });setContentState((prev) => ({...prev,@@ -498,7 +508,6 @@ const ContentState = (props) => {const isSubError = error === "Subscription inactive";const isAuthError = error === "Not authenticated";- // Update content state if subscription is inactiveif (isSubError) {contentStateRef.current.setContentState((prev) => ({...prev,@@ -524,7 +533,7 @@ const ContentState = (props) => {chrome.i18n.getMessage("retryButtonLabel"),chrome.i18n.getMessage("closeModalLabel"),async () => {- window.location.reload(); // or retry logic+ window.location.reload();},() => {},);@@ -539,11 +548,10 @@ const ContentState = (props) => {pendingRecording: false,preparingRecording: false,}));- return; // Stop recording setup+ return;}}- // Check if in content script or extension page (Chrome)if (isExtensionPage) {permission = await checkChromeCapturePermissions();} else {@@ -557,8 +565,7 @@ const ContentState = (props) => {chrome.i18n.getMessage("chromePermissionsModalAction"),chrome.i18n.getMessage("chromePermissionsModalCancel"),() => {- // Direct call so the click's gesture reaches startStreaming's- // synchronous permission check.+ // Direct call so the click's gesture reaches the sync permission check.startStreaming();},() => {},@@ -617,7 +624,7 @@ const ContentState = (props) => {null,chrome.i18n.getMessage("learnMoreDot"),helpURL,- false, // colorSafe+ false,chrome.i18n.getMessage("getHelpButton"),() => {chrome.runtime.sendMessage({@@ -708,6 +715,7 @@ const ContentState = (props) => {},);} else {+ perfMark("Content desktop-capture.sent");chrome.runtime.sendMessage({type: "desktop-capture",region:@@ -769,7 +777,6 @@ const ContentState = (props) => {const handleDevicePermissions = (data) => {if (data && data != undefined && data.success) {- // I need to convert to a regular array of objectsconst audioInput = data.audioinput;const videoInput = data.videoinput;const cameraPermission = data.cameraPermission;@@ -821,10 +828,7 @@ const ContentState = (props) => {id: contentStateRef.current.defaultVideoInput,});- // Check if first time setting devicesif (!contentStateRef.current.setDevices) {- // Set default devices- // Check if audio devices existif (audioInput.length > 0) {setContentState((prevContentState) => ({...prevContentState,@@ -930,7 +934,6 @@ const ContentState = (props) => {};}, []);- // These settings are available throughout the Contentconst [contentState, setContentStateInternal] = useState({color: "#4597F7",strokeWidth: 2,@@ -954,12 +957,8 @@ const ContentState = (props) => {setToolbarMode: null,openModal: null,openToast: null,- // True when the current page's Permissions-Policy header disallows- // camera and/or microphone. Computed once on content-script mount.- // Used to show a site-specific modal instead of the generic "check- // your permissions" one, which otherwise misleads users into- // clicking the camera icon in the address bar (which does nothing- // against a site-level Permissions-Policy block).+ // Page-level Permissions-Policy disallows camera/mic. Lets us show a+ // site-specific modal instead of the misleading "check your permissions" one.sitePermissionsBlocked: false,timeWarning: false,audioInput: [],@@ -1078,9 +1077,8 @@ const ContentState = (props) => {},cancelCountdown: () => {setStartFlowOutcome("cancelled");- // Eagerly clear recording flags in storage so the action button never- // sees a stale isRecordingActive state between now and when the- // background processes dismiss-recording-tab.+ // Eagerly clear flags so the action button doesn't see stale+ // isRecordingActive before BG processes dismiss-recording-tab.chrome.storage.local.set({pendingRecording: false,recording: false,@@ -1096,7 +1094,6 @@ const ContentState = (props) => {showPopup: true,showExtension: true,}));- // Call dismissRecording to ensure everything is properly cleaned upcontentStateRef.current.dismissRecording();},resetCountdown: () => {@@ -1106,8 +1103,17 @@ const ContentState = (props) => {}));},onCountdownFinished: () => {- if (!contentStateRef.current?.countdownCancelled && isTargetTab()) {+ const isTarget = isTargetTab();+ const cancelled = Boolean(contentStateRef.current?.countdownCancelled);+ lifecycle("Content.ContentState", "onCountdownFinished", {+ isTarget,+ cancelled,+ });+ if (!cancelled && isTarget) {suppressStartBeepRef.current = true;+ lifecycle("Content.ContentState", "beep-play-attempt", {+ beep: "start",+ });playBeep(startBeepRef, "assets/sounds/beep2.mp3");}},@@ -1128,6 +1134,8 @@ const ContentState = (props) => {};const playBeep = (ref, filename) => {+ const calledAt = Date.now();+ const wasPreloaded = !!ref.current;if (!ref.current) {ref.current = new Audio(chrome.runtime.getURL(filename));}@@ -1137,10 +1145,23 @@ const ContentState = (props) => {audio.currentTime = 0;} catch {}const playPromise = audio.play();- if (playPromise?.catch) {- playPromise.catch((error) => {- console.warn("Beep playback failed:", error);- });+ if (playPromise?.then) {+ playPromise+ .then(() => {+ lifecycle("Content.ContentState", "beep-play-ok", {+ filename,+ wasPreloaded,+ elapsedMs: Date.now() - calledAt,+ });+ })+ .catch((error) => {+ console.warn("Beep playback failed:", error);+ lifecycle("Content.ContentState", "beep-play-fail", {+ filename,+ err: String(error?.message || error).slice(0, 120),+ elapsedMs: Date.now() - calledAt,+ });+ });}};@@ -1195,13 +1216,10 @@ const ContentState = (props) => {chrome.storage.onChanged.addListener(onChanged);+ // Seed once; subsequent updates arrive via onChanged.(async () => {const status = await getStatus();applyStatus(status);- pollTimer = setInterval(async () => {- const s = await getStatus();- applyStatus(s);- }, 500);})();return () => {@@ -1211,13 +1229,12 @@ const ContentState = (props) => {};}, [contentState.preparingRecording]);- // Stuck-state detector (diagnostics only).- // Writes to startFlowTrace if pending/preparing stays active too long.+ // Stuck-state diagnostics: writes to startFlowTrace when pending/preparing lingers.useEffect(() => {const PENDING_TIMEOUT_MS = 30000;const PREPARING_TIMEOUT_MS = 45000;- if (contentState.recording) return; // not stuck if recording started+ if (contentState.recording) return;let timer = null;let fired = false;@@ -1284,6 +1301,13 @@ const ContentState = (props) => {prevRecordingRef.current = isRecording;return;}+ // Countdown plays its own start beep.+ if (+ contentStateRef.current?.countdownActive ||+ contentStateRef.current?.isCountdownVisible+ ) {+ return;+ }const startTime = recordingStartTimeRef.current;const hasStartTime = Number.isFinite(startTime) && startTime > 0;const sessionMarker = hasStartTime ? startTime : Date.now();@@ -1309,7 +1333,6 @@ const ContentState = (props) => {prevRecordingRef.current = isRecording;}, [contentState.recording, isTargetTab]);- // Check Chrome versionuseEffect(() => {const version = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);@@ -1354,7 +1377,6 @@ const ContentState = (props) => {"AudioIcon",10000,);- // Check if url contains "playground.html" and "chrome-extension://"} else if (window.location.href.includes("playground.html") &&window.location.href.includes("chrome-extension://") &&@@ -1422,7 +1444,9 @@ const ContentState = (props) => {useEffect(() => {updateTimerFromStorage();+ // This runs in every open tab; skip reads on hidden ones.const interval = setInterval(() => {+ if (document.hidden) return;updateTimerFromStorage();}, 1000);const handleVisibility = () => {@@ -1470,9 +1494,8 @@ const ContentState = (props) => {changes.lastAuthCheck ||changes.isLoggedIn) {- // Debounce: multiple auth-related storage keys change in quick- // succession (e.g. loginWithWebsite writes isLoggedIn + isSubscribed- // + lastAuthCheck). Coalesce into one verify call.+ // Coalesce: loginWithWebsite writes isLoggedIn + isSubscribed ++ // lastAuthCheck in quick succession.clearTimeout(verifyDebounceRef.current);verifyDebounceRef.current = setTimeout(verifyUser, 2000);}@@ -1486,13 +1509,57 @@ const ContentState = (props) => {}));shouldUpdateTimer = true;}+ if (changes.cameraActive && isTargetTab()) {+ // CameraWrap renders off contentState.cameraActive; without this listener+ // a storage toggle (from another tab's popup, automation seed) never reaches React.+ setContentState((prev) => ({+ ...prev,+ cameraActive: Boolean(changes.cameraActive.newValue),+ }));+ }if (changes.recording) {const isRecording = Boolean(changes.recording.newValue);+ // Read recordingType from this batch; the React ref may lag.+ const recordingTypeFromChange =+ changes.recordingType?.newValue ?? null;+ lifecycle("Content.ContentState", "recording-flag-observed", {+ isRecording,+ isTargetTab: isTargetTab(),+ recordingType:+ recordingTypeFromChange ??+ contentStateRef.current?.recordingType ??+ null,+ });if (isRecording && !isTargetTab()) {- setContentState((prev) => ({- ...prev,- recording: false,- }));+ // Tab/region recordings: clear UI flags that preparing-recording set on non-target tabs.+ const recordingType =+ recordingTypeFromChange ??+ contentStateRef.current?.recordingType;+ const isTabBound =+ recordingType === "tab" || recordingType === "region";+ if (isTabBound) {+ setContentState((prev) => ({+ ...prev,+ recording: false,+ showExtension: false,+ showPopup: false,+ preparingRecording: false,+ countdownActive: false,+ isCountdownVisible: false,+ drawingMode: false,+ blurMode: false,+ cursorMode: "none",+ cursorEffects: [],+ // Camera bubble belongs to the captured tab; the cameraActive+ // listener is isTargetTab-gated so stale-true would stick here.+ cameraActive: false,+ }));+ } else {+ setContentState((prev) => ({+ ...prev,+ recording: false,+ }));+ }return;}const shouldHideCountdown =@@ -1565,7 +1632,6 @@ const ContentState = (props) => {}}, [contentState.customRegion]);- // Check when hiding the toolbaruseEffect(() => {if (contentState.hideToolbar && contentState.hideUI) {setContentState((prevContentState) => ({@@ -1588,10 +1654,9 @@ const ContentState = (props) => {});}, [contentState.pendingRecording]);- // Check if user has enough RAM to record for each quality optionuseEffect(() => {if (!contentState.qualityValue) {- const suggested = "1080p"; // safe and high enough quality+ const suggested = "1080p";setContentState((prev) => ({ ...prev, qualityValue: suggested }));chrome.storage.local.set({ qualityValue: suggested });}@@ -1633,11 +1698,9 @@ const ContentState = (props) => {}}, [contentState.backgroundEffect, contentState.backgroundEffectsActive]);- // Programmatically add custom scrollbarsuseEffect(() => {if (!contentState.parentRef) return;- // Check if on macconst isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;if (isMac) return;@@ -1739,13 +1802,14 @@ const ContentState = (props) => {updateFromStorage();}, []);- // (No storage fallback listener here; use direct messaging flow)+ // Memoize: a fresh array literal would re-render every consumer per parent update.+ const providerValue = useMemo(+ () => [contentState, setContentState, timer, setTimer],+ [contentState, timer],+ );return (- // this is the provider providing state- <contentStateContext.Provider- value={[contentState, setContentState, timer, setTimer]}- >+ <contentStateContext.Provider value={providerValue}>{props.children}<Shortcuts shortcuts={contentState.shortcuts} />{process.env.SCREENITY_DEV_MODE === "true" && (diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.jsindex 2e93069..f34326c 100644--- a/src/pages/Content/context/messaging/handlers.js+++ b/src/pages/Content/context/messaging/handlers.js@@ -1,4 +1,3 @@-// src/content/handlers/recordingHandlers.jsimport {registerMessage,messageRouter,@@ -8,6 +7,7 @@ import { updateFromStorage } from "../utils/updateFromStorage";import { checkAuthStatus } from "../utils/checkAuthStatus";import { traceStep, setStartFlowOutcome } from "../../../utils/startFlowTrace";+import { perfMark } from "../../../utils/perfMarks";import JSZip from "jszip";const CLOUD_FEATURES_ENABLED =@@ -60,7 +60,7 @@ export const setupHandlers = () => {}window.postMessage(payload, targetOrigin);- // Replay once shortly after first post to reduce race conditions with late listeners.+ // Replay shortly after to reduce races with late listeners.setTimeout(() => {window.postMessage({@@ -100,9 +100,7 @@ export const setupHandlers = () => {sceneId: sceneId || null,reason: reason || "unknown",});- } catch {- // best effort- }+ } catch {}};const fetchLocalPlaybackSourceFromExtension = async ({@@ -210,9 +208,7 @@ export const setupHandlers = () => {sceneId: source.offer.sceneId || null,usedBy: "app-editor",});- } catch {- // best effort- }+ } catch {}return activeLocalPlaybackSource;})();@@ -256,10 +252,30 @@ export const setupHandlers = () => {},});+ // Pending scene-create handoffs awaiting reply from the editor page.+ // Keyed by requestId so concurrent multi-scene flows don't collide.+ const pendingSceneCreates = new Map();+const onWindowProjectMessage = (event) => {if (event.source !== window) return;if (event.origin !== TRUSTED_APP_ORIGIN) return;const data = event?.data || {};++ if (data?.source === "create-scene-from-recording-result") {+ const pending = pendingSceneCreates.get(data.requestId);+ if (pending) {+ pendingSceneCreates.delete(data.requestId);+ clearTimeout(pending.timeout);+ pending.respond({+ ok: !!data.ok,+ status: data.status ?? 0,+ body: data.body ?? null,+ error: data.error || null,+ });+ }+ return;+ }+if (data?.type !== "screenity-local-playback-request") return;const requestedProjectId = data?.projectId || null;@@ -362,16 +378,59 @@ export const setupHandlers = () => {revokeActiveLocalPlaybackSource("content-beforeunload");});- // Initialize message routerif (!window.__screenityHandlersInitialized) {messageRouter();window.__screenityHandlersInitialized = true;}- // Register content message handlers+ // Bridge from BG to the editor page: BG forwards a scene-create payload+ // here; we postMessage it into the page (same-origin) so the editor's own+ // app code does the API call (cookie auth, no CORS, no SW lifecycle).+ registerMessage("proxy-create-scene", (message, sender) => {+ if (window.location.origin !== TRUSTED_APP_ORIGIN) {+ return { ok: false, error: "untrusted-origin" };+ }+ const { projectId, requestId, payload } = message || {};+ if (!projectId || !requestId || !payload) {+ return { ok: false, error: "invalid-proxy-create-scene" };+ }+ return new Promise((resolve) => {+ const post = () => {+ window.postMessage(+ {+ source: "create-scene-from-recording",+ projectId,+ requestId,+ payload,+ },+ TRUSTED_APP_ORIGIN,+ );+ };+ // Repost on a 500ms cadence in case the editor app's listener+ // isn't mounted yet (?load=true loading shell, async route swap).+ // The pending entry gates against duplicate replies.+ post();+ const repost = setInterval(post, 500);+ const timeout = setTimeout(() => {+ if (pendingSceneCreates.has(requestId)) {+ pendingSceneCreates.delete(requestId);+ clearInterval(repost);+ resolve({ ok: false, error: "editor-no-reply-timeout" });+ }+ }, 15_000);+ pendingSceneCreates.set(requestId, {+ respond: (val) => {+ clearInterval(repost);+ resolve(val);+ },+ timeout,+ });+ });+ });+registerMessage("time", () => {- // Timer is driven by ContentState's storage-based tick.- // Ignore external timer pushes to avoid jitter/skips.+ // Timer is driven by ContentState's storage tick;+ // ignore external pushes to avoid jitter/skips.});registerMessage("toggle-popup", () => {@@ -385,7 +444,8 @@ export const setupHandlers = () => {updateFromStorage();});- registerMessage("ready-to-record", () => {+ registerMessage("ready-to-record", async () => {+ perfMark("Content ready-to-record.received");traceStep("readyToRecordReceived");setContentState((prev) => ({@@ -395,10 +455,16 @@ export const setupHandlers = () => {preparingRecording: false,pendingRecording: true,}));++ // BG is source of truth; reading React default would race the user+ // setting and produce double beeps.+ const { countdown: storedCountdown } = await chrome.storage.local.get([+ "countdown",+ ]);const state = getState();- if (state.countdown) {- // Start countdown+ if (storedCountdown) {+ perfMark("Content countdown.start");traceStep("countdownStart");setContentState((prev) => ({...prev,@@ -408,8 +474,7 @@ export const setupHandlers = () => {}));chrome.runtime.sendMessage({ type: "diag-countdown-started" }).catch(() => {});} else {- // No countdown, start immediately. countdownCancelled is cleared- // in startStreaming so it can't be stale here.+ // countdownCancelled is cleared in startStreaming, so not stale here.state.startRecordingAfterCountdown();}});@@ -505,8 +570,7 @@ export const setupHandlers = () => {registerMessage("recording-ended", async () => {const state = getState();- // Double-check with storage before resetting UI- // This prevents false positives when service worker restarts with stale state+ // SW restart can leave stale state; double-check storage before reset.const { recording, recorderSession, pendingRecording } =await chrome.storage.local.get(["recording",@@ -517,9 +581,7 @@ export const setupHandlers = () => {const isActuallyRecording =recording || (recorderSession && recorderSession.status === "recording");- // Only reset if we're truly not recordingif (isActuallyRecording || pendingRecording) {- // Recording is actually still active - ignore this stale messageconsole.warn("Ignoring stale recording-ended message - recording still active",);@@ -545,8 +607,23 @@ export const setupHandlers = () => {...prev,pendingRecording: false,preparingRecording: false,+ recording: false,+ paused: false,+ time: 0,+ timer: 0,pipEnded: false,}));+ const state = getState();+ if (state && typeof state.openModal === "function") {+ state.openModal(+ chrome.i18n.getMessage("recordingFailedModalTitle"),+ chrome.i18n.getMessage("recordingFailedModalDescription"),+ chrome.i18n.getMessage("permissionsModalDismiss"),+ null,+ () => {},+ () => {},+ );+ }});registerMessage("start-stream", () => {@@ -681,10 +758,10 @@ export const setupHandlers = () => {() => {state.dismissRecording();},- null, // image- null, // learnMore- null, // learnMoreLink- false, // colorSafe+ null,+ null,+ null,+ false,chrome.i18n.getMessage("getHelpButton"),() => {chrome.runtime.sendMessage({@@ -699,14 +776,12 @@ export const setupHandlers = () => {registerMessage("stream-ended-warning", (message) => {const state = getState();- // Show a toast warning but don't stop the recording- // The user can decide whether to continue or stop manuallyif (state.openToast) {state.openToast(message.message ||chrome.i18n.getMessage("streamEndedWarningToast"),() => {},- 10000, // Show for 10 seconds+ 10000,);}});@@ -833,11 +908,9 @@ export const setupHandlers = () => {updateFromStorage(true, sender.id);}} else {- // After navigation, PiP is always destroyed (the iframe that owned it- // was torn down with the old page). Set pipEnded: true so the inline- // camera overlay is visible immediately. If the camera iframe- // successfully re-enters PiP later, a "pip-started" message will flip- // this back to false.+ // Post-navigation, PiP is destroyed with the old iframe. Set pipEnded+ // so the inline camera overlay shows immediately; "pip-started" will+ // flip it back if the new iframe re-enters PiP.setContentState((prev) => ({...prev,showExtension: true,@@ -900,7 +973,6 @@ export const setupHandlers = () => {});registerMessage("time-warning", () => {- // Only trigger when actively recordingconst state = getState();if (state.recording && !state.paused) {@@ -920,7 +992,6 @@ export const setupHandlers = () => {});registerMessage("time-stopped", () => {const state = getState();- // Only trigger when actively recordingif (state.recording && !state.paused) {setContentState((prev) => ({...prev,@@ -960,7 +1031,6 @@ export const setupHandlers = () => {});registerMessage("check-auth", async (message) => {if (!CLOUD_FEATURES_ENABLED) {- // Default to local userconst { recording } = await chrome.storage.local.get("recording");setContentState((prev) => ({@@ -992,7 +1062,7 @@ export const setupHandlers = () => {}));if (result.authenticated) {- // Client-side zoom is not available for authenticated users.+ // Client-side zoom is unavailable for authenticated users.setContentState((prev) => ({...prev,onboarding: false,diff --git a/src/pages/Content/countdown/Countdown.jsx b/src/pages/Content/countdown/Countdown.jsxindex 2bc8282..e231ace 100644--- a/src/pages/Content/countdown/Countdown.jsx+++ b/src/pages/Content/countdown/Countdown.jsx@@ -1,7 +1,7 @@import React, { useState, useEffect, useContext, useRef } from "react";-// Contextimport { contentStateContext } from "../context/ContentState";+import { lifecycle } from "../../utils/lifecycleLog";const COUNTDOWN_TIME = 3;const DEBUG_START_FLOW =@@ -82,7 +82,6 @@ const Countdown = () => {contentState.resetCountdown,]);- // Handle cancellationconst handleCancel = () => {if (contentState.countdownActive || contentState.isCountdownVisible) {cleanupTimers();@@ -95,7 +94,6 @@ const Countdown = () => {}};- // Countdown logicuseEffect(() => {if (!contentState.countdownActive) {cleanupTimers();@@ -104,14 +102,18 @@ const Countdown = () => {}cleanupTimers();- // Reset immediately at run start so a stale previous `1` cannot- // short-circuit the next countdown cycle.+ // Reset immediately so a stale previous `1` cannot short-circuit+ // the next cycle.setCount(COUNTDOWN_TIME);completedRef.current = false;runIdRef.current += 1;const runId = runIdRef.current;startAtRef.current = performance.now();logStartFlow("countdown_start", { visible: true });+ lifecycle("Content.Countdown", "ui-countdown-start", {+ runId,+ countdownTimeS: COUNTDOWN_TIME,+ });const tick = () => {if (runIdRef.current !== runId) return;@@ -141,8 +143,7 @@ const Countdown = () => {return;}const elapsedMs = performance.now() - startAtRef.current;- // Ignore stale count=1 carried from a previous run; valid final-second- // entry happens after ~2s for a 3..2..1 countdown.+ // Ignore stale count=1 carried from a previous run.if (elapsedMs < (COUNTDOWN_TIME - 1) * 1000) {return;}@@ -157,6 +158,9 @@ const Countdown = () => {}if (!cancelledRef.current && activeRef.current) {+ lifecycle("Content.Countdown", "ui-end-hold-scheduled", {+ endHoldMs: END_HOLD_MS,+ });finishTimeoutRef.current = setTimeout(() => {if (cancelledRef.current || !activeRef.current) {finishTimeoutRef.current = null;@@ -168,6 +172,7 @@ const Countdown = () => {countdownActive: false,}));const endedAt = Date.now();+ lifecycle("Content.Countdown", "ui-end-hidden", { endedAt });const dispatchStartAfterHide = () => {if (cancelledRef.current) return;const startDispatchedAt = Date.now();@@ -176,6 +181,11 @@ const Countdown = () => {endedAt,startDispatchedAt,});+ lifecycle("Content.Countdown", "ui-dispatch-start", {+ endedAt,+ startDispatchedAt,+ postHideDelayMs: startDispatchedAt - endedAt,+ });chrome.storage.local.set({countdownFinishedAt: endedAt,lastCountdownStartGate: {@@ -187,13 +197,16 @@ const Countdown = () => {},});finishRef.current?.();- // Countdown-enabled flow should start from background only.- // Waiting briefly after hide avoids capturing the countdown frame.+ // Brief wait after hide so the countdown frame isn't captured.startTimeoutRef.current = setTimeout(() => {if (cancelledRef.current) {startTimeoutRef.current = null;return;}+ lifecycle("Content.Countdown", "ui-send-countdown-finished", {+ endedAt,+ ageMs: Date.now() - endedAt,+ });chrome.runtime.sendMessage({type: "countdown-finished",@@ -215,7 +228,16 @@ const Countdown = () => {}}, [count, setContentState]);- // Start animation when countdown becomes visible+ // Log every visible digit so UI ticks correlate with BG events.+ useEffect(() => {+ if (!contentState.isCountdownVisible) return;+ if (!activeRef.current) return;+ lifecycle("Content.Countdown", "ui-tick", {+ count,+ elapsedMs: Math.round(performance.now() - (startAtRef.current || 0)),+ });+ }, [count, contentState.isCountdownVisible]);+useEffect(() => {if (contentState.isCountdownVisible && !wasVisibleRef.current) {resetRef.current?.();@@ -251,7 +273,6 @@ const Countdown = () => {wasVisibleRef.current = contentState.isCountdownVisible;}, [contentState.isCountdownVisible]);- // Cleanup on unmountuseEffect(() => {return cleanupTimers;}, []);diff --git a/src/pages/Content/cursor/trackClicks.js b/src/pages/Content/cursor/trackClicks.jsindex fcb8289..f1581e0 100644--- a/src/pages/Content/cursor/trackClicks.js+++ b/src/pages/Content/cursor/trackClicks.js@@ -6,11 +6,35 @@ export function startClickTracking(regionY = 0,contentStateRef = null // <- optional) {- const handleClick = async (e) => {- // Skip if blur mode is active+ // Refreshed on storage change: a restart can swap recordingType+ // (camera ↔ screen) and we'd otherwise dispatch against the prior mode.+ let cachedSurface = "unknown";+ let cachedRecordingWindowId = null;+ let cachedRecordingType = null;+ chrome.storage.local+ .get(["surface", "recordingWindowId", "recordingType"])+ .then((vals) => {+ cachedSurface = vals.surface || "unknown";+ cachedRecordingWindowId = vals.recordingWindowId ?? null;+ cachedRecordingType = vals.recordingType ?? null;+ })+ .catch(() => {});++ const onStorageChanged = (changes, area) => {+ if (area !== "local") return;+ if (changes.surface) cachedSurface = changes.surface.newValue || "unknown";+ if (changes.recordingWindowId)+ cachedRecordingWindowId = changes.recordingWindowId.newValue ?? null;+ if (changes.recordingType)+ cachedRecordingType = changes.recordingType.newValue ?? null;+ };+ try {+ chrome.storage.onChanged.addListener(onStorageChanged);+ } catch {}++ const handleClick = (e) => {if (contentStateRef?.current?.blurMode) return;- // Ignore clicks inside the toolbarif (e.target.closest(".ToolbarRoot") ||e.target.closest(".ToolbarRecordingControls") ||@@ -27,14 +51,7 @@ export function startClickTracking(return;}- const { surface, recordingWindowId, recordingType } =- await chrome.storage.local.get([- "surface",- "recordingWindowId",- "recordingType",- ]);-- if (recordingType === "camera") {+ if (cachedRecordingType === "camera") {return;}@@ -42,7 +59,6 @@ export function startClickTracking(let clickY = e.clientY;if (isRegion) {- // Check if click is inside region boundsconst inRegion =clickX >= regionX &&clickX <= regionX + regionWidth &&@@ -53,7 +69,6 @@ export function startClickTracking(return;}- // Normalize to region-relative coordinatesclickX = clickX - regionX;clickY = clickY - regionY;}@@ -64,15 +79,20 @@ export function startClickTracking(x: clickX,y: clickY,relativeToRegion: isRegion,- surface: surface || "unknown",- recordingWindowId,+ surface: cachedSurface,+ recordingWindowId: cachedRecordingWindowId,timestamp: Date.now(),region: isRegion,- isTab: recordingType === "region",+ isTab: cachedRecordingType === "region",},});};window.addEventListener("mousedown", handleClick, true);- return () => window.removeEventListener("mousedown", handleClick, true);+ return () => {+ window.removeEventListener("mousedown", handleClick, true);+ try {+ chrome.storage.onChanged.removeListener(onStorageChanged);+ } catch {}+ };}diff --git a/src/pages/Content/index.jsx b/src/pages/Content/index.jsxindex 1678452..56d7a86 100644--- a/src/pages/Content/index.jsx+++ b/src/pages/Content/index.jsx@@ -2,15 +2,23 @@ import React from "react";import { createRoot } from "react-dom/client";import Content from "./Content";-// Check if screenity-ui already exists, if so, remove it-const existingRoot = document.getElementById("screenity-ui");-if (existingRoot) {- document.body.removeChild(existingRoot);-}+// Idempotency guard: content script is injected via manifest AND re-injected+// by executeScripts() from onInstalled (every MV3 session start). Without+// this, both mounts orphan listeners and double-fire side effects (e.g.+// double start beeps).+if (window.__screenityContentBootstrapped) {+} else {+ window.__screenityContentBootstrapped = true;++ const existingRoot = document.getElementById("screenity-ui");+ if (existingRoot) {+ document.body.removeChild(existingRoot);+ }-const root = document.createElement("div");-root.id = "screenity-ui";-document.body.appendChild(root);+ const root = document.createElement("div");+ root.id = "screenity-ui";+ document.body.appendChild(root);-const appRoot = createRoot(root);-appRoot.render(<Content />);+ const appRoot = createRoot(root);+ appRoot.render(<Content />);+}diff --git a/src/pages/Content/popup/PopupContainer.jsx b/src/pages/Content/popup/PopupContainer.jsxindex 78c2602..77980a8 100644--- a/src/pages/Content/popup/PopupContainer.jsx+++ b/src/pages/Content/popup/PopupContainer.jsx@@ -24,11 +24,9 @@ import {HelpIconPopup,} from "../toolbar/components/SVG";-/* Component import */import RecordingTab from "./layout/RecordingTab";import VideosTab from "./layout/VideosTab";-// Layoutsimport SettingsMenu from "./layout/SettingsMenu";import InactiveSubscription from "./layout/InactiveSubscription";import LoggedOut from "./layout/LoggedOut";@@ -38,7 +36,6 @@ import {runProCameraOnboardingIfNeeded,} from "./onboarding/proOnboarding";-// Contextimport { contentStateContext } from "../context/ContentState";import { supportContextQuery } from "../../utils/buildSupportContext";@@ -94,10 +91,8 @@ const PopupContainer = (props) => {const buildURL = async () => {const locale = chrome.i18n.getMessage("@@ui_locale");- // Default URLlet baseURL = "https://help.screenity.io/";- // If logged in, switch to Tally with prefilled paramsif (contentState?.isLoggedIn && contentState?.screenityUser) {const { name, email } = contentState.screenityUser;const qs = await supportContextQuery({@@ -108,7 +103,6 @@ const PopupContainer = (props) => {baseURL = `https://tally.so/r/310MNg?extension=true&${qs}`;}- // If non-English locale, wrap with Google Translateif (!locale.includes("en")) {setURL(`https://translate.google.com/translate?sl=en&tl=${locale}&u=${encodeURIComponent(@@ -195,11 +189,11 @@ const PopupContainer = (props) => {let xpos = DragRef.current.getDraggablePosition().x;let ypos = DragRef.current.getDraggablePosition().y;- // Width and height of popup- const width = PopupRef.current.getBoundingClientRect().width;- const height = PopupRef.current.getBoundingClientRect().height;+ const rect = PopupRef.current.getBoundingClientRect();+ const width = rect.width;+ const height = rect.height;- // Keep popup positioned relative to the bottom and right of the screen, proportionally+ // Keep popup positioned proportionally to bottom-right.if (xpos > window.innerWidth + 10) {xpos = window.innerWidth + 10;}@@ -207,7 +201,6 @@ const PopupContainer = (props) => {ypos = window.innerHeight - height - 40;}- // Check if attached to right or bottom, if so, keep it thereif (contentStateRef.current.popupPosition.fixed) {if (xpos < window.innerWidth) {xpos = window.innerWidth + 10;@@ -226,9 +219,10 @@ const PopupContainer = (props) => {};const handleDrag = (e, d) => {- // Width and height- const width = PopupRef.current.getBoundingClientRect().width;- const height = PopupRef.current.getBoundingClientRect().height;+ // Drag fires ~60Hz; cache rect to avoid 120 reflows/sec.+ const rect = PopupRef.current.getBoundingClientRect();+ const width = rect.width;+ const height = rect.height;if (d.x - 40 < width ||@@ -252,11 +246,10 @@ const PopupContainer = (props) => {let xpos = d.x;let ypos = d.y;- // Width and height- const width = PopupRef.current.getBoundingClientRect().width;- const height = PopupRef.current.getBoundingClientRect().height;+ const rect = PopupRef.current.getBoundingClientRect();+ const width = rect.width;+ const height = rect.height;- // Check if popup is off screenif (d.x - 40 < width) {setElastic(anim);xpos = width + 40;@@ -291,7 +284,6 @@ const PopupContainer = (props) => {},}));- // Is it on the left or right, also top or bottomlet left = xpos < window.innerWidth / 2 ? true : false;let right = xpos < window.innerWidth / 2 ? false : true;let top = ypos < window.innerHeight / 2 ? true : false;@@ -604,7 +596,6 @@ const PopupContainer = (props) => {contentState.wasLoggedIn ? (<LoggedOutonManageClick={() => {- // Log back inchrome.runtime.sendMessage({ type: "handle-login" });}}onDowngradeClick={() => {@@ -616,9 +607,9 @@ const PopupContainer = (props) => {...prev,isLoggedIn: false,wasLoggedIn: false,- bigTab: "record", // Ensure UI state sync+ bigTab: "record",}));- setTab("record"); // Switch immediately+ setTab("record");requestAnimationFrame(() => {if (recordTabRef.current && pillRef.current) {diff --git a/src/pages/Content/popup/layout/RecordingTab.jsx b/src/pages/Content/popup/layout/RecordingTab.jsxindex f6c6884..023f2ef 100644--- a/src/pages/Content/popup/layout/RecordingTab.jsx+++ b/src/pages/Content/popup/layout/RecordingTab.jsx@@ -90,7 +90,11 @@ const RecordingTab = (props) => {className="TabsRoot"defaultValue="screen"onValueChange={onValueChange}- value={contentState.recordingType}+ value={+ contentState.recordingType === "tab"+ ? "region"+ : contentState.recordingType+ }>{contentState.recordingToScene && (<div className="projectActiveBanner">diff --git a/src/pages/Content/popup/layout/SettingsMenu.jsx b/src/pages/Content/popup/layout/SettingsMenu.jsxindex 1b376cb..c56df23 100644--- a/src/pages/Content/popup/layout/SettingsMenu.jsx+++ b/src/pages/Content/popup/layout/SettingsMenu.jsx@@ -23,12 +23,12 @@ import { runProPopupOnboardingIfNeeded } from "../onboarding/proOnboarding";const CLOUD_FEATURES_ENABLED =process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";+const DEV_MODE = process.env.SCREENITY_DEV_MODE === "true";const SettingsMenu = (props) => {const [contentState, setContentState] = useContext(contentStateContext);const [restore, setRestore] = useState(false);const [cloudRestore, setCloudRestore] = useState(false);- const [oldChrome, setOldChrome] = useState(false);const [openQuality, setOpenQuality] = useState(false);const [openResize, setOpenResize] = useState(false);const [openFPS, setOpenFPS] = useState(false);@@ -45,16 +45,6 @@ const SettingsMenu = (props) => {disabledAt: null,});- useEffect(() => {- // Check chrome version- const chromeVersion = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);- const MIN_CHROME_VERSION = 110;-- if (chromeVersion && parseInt(chromeVersion[2], 10) < MIN_CHROME_VERSION) {- setOldChrome(true);- }- }, []);-const handleTroubleshooting = () => {if (typeof contentState.openModal === "function") {contentState.openModal(@@ -745,36 +735,6 @@ const SettingsMenu = (props) => {</DropdownMenu.ItemIndicator></DropdownMenu.CheckboxItem>)}- {!oldChrome &&- !contentState.isSubscribed &&- !contentState.isLoggedIn && (- <DropdownMenu.CheckboxItem- className="DropdownMenuItem"- onSelect={(e) => {- e.preventDefault();- }}- onCheckedChange={(checked) => {- if (!checked) {- chrome.runtime.sendMessage({ type: "close-backup-tab" });- }- setContentState((prevContentState) => ({- ...prevContentState,- backup: checked,- backupSetup: false,- }));- chrome.storage.local.set({- backup: checked,- backupSetup: false,- });- }}- checked={contentState.backup}- >- {chrome.i18n.getMessage("backupsToggle")}- <DropdownMenu.ItemIndicator className="ItemIndicator">- <img src={CheckWhiteIcon} />- </DropdownMenu.ItemIndicator>- </DropdownMenu.CheckboxItem>- )}{!contentState.isSubscribed && !contentState.isLoggedIn && (<DropdownMenu.ItemclassName="DropdownMenuItem"@@ -787,17 +747,15 @@ const SettingsMenu = (props) => {{chrome.i18n.getMessage("restoreRecording")}</DropdownMenu.Item>)}- {!contentState.isSubscribed && !contentState.isLoggedIn && (- <DropdownMenu.Item- className="DropdownMenuItem"- onSelect={(e) => {- e.preventDefault();- handleTroubleshooting();- }}- >- {chrome.i18n.getMessage("downloadForTroubleshootingOption")}- </DropdownMenu.Item>- )}+ <DropdownMenu.Item+ className="DropdownMenuItem"+ onSelect={(e) => {+ e.preventDefault();+ handleTroubleshooting();+ }}+ >+ {chrome.i18n.getMessage("downloadForTroubleshootingOption")}+ </DropdownMenu.Item>{contentState.isLoggedIn && !CLOUD_FEATURES_ENABLED && (<DropdownMenu.Itemdiff --git a/src/pages/Content/popup/layout/WelcomeAlternate.jsx b/src/pages/Content/popup/layout/WelcomeAlternate.jsxindex 8e6c980..7b6ee37 100644--- a/src/pages/Content/popup/layout/WelcomeAlternate.jsx+++ b/src/pages/Content/popup/layout/WelcomeAlternate.jsx@@ -3,7 +3,6 @@ import CheckBlueIcon from "../../../../assets/check-blue.svg";import SoloDev from "../../../../assets/solo-dev.png";const FeatureItem = ({ text }) => {- // render with a checkmark icon on left and text on rightreturn (<div className="welcome-feature-item"><div className="welcome-feature-icon">@@ -99,7 +98,7 @@ const Welcome = (props) => {</a><aclassName="welcome-support"- href="https://https://alyssax.substack.com/"+ href="https://alyssax.substack.com/"target="_blank"rel="noopener noreferrer">diff --git a/src/pages/Content/region/Region.jsx b/src/pages/Content/region/Region.jsxindex dfb3e90..d8b6878 100644--- a/src/pages/Content/region/Region.jsx+++ b/src/pages/Content/region/Region.jsx@@ -1,7 +1,6 @@import React, { useRef, useContext, useEffect } from "react";import { Rnd } from "react-rnd";-// Contextimport { contentStateContext } from "../context/ContentState";const ResizableBox = () => {@@ -15,7 +14,6 @@ const ResizableBox = () => {recordingRef.current = contentState.recording;}, [contentState.recording]);- // Check for contentState.regionDimensions to update the Rnd component width and heightuseEffect(() => {if (contentState.recordingType != "region") return;if (!contentState.customRegion) return;@@ -34,17 +32,14 @@ const ResizableBox = () => {if (contentState.regionY === undefined) return;if (contentState.fromRegion) return;- // Get parent element dimensionsconst parentWidth = parentRef.current.offsetWidth;const parentHeight = parentRef.current.offsetHeight;- // Calculate maximum size that fits within parent elementconst maxWidth = parentWidth - contentState.regionX;const maxHeight = parentHeight - contentState.regionY;const newWidth = Math.min(contentState.regionWidth, maxWidth);const newHeight = Math.min(contentState.regionHeight, maxHeight);- // Update content state with new sizesetContentState((prevContentState) => ({...prevContentState,regionWidth: newWidth,@@ -82,11 +77,9 @@ const ResizableBox = () => {};const handleResize = (e, direction, ref, delta, position) => {- // Get numeric values of width and heightconst width = parseInt(ref.style.width, 10);const height = parseInt(ref.style.height, 10);- // Update content statesetContentState((prevContentState) => ({...prevContentState,regionWidth: width,@@ -139,10 +132,9 @@ const ResizableBox = () => {};}, []);- // Shadow DOM event forwarding: mouse events from inside the Shadow DOM- // get retargeted to the shadow host and stop at `document` — they never- // reach `window`. re-resizable listens on `window`, so we forward the- // events that originate from our shadow container.+ // Shadow DOM mouse events retarget to the host and stop at `document`,+ // never reaching `window`. re-resizable listens on `window`, so forward+ // events from our shadow container.useEffect(() => {const shadowHostId = "screenity-root-container";@@ -174,6 +166,15 @@ const ResizableBox = () => {};}, []);+ // Hide handles + dashed outline as soon as the countdown starts (or pending+ // recording is set), not when contentState.recording flips. The latter races+ // the cloudrecorder's first frame capture, leaking handles into the first+ // ~33ms of the recording.+ const hideRegionUI =+ contentState.recording ||+ contentState.countdownActive ||+ contentState.pendingRecording;+return (<divstyle={{@@ -184,24 +185,19 @@ const ResizableBox = () => {height: "100%",zIndex: -1,pointerEvents:- recordingRef.current ||+ hideRegionUI ||contentState.drawingMode ||contentState.blurMode? "none": "auto",}}- className={recordingRef.current ? "region-recording" : ""}+ className={hideRegionUI ? "region-recording" : ""}onClick={(e) => {- // showExtension false, as long as not clicking on the regionif (e.target.className.indexOf("resize-handle") === -1 &&e.target.className.indexOf("react-draggable") === -1 &&e.target.className.indexOf("region-rect") === -1) {- // setContentState((prevContentState) => ({- // ...prevContentState,- // showExtension: false,- // }));}}}ref={parentRef}@@ -215,7 +211,7 @@ const ResizableBox = () => {height: "100%",zIndex: 1,pointerEvents:- recordingRef.current ||+ hideRegionUI ||contentState.drawingMode ||contentState.blurMode? "none"@@ -230,7 +226,7 @@ const ResizableBox = () => {position: "relative",zIndex: 2,pointerEvents:- recordingRef.current ||+ hideRegionUI ||contentState.drawingMode ||contentState.blurMode? "none"@@ -260,15 +256,15 @@ const ResizableBox = () => {onResizeStop={handleResize}onDragStop={handleMove}disableDragging={- contentState.recording ||+ hideRegionUI ||contentState.drawingMode ||contentState.blurMode- } // Disable dragging when recording+ }enableResizing={- !contentState.recording &&+ !hideRegionUI &&!contentState.drawingMode &&!contentState.blurMode- } // Disable resizing when recording+ }><divref={cropRef}@@ -276,14 +272,15 @@ const ResizableBox = () => {style={{width: "100%",height: "100%",- outline: recordingRef.current ? "none" : "2px dashed #D9D9D9",- outlineOffset: "2px", // Pushes it inside the box to avoid it being visible in recordings+ outline: hideRegionUI ? "none" : "2px dashed #D9D9D9",+ // Push outline inside the box so it isn't visible in recordings.+ outlineOffset: "2px",boxShadow: "0 0 0 9999px rgba(0, 0, 0, 0.2)",borderRadius: "5px",zIndex: 2,boxSizing: "border-box",pointerEvents:- recordingRef.current ||+ hideRegionUI ||contentState.drawingMode ||contentState.blurMode? "none"diff --git a/src/pages/Content/region/layout/CameraWrap.jsx b/src/pages/Content/region/layout/CameraWrap.jsxindex 024a1c3..9338c95 100644--- a/src/pages/Content/region/layout/CameraWrap.jsx+++ b/src/pages/Content/region/layout/CameraWrap.jsx@@ -2,7 +2,6 @@ import React, { useEffect, useContext, useRef, useState } from "react";import { Rnd } from "react-rnd";-// Contextimport { contentStateContext } from "../../context/ContentState";import CameraToolbar from "./CameraToolbar";@@ -19,21 +18,18 @@ const CameraWrap = (props) => {const updateUIPosition = () => {const ref =props.shadowRef.current.shadowRoot.querySelector(".camera-draggable");- const circleCenterX =- ref.getBoundingClientRect().left + ref.getBoundingClientRect().width / 2;- const circleCenterY =- ref.getBoundingClientRect().top + ref.getBoundingClientRect().height / 2;- const circleRadius = ref.getBoundingClientRect().width / 2;- const squareBottomRightX =- ref.getBoundingClientRect().left + ref.getBoundingClientRect().width;- const squareBottomRightY =- ref.getBoundingClientRect().top + ref.getBoundingClientRect().height;+ // Cached: fires at ~60Hz during resize, was 12 reflows/call.+ const refRect = ref.getBoundingClientRect();+ const circleCenterX = refRect.left + refRect.width / 2;+ const circleCenterY = refRect.top + refRect.height / 2;+ const circleRadius = refRect.width / 2;+ const squareBottomRightX = refRect.left + refRect.width;+ const squareBottomRightY = refRect.top + refRect.height;const handle =props.shadowRef.current.shadowRoot.querySelector(".camera-resize");const toolbar =props.shadowRef.current.shadowRoot.querySelector(".camera-toolbar");- // Calculate 'r' using the formula we derived earlierconst c = Math.sqrt(Math.pow(circleCenterX - squareBottomRightX, 2) +Math.pow(circleCenterY - squareBottomRightY, 2)@@ -41,36 +37,28 @@ const CameraWrap = (props) => {const a = circleRadius / Math.sqrt(2);const r = (c + Math.sqrt(c ** 2 + 16 * a ** 2)) / 4;- // Calculate the handle positionconst x = r - r / Math.sqrt(2);const y = r - r / Math.sqrt(2);- // Position the handle element to the calculated coordinates- handle.style.bottom = `${y - handle.getBoundingClientRect().width / 2}px`;- handle.style.right = `${x - handle.getBoundingClientRect().height / 2}px`;- toolbar.style.top = `${y - toolbar.getBoundingClientRect().width / 2}px`;- toolbar.style.left = `${x - toolbar.getBoundingClientRect().height / 2}px`;+ const handleRect = handle.getBoundingClientRect();+ const toolbarRect = toolbar.getBoundingClientRect();+ handle.style.bottom = `${y - handleRect.width / 2}px`;+ handle.style.right = `${x - handleRect.height / 2}px`;+ toolbar.style.top = `${y - toolbarRect.width / 2}px`;+ toolbar.style.left = `${x - toolbarRect.height / 2}px`;};const saveDimensions = () => {const ref =props.shadowRef.current.shadowRoot.querySelector(".camera-draggable");+ const rect = ref.getBoundingClientRect();+ const dims = { size: rect.width, x: rect.x, y: rect.y };setContentState((prevContentState) => ({...prevContentState,- cameraDimensions: {- size: ref.getBoundingClientRect().width,- x: ref.getBoundingClientRect().x,- y: ref.getBoundingClientRect().y,- },+ cameraDimensions: dims,}));- chrome.storage.local.set({- cameraDimensions: {- size: ref.getBoundingClientRect().width,- x: ref.getBoundingClientRect().x,- y: ref.getBoundingClientRect().y,- },- });+ chrome.storage.local.set({ cameraDimensions: dims });};useEffect(() => {diff --git a/src/pages/Content/shortcuts/Shortcuts.jsx b/src/pages/Content/shortcuts/Shortcuts.jsxindex 78320b7..7577fb1 100644--- a/src/pages/Content/shortcuts/Shortcuts.jsx+++ b/src/pages/Content/shortcuts/Shortcuts.jsx@@ -1,6 +1,5 @@import React, { useEffect, useContext, useRef } from "react";-// Contextimport { contentStateContext } from "../context/ContentState";import { undoCanvas, redoCanvas, saveCanvas } from "../canvas/modules/History";@@ -11,30 +10,7 @@ const Shortcuts = ({ shortcuts }) => {useEffect(() => {contentStateRef.current = contentState;}, [contentState]);- /* For the record, this is the shortcuts object:- shortcuts: {- "start-recording": "ctrl+shift+1",- "stop-recording": "ctrl+shift+2",- "pause-recording": "ctrl+shift+3",- "resume-recording": "ctrl+shift+4",- "dismiss-recording": "ctrl+shift+5",- "restart-recording": "ctrl+shift+6",- "toggle-drawing-mode": "ctrl+shift+7",- },- */-- // Set up all the hotkeys programmatically from the shortcuts object, without using useEffect-- /*- useHotkeys(shortcuts["toggle-drawing-mode"], () => {- setContentState((prevContentState) => ({- ...prevContentState,- drawingMode: !prevContentState.drawingMode,- }));- });- */-- // in-app shortcuts for screenity tools+useEffect(() => {const getDeepActiveElement = () => {let active = document.activeElement;@@ -263,54 +239,89 @@ const Shortcuts = ({ shortcuts }) => {};}, []);- // Push to talk (while Alt/Option + Shift + J key is pressed enable microphone, disable on key up)+ // Push-to-talk: Alt+Shift+U held = mic on; release = off. Guards against+ // "mic stayed on after I let go":+ // 1. Modifier released before U: keyup arrives with altKey/shiftKey=false.+ // Track armed state in a ref and disarm on ANY of {U, Alt, Shift}.+ // 2. Auto-repeat: holding fires keydown repeatedly. Skip event.repeat.+ // 3. Blur/visibility change (Cmd-Tab, Alt-Tab): we never see the keyup.+ // Disarm on blur and visibilitychange.+ const pttArmedRef = useRef(false);useEffect(() => {+ const isPttChord = (event) =>+ event.code === "KeyU" && event.altKey && event.shiftKey;++ const armPtt = () => {+ if (pttArmedRef.current) return;+ pttArmedRef.current = true;+ setContentState((prevContentState) => ({+ ...prevContentState,+ micActive: true,+ }));+ chrome.storage.local.set({ micActive: true });+ chrome.runtime.sendMessage({+ type: "set-mic-active-tab",+ active: true,+ defaultAudioInput: contentStateRef.current.defaultAudioInput,+ });+ };++ const disarmPtt = () => {+ if (!pttArmedRef.current) return;+ pttArmedRef.current = false;+ setContentState((prevContentState) => ({+ ...prevContentState,+ micActive: false,+ }));+ chrome.storage.local.set({ micActive: false });+ chrome.runtime.sendMessage({+ type: "set-mic-active-tab",+ active: false,+ defaultAudioInput: contentStateRef.current.defaultAudioInput,+ });+ };+const handleKeyDown = (event) => {if (!contentStateRef.current.pushToTalk) return;- if (event.code === "KeyU" && event.altKey && event.shiftKey) {- setContentState((prevContentState) => ({- ...prevContentState,- micActive: true,- }));-- chrome.storage.local.set({- micActive: true,- });-- chrome.runtime.sendMessage({- type: "set-mic-active-tab",- active: true,- defaultAudioInput: contentState.defaultAudioInput,- });- }+ if (event.repeat) return;+ if (isPttChord(event)) armPtt();};const handleKeyUp = (event) => {if (!contentStateRef.current.pushToTalk) return;- if (event.code === "KeyU" && event.altKey && event.shiftKey) {- setContentState((prevContentState) => ({- ...prevContentState,- micActive: false,- }));-- chrome.storage.local.set({- micActive: false,- });-- chrome.runtime.sendMessage({- type: "set-mic-active-tab",- active: false,- defaultAudioInput: contentState.defaultAudioInput,- });- }+ if (!pttArmedRef.current) return;+ // Users may release chord members in any order.+ const isChordKey =+ event.code === "KeyU" ||+ event.code === "AltLeft" ||+ event.code === "AltRight" ||+ event.code === "ShiftLeft" ||+ event.code === "ShiftRight";+ if (isChordKey) disarmPtt();+ };++ const handleBlurOrHidden = () => {+ // Focus loss eats further key events; disarm proactively so the+ // user doesn't end up with a hot mic they can't see.+ if (contentStateRef.current.pushToTalk) disarmPtt();};window.addEventListener("keydown", handleKeyDown);window.addEventListener("keyup", handleKeyUp);+ window.addEventListener("blur", handleBlurOrHidden);+ document.addEventListener("visibilitychange", handleBlurOrHidden);return () => {window.removeEventListener("keydown", handleKeyDown);window.removeEventListener("keyup", handleKeyUp);+ window.removeEventListener("blur", handleBlurOrHidden);+ document.removeEventListener("visibilitychange", handleBlurOrHidden);+ // Don't leak "on" state if unmounted while armed (recording ended,+ // tab navigation).+ if (pttArmedRef.current) {+ pttArmedRef.current = false;+ chrome.storage.local.set({ micActive: false });+ }};}, []);diff --git a/src/pages/Content/toolbar/components/TooltipWrap.jsx b/src/pages/Content/toolbar/components/TooltipWrap.jsxindex 025e075..5b3e27a 100644--- a/src/pages/Content/toolbar/components/TooltipWrap.jsx+++ b/src/pages/Content/toolbar/components/TooltipWrap.jsx@@ -1,21 +1,23 @@-import React, { useEffect, useContext, useState } from "react";+import React, { useEffect, useContext, useRef, useState } from "react";import * as Tooltip from "@radix-ui/react-tooltip";-// Contextimport { contentStateContext } from "../../context/ContentState";+const HOVER_DELAY = 700;+const TooltipWrap = (props) => {const [contentState, setContentState] = useContext(contentStateContext);const classname = props.name ? props.name : "";const [override, setOverride] = useState("");+ const [open, setOpen] = useState(false);+ const openTimerRef = useRef(null);const content =props.shortcut && props.content? `${props.content} (${props.shortcut})`: props.content;useEffect(() => {- // Check if hideUI is setif (contentState.hideUI) {setOverride("override");} else {@@ -23,20 +25,51 @@ const TooltipWrap = (props) => {}}, [contentState.hideUI]);+ useEffect(() => {+ return () => {+ if (openTimerRef.current) clearTimeout(openTimerRef.current);+ };+ }, []);++ const cancelOpenTimer = () => {+ if (openTimerRef.current) {+ clearTimeout(openTimerRef.current);+ openTimerRef.current = null;+ }+ };++ const handlePointerEnter = () => {+ cancelOpenTimer();+ openTimerRef.current = setTimeout(() => setOpen(true), HOVER_DELAY);+ };++ const handlePointerLeave = () => {+ cancelOpenTimer();+ setOpen(false);+ };+return (<div className={classname} style={props.style}>{props.content == "" ? (<div>{props.children}</div>) : (<Tooltip.Provider>- <Tooltip.Root delayDuration={700} defaultOpen={false}>- <Tooltip.Trigger asChild>{props.children}</Tooltip.Trigger>+ <Tooltip.Root open={open && override !== "override"}>+ <Tooltip.Trigger+ asChild+ onPointerEnter={handlePointerEnter}+ onPointerLeave={handlePointerLeave}+ >+ {props.children}+ </Tooltip.Trigger><Tooltip.Portalcontainer={document.getElementsByClassName("screenity-shadow-dom")[0]}><Tooltip.Content+ onPointerEnter={cancelOpenTimer}+ onPointerLeave={() => setOpen(false)}className={"TooltipContent" +" " +@@ -46,9 +79,6 @@ const TooltipWrap = (props) => {" " +override}- style={{- display: override === "override" ? "none" : "block",- }}>{content}</Tooltip.Content>diff --git a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx b/src/pages/Content/toolbar/layout/ToolbarWrap.jsxindex 2cf7e06..15f8b4f 100644--- a/src/pages/Content/toolbar/layout/ToolbarWrap.jsx+++ b/src/pages/Content/toolbar/layout/ToolbarWrap.jsx@@ -9,21 +9,17 @@ import * as Toolbar from "@radix-ui/react-toolbar";import { Rnd } from "react-rnd";-// Layoutimport DrawingToolbar from "./DrawingToolbar";import CursorToolbar from "./CursorToolbar";import BlurToolbar from "./BlurToolbar";-// Componentsimport ToolTrigger from "../components/ToolTrigger";import Toast from "../components/Toast";import { CloseIconPopup } from "../components/SVG";-// Contextimport { contentStateContext } from "../../context/ContentState";-// Iconsimport {GrabIcon,StopIcon,@@ -83,14 +79,12 @@ const ToolbarWrap = () => {}}, [contentState.toolbarHover, contentState.hideUI]);- // If mouse is down and toolbarHover is true, set forceTransparentuseEffect(() => {if (!contentState.toolbarHover) return;if (!contentState.shadowRef) return;if (!contentState.hideUI) return;const handleMouseDown = (e) => {if (contentState.toolbarHover && contentState.hideUI) {- // check if mouse is over toolbarif (ToolbarRef.current && ToolbarRef.current.contains(e.target)) return;if (contentState.shadowRef &&@@ -120,12 +114,11 @@ const ToolbarWrap = () => {useEffect(() => {if (!isNaN(t)) {setTimer(t);- const clampedT = Math.max(0, t); // prevent negative values+ const clampedT = Math.max(0, t);const hours = Math.floor(clampedT / 3600);const minutes = Math.floor((clampedT % 3600) / 60);const seconds = clampedT % 60;- // Determine the timestamp format based on the total duration (t)let newTimestamp =hours > 0? `${hours.toString().padStart(2, "0")}:${minutes@@ -135,13 +128,10 @@ const ToolbarWrap = () => {.toString().padStart(2, "0")}`;- // Adjust the width of the time display based on the durationif (hours > 0) {- // Adjust for HH:MM:SS format when hours are present- timeRef.current.style.width = "58px"; // You might need to adjust this value based on your actual UI+ timeRef.current.style.width = "58px";} else {- // Adjust for MM:SS format when there are no hours- timeRef.current.style.width = "42px"; // Adjust this value as needed+ timeRef.current.style.width = "42px";}setTimestamp(newTimestamp);@@ -153,11 +143,11 @@ const ToolbarWrap = () => {let xpos = DragRef.current.getDraggablePosition().x;let ypos = DragRef.current.getDraggablePosition().y;- // Width and height of toolbar- const width = ToolbarRef.current.getBoundingClientRect().width;- const height = ToolbarRef.current.getBoundingClientRect().height;+ const rect = ToolbarRef.current.getBoundingClientRect();+ const width = rect.width;+ const height = rect.height;- // Keep toolbar positioned relative to the bottom and right of the screen, proportionally+ // Keep toolbar proportional to bottom-right.if (xpos + width + 30 > window.innerWidth) {xpos = window.innerWidth - width - 30;}@@ -181,9 +171,10 @@ const ToolbarWrap = () => {};const handleDrag = (e, d) => {- // Width and height- const width = ToolbarRef.current.getBoundingClientRect().width;- const height = ToolbarRef.current.getBoundingClientRect().height;+ // Drag fires ~60Hz; cache rect.+ const rect = ToolbarRef.current.getBoundingClientRect();+ const width = rect.width;+ const height = rect.height;if (d.y < 130) {setSide("ToolbarBottom");@@ -209,11 +200,10 @@ const ToolbarWrap = () => {let xpos = d.x;let ypos = d.y;- // Width and height- const width = ToolbarRef.current.getBoundingClientRect().width;- const height = ToolbarRef.current.getBoundingClientRect().height;+ const rect = ToolbarRef.current.getBoundingClientRect();+ const width = rect.width;+ const height = rect.height;- // Check if toolbar is off screenif (d.x < -10) {setElastic("ToolbarElastic");xpos = -10;@@ -254,8 +244,6 @@ const ToolbarWrap = () => {},}));- // Is it on the left or right, also top or bottom-let left = xpos < window.innerWidth / 2 ? true : false;let right = xpos < window.innerWidth / 2 ? false : true;let top = ypos < window.innerHeight / 2 ? true : false;@@ -307,6 +295,16 @@ const ToolbarWrap = () => {x = window.innerWidth - contentState.toolbarPosition.offsetX;}+ // Clamp into viewport: saved positions from a larger display can land+ // off-screen (external monitor saved, restored on built-in).+ const rect = ToolbarRef.current?.getBoundingClientRect();+ const tbWidth = rect?.width || 0;+ const tbHeight = rect?.height || 0;+ if (x + tbWidth > window.innerWidth) x = window.innerWidth - tbWidth;+ if (y + tbHeight > window.innerHeight) y = window.innerHeight - tbHeight;+ if (x < 0) x = 0;+ if (y < 0) y = 0;+DragRef.current.updatePosition({ x: x, y: y });handleDrop(null, { x: x, y: y });@@ -326,23 +324,7 @@ const ToolbarWrap = () => {}}, [contentState.drawingMode, contentState.blurMode, contentState.openToast]);- // useEffect(() => {- // let nextMode = modeRef.current;- // if (contentState.drawingMode) {- // nextMode = "draw";- // } else if (contentState.blurMode) {- // nextMode = "blur";- // } else if (modeRef.current === "draw" || modeRef.current === "blur") {- // nextMode = "";- // }-- // if (nextMode !== modeRef.current) {- // setMode(nextMode);- // }- // }, [contentState.drawingMode, contentState.blurMode]);-useEffect(() => {- // one-time initif (contentState.drawingMode) setMode("draw");else if (contentState.blurMode) setMode("blur");else setMode("");@@ -446,7 +428,6 @@ const ToolbarWrap = () => {hovering ? "open" : ""}`}onClick={() => {- // Show the toast firstif (contentState.openToast) {contentState.openToast(chrome.i18n.getMessage("reopenToolbarToast"),@@ -454,7 +435,6 @@ const ToolbarWrap = () => {);}- // Visually hide the toolbarsetVisuallyHidden(true);setContentState((prev) => ({@@ -463,7 +443,7 @@ const ToolbarWrap = () => {drawingMode: false,blurMode: false,}));- // After toast finishes (~3s), apply real hiding logic+ // Wait for toast (~3s) before real hide.setTimeout(() => {setContentState((prev) => ({...prev,@@ -481,7 +461,7 @@ const ToolbarWrap = () => {toolbarHover: false,hideUI: true,});- }, 3000); // match your toast duration+ }, 3000);}}><div className="popup-control popup-close">diff --git a/src/pages/Content/toolbar/styles/components/_Toast.scss b/src/pages/Content/toolbar/styles/components/_Toast.scssindex 4891c7f..901f096 100644--- a/src/pages/Content/toolbar/styles/components/_Toast.scss+++ b/src/pages/Content/toolbar/styles/components/_Toast.scss@@ -31,10 +31,12 @@gap: 8px;font-size: 15px;line-height: 1.5;- max-width: 100%;+ max-width: min(480px, calc(100vw - 50px));overflow: hidden;justify-content: center;align-items: center;+ word-wrap: break-word;+ overflow-wrap: anywhere;}.ToastRoot[data-state='open'] {animation: slideIn 150ms cubic-bezier(0.16, 1, 0.3, 1);diff --git a/src/pages/Content/utils/CursorModes.jsx b/src/pages/Content/utils/CursorModes.jsxindex 96c5a3c..27e7e23 100644--- a/src/pages/Content/utils/CursorModes.jsx+++ b/src/pages/Content/utils/CursorModes.jsx@@ -1,11 +1,14 @@-import React, { useState, useEffect, useContext, useRef } from "react";+import React, { useState, useEffect, useContext, useMemo, useRef } from "react";-// Contextimport { contentStateContext } from "../context/ContentState";const CursorModes = () => {const [contentState, setContentState] = useContext(contentStateContext);const effectsRef = useRef(new Set());+ // Refs to avoid querySelector per mousemove.+ const cursorHighlightRef = useRef(null);+ const cursorClickTargetRef = useRef(null);+ const spotlightRef = useRef(null);useEffect(() => {const nextEffects = Array.isArray(contentState.cursorEffects)@@ -16,7 +19,7 @@ const CursorModes = () => {const mouseDownHandler = (e) => {if (effectsRef.current.has("target")) {- const target = document.querySelector(".cursor-click-target");+ const target = cursorClickTargetRef.current;if (!target) return;target.style.transform ="translate(-50%, -50%) scale(1)";@@ -26,14 +29,14 @@ const CursorModes = () => {const mouseUpHandler = (e) => {if (effectsRef.current.has("target")) {- const target = document.querySelector(".cursor-click-target");+ const target = cursorClickTargetRef.current;if (!target) return;target.style.transform ="translate(-50%, -50%) scale(0)";target.style.opacity = "0";window.setTimeout(() => {- const targetReset = document.querySelector(".cursor-click-target");+ const targetReset = cursorClickTargetRef.current;if (!targetReset) return;targetReset.style.transform ="translate(-50%, -50%) scale(1)";@@ -51,44 +54,59 @@ const CursorModes = () => {const updateCursorPosition = () => {const scrollTop = window.scrollY;const scrollLeft = window.scrollX;+ const mouseX = lastMouseRef.current.x;+ const mouseY = lastMouseRef.current.y;if (effectsRef.current.has("target")) {- const target = document.querySelector(".cursor-click-target");+ const target = cursorClickTargetRef.current;if (target) {- target.style.top = lastMouseRef.current.y + scrollTop + "px";- target.style.left = lastMouseRef.current.x + scrollLeft + "px";+ target.style.top = mouseY + scrollTop + "px";+ target.style.left = mouseX + scrollLeft + "px";}}if (effectsRef.current.has("highlight")) {- const highlight = document.querySelector(".cursor-highlight");+ const highlight = cursorHighlightRef.current;if (highlight) {- highlight.style.top = lastMouseRef.current.y + scrollTop + "px";- highlight.style.left = lastMouseRef.current.x + scrollLeft + "px";+ highlight.style.top = mouseY + scrollTop + "px";+ highlight.style.left = mouseX + scrollLeft + "px";}}if (effectsRef.current.has("spotlight")) {- const spotlight = document.querySelector(".spotlight");+ const spotlight = spotlightRef.current;if (spotlight) {- spotlight.style.top = lastMouseRef.current.y + scrollTop + "px";- spotlight.style.left = lastMouseRef.current.x + scrollLeft + "px";+ spotlight.style.top = mouseY + scrollTop + "px";+ spotlight.style.left = mouseX + scrollLeft + "px";}}};+ // Coalesce DOM writes + setState into one RAF; mousemove fires at >120Hz+ // on modern trackpads.+ const stateRafRef = useRef(null);+ const scheduleCursorUpdate = () => {+ if (stateRafRef.current !== null) return;+ stateRafRef.current = requestAnimationFrame(() => {+ stateRafRef.current = null;+ if (effectsRef.current.size > 0) {+ updateCursorPosition();+ }+ // Spotlight is the only effect reading lastMousePosition from render.+ if (effectsRef.current.has("spotlight")) {+ setLastMousePosition(lastMouseRef.current);+ }+ });+ };const mouseMoveHandler = (e) => {- const next = { x: e.clientX, y: e.clientY };- lastMouseRef.current = next;- setLastMousePosition(next);- updateCursorPosition();+ lastMouseRef.current = { x: e.clientX, y: e.clientY };+ scheduleCursorUpdate();};const scrollHandler = () => {- updateCursorPosition();+ scheduleCursorUpdate();};- // Show click target when user clicks anywhere for 1 second, animate scale up and fade outuseEffect(() => {document.addEventListener("mousedown", mouseDownHandler);document.addEventListener("mousemove", mouseMoveHandler);@@ -100,65 +118,81 @@ const CursorModes = () => {document.removeEventListener("mousemove", mouseMoveHandler);document.removeEventListener("mouseup", mouseUpHandler);document.removeEventListener("scroll", scrollHandler);+ if (stateRafRef.current !== null) {+ cancelAnimationFrame(stateRafRef.current);+ stateRafRef.current = null;+ }};}, []);+ // Derive once per render so JSX doesn't re-scan the array three times.+ // Memoized styles let React skip diffing on highlight/target while+ // spotlight (depends on lastMousePosition) re-styles freely.+ const effects = contentState.cursorEffects;+ const showHighlight = Array.isArray(effects) && effects.includes("highlight");+ const showTarget = Array.isArray(effects) && effects.includes("target");+ const showSpotlight = Array.isArray(effects) && effects.includes("spotlight");++ const highlightStyle = useMemo(+ () => ({+ display: "block",+ visibility: showHighlight ? "visible" : "hidden",+ position: "absolute",+ top: 0,+ left: 0,+ width: "80px",+ height: "80px",+ pointerEvents: "none",+ zIndex: 99999999999,+ background: "yellow",+ opacity: ".5",+ transform: "translate(-50%, -50%)",+ borderRadius: "50%",+ animation: "none",+ }),+ [showHighlight],+ );++ const targetStyle = useMemo(+ () => ({+ display: "block",+ visibility: showTarget ? "visible" : "hidden",+ position: "absolute",+ top: 0,+ opacity: 0,+ left: 0,+ width: "40px",+ height: "40px",+ pointerEvents: "none",+ zIndex: 99999999999,+ border: "3px solid red",+ transform: "none",+ borderRadius: "50%",+ animation: "none",+ transition:+ "opacity .5s cubic-bezier(.25,.8,.25,1), transform .35s cubic-bezier(.25,.8,.25,1)",+ }),+ [showTarget],+ );+return (<div><div+ ref={cursorHighlightRef}className="cursor-highlight"- style={{- display: "block",- visibility:- contentState.cursorEffects?.includes("highlight")- ? "visible"- : "hidden",- position: "absolute",- top: 0,- left: 0,- width: "80px",- height: "80px",- pointerEvents: "none",- zIndex: 99999999999,- background: "yellow",- opacity: ".5",- transform: "translate(-50%, -50%)",- borderRadius: "50%",- animation: "none",- }}+ style={highlightStyle}></div><div+ ref={cursorClickTargetRef}className="cursor-click-target"- style={{- display: "block",- visibility:- contentState.cursorEffects?.includes("target")- ? "visible"- : "hidden",- position: "absolute",- top: 0,- opacity: 0,- left: 0,- width: "40px",- height: "40px",- transform: "translate(-50%, -50%) scale(1)",- pointerEvents: "none",- zIndex: 99999999999,- border: "3px solid red",- transform: "none",- borderRadius: "50%",- animation: "none",- transition:- "opacity .5s cubic-bezier(.25,.8,.25,1), transform .35s cubic-bezier(.25,.8,.25,1)",- }}+ style={targetStyle}></div><div+ ref={spotlightRef}className="spotlight"style={{position: "absolute",- display: contentState.cursorEffects?.includes("spotlight")- ? "block"- : "none",+ display: showSpotlight ? "block" : "none",top: lastMousePosition.y + "px",left: lastMousePosition.x + "px",width: "100px",diff --git a/src/pages/Content/utils/ZoomContainer.jsx b/src/pages/Content/utils/ZoomContainer.jsxindex 4046912..ba7ffff 100644--- a/src/pages/Content/utils/ZoomContainer.jsx+++ b/src/pages/Content/utils/ZoomContainer.jsx@@ -1,6 +1,5 @@import React, { useState, useEffect, useRef, useContext } from "react";-// Contextimport { contentStateContext } from "../context/ContentState";const ZoomContainer = () => {@@ -37,9 +36,8 @@ const ZoomContainer = () => {}, [contentState]);const handleKeyDown = (e) => {- // Alt / Option + Shift + Z+ // Alt/Option + Shift + Zif (e.code === "KeyE" && e.altKey && e.shiftKey) {- //if (!contentStateRef.current.recording) return;if (!contentStateRef.current.zoomEnabled) return;if (isKeyDownRef.current) return;isKeyDownRef.current = true;@@ -48,6 +46,8 @@ const ZoomContainer = () => {};const handleKeyUp = (e) => {+ // Skip when we didn't zoom in; avoids re-render on plain shift/alt keyup.+ if (!isKeyDownRef.current) return;if (e.code === "KeyE" || e.altKey || e.shiftKey) {isKeyDownRef.current = false;isKeyUpRef.current = true;@@ -63,13 +63,11 @@ const ZoomContainer = () => {};const handleMouseMove = (e) => {- //if (!contentStateRef.current.recording) return;if (!contentStateRef.current.zoomEnabled) return;- const { top, left } = document.documentElement.getBoundingClientRect();-- cursorXRef.current = e.clientX - left;- cursorYRef.current = e.clientY - top;+ // pageX/pageY avoid the getBoundingClientRect reflow.+ cursorXRef.current = e.pageX;+ cursorYRef.current = e.pageY;applyTransform();};@@ -85,13 +83,20 @@ const ZoomContainer = () => {translateXRef.current = 0;translateYRef.current = 0;setZoomLevel(scaleRef.current);- //applyTransformWithTransition();- //enableScrolling();+ };++ // applyTransform runs every mousemove.+ const canvasWrapperCache = useRef(null);+ const getCanvasWrapper = () => {+ const cached = canvasWrapperCache.current;+ if (cached && cached.isConnected) return cached;+ const node = document.querySelector("#canvas-wrapper-screenity");+ canvasWrapperCache.current = node;+ return node;};const applyTransform = () => {if (!zoomSelector.current) return;- //if (!contentStateRef.current.recording) return;const { current: scale } = scaleRef;const { current: translateX } = translateXRef;const { current: translateY } = translateYRef;@@ -102,50 +107,28 @@ const ZoomContainer = () => {zoomSelector.current.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;zoomSelector.current.style.transformOrigin = `${originX}px ${originY}px`;- // I also need to apply the transform to the #canvas-wrapper, if it exists- const canvasWrapper = document.querySelector("#canvas-wrapper-screenity");+ const canvasWrapper = getCanvasWrapper();- // Substract scroll positionconst fixedOriginX = originX - window.scrollX;const fixedOriginY = originY - window.scrollY;if (canvasWrapper) {canvasWrapper.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;canvasWrapper.style.transformOrigin = `${fixedOriginX}px ${fixedOriginY}px`;}-- // Also to #mockup-wrapper- //const mockupWrapper = document.querySelector("#mockup-wrapper");- //if (mockupWrapper) {- // mockupWrapper.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;- // mockupWrapper.style.transformOrigin = `${originX}px ${originY}px`;- //}};const applyTransformWithTransition = () => {if (!zoomSelector.current) return;zoomSelector.current.style.transition = "transform 0.5s";- if (document.querySelector("#canvas-wrapper-screenity")) {- document.querySelector("#canvas-wrapper-screenity").style.transition =- "transform 0.5s";+ const canvasWrapper = getCanvasWrapper();+ if (canvasWrapper) {+ canvasWrapper.style.transition = "transform 0.5s";}- //if (document.querySelector("#mockup-wrapper")) {- // document.querySelector("#mockup-wrapper").style.transition =- // "transform 0.5s";- //}applyTransform();};- const preventScrolling = () => {- /*- zoomSelector.current.style.position = "fixed";- zoomSelector.current.style.top = "0";- zoomSelector.current.style.left = "0";- zoomSelector.current.style.overflow = "hidden";- zoomSelector.current.style.width = "100vw";- zoomSelector.current.style.height = "100vh";- */- };+ const preventScrolling = () => {};const enableScrolling = () => {if (!zoomSelector.current) return;@@ -174,14 +157,12 @@ const ZoomContainer = () => {if (!contentState.showPopup) return;setTimeout(() => {- //if (!contentState.recording) return;if (document.querySelector("#screenity-zoom-wrap")) return;const div = document.createElement("div");div.id = "screenity-zoom-wrap";div.style.width = "100vw";div.style.height = "100vh";- // Move the body's children into this wrapperwhile (document.body.firstChild &&document.body.firstChild.id !== "screenity-ui"@@ -191,7 +172,6 @@ const ZoomContainer = () => {}}- // Append the wrapper to the bodydocument.body.prepend(div);document.body.appendChild(document.getElementById("screenity-ui"));@@ -203,7 +183,6 @@ const ZoomContainer = () => {if (mutation.addedNodes.length > 0) {const screenityUi = document.querySelector("#screenity-ui");if (screenityUi) {- // Disconnect the observerobserver.current.disconnect();}}@@ -232,7 +211,6 @@ const ZoomContainer = () => {document.body.removeChild(zoomWrap);}}- // resetscaleRef.current = 1;translateXRef.current = 0;translateYRef.current = 0;@@ -254,7 +232,6 @@ const ZoomContainer = () => {document.body.removeChild(zoomWrap);}}- // resetscaleRef.current = 1;translateXRef.current = 0;translateYRef.current = 0;@@ -265,10 +242,8 @@ const ZoomContainer = () => {useEffect(() => {if (!zoomSelector.current) return;- //if (!contentStateRef.current.recording) return;if (!contentStateRef.current.zoomEnabled) return;if (isKeyDownRef.current || isKeyUpRef.current) {- //preventScrolling();applyTransform();}}, [zoomLevel]);diff --git a/src/pages/Download/Download.jsx b/src/pages/Download/Download.jsxindex 04692ee..7830f65 100644Binary files a/src/pages/Download/Download.jsx and b/src/pages/Download/Download.jsx differdiff --git a/src/pages/Editor/Sandbox.jsx b/src/pages/Editor/Sandbox.jsxindex 007ed4b..c866aa2 100644--- a/src/pages/Editor/Sandbox.jsx+++ b/src/pages/Editor/Sandbox.jsx@@ -1,6 +1,5 @@import React, { useEffect, useRef } from "react";-// Import all the utilsimport addAudioToVideo from "./utils/addAudioToVideo";import base64ToBlob from "./utils/base64toBlob";import blobToArrayBuffer from "./utils/blobToArrayBuffer";@@ -30,11 +29,9 @@ const Sandbox = () => {try {const { createFFmpeg } = FFmpeg;- // Initialize ffmpeg.jsffmpegInstance.current = createFFmpeg({log: false,progress: (params) => {- // Send progress updates to parent windowif (params.ratio && params.ratio >= 0) {const percentage = Math.min(Math.round(params.ratio * 100), 100);sendMessage({@@ -62,7 +59,6 @@ const Sandbox = () => {script.src = "assets/vendor/ffmpeg.min.js";script.async = true;- // On load, set scriptLoaded to truescript.onload = () => {scriptLoaded.current = true;loadFfmpeg();@@ -103,7 +99,12 @@ const Sandbox = () => {const base64 = await toBase64(blob);sendMessage({ type: "updated-blob", base64: base64, topLevel: true });} catch (error) {- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });+ const errMsg = error instanceof Error ? error.message : String(error);+ if (errMsg.includes("background-audio-too-large")) {+ sendMessage({ type: "audio-too-large" });+ } else {+ sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });+ }}} else if (message.type === "base64-to-blob") {try {@@ -138,7 +139,6 @@ const Sandbox = () => {});const base64 = await toBase64(blob);sendMessage({ type: "updated-blob", base64: base64, topLevel: true });- //sendMessage({ type: "crop-update" });} catch (error) {sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error) });}@@ -247,6 +247,56 @@ const Sandbox = () => {return () => window.removeEventListener("message", handler);}, []);+ useEffect(() => {+ // editor.html is sandboxed (manifest sandbox.pages); chrome.storage+ // is undefined. Skip the storage-bridge.+ if (+ typeof chrome === "undefined" ||+ !chrome.storage ||+ !chrome.storage.onChanged+ ) {+ return;+ }+ const storageHandler = (changes, areaName) => {+ if (areaName !== "local") return;+ if (!changes.editorRecordingError) return;+ const payload = changes.editorRecordingError.newValue;+ if (!payload) return;+ try {+ iframeRef.current?.contentWindow?.postMessage(+ { type: "recording-error-from-parent", payload },+ "*",+ );+ } catch {}+ };+ chrome.storage.onChanged.addListener(storageHandler);+ const respondWithLatest = () => {+ chrome.storage.local.get(["editorRecordingError"]).then((res) => {+ if (!res?.editorRecordingError) return;+ try {+ iframeRef.current?.contentWindow?.postMessage(+ {+ type: "recording-error-from-parent",+ payload: res.editorRecordingError,+ },+ "*",+ );+ } catch {}+ });+ };+ const requestHandler = (event) => {+ if (event?.data?.type === "request-recording-error-state") {+ respondWithLatest();+ }+ };+ window.addEventListener("message", requestHandler);+ respondWithLatest();+ return () => {+ chrome.storage.onChanged.removeListener(storageHandler);+ window.removeEventListener("message", requestHandler);+ };+ }, []);+return (<div><iframediff --git a/src/pages/Editor/utils/addAudioToVideo.js b/src/pages/Editor/utils/addAudioToVideo.jsindex 80cd717..5837330 100644--- a/src/pages/Editor/utils/addAudioToVideo.js+++ b/src/pages/Editor/utils/addAudioToVideo.js@@ -6,17 +6,17 @@ async function addAudioToVideo(audioVolume = 1.0,replaceAudio = false) {+ if (audioBlob.size > 50_000_000) {+ throw new Error("background-audio-too-large");+ }const videoData = new Uint8Array(await videoBlob.arrayBuffer());const audioData = new Uint8Array(await audioBlob.arrayBuffer());- // Set the input video and audio file namesffmpeg.FS("writeFile", "input-video.mp4", videoData);ffmpeg.FS("writeFile", "input-audio.mp3", audioData);- // Set the output video file nameconst outputFileName = "output-with-audio.mp4";- // Build FFmpeg command for merging video and audio with volume adjustmentlet ffmpegCommand = ["-i","input-video.mp4",@@ -25,9 +25,9 @@ async function addAudioToVideo("-filter_complex",`[0:a]volume=1[a];[1:a]volume=${audioVolume}[b];[a][b]amix=inputs=2:duration=first:dropout_transition=2[v]`,"-map",- "0:v", // Map the original video stream+ "0:v","-map",- "[v]", // Map the merged audio+ "[v]","-c:v","copy","-c:a",@@ -39,7 +39,6 @@ async function addAudioToVideo(];if (replaceAudio) {- // Remove the original audio stream and replace it with the audio from the audio blobffmpegCommand = ["-i","input-video.mp4",@@ -48,9 +47,9 @@ async function addAudioToVideo("-filter_complex","[0:a]volume=0[a];[1:a]volume=1[b];[a][b]amix=inputs=2:duration=first:dropout_transition=2[v]","-map",- "0:v", // Map the original video stream+ "0:v","-map",- "[v]", // Map the merged audio+ "[v]","-c:v","copy","-c:a",@@ -62,16 +61,12 @@ async function addAudioToVideo(];}- // Run FFmpeg to merge video and audio with volume adjustmentawait ffmpeg.run(...ffmpegCommand);- // Get the merged video dataconst data = ffmpeg.FS("readFile", outputFileName);- // Create a Blob from the merged video dataconst videoWithAudioBlob = new Blob([data.buffer], { type: "video/mp4" });- // Return the video with merged audio Blobreturn videoWithAudioBlob;}diff --git a/src/pages/EditorViewer/Sandbox.jsx b/src/pages/EditorViewer/Sandbox.jsxindex 1ed8069..d6aeca5 100644--- a/src/pages/EditorViewer/Sandbox.jsx+++ b/src/pages/EditorViewer/Sandbox.jsx@@ -35,6 +35,47 @@ const Sandbox = () => {return () => window.removeEventListener("message", handler);}, []);+ useEffect(() => {+ const storageHandler = (changes, areaName) => {+ if (areaName !== "local") return;+ if (!changes.editorRecordingError) return;+ const payload = changes.editorRecordingError.newValue;+ if (!payload) return;+ try {+ iframeRef.current?.contentWindow?.postMessage(+ { type: "recording-error-from-parent", payload },+ "*",+ );+ } catch {}+ };+ chrome.storage.onChanged.addListener(storageHandler);+ const respondWithLatest = () => {+ chrome.storage.local.get(["editorRecordingError"]).then((res) => {+ if (!res?.editorRecordingError) return;+ try {+ iframeRef.current?.contentWindow?.postMessage(+ {+ type: "recording-error-from-parent",+ payload: res.editorRecordingError,+ },+ "*",+ );+ } catch {}+ });+ };+ const requestHandler = (event) => {+ if (event?.data?.type === "request-recording-error-state") {+ respondWithLatest();+ }+ };+ window.addEventListener("message", requestHandler);+ respondWithLatest();+ return () => {+ chrome.storage.onChanged.removeListener(storageHandler);+ window.removeEventListener("message", requestHandler);+ };+ }, []);+return (<div><iframediff --git a/src/pages/EditorWebCodecs/Sandbox.jsx b/src/pages/EditorWebCodecs/Sandbox.jsxindex 6097511..947d149 100644--- a/src/pages/EditorWebCodecs/Sandbox.jsx+++ b/src/pages/EditorWebCodecs/Sandbox.jsx@@ -89,12 +89,16 @@ const Sandbox = () => {base64,topLevel: true,fromAudio: true,+ skipReencode: true,_opId: message._opId,});break;}case "compress-video": {+ if (typeof message.base64 !== "string" || !message.base64.startsWith("data:")) {+ throw new Error("compress-video: expected data: URL");+ }const rawBlob = await fetch(message.base64).then((r) => r.blob());const compressed = await reencodeVideo(@@ -118,6 +122,9 @@ const Sandbox = () => {}case "base64-to-blob": {+ if (typeof message.base64 !== "string" || !message.base64.startsWith("data:")) {+ throw new Error("base64-to-blob: expected data: URL");+ }const rawBlob = await fetch(message.base64).then((r) => r.blob());const header = await rawBlob.slice(4, 8).text();@@ -276,10 +283,27 @@ const Sandbox = () => {}} catch (error) {const errMsg = error instanceof Error ? error.message : String(error);+ const errStack = error instanceof Error ? error.stack : null;+ // Error props are non-enumerable; JSON.stringify drops them.+ console.error("[Screenity][EditorWebCodecs] op failed", {+ type: message.type,+ message: errMsg,+ stack: errStack,+ opId: message._opId,+ });if (errMsg.includes("too long")) {sendMessage({ type: "edit-too-long", _opId: message._opId });+ } else if (errMsg.includes("background-audio-too-large")) {+ sendMessage({ type: "audio-too-large", _opId: message._opId });} else {- sendMessage({ type: "ffmpeg-error", error: JSON.stringify(error), _opId: message._opId });+ sendMessage({+ type: "ffmpeg-error",+ error: errMsg || "unknown",+ errorStack: errStack,+ errorMessage: errMsg,+ opType: message.type,+ _opId: message._opId,+ });}}};@@ -290,6 +314,47 @@ const Sandbox = () => {return () => window.removeEventListener("message", handler);}, []);+ useEffect(() => {+ const storageHandler = (changes, areaName) => {+ if (areaName !== "local") return;+ if (!changes.editorRecordingError) return;+ const payload = changes.editorRecordingError.newValue;+ if (!payload) return;+ try {+ iframeRef.current?.contentWindow?.postMessage(+ { type: "recording-error-from-parent", payload },+ "*",+ );+ } catch {}+ };+ chrome.storage.onChanged.addListener(storageHandler);+ const respondWithLatest = () => {+ chrome.storage.local.get(["editorRecordingError"]).then((res) => {+ if (!res?.editorRecordingError) return;+ try {+ iframeRef.current?.contentWindow?.postMessage(+ {+ type: "recording-error-from-parent",+ payload: res.editorRecordingError,+ },+ "*",+ );+ } catch {}+ });+ };+ const requestHandler = (event) => {+ if (event?.data?.type === "request-recording-error-state") {+ respondWithLatest();+ }+ };+ window.addEventListener("message", requestHandler);+ respondWithLatest();+ return () => {+ chrome.storage.onChanged.removeListener(storageHandler);+ window.removeEventListener("message", requestHandler);+ };+ }, []);+return (<div><iframediff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.tsindex 51b145c..db8960f 100644--- a/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.ts+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoAudioMixer.ts@@ -7,6 +7,7 @@ import {Mp4OutputFormat,VideoSampleSource,AudioSampleSource,+ AudioSampleSink,VideoSampleSink,AudioSample,ALL_FORMATS,@@ -50,19 +51,9 @@ export class VideoAudioMixer {const videoDuration = await this._getDuration(videoBlob);- // Mixing decodes the full audio track + allocates a mixBuffer — cap at- // 15 min to avoid OOM in the renderer process.- if (videoDuration > 900) {- throw new Error(- `Video is too long for in-browser audio mixing (${Math.round(videoDuration / 60)} min). ` +- `Maximum supported length is 15 minutes.`- );- }-- const hasVideoAudio = await input- .getPrimaryAudioTrack()- .then((t) => !!t)- .catch(() => false);+ const videoAudioTrack = await input.getPrimaryAudioTrack().catch(() => null);+ const hasVideoAudio =+ !!videoAudioTrack && (await videoAudioTrack.canDecode().catch(() => false));const audioSource = new AudioSampleSource({codec: "aac",@@ -70,17 +61,40 @@ export class VideoAudioMixer {});output.addAudioTrack(audioSource);+ if (audioBlob.size > 50_000_000) {+ throw new Error("background-audio-too-large");+ }let bgArrayBuffer = await audioBlob.arrayBuffer();const audioCtx = new AudioContext();let decodedAudio;try {decodedAudio = await audioCtx.decodeAudioData(bgArrayBuffer);- bgArrayBuffer = null; // release compressed audio bytes; PCM is now in decodedAudio+ bgArrayBuffer = null;} finally {audioCtx.close().catch(() => {});}- const sr = decodedAudio.sampleRate;- const audioDur = decodedAudio.duration;+ const bgSr = decodedAudio.sampleRate;+ const bgDur = decodedAudio.duration;+ const bgData = decodedAudio.getChannelData(0);+ const bgLen = bgData.length;++ const bgSampleAt = (tSec) => {+ // Zero-duration BG would NaN through the modulo below.+ if (!(bgDur > 0)) return 0;+ let t = tSec;+ if (loop) {+ t = ((t % bgDur) + bgDur) % bgDur;+ } else if (t < 0 || t >= bgDur) {+ return 0;+ }+ const idx = t * bgSr;+ const i0 = Math.floor(idx);+ if (i0 < 0 || i0 >= bgLen) return 0;+ const frac = idx - i0;+ const s0 = bgData[i0];+ const s1 = i0 + 1 < bgLen ? bgData[i0 + 1] : s0;+ return s0 + (s1 - s0) * frac;+ };await output.start();@@ -88,58 +102,108 @@ export class VideoAudioMixer {await videoSource.add(frame);frame.close();if (onProgress && videoDuration > 0)- onProgress(frame.timestamp / videoDuration);+ onProgress((frame.timestamp / videoDuration) * 0.8);}- const mixBuffer = new Float32Array(Math.ceil(sr * videoDuration));- const writeMix = (data, offset, vol) => {- for (let i = 0; i < data.length && offset + i < mixBuffer.length; i++) {- mixBuffer[offset + i] += data[i] * vol;- }- };-if (hasVideoAudio && mode === "mix") {- const videoAudioCtx = new AudioContext();- try {- const videoArrayBuffer = await videoBlob.arrayBuffer();- const decodedVideoAudio = await videoAudioCtx.decodeAudioData(- videoArrayBuffer- );- const videoSamples = decodedVideoAudio.getChannelData(0);- writeMix(videoSamples, 0, videoVolume);- } catch {- } finally {- videoAudioCtx.close().catch(() => {});+ const audioSink = new AudioSampleSink(videoAudioTrack);+ let lastSr = bgSr;+ let lastNumCh = 1;+ let lastEnd = 0;+ for await (const sample of audioSink.samples()) {+ const numCh = sample.numberOfChannels;+ const sr = sample.sampleRate;+ const N = sample.numberOfFrames;+ const ts = sample.timestamp;+ lastSr = sr;+ lastNumCh = numCh;++ const mixed = new Float32Array(N * numCh);+ for (let ch = 0; ch < numCh; ch++) {+ const plane = mixed.subarray(ch * N, (ch + 1) * N);+ sample.copyTo(plane, { format: "f32-planar", planeIndex: ch });+ }+ for (let ch = 0; ch < numCh; ch++) {+ const offset = ch * N;+ for (let f = 0; f < N; f++) {+ const t = ts + f / sr;+ mixed[offset + f] =+ mixed[offset + f] * videoVolume + bgSampleAt(t) * audioVolume;+ }+ }++ const out = new AudioSample({+ data: mixed,+ format: "f32-planar",+ numberOfChannels: numCh,+ sampleRate: sr,+ timestamp: ts,+ duration: N / sr,+ });+ await audioSource.add(out);+ out.close();+ sample.close();+ lastEnd = ts + N / sr;+ if (onProgress && videoDuration > 0)+ onProgress(0.8 + Math.min(1, ts / videoDuration) * 0.2);}- }-- const loopCount = loop- ? Math.ceil(videoDuration / audioDur)- : Math.min(1, Math.ceil(videoDuration / audioDur));-- for (let i = 0; i < loopCount; i++) {- const offset = Math.floor(i * audioDur * sr);- writeMix(decodedAudio.getChannelData(0), offset, audioVolume);- }- const totalSamples = Math.floor(videoDuration * sr);- const chunkSize = sr * 2;- let written = 0;-- while (written < totalSamples) {- const slice = mixBuffer.slice(written, written + chunkSize);- const dur = slice.length / sr;- const sample = new AudioSample({- data: slice,- format: "f32-planar",- numberOfChannels: 1,- sampleRate: sr,- timestamp: written / sr,- duration: dur,- });- await audioSource.add(sample);- sample.close();- written += chunkSize;+ // Source audio shorter than video: fill remainder with BG only.+ if (lastEnd < videoDuration - 0.01) {+ const sr = lastSr;+ const numCh = lastNumCh;+ const totalFrames = Math.floor((videoDuration - lastEnd) * sr);+ const chunkFrames = sr * 2;+ let frame = 0;+ while (frame < totalFrames) {+ const n = Math.min(chunkFrames, totalFrames - frame);+ const chunk = new Float32Array(n * numCh);+ for (let ch = 0; ch < numCh; ch++) {+ const offset = ch * n;+ for (let f = 0; f < n; f++) {+ const t = lastEnd + (frame + f) / sr;+ chunk[offset + f] = bgSampleAt(t) * audioVolume;+ }+ }+ const out = new AudioSample({+ data: chunk,+ format: "f32-planar",+ numberOfChannels: numCh,+ sampleRate: sr,+ timestamp: lastEnd + frame / sr,+ duration: n / sr,+ });+ await audioSource.add(out);+ out.close();+ frame += n;+ }+ }+ } else {+ const sr = bgSr;+ const totalFrames = Math.floor(videoDuration * sr);+ const chunkFrames = sr * 2;+ let frame = 0;+ while (frame < totalFrames) {+ const n = Math.min(chunkFrames, totalFrames - frame);+ const chunk = new Float32Array(n);+ for (let f = 0; f < n; f++) {+ const t = (frame + f) / sr;+ chunk[f] = bgSampleAt(t) * audioVolume;+ }+ const out = new AudioSample({+ data: chunk,+ format: "f32-planar",+ numberOfChannels: 1,+ sampleRate: sr,+ timestamp: frame / sr,+ duration: n / sr,+ });+ await audioSource.add(out);+ out.close();+ frame += n;+ if (onProgress && totalFrames > 0)+ onProgress(0.8 + (frame / totalFrames) * 0.2);+ }}await output.finalize();@@ -149,12 +213,16 @@ export class VideoAudioMixer {async _getDuration(blob) {return new Promise((resolve, reject) => {const v = document.createElement("video");- v.src = URL.createObjectURL(blob);+ const url = URL.createObjectURL(blob);+ v.src = url;v.onloadedmetadata = () => {+ URL.revokeObjectURL(url);resolve(v.duration);- URL.revokeObjectURL(v.src);};- v.onerror = reject;+ v.onerror = (e) => {+ URL.revokeObjectURL(url);+ reject(e);+ };});}}\ No newline at end of filediff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.tsindex 31fcb72..42f6854 100644--- a/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.ts+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoConverter.ts@@ -52,7 +52,7 @@ export class VideoConverter {async detectBestCodec(format: SupportedFormat): Promise<CodecInfo | null> {const outputFormat =format === "mp4"- ? new Mp4OutputFormat({ fastStart: "in-memory" })+ ? new Mp4OutputFormat({ fastStart: false }): new WebMOutputFormat();const supportedCodecs = outputFormat.getSupportedVideoCodecs();@@ -127,7 +127,7 @@ export class VideoConverter {const outputFormat =targetFormat === "mp4"- ? new Mp4OutputFormat({ fastStart: "in-memory" })+ ? new Mp4OutputFormat({ fastStart: false }): new WebMOutputFormat();const target = new BufferTarget();diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.tsindex 0984cb0..7f99d6c 100644--- a/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.ts+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoCropper.ts@@ -66,12 +66,15 @@ export class VideoCropper {const originalWidth = videoTrack.displayWidth;const originalHeight = videoTrack.displayHeight;- if (left + width > originalWidth || top + height > originalHeight) {- const clampedWidth = Math.min(width, originalWidth - left);- const clampedHeight = Math.min(height, originalHeight - top);- options.width = clampedWidth;- options.height = clampedHeight;- }+ let cropWidth = width;+ let cropHeight = height;+ if (left + cropWidth > originalWidth) cropWidth = originalWidth - left;+ if (top + cropHeight > originalHeight) cropHeight = originalHeight - top;+ // H.264/HEVC require even dimensions.+ cropWidth = Math.max(2, cropWidth - (cropWidth % 2));+ cropHeight = Math.max(2, cropHeight - (cropHeight % 2));+ options.width = cropWidth;+ options.height = cropHeight;let format: OutputFormat;const targetFormat =@@ -80,7 +83,7 @@ export class VideoCropper {format =targetFormat === "mp4"- ? new Mp4OutputFormat({ fastStart: "in-memory" })+ ? new Mp4OutputFormat({ fastStart: false }): new WebMOutputFormat();const target = new BufferTarget();@@ -90,7 +93,7 @@ export class VideoCropper {input,output,video: {- crop: { left, top, width, height },+ crop: { left, top, width: cropWidth, height: cropHeight },...(videoBitrate && { bitrate: videoBitrate }),},...(audioBitrate && { audio: { bitrate: audioBitrate } }),diff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.tsindex c34288b..007c496 100644--- a/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.ts+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoCutter.ts@@ -59,12 +59,34 @@ export class VideoCutter {];let processedTime = 0;- const addSegment = async (start, end) => {+ const debugLog = process.env.SCREENITY_DEV_MODE === "true";+ if (debugLog) {+ console.log("[cut-debug][cutter] start", {+ cutStart,+ cutEnd,+ total,+ sourceBlobSize: sourceBlob.size,+ sourceBlobType: sourceBlob.type,+ videoCodec,+ hasAudio: !!audioTrack,+ });+ }++ const addSegment = async (start: number, end: number, segIdx: number) => {const segDur = end - start;const baseTimestamp = outPts / 1_000_000;+ let videoSampleCount = 0;+ let audioSampleCount = 0;+ let firstVideoTs: number | null = null;+ let lastVideoTs: number | null = null;+ let firstAudioTs: number | null = null;+ let lastAudioTs: number | null = null;const videoSink = new VideoSampleSink(videoTrack);for await (const sample of videoSink.samples(start, end)) {+ if (firstVideoTs === null) firstVideoTs = sample.timestamp;+ lastVideoTs = sample.timestamp;+ videoSampleCount += 1;const adjusted = Math.max(0, baseTimestamp + (sample.timestamp - start));sample.setTimestamp(adjusted);await videoSource.add(sample);@@ -76,6 +98,9 @@ export class VideoCutter {if (audioTrack && audioSource) {const audioSink = new AudioSampleSink(audioTrack);for await (const sample of audioSink.samples(start, end)) {+ if (firstAudioTs === null) firstAudioTs = sample.timestamp;+ lastAudioTs = sample.timestamp;+ audioSampleCount += 1;const adjusted = Math.max(0, baseTimestamp + (sample.timestamp - start));sample.setTimestamp(adjusted);await audioSource.add(sample);@@ -85,17 +110,38 @@ export class VideoCutter {}}+ if (debugLog) {+ console.log(`[cut-debug][cutter] segment ${segIdx} done`, {+ requestedRange: [start, end],+ segDur,+ baseTimestamp,+ videoSampleCount,+ audioSampleCount,+ firstVideoTs,+ lastVideoTs,+ firstAudioTs,+ lastAudioTs,+ outPtsAfter: outPts + segDur * 1_000_000,+ });+ }+outPts += segDur * 1_000_000;};for (let i = 0; i < totalSegments.length; i++) {const [start, end] = totalSegments[i];- await addSegment(start, end);+ await addSegment(start, end, i);}await output.finalize();const blob = new Blob([outputTarget.buffer], { type: "video/mp4" });+ if (debugLog) {+ console.log("[cut-debug][cutter] finalize complete", {+ outputBlobSize: blob.size,+ expectedDuration: total - (cutEnd - cutStart),+ });+ }if (onProgress) onProgress(1);return blob;}@@ -103,12 +149,16 @@ export class VideoCutter {getDuration(blob) {return new Promise((res, rej) => {const v = document.createElement("video");- v.src = URL.createObjectURL(blob);+ const url = URL.createObjectURL(blob);+ v.src = url;v.onloadedmetadata = () => {- URL.revokeObjectURL(v.src);+ URL.revokeObjectURL(url);res(v.duration);};- v.onerror = () => rej(new Error("Failed to load video"));+ v.onerror = () => {+ URL.revokeObjectURL(url);+ rej(new Error("Failed to load video"));+ };});}}\ No newline at end of filediff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.tsindex 3879714..05564ae 100644--- a/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.ts+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoMuter.ts@@ -8,6 +8,7 @@ import {VideoSampleSource,VideoSampleSink,AudioSampleSource,+ AudioSampleSink,AudioSample,ALL_FORMATS,QUALITY_HIGH,@@ -27,14 +28,6 @@ export class VideoMuter {) {const videoDuration = await this._getDuration(videoBlob);- // Cap at 15 min to avoid OOM — re-encoding needs several copies in memory.- if (videoDuration > 900) {- throw new Error(- `Video is too long for in-browser audio muting (${Math.round(videoDuration / 60)} min). ` +- `Maximum supported length is 15 minutes.`- );- }-const input = new Input({source: new BlobSource(videoBlob),formats: ALL_FORMATS,@@ -56,81 +49,91 @@ export class VideoMuter {});output.addVideoTrack(videoSource);- let decodedAudio = null;- const ctx = new AudioContext();- try {- let buf = await videoBlob.arrayBuffer();- decodedAudio = await ctx.decodeAudioData(buf);- buf = null; // release compressed bytes; PCM is now in decodedAudio- } catch {- // decode failed; mute returns original blob below- } finally {- ctx.close().catch(() => {});- }-- const sr = decodedAudio?.sampleRate || 48000;- const mixBuffer = new Float32Array(Math.ceil(sr * videoDuration));-- if (decodedAudio) {- const channelData = decodedAudio.getChannelData(0);- const muteStartSample = Math.floor(muteStart * sr);- const muteEndSample = Math.floor(muteEnd * sr);-- for (let i = 0; i < channelData.length; i++) {- mixBuffer[i] =- i >= muteStartSample && i < muteEndSample ? 0 : channelData[i] * videoVolume;- }- } else {- return videoBlob;+ const audioTrack = await input.getPrimaryAudioTrack();+ const audioDecodable = audioTrack+ ? await audioTrack.canDecode().catch(() => false)+ : false;+ let audioSink = null;+ let audioSource = null;+ if (audioTrack && audioDecodable) {+ audioSink = new AudioSampleSink(audioTrack);+ audioSource = new AudioSampleSource({+ codec: "aac",+ bitrate: 128000,+ });+ output.addAudioTrack(audioSource);}- const audioSource = new AudioSampleSource({- codec: "aac",- bitrate: 128000,- });- output.addAudioTrack(audioSource);-await output.start();+for await (const frame of videoSink.samples(0, videoDuration)) {await videoSource.add(frame);frame.close();if (onProgress) onProgress(frame.timestamp / videoDuration);}- const totalSamples = Math.floor(videoDuration * sr);- const chunkSize = sr * 2;- let written = 0;+ if (audioSink && audioSource) {+ for await (const sample of audioSink.samples()) {+ const s = sample.timestamp;+ const e = s + sample.duration;+ const fullyOutside = e <= muteStart || s >= muteEnd;- while (written < totalSamples) {- const slice = mixBuffer.slice(written, written + chunkSize);- const dur = slice.length / sr;- const sample = new AudioSample({- data: slice,- format: "f32-planar",- numberOfChannels: 1,- sampleRate: sr,- timestamp: written / sr,- duration: dur,- });- await audioSource.add(sample);- sample.close();- written += chunkSize;+ if (fullyOutside && videoVolume === 1) {+ await audioSource.add(sample);+ sample.close();+ continue;+ }++ const numChannels = sample.numberOfChannels;+ const sr = sample.sampleRate;+ const frameCount = sample.numberOfFrames;+ const data = new Float32Array(frameCount * numChannels);+ for (let ch = 0; ch < numChannels; ch++) {+ const view = data.subarray(ch * frameCount, (ch + 1) * frameCount);+ sample.copyTo(view, { format: "f32-planar", planeIndex: ch });+ }++ for (let f = 0; f < frameCount; f++) {+ const t = s + f / sr;+ const gain = t >= muteStart && t < muteEnd ? 0 : videoVolume;+ if (gain !== 1) {+ for (let ch = 0; ch < numChannels; ch++) {+ data[ch * frameCount + f] *= gain;+ }+ }+ }++ const out = new AudioSample({+ data,+ format: "f32-planar",+ numberOfChannels: numChannels,+ sampleRate: sr,+ timestamp: s,+ duration: frameCount / sr,+ });+ await audioSource.add(out);+ out.close();+ sample.close();+ }}await output.finalize();- // Always MP4 container — use correct MIME type.return new Blob([outputTarget.buffer], { type: "video/mp4" });}async _getDuration(blob) {return new Promise((resolve, reject) => {const v = document.createElement("video");- v.src = URL.createObjectURL(blob);+ const url = URL.createObjectURL(blob);+ v.src = url;v.onloadedmetadata = () => {+ URL.revokeObjectURL(url);resolve(v.duration);- URL.revokeObjectURL(v.src);};- v.onerror = reject;+ v.onerror = (e) => {+ URL.revokeObjectURL(url);+ reject(e);+ };});}}\ No newline at end of filediff --git a/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.ts b/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.tsindex 8e0aecf..61d7a0e 100644--- a/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.ts+++ b/src/pages/EditorWebCodecs/mediabunny/lib/videoTrimmer.ts@@ -3,11 +3,13 @@ import {Input,Output,BlobSource,- BufferTarget,+ StreamTarget,Mp4OutputFormat,WebMOutputFormat,ALL_FORMATS,- Conversion,+ EncodedPacketSink,+ EncodedVideoPacketSource,+ EncodedAudioPacketSource,type OutputFormat,} from "mediabunny";@@ -20,21 +22,34 @@ export interface TrimOptions {onProgress?: (progress: number) => void;}-export interface TrimInfo {- originalDuration: number;- trimmedDuration: number;- startTime: number;- endTime: number;- format: string;-}+const TEMP_FILE_PREFIX = "trim-";+const STALE_AGE_MS = 5 * 60 * 1000;++const sweepStaleTrimFiles = async () => {+ try {+ const dir = await navigator.storage.getDirectory();+ const now = Date.now();+ for await (const [name, handle] of (dir as any).entries()) {+ if (!name.startsWith(TEMP_FILE_PREFIX)) continue;+ try {+ const file = await handle.getFile();+ if (now - file.lastModified > STALE_AGE_MS) {+ await dir.removeEntry(name).catch(() => {});+ }+ } catch {}+ }+ } catch {}+};export class VideoTrimmer {async trim(sourceBlob: Blob, options: TrimOptions): Promise<Blob> {- const { startTime, endTime, outputFormat, videoBitrate, audioBitrate, onProgress } = options;+ const { startTime, endTime, outputFormat, onProgress } = options;if (startTime < 0) throw new Error("Start time cannot be negative");if (endTime <= startTime) throw new Error("End time must be greater than start time");+ await sweepStaleTrimFiles();+const input = new Input({formats: ALL_FORMATS,source: new BlobSource(sourceBlob),@@ -45,36 +60,115 @@ export class VideoTrimmer {outputFormat ||(inputFormat.name.toLowerCase().includes("mp4") ? "mp4" : "webm");+ const videoTrack = await input.getPrimaryVideoTrack();+ if (!videoTrack) throw new Error("Trimming failed - no video track");+ const audioTrack = await input.getPrimaryAudioTrack().catch(() => null);++ // Stream-copy needs a keyframe at the cut; output is rebased to 0.+ const videoSink = new EncodedPacketSink(videoTrack);+ const startKey = await videoSink.getKeyPacket(startTime);+ if (!startKey) throw new Error("Trimming failed - no key packet at start");+ const baseTime = startKey.timestamp;+ const endVideoPacket = Number.isFinite(endTime)+ ? await videoSink.getPacket(endTime)+ : null;++ const dir = await navigator.storage.getDirectory();+ const outFileName = `${TEMP_FILE_PREFIX}${Date.now()}-${Math.random()+ .toString(36)+ .slice(2, 8)}.${targetFormat}`;+ const outHandle = await dir.getFileHandle(outFileName, { create: true });+ const writable = await (outHandle as any).createWritable();+const format: OutputFormat =targetFormat === "mp4"- ? new Mp4OutputFormat({ fastStart: "in-memory" })+ ? new Mp4OutputFormat({ fastStart: false }): new WebMOutputFormat();- const target = new BufferTarget();+ const target = new StreamTarget(writable, { chunked: true });const output = new Output({ format, target });- const conversion = await Conversion.init({- input,- output,- trim: { start: startTime, end: endTime },- ...(videoBitrate && { video: { bitrate: videoBitrate } }),- ...(audioBitrate && { audio: { bitrate: audioBitrate } }),- });-- if (!conversion.isValid) {- const reasons = conversion.discardedTracks- .map((t) => `${t.track.type}: ${t.reason}`)- .join(", ");- throw new Error(`Trimming failed - ${reasons}`);+ const videoCodec = videoTrack.codec;+ const videoDecoderConfig = await videoTrack.getDecoderConfig();+ const videoSource = new EncodedVideoPacketSource(videoCodec);+ output.addVideoTrack(videoSource);++ let audioSource: any = null;+ let audioDecoderConfig: any = null;+ if (audioTrack) {+ try {+ audioDecoderConfig = await audioTrack.getDecoderConfig();+ audioSource = new EncodedAudioPacketSource(audioTrack.codec);+ output.addAudioTrack(audioSource);+ } catch {+ audioSource = null;+ audioDecoderConfig = null;+ }}- if (onProgress) conversion.onProgress = onProgress;+ await output.start();++ const totalSpan = Math.max(0.001, endTime - baseTime);++ const pipeVideo = async () => {+ let isFirst = true;+ const iter = endVideoPacket+ ? videoSink.packets(startKey, endVideoPacket)+ : videoSink.packets(startKey);+ for await (const packet of iter) {+ const rebased = packet.clone({ timestamp: packet.timestamp - baseTime });+ if (isFirst) {+ await videoSource.add(rebased, { decoderConfig: videoDecoderConfig });+ isFirst = false;+ } else {+ await videoSource.add(rebased);+ }+ if (onProgress) {+ const pct = Math.min(1, (packet.timestamp - baseTime) / totalSpan);+ onProgress(pct);+ }+ }+ };- await conversion.execute();+ const pipeAudio = async () => {+ if (!audioSource || !audioTrack) return;+ const audioSink = new EncodedPacketSink(audioTrack);+ const startA = await audioSink.getPacket(baseTime);+ if (!startA) return;+ const endA = Number.isFinite(endTime)+ ? await audioSink.getPacket(endTime)+ : null;+ let isFirst = true;+ const iter = endA ? audioSink.packets(startA, endA) : audioSink.packets(startA);+ for await (const packet of iter) {+ // First audio packet may sit slightly before baseTime.+ const ts = Math.max(0, packet.timestamp - baseTime);+ const rebased = packet.clone({ timestamp: ts });+ if (isFirst) {+ await audioSource.add(rebased, { decoderConfig: audioDecoderConfig });+ isFirst = false;+ } else {+ await audioSource.add(rebased);+ }+ }+ };- if (!target.buffer) throw new Error("Trimming failed - no output buffer");+ try {+ await Promise.all([pipeVideo(), pipeAudio()]);+ await output.finalize();+ // finalize() owns the writable lock; don't close here.+ } catch (err) {+ try { await writable.abort(); } catch {}+ try { await dir.removeEntry(outFileName); } catch {}+ throw err;+ }- return new Blob([target.buffer], {+ const file = await outHandle.getFile();+ // Read into ArrayBuffer so deleting the OPFS entry doesn't invalidate+ // the returned Blob (some impls back File lazily by the handle).+ const bytes = await file.arrayBuffer();+ try { await dir.removeEntry(outFileName); } catch {}+ return new Blob([bytes], {type: targetFormat === "mp4" ? "video/mp4" : "video/webm",});}@@ -121,4 +215,4 @@ export async function trimVideo(options?: Omit<TrimOptions, "startTime" | "endTime">): Promise<Blob> {return videoTrimmer.trim(blob, { startTime, endTime, ...options });-}\ No newline at end of file+}diff --git a/src/pages/EditorWebCodecs/utils/cutVideo.js b/src/pages/EditorWebCodecs/utils/cutVideo.jsindex 08f6a7e..8db3799 100644--- a/src/pages/EditorWebCodecs/utils/cutVideo.js+++ b/src/pages/EditorWebCodecs/utils/cutVideo.js@@ -13,7 +13,28 @@ export default async function cutVideo() {let result;- if (cut) {+ // Edge cuts collapse to a single range; delegate to trimmer for stream-copy.+ // Trimmer snaps START back to the prior keyframe, so cutting [0, endTime]+ // can re-include up to one GOP (~1s) of "deleted" content. Accepted trade+ // because stream-copy is multi-second faster than re-encode.+ const EPS = 0.05;+ if (cut && startTime <= EPS) {+ const trimmer = new VideoTrimmer();+ result = await trimmer.trim(videoBlob, {+ startTime: endTime,+ endTime: duration ?? Number.POSITIVE_INFINITY,+ outputFormat: "mp4",+ onProgress,+ });+ } else if (cut && duration && endTime >= duration - EPS) {+ const trimmer = new VideoTrimmer();+ result = await trimmer.trim(videoBlob, {+ startTime: 0,+ endTime: startTime,+ outputFormat: "mp4",+ onProgress,+ });+ } else if (cut) {const cutter = new VideoCutter();result = await cutter.cut(videoBlob, {cutStart: startTime,diff --git a/src/pages/EditorWebCodecs/utils/toGIF.js b/src/pages/EditorWebCodecs/utils/toGIF.jsindex 28abb35..45fa6a1 100644--- a/src/pages/EditorWebCodecs/utils/toGIF.js+++ b/src/pages/EditorWebCodecs/utils/toGIF.js@@ -20,7 +20,7 @@ async function toGIF(ffmpeg, videoBlob, onProgress = () => {}) {canvas.height = height;const gif = new GIF({- workers: 2,+ workers: Math.max(2, Math.min(4, navigator.hardwareConcurrency || 2)),quality,width,height,diff --git a/src/pages/OffscreenRecorder/resumeJournal.js b/src/pages/OffscreenRecorder/resumeJournal.jsindex 904cc29..f85b927 100644--- a/src/pages/OffscreenRecorder/resumeJournal.js+++ b/src/pages/OffscreenRecorder/resumeJournal.js@@ -1,5 +1,6 @@import localforage from "localforage";import BunnyTusUploader from "../CloudRecorder/bunnyTusUploader";+import { openExistingChunksStore } from "../CloudRecorder/recorderStorage/chooseChunksStore";localforage.config({driver: localforage.INDEXEDDB,@@ -9,23 +10,64 @@ localforage.config({const JOURNAL_KEY_PREFIX = "uploadJournal-";-const chunkStoreForTrack = (trackType) => {- if (trackType === "camera") {- return localforage.createInstance({ name: "cameraChunks" });+const trackName = (trackType) =>+ trackType === "camera" ? "camera" : "screen";++// Pulls per-journal storage backend from the persisted recorder session.+// Journals written before the OPFS migration default to IDB. The uploader+// itself doesn't carry backend state, so this routes through chrome.storage.+const resolveBackendForJournal = async (journal) => {+ const sessionId = journal?.sessionId || null;+ const trackKey = trackName(journal?.trackType || "screen");++ // Try the per-session snapshot first (it survives even after a newer+ // session has overwritten the latest `recorderSession`).+ if (sessionId) {+ const sessionStateKey = `cloudRecorderSession:${sessionId}`;+ try {+ const snap = await chrome.storage.local.get([sessionStateKey]);+ const session = snap?.[sessionStateKey];+ if (session?.storageBackends) {+ return {+ backend: session.storageBackends[trackKey] || "idb",+ opfsSessionId: session.opfsSessionId || sessionId,+ };+ }+ } catch {}}- return localforage.createInstance({ name: "chunks" });++ // Fallback: latest recorderSession may match if we're resuming the only+ // outstanding session.+ try {+ const snap = await chrome.storage.local.get(["recorderSession"]);+ const session = snap?.recorderSession;+ if (+ session?.storageBackends &&+ (session.id === sessionId || !sessionId)+ ) {+ return {+ backend: session.storageBackends[trackKey] || "idb",+ opfsSessionId: session.opfsSessionId || sessionId,+ };+ }+ } catch {}++ return { backend: "idb", opfsSessionId: sessionId };};-const loadChunksSorted = async (store) => {+const chunkKeyPrefixForTrack = (trackType) =>+ trackType === "camera" ? "camera_chunk_" : "chunk_";++const loadChunksSorted = async (store, prefix = "chunk_") => {const items = [];await store.iterate((value, key) => {- if (!key || !key.startsWith("chunk_")) return;+ if (!key || !key.startsWith(prefix)) return;if (!value || !value.chunk) return;items.push({index:typeof value.index === "number"? value.index- : parseInt(key.replace("chunk_", ""), 10) || 0,+ : parseInt(key.replace(prefix, ""), 10) || 0,chunk: value.chunk,timestamp: value.timestamp || 0,});@@ -34,6 +76,32 @@ const loadChunksSorted = async (store) => {return items;};+// Tus PATCH writes at the offset header without content validation, so+// re-sending chunks already received corrupts the file silently.+const skipAlreadyUploadedChunks = (chunks, alreadyUploadedBytes) => {+ if (!alreadyUploadedBytes || alreadyUploadedBytes <= 0) return chunks;+ let cumulative = 0;+ for (let i = 0; i < chunks.length; i++) {+ const chunkSize = chunks[i].chunk?.size || 0;+ const chunkEnd = cumulative + chunkSize;+ if (chunkEnd <= alreadyUploadedBytes) {+ cumulative = chunkEnd;+ continue;+ }+ // Boundary chunk straddles serverOffset; slice the uploaded prefix.+ const sliceOffset = alreadyUploadedBytes - cumulative;+ const remaining = chunks.slice(i);+ if (sliceOffset > 0 && typeof remaining[0]?.chunk?.slice === "function") {+ remaining[0] = {+ ...remaining[0],+ chunk: remaining[0].chunk.slice(sliceOffset),+ };+ }+ return remaining;+ }+ return [];+};+const bumpResumeAttempts = async (journal) => {const key = `${JOURNAL_KEY_PREFIX}${journal.mediaId}`;try {@@ -80,11 +148,19 @@ export const resumeOneJournal = async (journal) => {resumeAttempts: journal.resumeAttempts || 0,});- const store = chunkStoreForTrack(trackType);- const chunks = await loadChunksSorted(store);+ const { backend, opfsSessionId } = await resolveBackendForJournal(journal);+ const { store } = openExistingChunksStore({+ sessionId: opfsSessionId,+ track: trackName(trackType),+ backend,+ });+ const chunks = await loadChunksSorted(+ store,+ chunkKeyPrefixForTrack(trackType),+ );if (!chunks.length) {- // Orphan journal - chunks cleared or never written. GC.+ // Orphan journal: chunks cleared or never written. GC.emit("upload_resume_chunks_missing", { mediaId, trackType });try {await chrome.storage.local.remove([@@ -94,24 +170,6 @@ export const resumeOneJournal = async (journal) => {return { ok: false, error: "chunks-missing" };}- // Sparse chunks (purge ran mid-recording) would corrupt the replay - abandon and let server state stand.- const isContiguous = chunks.every((c, i) => c.index === i);- if (!isContiguous) {- emit("upload_resume_sparse_chunks", {- mediaId,- trackType,- firstIndex: chunks[0]?.index,- lastIndex: chunks[chunks.length - 1]?.index,- count: chunks.length,- });- try {- await chrome.storage.local.remove([- `${JOURNAL_KEY_PREFIX}${mediaId}`,- ]);- } catch {}- return { ok: false, error: "sparse-chunks" };- }-const uploader = new BunnyTusUploader({ trackType });try {@@ -135,8 +193,52 @@ export const resumeOneJournal = async (journal) => {return { ok: false, error: `initialize: ${err?.message || err}` };}+ // uploader.offset = bytes Bunny has. Finalize-only if full, else replay+ // the gap (bail on sparse local chunks).+ const serverOffset = uploader.offset || 0;+ const journalTotalBytes = journal.totalBytes || 0;+ const serverHasEverything =+ journalTotalBytes > 0 && serverOffset >= journalTotalBytes;++ let remainingChunks = [];+ if (serverHasEverything) {+ emit("upload_resume_finalize_only", {+ mediaId,+ trackType,+ serverOffset,+ journalTotalBytes,+ });+ } else {+ const isContiguous = chunks.every((c, i) => c.index === i);+ if (!isContiguous) {+ emit("upload_resume_sparse_chunks", {+ mediaId,+ trackType,+ firstIndex: chunks[0]?.index,+ lastIndex: chunks[chunks.length - 1]?.index,+ count: chunks.length,+ serverOffset,+ journalTotalBytes,+ });+ try {+ await chrome.storage.local.remove([+ `${JOURNAL_KEY_PREFIX}${mediaId}`,+ ]);+ } catch {}+ return { ok: false, error: "sparse-chunks" };+ }++ remainingChunks = skipAlreadyUploadedChunks(chunks, serverOffset);+ emit("upload_resume_chunks_skipped", {+ mediaId,+ serverOffset,+ totalChunks: chunks.length,+ remainingChunks: remainingChunks.length,+ });+ }+try {- for (const { chunk } of chunks) {+ for (const { chunk } of remainingChunks) {if (uploader.status === "aborted" || uploader.status === "error") break;await uploader.write(chunk);}diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsxindex a6148af..f136198 100644--- a/src/pages/Recorder/Recorder.jsx+++ b/src/pages/Recorder/Recorder.jsx@@ -4,9 +4,17 @@ import RecorderUI from "./RecorderUI";import { createMediaRecorder } from "./mediaRecorderUtils";import { sendRecordingError, sendStopRecording } from "./messaging";import { getBitrates, getResolutionForQuality } from "./recorderConfig";-import { WebCodecsRecorder } from "./webcodecs/WebCodecsRecorder";+import {+ WebCodecsRecorder,+ preloadWebCodecsModules,+} from "./webcodecs/WebCodecsRecorder";+import { startPrewarm, stopPrewarm } from "./streamWarmup";import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";import { IS_OFFSCREEN_HOST } from "../utils/recordingHost";+import { chooseWriter } from "./recorderStorage/chooseWriter";+import { chooseReader } from "./recorderStorage/chooseReader";+import { lifecycle } from "../utils/lifecycleLog";+import { perfMark, perfSpan } from "../utils/perfMarks";import {debugRecordingEvent,resetRecordingDebugSession,@@ -19,6 +27,7 @@ import {getFastRecorderStickyState,markFastRecorderFailure,validateFastRecorderOutputBlob,+ isTransientFastRecorderError,} from "../../media/fastRecorderGate";localforage.config({@@ -33,8 +42,7 @@ const chunksStore = localforage.createInstance({document.body.style.willChange = "contents";-// Debug flag for logging-// window.SCREENITY_DEBUG_RECORDER = true;+// Toggle: window.SCREENITY_DEBUG_RECORDER = trueconst DEBUG_RECORDER =typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;const FORCE_MEDIARECORDER =@@ -61,9 +69,9 @@ function debugError(...args) {console.error(logPrefix, ...args);}-// Stream lifecycle ring-buffer — persisted to storage, survives tab discards.+// Stream lifecycle ring-buffer, persisted to storage, survives tab discards.const SL_KEY = "streamLifecycleLog";-const SL_MAX = 40; // keep last N entries+const SL_MAX = 40;const _slBuffer = [];function slLog(tag, extra = {}) {@@ -74,10 +82,9 @@ function slLog(tag, extra = {}) {}_slBuffer.push(entry);if (_slBuffer.length > SL_MAX) _slBuffer.splice(0, _slBuffer.length - SL_MAX);- // Fire-and-forget persist.try {chrome.storage.local.set({ [SL_KEY]: [..._slBuffer] });- } catch { /* storage unavailable — tab possibly being torn down */ }+ } catch {}}function logCaptureContext(label, stream) {@@ -165,11 +172,18 @@ const getFreeCaptureCaps = async () => {}};-const computeTargetVideoBps = (width, height, fps) => {+// bits/pixel/sec. Pro gets higher quality, Free smaller files.+const VIDEO_BPP_FPS_PRO = 0.10;+const VIDEO_BPP_FPS_FREE = 0.08;+const VIDEO_BPS_MIN = 4_000_000;+const VIDEO_BPS_MAX = 24_000_000;++const computeTargetVideoBps = (width, height, fps, isPro = false) => {const pixels = Number(width) * Number(height);const rate = Number.isFinite(fps) && fps > 0 ? fps : 30;- const target = Math.round(pixels * rate * 0.1);- return clamp(target, 6_000_000, 24_000_000);+ const factor = isPro ? VIDEO_BPP_FPS_PRO : VIDEO_BPP_FPS_FREE;+ const target = Math.round(pixels * rate * factor);+ return clamp(target, VIDEO_BPS_MIN, VIDEO_BPS_MAX);};const selectMimeType = (preferredCodec) => {@@ -216,25 +230,32 @@ const Recorder = () => {const [started, setStarted] = useState(false);const streamReadyAt = useRef(null);- // Start gate: defers startRecording() until the stream is ready.+ // Keep getDisplayMedia track hot during countdown so the OS capture pipeline+ // doesn't go idle between warm-up and recorder.start(). On macOS, an idle+ // capture stream re-warms in ~1s and emits stale frames in the meantime.+ const prewarmRef = useRef(null);+ // Holds an in-flight chunksStore.clear() kicked off during the countdown so+ // startRecording's await is near-instant. Re-clearing on the actual start+ // path is a no-op since the store is already empty.+ const prewarmChunksClearRef = useRef(null);+ // Pre-opened OPFS writer + recordingId. Saves ~30-90ms of file create + sync+ // handle setup off the post-countdown critical path. Aborted if startRecording+ // determines a different backend is needed, or if the prewarm is cancelled.+ const prewarmedWriterRef = useRef(null);++ // Start gate: defer startRecording() until the stream is ready.const startRequested = useRef(false);const startRequestedAt = useRef(null);- // Null on start-gate timeout: SW-to-tab handoff failed (distinct error code).+ // Null after a start-gate timeout marks SW-to-tab handoff failure.const streamingDataReceivedAt = useRef(null);- // Timeout if the stream never arrivesconst startGateTimeout = useRef(null);- // 12s accounts for cold SW wake-ups on Windows Chrome, where the SW can- // take several seconds to revive after suspension before it can process- // get-streaming-data. 8s was too tight under that workload.+ // 12s: cold SW wake-ups on Windows Chrome can take several seconds; 8s was too tight.const START_GATE_TIMEOUT_MS = 12000;const streamingDataRetryTimer = useRef(null);- // Pulls streaming-data from the SW with retry. Chrome can fail the initial- // sendMessage if the SW is in the middle of waking up (returns lastError- // "Receiving end does not exist") and silently drop the request. Retry- // with backoff until streaming-data arrives or the start gate times out.- // The SW also pushes streaming-data proactively, so duplicate delivery- // is possible; the streaming-data handler is idempotent to cover that.+ // Retry get-streaming-data: an initial sendMessage during SW wake-up can fail+ // with "Receiving end does not exist" and silently drop. The SW also pushes+ // streaming-data proactively, so the handler must remain idempotent.const requestStreamingDataWithRetry = (attempt = 0) => {if (streamingDataReceivedAt.current != null) return;const maxAttempts = 5;@@ -293,9 +314,18 @@ const Recorder = () => {const recorder = useRef(null);const useWebCodecs = useRef(false);+ // null on MediaRecorder path.+ const chunkWriter = useRef(null);+ const chunkWriterBackend = useRef(null);+ // Set at writer.close(); validator + sandbox use this to pick the reader.+ const chunkBackendRef = useRef(null);const isTab = useRef(false);const tabID = useRef(null);+ // Numeric chrome tab id (tabID holds the chromeMediaSourceId from+ // tabCapture). Used to query the tab's viewport for aspect-correct+ // capture constraints.+ const recordedTabId = useRef(null);const tabPreferred = useRef(false);const backupRef = useRef(false);@@ -308,19 +338,22 @@ const Recorder = () => {const lastEstimateAt = useRef(0);const ESTIMATE_INTERVAL_MS = 5000;const MIN_HEADROOM = 25 * 1024 * 1024;- const WARN_HEADROOM = 100 * 1024 * 1024; // early warning before hard abort+ const WARN_HEADROOM = 100 * 1024 * 1024;const MAX_PENDING_BYTES = 8 * 1024 * 1024;const pendingBytes = useRef(0);const lowStorageWarned = useRef(false);+ const estimateFailed = useRef(false);+ const deviceChangeListenerRef = useRef(null);+ const silenceWatchdogRef = useRef(null);const uiClosing = useRef(false);const isRecording = useRef(false);const isStarting = useRef(false);const pausedStateRef = useRef(false);+ const pausedAtRef = useRef(null);const stopSignalSent = useRef(false);- // Keep-alive mechanism to prevent Chrome from freezing this background tabconst keepAliveAudioCtx = useRef(null);const keepAliveOscillator = useRef(null);const keepAliveLockAbort = useRef(null);@@ -344,12 +377,15 @@ const Recorder = () => {async function canFitChunk(byteLength) {const now = performance.now();if (now - lastEstimateAt.current < ESTIMATE_INTERVAL_MS) {+ // In the throttle window: trust prior result; bail if last estimate failed.+ if (estimateFailed.current) return false;return !lowStorageAbort.current;}lastEstimateAt.current = now;try {const { usage = 0, quota = 0 } = await navigator.storage.estimate();+ estimateFailed.current = false;const remaining = quota - usage;const ok = remaining > MIN_HEADROOM + (byteLength || 0);if (DEBUG_RECORDER) {@@ -361,7 +397,6 @@ const Recorder = () => {ok,});}- // Early warning before hard abortif (!lowStorageWarned.current && remaining < WARN_HEADROOM) {lowStorageWarned.current = true;chrome.runtime.sendMessage({@@ -372,83 +407,135 @@ const Recorder = () => {}return ok;} catch (err) {- debugWarn("navigator.storage.estimate() failed, assuming OK", err);- return !lowStorageAbort.current;+ // No quota info: caller bails ("stop recording" beats QuotaExceeded mid-write).+ debugWarn("navigator.storage.estimate() failed, treating as low-storage", err);+ estimateFailed.current = true;+ return false;}}- /**- * Start silent audio playback to prevent Chrome from freezing this tab.- * Chrome throttles/freezes background tabs after ~5 minutes of inactivity,- * which would stop our recording. Playing silent audio keeps the tab active.- */+ // Tab keep-alive: Chrome throttles/freezes background tabs after ~5 minutes of+ // inactivity. Multi-layered signals stack against the freeze heuristic.+ // recorder.html runs an inline keepalive bootstrap (see Recorder/index.html)+ // so throttling can't kick in before React mounts; we reuse those resources+ // to avoid a duplicate AudioContext or second lock holder.const startTabKeepAlive = () => {if (IS_OFFSCREEN_HOST) return;- // Multi-layered keepalive - Chrome's freeze heuristic stacks several signals.+ perfMark("Recorder keepalive.enter");++ const inlineKA =+ typeof window !== "undefined" ? window.__SCREENITY_KEEPALIVE : null;++ // startedAt/completedAt are written by the inline IIFE in recorder.html.+ // Missing means the inline path failed (or was stripped) and we're cold.+ perfMark("Recorder keepalive.inline-state", {+ hasInline: Boolean(inlineKA),+ hasAudioCtx: Boolean(inlineKA?.audioCtx),+ hasLock: Boolean(inlineKA?.lockAbort),+ hasMediaSession: Boolean(inlineKA?.mediaSession),+ inlineStartedAt: inlineKA?.startedAt || null,+ inlineCompletedAt: inlineKA?.completedAt || null,+ inlineDurationMs:+ inlineKA?.startedAt && inlineKA?.completedAt+ ? inlineKA.completedAt - inlineKA.startedAt+ : null,+ });++ const endAudio = perfSpan("Recorder keepalive.audio");+ let audioPath = "skip-already-set";try {if (!keepAliveAudioCtx.current) {- const ctx = new (window.AudioContext || window.webkitAudioContext)();- keepAliveAudioCtx.current = ctx;- const oscillator = ctx.createOscillator();- const gainNode = ctx.createGain();- oscillator.type = "sine";- oscillator.frequency.value = 20000;- gainNode.gain.value = 0.0001;- oscillator.connect(gainNode);- gainNode.connect(ctx.destination);- oscillator.start();- keepAliveOscillator.current = oscillator;+ if (inlineKA?.audioCtx && inlineKA?.oscillator) {+ // Adopt the inline context so it survives GC and stop can clean it up.+ keepAliveAudioCtx.current = inlineKA.audioCtx;+ keepAliveOscillator.current = inlineKA.oscillator;+ audioPath = "adopt-inline";+ } else {+ audioPath = "create-fresh";+ const ctx = new (window.AudioContext || window.webkitAudioContext)();+ keepAliveAudioCtx.current = ctx;+ const oscillator = ctx.createOscillator();+ const gainNode = ctx.createGain();+ oscillator.type = "sine";+ oscillator.frequency.value = 20000;+ gainNode.gain.value = 0.0001;+ oscillator.connect(gainNode);+ gainNode.connect(ctx.destination);+ oscillator.start();+ keepAliveOscillator.current = oscillator;+ }}} catch (err) {debugWarn("keepalive: audio layer failed:", err);+ audioPath = "error";}+ endAudio({ path: audioPath });+ const endLocks = perfSpan("Recorder keepalive.locks");+ let lockPath = "skip-already-set";try {if (typeof navigator.locks !== "undefined" && !keepAliveLockAbort.current) {- const ac = new AbortController();- keepAliveLockAbort.current = ac;- navigator.locks- .request(- "screenity-recorder-keepalive",- { mode: "exclusive", signal: ac.signal },- () => new Promise(() => {}),- )- .catch(() => {});+ if (inlineKA?.lockAbort) {+ keepAliveLockAbort.current = inlineKA.lockAbort;+ lockPath = "adopt-inline";+ } else {+ lockPath = "create-fresh";+ const ac = new AbortController();+ keepAliveLockAbort.current = ac;+ navigator.locks+ .request(+ "screenity-recorder-keepalive",+ { mode: "exclusive", signal: ac.signal },+ () => new Promise(() => {}),+ )+ .catch(() => {});+ }}} catch (err) {debugWarn("keepalive: lock layer failed:", err);+ lockPath = "error";}+ endLocks({ path: lockPath });+ const endMs = perfSpan("Recorder keepalive.mediaSession");+ let msPath = "skip-already-set";try {if (navigator.mediaSession && !keepAliveMediaSessionActive.current) {- navigator.mediaSession.metadata = new window.MediaMetadata({- title: "Screenity recording",- artist: "Screenity",- });- navigator.mediaSession.playbackState = "playing";- try {- navigator.mediaSession.setActionHandler("pause", () => {});- } catch {}- keepAliveMediaSessionActive.current = true;+ if (inlineKA?.mediaSession) {+ keepAliveMediaSessionActive.current = true;+ msPath = "adopt-inline";+ } else {+ msPath = "create-fresh";+ navigator.mediaSession.metadata = new window.MediaMetadata({+ title: "Screenity recording",+ artist: "Screenity",+ });+ navigator.mediaSession.playbackState = "playing";+ try {+ navigator.mediaSession.setActionHandler("pause", () => {});+ } catch {}+ keepAliveMediaSessionActive.current = true;+ }}} catch (err) {debugWarn("keepalive: mediaSession layer failed:", err);+ msPath = "error";}+ endMs({ path: msPath });+ perfMark("Recorder keepalive.bg-messages.start");chrome.runtime.sendMessage({ type: "set-tab-auto-discardable", discardable: false }).catch(() => {});chrome.runtime.sendMessage({ type: "start-recorder-keepalive-alarm" }).catch(() => {});+ perfMark("Recorder keepalive.bg-messages.end");debug("Tab keep-alive started");};- /**- * Stop the silent audio playback when recording ends.- */const stopTabKeepAlive = () => {try {if (keepAliveOscillator.current) {@@ -474,12 +561,10 @@ const Recorder = () => {.sendMessage({ type: "stop-recorder-keepalive-alarm" }).catch(() => {});- // Allow Chrome to discard this tab again if neededchrome.runtime.sendMessage({ type: "set-tab-auto-discardable", discardable: true }).catch(() => {});- // Cancel first-chunk watchdogchrome.runtime.sendMessage({ type: "cancel-first-chunk-watchdog" }).catch(() => {});@@ -490,9 +575,6 @@ const Recorder = () => {}};- /**- * Persist recording session state for recovery and diagnostics.- */const persistSessionState = async (status = "recording") => {try {await chrome.storage.local.set({@@ -516,7 +598,7 @@ const Recorder = () => {if (sessionHeartbeat.current) clearInterval(sessionHeartbeat.current);// For WebCodecs: the muxer only emits a single chunk at finalize, so// handleChunk can't drive the recording-stall watchdog heartbeat during- // the recording. Drive it from here instead — writes lastChunkAt every+ // the recording. Drive it from here instead, writes lastChunkAt every// 10s, plus firstChunkAt on the first tick (also overwrites any stale// values left from a prior session that hadn't been cleaned up yet).let firstHeartbeat = true;@@ -533,13 +615,10 @@ const Recorder = () => {chrome.storage.local.set(update).catch(() => {});}};- tick(); // fire immediately so first heartbeat lands before the 30s stall window+ tick(); // first heartbeat must land before the 30s stall windowsessionHeartbeat.current = setInterval(tick, 10000);};- /**- * Stop the session heartbeat.- */const stopSessionHeartbeat = () => {if (sessionHeartbeat.current) {clearInterval(sessionHeartbeat.current);@@ -547,10 +626,7 @@ const Recorder = () => {}};- /**- * Keep timer UI responsive in content scripts by updating a tick in storage.- * This runs in the recorder tab, which is kept alive during recording.- */+ // Update a storage tick so content-script timer UIs stay responsive.const startRecordingTick = () => {if (recordingTick.current) clearInterval(recordingTick.current);recordingTick.current = setInterval(async () => {@@ -576,7 +652,7 @@ const Recorder = () => {}};- // Emit stop to background at most once per recording session.+ // At most one stop emission per recording session.const requestStop = (reason = "generic", extra = {}) => {if (stopSignalSent.current) {debugWarn("requestStop() ignored; already sent", { reason });@@ -601,6 +677,19 @@ const Recorder = () => {if (!(await canFitChunk(e.data.size))) {debugWarn("Low storage, aborting recording");if (!lowStorageAbort.current) {+ // Forward to BG diag so the support zip captures abort timing/amount.+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-low-storage-abort",+ data: {+ chunkSize: e.data.size,+ chunkIndex: index.current,+ savedCount: savedCount.current,+ estimateFailed: estimateFailed.current,+ },+ });+ } catch {}chrome.runtime.sendMessage({type: "show-toast",message: chrome.i18n.getMessage("toastStorageCritical"),@@ -681,7 +770,30 @@ const Recorder = () => {}while (pending.current.length) {if (lowStorageAbort.current) {- debugWarn("Low storage while draining, clearing queue");+ // Bypass the 25MB headroom gate post-abort: chunks are <500KB so disk+ // usually accepts a few more, recovering the last 1-2s. Stop on first throw.+ let savedDuringAbort = 0;+ while (pending.current.length) {+ const tail = pending.current.shift();+ pendingBytes.current -= tail.data.size;+ try {+ const i = index.current;+ await chunksStore.setItem(`chunk_${i}`, {+ index: i,+ chunk: tail.data,+ timestamp: tail.timecode ?? 0,+ });+ index.current = i + 1;+ savedCount.current += 1;+ savedDuringAbort += 1;+ } catch (writeErr) {+ debugWarn("low-storage tail write failed, stopping drain", writeErr);+ break;+ }+ }+ if (DEBUG_RECORDER) {+ debug("Low-storage tail drained", { savedDuringAbort });+ }pending.current.length = 0;pendingBytes.current = 0;break;@@ -709,6 +821,17 @@ const Recorder = () => {lowStorageAbortChunks: index.current,});requestStop("low-storage", { memoryError: true, savedChunks: savedCount.current });+ // Save the dequeued chunk as a tail; mirrors the abort branch above.+ try {+ const i = index.current;+ await chunksStore.setItem(`chunk_${i}`, {+ index: i,+ chunk: e.data,+ timestamp: e.timecode ?? 0,+ });+ index.current = i + 1;+ savedCount.current += 1;+ } catch {}pending.current.length = 0;pendingBytes.current = 0;break;@@ -733,7 +856,16 @@ const Recorder = () => {if (DEBUG_RECORDER) {debug("waitForDrain() called");}+ // Cap so a wedged drain doesn't block stop forever.+ const deadline = Date.now() + 30000;while (draining.current || pending.current.length) {+ if (Date.now() > deadline) {+ debugWarn("waitForDrain timed out", {+ pending: pending.current.length,+ draining: draining.current,+ });+ break;+ }await new Promise((r) => setTimeout(r, 10));}if (DEBUG_RECORDER) {@@ -748,7 +880,17 @@ const Recorder = () => {});}, []);- // Check whether the stream is in a startable state.+ // The recorder tab opens hidden (active:false for region/non-camera). Chrome+ // throttles silent hidden tabs after ~1s, before streaming-data arrives, so+ // start keepalive at mount.+ useEffect(() => {+ perfMark("Recorder mount.useEffect");+ try {+ startTabKeepAlive();+ perfMark("Recorder mount.startTabKeepAlive-done");+ } catch (err) {}+ }, []);+function getStreamReadiness() {if (!helperVideoStream.current) return { ready: false, reason: "stream-ref-null" };const vt = helperVideoStream.current.getVideoTracks();@@ -779,14 +921,13 @@ const Recorder = () => {};}- /** Arm a timeout that errors if the stream never shows up. */function armStartGateTimeout() {clearStartGateTimeout();startGateTimeout.current = setTimeout(() => {- if (!startRequested.current) return; // request was fulfilled or cancelled+ if (!startRequested.current) return;const readiness = getStreamReadiness();if (readiness.ready) {- // Race: stream arrived just before timeout+ // Stream arrived just before timeout.slLog("start-gate-timeout-race-ok");tryStartIfReady();return;@@ -798,7 +939,6 @@ const Recorder = () => {console.warn("[Screenity:startRec] stream never became ready", diagInfo);slLog("start-gate-timeout", diagInfo);chrome.storage.local.set({ lastStreamCheckFail: diagInfo });- // Full reset so no gate state leaks into a future session.resetGateState();if (streamingDataReceivedAt.current == null) {sendRecordingError(@@ -819,7 +959,6 @@ const Recorder = () => {}}- /** Reset gate state on stop/dismiss/restart. */function resetGateState() {startRequested.current = false;startRequestedAt.current = null;@@ -832,7 +971,6 @@ const Recorder = () => {}}- /** Request recording start — immediate if stream is ready, deferred otherwise. */function requestStart() {if (recorder.current !== null || isStarting.current) {debugWarn("requestStart() called but recorder already exists or start in flight");@@ -849,7 +987,6 @@ const Recorder = () => {return;}if (startRequested.current) {- // Already waiting — ignore duplicate.slLog("requestStart-bail-already-requested");return;}@@ -873,7 +1010,6 @@ const Recorder = () => {}}- /** If a start was requested and the stream is ready, fire startRecording(). */function tryStartIfReady() {if (!startRequested.current) return;const readiness = getStreamReadiness();@@ -882,11 +1018,12 @@ const Recorder = () => {clearStartGateTimeout();startRecording();}- // Otherwise the gate timeout handles it.}- // startRecording — stream must be ready (verified by the gate above).async function startRecording() {+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][recorder] startRecording entry");+ }slLog("startRecording-enter", {hasRecorder: recorder.current !== null,hasStream: !!helperVideoStream.current,@@ -895,7 +1032,6 @@ const Recorder = () => {docHidden: document.hidden,});- // Acting on the request now — reset gate state.resetGateState();if (recorder.current !== null || isStarting.current) {@@ -912,13 +1048,21 @@ const Recorder = () => {recordingGeneration.current += 1;const runGeneration = recordingGeneration.current;- // Ensure keepalive is runningstartTabKeepAlive();- // Record the start time for session tracking+ // Fire-and-forget prewarm cancel: awaiting it leaves a gap with no+ // reader on the track, which macOS interprets as "no demand" and puts+ // capture back to sleep. Re-spinning takes 5s under load and the first+ // encoded frame freezes on screen for that long. Not awaiting lets+ // WebCodecsRecorder.start() open its own processor while the prewarm+ // reader is still releasing, so the OS sees continuous demand.+ // keepClear / keepWriter pass the in-flight clear and pre-opened writer+ // to the preflight code below.+ endPrewarm({ keepClear: true, keepWriter: true });+recordingStartTime.current = Date.now();- // Final preflight — edge-case guard in case state changed since the gate.+ // Final preflight: state may have changed since the gate.navigator.storage.persist();if (!helperVideoStream.current) {const diagInfo = buildStreamDiagInfo("stream-ref-null");@@ -968,7 +1112,15 @@ const Recorder = () => {}}- await chunksStore.clear();+ perfMark("Recorder.preflight.enter");+ const endChunksClear = perfSpan("Recorder.preflight chunksStore.clear");+ if (prewarmChunksClearRef.current) {+ await prewarmChunksClearRef.current;+ prewarmChunksClearRef.current = null;+ } else {+ await chunksStore.clear();+ }+ endChunksClear();debug("Cleared chunksStore");lastTimecode.current = 0;@@ -983,8 +1135,15 @@ const Recorder = () => {isFinishing.current = false;stopSignalSent.current = false;- const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);- const { isPro, maxQuality, maxFps } = await getFreeCaptureCaps();+ const endCapsRead = perfSpan("Recorder.preflight storage+caps");+ const [+ { qualityValue, useWebCodecsRecorder: prefUseWebCodecs },+ { isPro, maxQuality, maxFps },+ ] = await Promise.all([+ chrome.storage.local.get(["qualityValue", "useWebCodecsRecorder"]),+ getFreeCaptureCaps(),+ ]);+ endCapsRead();const effectiveQualityValue = isPro? qualityValue: clampQualityValue(qualityValue, maxQuality);@@ -998,20 +1157,130 @@ const Recorder = () => {videoBitsPerSecond,});- const recordingId = `${Date.now()}-${Math.random()- .toString(16)- .slice(2, 8)}`;+ // If the prewarm pre-opened an OPFS writer, consume it (saves ~30-90ms).+ // Resolve the in-flight promise here without blocking on it later.+ const prewarmedWriter = prewarmedWriterRef.current+ ? await prewarmedWriterRef.current.catch(() => null)+ : null;+ prewarmedWriterRef.current = null;++ const recordingId =+ prewarmedWriter?.recordingId ||+ `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;+ const endActiveSet = perfSpan("Recorder.preflight set fastRecorderActive");await chrome.storage.local.set({fastRecorderActiveRecordingId: recordingId,fastRecorderInUse: false,fastRecorderValidationFailed: false,fastRecorderValidation: null,});+ endActiveSet();++ // Chunk backend: fall back to IDB if OPFS open() fails. Prefer IDB up-front+ // when WebCodecs is skipped: the legacy editor's sandboxed iframe lacks+ // allow-same-origin and can't read OPFS.+ const endStickyRead = perfSpan("Recorder.preflight getStickyState");+ const earlyStickyState = await getFastRecorderStickyState();+ endStickyRead();+ const willLikelyUseFast =+ prefUseWebCodecs !== false &&+ !(earlyStickyState?.disabled && prefUseWebCodecs !== true);++ chunkWriter.current = null;+ chunkWriterBackend.current = null;+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][recorder] chooseWriter entry", {+ recordingId,+ willLikelyUseFast,+ });+ }+ try {+ const endChoose = perfSpan("Recorder.preflight chooseWriter");+ let selection;+ let openResult = null;+ const wantBackend = willLikelyUseFast ? "opfs" : "idb";+ const prewarmedMatches =+ prewarmedWriter && prewarmedWriter.selection.backend === wantBackend;+ if (prewarmedMatches) {+ selection = prewarmedWriter.selection;+ openResult = prewarmedWriter.openResult;+ } else {+ if (prewarmedWriter?.selection?.writer?.abort) {+ prewarmedWriter.selection.writer.abort().catch(() => {});+ }+ selection = await chooseWriter({ preferOpfs: willLikelyUseFast });+ }+ endChoose({ backend: selection?.backend, prewarmed: prewarmedMatches });+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][recorder] chooseWriter returned", {+ backend: selection.backend,+ prewarmed: prewarmedMatches,+ });+ }+ const endOpen = perfSpan("Recorder.preflight writer.open");+ try {+ if (!openResult) {+ openResult = await selection.writer.open(recordingId);+ }+ endOpen({ backend: selection.backend, prewarmed: prewarmedMatches });+ } catch (openErr) {+ endOpen({ backend: selection.backend, ok: false });+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.warn(+ "[recorder-opfs][recorder] writer.open failed",+ selection.backend,+ openErr,+ );+ }+ if (selection.backend === "opfs") {+ try {+ await selection.writer.abort();+ } catch {}+ selection = await chooseWriter({ preferOpfs: false });+ openResult = await selection.writer.open(recordingId);+ } else {+ throw openErr;+ }+ }+ chunkWriter.current = selection.writer;+ chunkWriterBackend.current = selection.backend;+ // Persist backendRef at open time - the OPFS file is wiped on open.+ const backendRefAtOpen = openResult?.backendRef || {+ backend: selection.backend,+ };+ chunkBackendRef.current = backendRefAtOpen;+ const endBackendRefSet = perfSpan("Recorder.preflight set backendRef");+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: backendRefAtOpen,+ });+ } catch {}+ endBackendRefSet();+ perfMark("Recorder.preflight.done");+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][recorder] writer-open", {+ backend: selection.backend,+ recordingId,+ backendRef: backendRefAtOpen,+ });+ }+ } catch (err) {+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.error("[recorder-opfs][recorder] chooseWriter path threw", err);+ }+ debugWarn("chooseWriter failed, falling back to direct chunksStore", err);+ chunkBackendRef.current = { backend: "idb" };+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: { backend: "idb" },+ });+ } catch {}+ }const { useWebCodecsRecorder } = await chrome.storage.local.get(["useWebCodecsRecorder",]);- // Default-on: treat undefined as enabled; only explicit `false` opts out.+ // Default-on: undefined means enabled; only explicit `false` opts out.const userSetting = useWebCodecsRecorder === false ? false : true;const stickyState = await getFastRecorderStickyState();const probeResult = await probeFastRecorderSupport();@@ -1083,13 +1352,14 @@ const Recorder = () => {if (!isPro) {fps = Math.min(fps, maxFps);}- const computedBps = computeTargetVideoBps(width, height, fps);+ const computedBps = computeTargetVideoBps(width, height, fps, isPro);videoBitsPerSecond = !isPro? Math.min(computedBps, bitratePreset): computedBps;debug("Video bitrate target", {bitratePreset,videoBitsPerSecond,+ isPro,});debug("Recorder capabilities", {@@ -1100,18 +1370,15 @@ const Recorder = () => {fps,});- // Reset pre-recording state. Recording-committed state (isRecording,- // heartbeat, timing) is set after the recorder is created successfully.+ // Pre-recording reset. isRecording/heartbeat/timing are set post-construction.pausedStateRef.current = false;chrome.storage.local.set({ restarting: false });isRestarting.current = false;index.current = 0;- // Tracks in-flight WebCodecs IDB writes. onChunk fires handleChunk- // fire-and-forget, and waitForDrain only covers the MediaRecorder- // pending queue — so onFinalized could race ahead of slicing and- // rebuild from a partially-written chunksStore. Chain every handleChunk- // call here and await this chain in onFinalized.+ // Track in-flight WebCodecs IDB writes: onChunk dispatches handleChunk+ // fire-and-forget, waitForDrain only covers MediaRecorder, so onFinalized+ // could race ahead of slicing. Chain handleChunks and await in onFinalized.let webcodecsWriteChain = Promise.resolve();const handleChunk = async (data, timestampMs) => {@@ -1121,21 +1388,15 @@ const Recorder = () => {if (useWebCodecs.current) {if (lowStorageAbort.current) return;- // Fragmented MP4 + StreamTarget: chunks stream in throughout the- // recording as the muxer writes fragments (~1MB each, coalesced- // upstream). Each chunk is already file-byte-order; concatenating- // them reconstructs a valid fMP4, which plays directly in <video>- // and is re-muxed to standard MP4 at download time.+ // fMP4 fragments stream in (~1MB each, coalesced upstream); concatenated+ // they form a valid fMP4 playable directly in <video> and re-muxable later.const blob =data instanceof Blob ? data : new Blob([data], { type: "video/mp4" });const ts = timestampMs ?? 0;- // Pre-flight the IDB write: if the device is running out of storage- // quota, abort cleanly so the user gets a toast + the already-saved- // fragments are preserved. Without this, setItem would throw- // QuotaExceededError mid-recording and the fragments after that point- // would silently vanish.+ // Pre-flight quota: setItem throwing QuotaExceededError mid-write would+ // silently drop subsequent fragments.if (!(await canFitChunk(blob.size))) {if (!lowStorageAbort.current) {chrome.runtime.sendMessage({@@ -1162,14 +1423,22 @@ const Recorder = () => {try {const i = index.current;- await chunksStore.setItem(`chunk_${i}`, {- index: i,- chunk: blob,- timestamp: ts,- });+ if (chunkWriter.current) {+ await chunkWriter.current.write({+ chunk: blob,+ index: i,+ timestamp: ts,+ });+ } else {+ // chooseWriter failed at start; write directly so data isn't lost.+ await chunksStore.setItem(`chunk_${i}`, {+ index: i,+ chunk: blob,+ timestamp: ts,+ });+ }- // Heartbeat + first-chunk watchdog fire on the first fragment- // only, so the SW's stall detector doesn't kill us early.+ // First-fragment heartbeat + watchdog cancel keeps the SW stall detector quiet.const heartbeatUpdate = { lastChunkAt: Date.now() };if (i === 0) heartbeatUpdate.firstChunkAt = Date.now();chrome.storage.local.set(heartbeatUpdate).catch(() => {});@@ -1197,20 +1466,34 @@ const Recorder = () => {}} catch (err) {debugError("Failed to save WebCodecs chunk", err);- // Quota check above is a best-effort pre-flight; the actual write- // can still fail (QuotaExceededError, IDB transaction aborted,- // disk full). Handle it the same way as a canFitChunk miss so the- // user gets a clear toast and already-saved fragments are kept.- const name = err?.name || "";+ // Stop recording but preserve what's on disk.+ const name = err?.name || err?.errorName || "";const msg = String(err?.message || err || "").toLowerCase();const looksLikeQuotaError =name === "QuotaExceededError" ||msg.includes("quota") ||msg.includes("disk");- if (looksLikeQuotaError && !lowStorageAbort.current) {+ const isOpfsWriterDead = err?.code === "opfs-writer-failed";++ if ((looksLikeQuotaError || isOpfsWriterDead) && !lowStorageAbort.current) {+ // Keep the OPFS ref: the partial MP4 is still readable.+ if (isOpfsWriterDead && err?.fileName) {+ chunkBackendRef.current = {+ backend: "opfs",+ fileName: err.fileName,+ };+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: chunkBackendRef.current,+ });+ } catch {}+ }+ const toastMessage = isOpfsWriterDead+ ? chrome.i18n.getMessage("recordingWriterFailedToast")+ : chrome.i18n.getMessage("toastStorageCritical");chrome.runtime.sendMessage({type: "show-toast",- message: chrome.i18n.getMessage("toastStorageCritical"),+ message: toastMessage,timeout: 8000,});lowStorageAbort.current = true;@@ -1222,7 +1505,7 @@ const Recorder = () => {lowStorageAbortAt: Date.now(),lowStorageAbortChunks: index.current,});- requestStop("low-storage", {+ requestStop(isOpfsWriterDead ? "opfs-writer-failed" : "low-storage", {memoryError: true,savedChunks: savedCount.current,});@@ -1243,7 +1526,6 @@ const Recorder = () => {};if (!hasChunks.current) {- // Cancel first-chunk watchdogchrome.runtime.sendMessage({ type: "cancel-first-chunk-watchdog" }).catch(() => {});@@ -1294,7 +1576,6 @@ const Recorder = () => {void drainQueue();};- // Abort if stop/dismiss was requested during async setup.if (isFinishing.current || uiClosing.current) {slLog("startRecording-abort-interrupted", {isFinishing: isFinishing.current,@@ -1314,8 +1595,40 @@ const Recorder = () => {typeof liveStream.current.getAudioTracks === "function" &&liveStream.current.getAudioTracks().length > 0;- debug("Initializing WebCodecsRecorder", {+ // Snapshot for diagnostic zip; useful when debugging "No video track".+ const lsVideoTracks = liveStream.current?.getVideoTracks?.() || [];+ const helperVideo = helperVideoStream.current?.getVideoTracks?.() || [];+ const constructSnapshot = {+ liveStreamPresent: !!liveStream.current,+ liveStreamId: liveStream.current?.id || null,+ liveStreamActive: liveStream.current?.active ?? null,+ liveVideoTrackCount: lsVideoTracks.length,+ liveVideoTrackStates: lsVideoTracks.map((t) => ({+ id: t.id,+ label: t.label,+ readyState: t.readyState,+ enabled: t.enabled,+ muted: t.muted,+ })),+ helperVideoStreamPresent: !!helperVideoStream.current,+ helperVideoStreamId: helperVideoStream.current?.id || null,+ helperVideoStreamActive: helperVideoStream.current?.active ?? null,+ helperVideoTrackCount: helperVideo.length,+ helperVideoTrackStates: helperVideo.map((t) => ({+ id: t.id,+ label: t.label,+ readyState: t.readyState,+ })),hasAudioTrack,+ at: Date.now(),+ };+ try {+ chrome.storage.local.set({+ webcodecsConstructSnapshot: constructSnapshot,+ });+ } catch {}+ debug("Initializing WebCodecsRecorder", {+ ...constructSnapshot,videoBitsPerSecond,audioBitsPerSecond,});@@ -1335,13 +1648,45 @@ const Recorder = () => {try {await webcodecsWriteChain;} catch {}+ // Close before validating: OPFS holds an exclusive handle until close.+ if (chunkWriter.current) {+ try {+ const closeResult = await chunkWriter.current.close();+ // Only overwrite chunkBackendRef when close returns one; otherwise+ // {backend:"idb"} would silently reroute editor reads from OPFS to IDB.+ if (closeResult?.backendRef) {+ chunkBackendRef.current = closeResult.backendRef;+ }+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][recorder] writer-close", {+ backendRef: chunkBackendRef.current,+ byteSize: closeResult?.byteSize,+ chunkCount: closeResult?.chunkCount,+ });+ }+ } catch (err) {+ debugWarn("chunkWriter.close failed before validate", err);+ if (err?.code === "opfs-writer-failed" && err?.fileName) {+ // Partial file still on disk.+ chunkBackendRef.current = {+ backend: "opfs",+ fileName: err.fileName,+ };+ } else {+ chunkBackendRef.current = { backend: "idb" };+ }+ }+ chunkWriter.current = null;+ chunkWriterBackend.current = null;+ }await updateFreeFinalizeStatus("chunks_ready", 95);let validation = null;try {const blob = await rebuildBlobFromChunks();validation = await validateFastRecorderOutputBlob(blob, {minBytes: 64 * 1024,- timeoutMs: 4000,+ // Multi-GB demuxer scans on slow disks need ~15s.+ timeoutMs: 15000,videoCodec: recorder.current?.selectedVideoCodec || undefined,audioCodec: hasAudioTrack ? "mp4a.40.2" : null,recordingId,@@ -1364,9 +1709,7 @@ const Recorder = () => {useWebCodecsRecorder: false,lastWebCodecsFailureAt: Date.now(),lastWebCodecsFailureCode: "validation-failed",- // Persistent record survives subsequent recording starts- // (which clear fastRecorderValidation), so we can always- // inspect why sticky-disable was triggered.+ // Survives subsequent starts (which clear fastRecorderValidation).lastFailedValidation: {at: Date.now(),recordingId,@@ -1388,6 +1731,10 @@ const Recorder = () => {message: chrome.i18n.getMessage("webcodecsFailedOffToast"),});if (hardFail) {+ // Clear backendRef: prevents the sandbox from reading a stale OPFS file.+ await chrome.storage.local.remove([+ "lastRecordingBackendRef",+ ]);chrome.runtime.sendMessage({type: "fast-recorder-hard-fail",recordingId,@@ -1405,6 +1752,11 @@ const Recorder = () => {fastRecorderValidation: validation,});}+ await chrome.storage.local.set({+ lastRecordingBackendRef: chunkBackendRef.current || {+ backend: "idb",+ },+ });await updateFreeFinalizeStatus("ready", 100);if (!sentLast.current) {sentLast.current = true;@@ -1430,20 +1782,26 @@ const Recorder = () => {},onError: (err) => {debugError("WebCodecsRecorder error", err);- markFastRecorderFailure("webcodecs-error", {- error: String(err),- });- chrome.storage.local.set({- useWebCodecsRecorder: false,+ const errStr = String(err);+ const transient = isTransientFastRecorderError(errStr);+ markFastRecorderFailure("webcodecs-error", { error: errStr });+ // Transient stream errors don't disable WebCodecs.+ const persisted = {lastWebCodecsFailureAt: Date.now(),- lastWebCodecsFailureCode: "webcodecs-error",- });- updateFreeFinalizeStatus("failed", 100, String(err));- chrome.runtime.sendMessage({- type: "show-toast",- message: chrome.i18n.getMessage("webcodecsFailedOffToast"),- });- sendRecordingError(String(err));+ lastWebCodecsFailureCode: transient+ ? "webcodecs-transient"+ : "webcodecs-error",+ };+ if (!transient) persisted.useWebCodecsRecorder = false;+ chrome.storage.local.set(persisted);+ updateFreeFinalizeStatus("failed", 100, errStr);+ if (!transient) {+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),+ });+ }+ sendRecordingError(errStr);},onStop: async () => {debug("WebCodecsRecorder onStop()");@@ -1451,6 +1809,24 @@ const Recorder = () => {},});+ // Records when .start() fires vs countdown end so a diag zip distinguishes+ // early-start (capturing the countdown overlay) from React paint lag.+ try {+ const { countdownFinishedAt } = await chrome.storage.local.get([+ "countdownFinishedAt",+ ]);+ chrome.storage.local.set({+ recorderStartTimings: {+ path: "webcodecs",+ startCalledAt: Date.now(),+ countdownFinishedAt: countdownFinishedAt || null,+ deltaSinceCountdownMs:+ countdownFinishedAt+ ? Date.now() - Number(countdownFinishedAt)+ : null,+ },+ });+ } catch {}const ok = await recorder.current.start();debug("WebCodecsRecorder.start() result", ok);@@ -1514,8 +1890,6 @@ const Recorder = () => {let activeMimeType = null;try {- // Ensure recorder.current is initialized (createMediaRecorder may- // be used elsewhere; create a MediaRecorder here if missing).if (!recorder.current) {try {recorder.current = createMediaRecorder(liveStream.current, {@@ -1534,10 +1908,87 @@ const Recorder = () => {}}+ // Same start-vs-countdown logging as the WebCodecs path.+ try {+ const { countdownFinishedAt } = await chrome.storage.local.get([+ "countdownFinishedAt",+ ]);+ chrome.storage.local.set({+ recorderStartTimings: {+ path: "mediarecorder",+ startCalledAt: Date.now(),+ countdownFinishedAt: countdownFinishedAt || null,+ deltaSinceCountdownMs:+ countdownFinishedAt+ ? Date.now() - Number(countdownFinishedAt)+ : null,+ },+ });+ } catch {}+ // Stream/track snapshot for diagnosing "no chunks" failures.+ try {+ const vTracks = liveStream.current?.getVideoTracks?.() || [];+ const aTracks = liveStream.current?.getAudioTracks?.() || [];+ lifecycle("Recorder", "mediarecorder-start", {+ videoTracks: vTracks.length,+ audioTracks: aTracks.length,+ videoState: vTracks[0]+ ? {+ readyState: vTracks[0].readyState,+ muted: vTracks[0].muted,+ enabled: vTracks[0].enabled,+ }+ : null,+ mimeType: recorder.current?.mimeType || null,+ recorderState: recorder.current?.state || null,+ });+ } catch {}+ // Re-attach listeners every (re)start so the new MediaRecorder doesn't+ // read from a track whose mute/end events would be silently missed.+ try {+ const vt0 = liveStream.current?.getVideoTracks?.()[0];+ if (vt0) {+ vt0.onmute = () => {+ lifecycle("Recorder", "videoTrack-mute", {+ readyState: vt0.readyState,+ enabled: vt0.enabled,+ savedCount: savedCount.current,+ });+ };+ vt0.onunmute = () => {+ lifecycle("Recorder", "videoTrack-unmute", {+ readyState: vt0.readyState,+ enabled: vt0.enabled,+ savedCount: savedCount.current,+ });+ };+ vt0.onended = () => {+ lifecycle("Recorder", "videoTrack-ended", {+ readyState: vt0.readyState,+ savedCount: savedCount.current,+ });+ };+ }+ } catch {}+ recorder.current.onstart = () => {+ lifecycle("Recorder", "mediarecorder-onstart", {+ recorderState: recorder.current?.state || null,+ videoState: (() => {+ const t = liveStream.current?.getVideoTracks?.()[0];+ return t+ ? {+ readyState: t.readyState,+ muted: t.muted,+ enabled: t.enabled,+ }+ : null;+ })(),+ });+ };recorder.current.start(5000);debug("MediaRecorder.start(5000) called");- // Start first-chunk watchdog (8s, via chrome.alarms)+ // First-chunk watchdog (8s, chrome.alarms-backed).chrome.runtime.sendMessage({ type: "start-first-chunk-watchdog" }).catch(() => {});@@ -1552,23 +2003,61 @@ const Recorder = () => {recorder.current.onerror = (ev) => {debugError("MediaRecorder.onerror", ev);- chrome.runtime.sendMessage({- type: "recording-error",- error: "mediarecorder",- why: String(ev?.error || "unknown"),+ const errStr = String(ev?.error || ev?.error?.name || "unknown");+ lifecycle("Recorder", "mediarecorder-onerror", {+ error: errStr,+ errorName: ev?.error?.name || null,+ recorderState: recorder.current?.state || null,+ savedCount: savedCount.current,});+ // Transient errors (stop-time state races, already-inactive) shouldn't+ // surface a modal; saved chunks are still valid via the normal stop path.+ const isTransient =+ /invalidstateerror/i.test(errStr) ||+ /not in recording state/i.test(errStr) ||+ /already (stopped|inactive)/i.test(errStr);+ if (!isTransient) {+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "mediarecorder",+ why: errStr,+ });+ }+ // Stop locally; don't wait for the BG round-trip.+ requestStop("mediarecorder-onerror");};recorder.current.onstop = async () => {+ perfMark("Recorder mediarecorder.onstop.fired", {+ savedCount: savedCount.current,+ });debug("MediaRecorder.onstop");try {recorder.current.requestData();} catch {}if (isRestarting.current) return;+ const endDrain = perfSpan("Recorder waitForDrain");await waitForDrain();+ endDrain({ savedCount: savedCount.current });if (!sentLast.current) {sentLast.current = true;isFinishing.current = false;+ // Skip video-ready if no chunks landed; otherwise the editor opens on a 0-byte file.+ if (!hasChunks.current || savedCount.current === 0) {+ debugWarn("MediaRecorder.onstop: no chunks saved", {+ hasChunks: hasChunks.current,+ savedCount: savedCount.current,+ });+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "stream-error",+ why: "No recording data was generated",+ });+ return;+ }+ perfMark("Recorder video-ready.sent", {+ savedCount: savedCount.current,+ });chrome.runtime.sendMessage({ type: "video-ready" });}};@@ -1579,6 +2068,13 @@ const Recorder = () => {}if (!e || !e.data || !e.data.size) {debugWarn("MediaRecorder.ondataavailable with empty data", e);+ lifecycle("Recorder", "ondataavailable-empty", {+ hasEvent: Boolean(e),+ hasData: Boolean(e?.data),+ size: e?.data?.size ?? null,+ recorderState: recorder.current?.state || null,+ savedCount: savedCount.current,+ });if (recorder.current instanceof MediaRecorder &&recorder.current.state === "inactive"@@ -1599,6 +2095,13 @@ const Recorder = () => {timecode: e.timecode ?? 0,});}+ if (savedCount.current < 3) {+ lifecycle("Recorder", "ondataavailable", {+ index: savedCount.current,+ size: e.data.size,+ timecode: e.timecode ?? 0,+ });+ }await handleChunk(e.data, e.timecode ?? 0);};@@ -1622,7 +2125,6 @@ const Recorder = () => {return;}- // Recorder created successfully — now advertise "recording" to the system.await setRecordingTimingState({recording: true,paused: false,@@ -1639,9 +2141,32 @@ const Recorder = () => {if (helperAudioStream.current) {const track = helperAudioStream.current.getAudioTracks()[0];if (track) {+ // Mute fires when OS/driver silences the mic without ending the track+ // (macOS DND, privacy revoke, BT disconnect): surface to avoid silent recordings.+ track.onmute = () => {+ if (isFinishing.current || !isRecording.current) return;+ console.warn("[Recorder] mic track muted (device may have switched)");+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-mic-track-muted",+ data: {+ trackLabel: String(track.label || "").slice(0, 80),+ trackReadyState: track.readyState,+ },+ });+ } catch {}+ };+ track.onunmute = () => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-mic-track-unmuted",+ });+ } catch {}+ };track.onended = () => {if (isFinishing.current || !isRecording.current) return;- // Log detailed diagnostics for debuggingconst diagnosticInfo = {reason: "audio-track-ended",savedChunks: savedCount.current,@@ -1656,7 +2181,6 @@ const Recorder = () => {"[Recorder] Audio track ended unexpectedly",diagnosticInfo,);- // Notify via stream-ended-warning toastchrome.runtime.sendMessage({type: "recording-error",error: "stream-ended",@@ -1671,12 +2195,44 @@ const Recorder = () => {}}+ // OS audio topology changes (BT/USB plug, default switch) keep the original+ // deviceId streaming, possibly silent. Surface diag event; don't auto-switch+ // (mid-recording device changes risk sample-rate mismatch and drift).+ if (+ typeof navigator !== "undefined" &&+ navigator.mediaDevices &&+ typeof navigator.mediaDevices.addEventListener === "function"+ ) {+ const onDeviceChange = async () => {+ if (isFinishing.current || !isRecording.current) return;+ try {+ const devices = await navigator.mediaDevices.enumerateDevices();+ const audioInputs = devices.filter((d) => d.kind === "audioinput");+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-devicechange-mid-recording",+ data: {+ audioInputCount: audioInputs.length,+ labels: audioInputs.map((d) => d.label).slice(0, 5),+ },+ });+ } catch {}+ };+ try {+ navigator.mediaDevices.addEventListener(+ "devicechange",+ onDeviceChange,+ );+ // Stashed so stop() can detach it.+ deviceChangeListenerRef.current = onDeviceChange;+ } catch {}+ }+const liveVideoTrack = liveStream.current?.getVideoTracks?.()[0] || null;if (liveVideoTrack) {liveVideoTrack.onended = () => {if (isFinishing.current || !isRecording.current) return;const track = liveStream.current?.getVideoTracks?.()[0] || null;- // Log detailed diagnostics for debuggingconst diagnosticInfo = {reason: "liveStream-video-track-ended",savedChunks: savedCount.current,@@ -1725,7 +2281,6 @@ const Recorder = () => {"[Recorder] helperVideoStream video track ended",diagnosticInfo,);- // Notify via stream-ended-warning toastchrome.runtime.sendMessage({type: "recording-error",error: "stream-ended",@@ -1750,72 +2305,179 @@ const Recorder = () => {const videoTrack = liveStream.getVideoTracks()[0];const audioTrack = liveStream.getAudioTracks()[0];-- await new Promise(async (resolve) => {- const proc = new MediaStreamTrackProcessor({ track: videoTrack });- const reader = proc.readable.getReader();-- while (true) {- const { value: frame } = await reader.read();- if (frame) {- if (frame.codedWidth > 0 && frame.codedHeight > 0) {- debug("warmUpStream() video frame OK", {- codedWidth: frame.codedWidth,- codedHeight: frame.codedHeight,- });- frame.close();- reader.releaseLock();- resolve();- break;+ const VIDEO_TIMEOUT_MS = 4000;+ const AUDIO_TIMEOUT_MS = 2000;++ // Hard-timeout track read: without it, a dormant tab-capture stream (e.g.+ // after a prior pause/restart) hangs reader.read() forever, leaving the+ // recorder stuck on "Starting recording..." since MediaRecorder.start() never runs.+ const readWithTimeout = async (track, timeoutMs, kind, isValid) => {+ const startedAt = Date.now();+ let proc;+ let reader;+ try {+ proc = new MediaStreamTrackProcessor({ track });+ reader = proc.readable.getReader();+ } catch (err) {+ lifecycle("Recorder", "warmUp-processor-error", {+ kind,+ error: String(err),+ trackState: {+ readyState: track.readyState,+ muted: track.muted,+ enabled: track.enabled,+ },+ });+ return { ok: false, reason: "processor-error" };+ }+ let done = false;+ const timeout = new Promise((resolve) =>+ setTimeout(() => {+ if (done) return;+ done = true;+ try {+ reader.cancel().catch(() => {});+ } catch {}+ resolve({ ok: false, reason: "timeout" });+ }, timeoutMs),+ );+ const readLoop = (async () => {+ try {+ while (!done) {+ const { value, done: streamDone } = await reader.read();+ if (streamDone) {+ return { ok: false, reason: "stream-ended" };+ }+ if (value && isValid(value)) {+ done = true;+ try {+ value.close?.();+ } catch {}+ try {+ reader.releaseLock();+ } catch {}+ return { ok: true };+ }+ try {+ value?.close?.();+ } catch {}}- frame.close();+ return { ok: false, reason: "cancelled" };+ } catch (err) {+ return { ok: false, reason: "read-error", error: String(err) };}- }- });+ })();+ const result = await Promise.race([readLoop, timeout]);+ lifecycle("Recorder", "warmUp-track", {+ kind,+ ok: result.ok,+ reason: result.reason || null,+ durMs: Date.now() - startedAt,+ trackState: {+ readyState: track.readyState,+ muted: track.muted,+ enabled: track.enabled,+ },+ });+ return result;+ };++ const videoResult = await readWithTimeout(+ videoTrack,+ VIDEO_TIMEOUT_MS,+ "video",+ (frame) => frame.codedWidth > 0 && frame.codedHeight > 0,+ );+ let audioResult = { ok: true, skipped: true };if (audioTrack) {- await new Promise(async (resolve) => {- const proc = new MediaStreamTrackProcessor({ track: audioTrack });- const reader = proc.readable.getReader();-- while (true) {- const { value: audio } = await reader.read();- if (audio && audio.numberOfFrames > 0) {- debug("warmUpStream() audio OK", {- numberOfFrames: audio.numberOfFrames,- });- audio.close?.();- reader.releaseLock();- resolve();- break;- }- audio?.close?.();- }+ audioResult = await readWithTimeout(+ audioTrack,+ AUDIO_TIMEOUT_MS,+ "audio",+ (a) => a.numberOfFrames > 0,+ );+ }++ if (!videoResult.ok || !audioResult.ok) {+ // Don't block startup: MediaRecorder.start may still wake the stream;+ // otherwise the first-chunk watchdog surfaces a clear error.+ lifecycle("Recorder", "warmUp-degraded-proceeding", {+ videoOk: videoResult.ok,+ audioOk: audioResult.ok,+ videoReason: videoResult.reason || null,+ audioReason: audioResult.reason || null,});}+ debug("warmUpStream() done", {+ videoOk: videoResult.ok,+ audioOk: audioResult.ok,+ });+ }++ function beginPrewarm(liveStream) {+ endPrewarm();+ prewarmRef.current = startPrewarm(liveStream);+ preloadWebCodecsModules();+ // Kick off the IDB clear in the background so startRecording's await+ // resolves immediately. Safe to re-run if it doesn't actually fire.+ if (!prewarmChunksClearRef.current) {+ prewarmChunksClearRef.current = chunksStore.clear().catch(() => {});+ }+ // Pre-open the OPFS writer in parallel. Default-on path: WebCodecs ++ // OPFS. If startRecording's preflight ends up wanting IDB instead, the+ // pre-opened writer is aborted and a fresh chooseWriter runs.+ if (!prewarmedWriterRef.current) {+ const recordingId = `${Date.now()}-${Math.random()+ .toString(16)+ .slice(2, 8)}`;+ prewarmedWriterRef.current = (async () => {+ try {+ const selection = await chooseWriter({ preferOpfs: true });+ const openResult = await selection.writer.open(recordingId);+ return { selection, openResult, recordingId };+ } catch {+ return null;+ }+ })();+ }+ }- debug("warmUpStream() done");+ async function endPrewarm({ keepClear = false, keepWriter = false } = {}) {+ const ctrl = prewarmRef.current;+ prewarmRef.current = null;+ if (!keepClear) {+ prewarmChunksClearRef.current = null;+ }+ if (!keepWriter) {+ const writerPromise = prewarmedWriterRef.current;+ prewarmedWriterRef.current = null;+ if (writerPromise) {+ writerPromise+ .then((pw) => {+ if (pw?.selection?.writer?.abort) {+ return pw.selection.writer.abort().catch(() => {});+ }+ })+ .catch(() => {});+ }+ }+ await stopPrewarm(ctrl);}const rebuildBlobFromChunks = async () => {- const items = [];- await chunksStore.ready();- await chunksStore.iterate((value) => (items.push(value), undefined));- // Primary sort by timestamp, tiebreak by index. Necessary since the- // WebCodecs slicing path writes multiple slices with the same timestamp- // (they all belong to the single muxer-emitted chunk).- items.sort((a, b) => {- const dt = (a.timestamp ?? 0) - (b.timestamp ?? 0);- if (dt !== 0) return dt;- return (a.index ?? 0) - (b.index ?? 0);- });- const parts = items.map((c) =>- c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),- );- if (!parts.length) return null;- const first = parts[0];- const inferredType = first?.type || "video/mp4";- return new Blob(parts, { type: inferredType });+ const backendRef = chunkBackendRef.current || { backend: "idb" };+ const reader = chooseReader(backendRef);+ try {+ await reader.open(backendRef);+ const { blob, chunkCount } = await reader.readBlob();+ if (!blob || chunkCount === 0) return null;+ return blob;+ } finally {+ try {+ await reader.close();+ } catch {}+ }};const updateFreeFinalizeStatus = async (stage, percent = 0, error = null) => {@@ -1857,14 +2519,17 @@ const Recorder = () => {debugWarn("stopRecording() called while already finishing");return;}+ perfMark("Recorder stopRecording.enter", {+ recorderType: useWebCodecs.current ? "webcodecs" : "mediarecorder",+ savedCount: savedCount.current,+ });debug("stopRecording()");- // Stop takes priority over any pending start gate.+ // Stop preempts any pending start gate.resetGateState();isFinishing.current = true;isRecording.current = false;await updateFreeFinalizeStatus("stopping", 0);- // Stop the session heartbeat and persist final statestopSessionHeartbeat();stopRecordingTick();persistSessionState("stopping");@@ -1892,8 +2557,26 @@ const Recorder = () => {recorder.current.requestData();} catch {}if (recorder.current.state !== "inactive") {+ perfMark("Recorder mediarecorder.stop()-called");recorder.current.stop();}+ // Watchdog: if onstop never fires (Chrome bug, stream crash, encoder+ // teardown race), recorder hangs in finalize forever; force-finalize at 15s.+ setTimeout(() => {+ if (sentLast.current) return;+ debugWarn("MediaRecorder.onstop watchdog: forcing finalize");+ sentLast.current = true;+ isFinishing.current = false;+ if (!hasChunks.current || savedCount.current === 0) {+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "stream-error",+ why: "Recorder stop timed out with no data",+ });+ return;+ }+ chrome.runtime.sendMessage({ type: "video-ready" });+ }, 15000);}} catch (err) {debugError("stopRecording() error while stopping recorder", err);@@ -1905,15 +2588,14 @@ const Recorder = () => {}recorder.current = null;- // Stop the silent audio keep-alivestopTabKeepAlive();- // Clear session state after successful stoppersistSessionState("completed");if (!isRestarting.current) {debug("Stopping tracks and clearing streams");slLog("helperVideoStream-nulling", { path: "stopRecording" });+ endPrewarm();liveStream.current?.getTracks().forEach((t) => t.stop());helperVideoStream.current?.getTracks().forEach((t) => t.stop());helperAudioStream.current?.getTracks().forEach((t) => t.stop());@@ -1922,6 +2604,24 @@ const Recorder = () => {helperVideoStream.current = null;helperAudioStream.current = null;}+ // Detach devicechange + silence watchdog: otherwise they keep firing for+ // subsequent recordings in the same tab with stale state.+ if (deviceChangeListenerRef.current) {+ try {+ navigator.mediaDevices.removeEventListener(+ "devicechange",+ deviceChangeListenerRef.current,+ );+ } catch {}+ deviceChangeListenerRef.current = null;+ }+ if (silenceWatchdogRef.current) {+ try {+ clearInterval(silenceWatchdogRef.current.intervalId);+ silenceWatchdogRef.current.analyser?.disconnect?.();+ } catch {}+ silenceWatchdogRef.current = null;+ }if (!useWebCodecs.current) {await updateFreeFinalizeStatus("ready", 100);}@@ -1934,7 +2634,7 @@ const Recorder = () => {isRecording.current = false;recordingGeneration.current += 1;- // Detach callbacks so a late ondataavailable can't re-arm lastChunkAt after watchdog reset.+ // Late ondataavailable could re-arm lastChunkAt after watchdog reset; detach.if (recorder.current instanceof MediaRecorder) {try {recorder.current.ondataavailable = null;@@ -1943,7 +2643,14 @@ const Recorder = () => {} catch {}}- // Clean up keep-alive and session tracking+ if (chunkWriter.current) {+ try {+ await chunkWriter.current.abort();+ } catch {}+ chunkWriter.current = null;+ chunkWriterBackend.current = null;+ }+stopTabKeepAlive();stopSessionHeartbeat();persistSessionState("dismissed");@@ -1968,7 +2675,6 @@ const Recorder = () => {debug("restartRecording()");recordingGeneration.current += 1;- // Kill any stale start-gate timeout from the previous session.resetGateState();isRestarting.current = true;@@ -2059,16 +2765,19 @@ const Recorder = () => {async function startAudioStream(id) {debug("startAudioStream()", { id });- const useExact = id && id !== "none";+ // "none" sentinel: bail before getUserMedia would otherwise grab the default mic.+ if (!id || id === "none") {+ debug("startAudioStream() skipped: no audio input selected");+ return null;+ }+ const useExact = true;const audioStreamOptions = {mimeType: "video/webm;codecs=vp8,opus",- audio: useExact- ? {- deviceId: {- exact: id,- },- }- : true,+ audio: {+ deviceId: {+ exact: id,+ },+ },};const { defaultAudioInputLabel, audioinput } =@@ -2160,6 +2869,11 @@ const Recorder = () => {};async function startStream(data, id, options, permissions, permissions2) {+ perfMark("Recorder startStream.enter", {+ recordingType: data?.recordingType,+ hasId: Boolean(id),+ isTab: Boolean(isTab.current),+ });slLog("startStream-enter", {recordingType: data.recordingType,hasId: !!id,@@ -2234,6 +2948,18 @@ const Recorder = () => {fps,});+ // Mic acquisition runs in parallel: startAudioStream() ~400ms; await later.+ const endMicPar = perfSpan("Recorder startAudioStream(mic).parallel", {+ hasDevice: Boolean(data?.defaultAudioInput && data.defaultAudioInput !== "none"),+ });+ const micPromise =+ permissions2?.state === "denied"+ ? Promise.resolve(null)+ : startAudioStream(data.defaultAudioInput).catch((err) => {+ debugWarn("startAudioStream parallel kickoff failed", err);+ return null;+ });+let userStream;if (permissions.state != "denied" &&@@ -2269,13 +2995,16 @@ const Recorder = () => {data.defaultVideoInput && data.defaultVideoInput !== "none";const cameraConstraints = {...userConstraints,- audio:- userConstraints.audio && hasAudioDevice+ // Drop audio entirely when "none"/missing; otherwise getUserMedia falls+ // back to system default and injects audio into every camera-only recording.+ audio: hasAudioDevice+ ? userConstraints.audio? {...userConstraints.audio,deviceId: { exact: data.defaultAudioInput },}- : userConstraints.audio,+ : userConstraints.audio+ : false,video:userConstraints.video && hasVideoDevice? {@@ -2338,6 +3067,50 @@ const Recorder = () => {helperVideoStream.current = userStream;slLog("helperVideoStream-assigned", { path: "camera", streamId: userStream.id });} else {+ // Chrome's tab capture defaults to a 1920x1080 frame and pillarboxes+ // narrower tabs to fit. Match the constraint box to the tab's real+ // aspect ratio so the captured frame has no padding. Desktop capture+ // is left unconstrained (the OS reports its own size).+ let videoMaxW = null;+ let videoMaxH = null;+ if (isTab.current) {+ const viewport = await getRecordedTabViewport(recordedTabId.current);+ if (viewport) {+ const tabW = viewport.width;+ const tabH = viewport.height;+ // Cap to the user's quality limits (width x height) while+ // preserving the tab's aspect ratio. Chrome won't upscale, so for+ // tabs smaller than the cap the request resolves to native size.+ const fitScale = Math.min(width / tabW, height / tabH, 1);+ videoMaxW = Math.max(2, Math.round(tabW * fitScale));+ videoMaxH = Math.max(2, Math.round(tabH * fitScale));+ if (videoMaxW % 2) videoMaxW -= 1;+ if (videoMaxH % 2) videoMaxH -= 1;+ debug("Tab viewport-aware constraints", {+ tabW,+ tabH,+ capW: width,+ capH: height,+ videoMaxW,+ videoMaxH,+ });+ } else {+ debug("Tab viewport unknown; falling back to no-dim constraints");+ }+ }++ const videoMandatory = {+ chromeMediaSource: isTab.current ? "tab" : "desktop",+ chromeMediaSourceId: id,+ maxFrameRate: fps,+ };+ if (videoMaxW && videoMaxH) {+ videoMandatory.maxWidth = videoMaxW;+ videoMandatory.maxHeight = videoMaxH;+ videoMandatory.minWidth = videoMaxW;+ videoMandatory.minHeight = videoMaxH;+ }+const constraints = {audio: {mandatory: {@@ -2346,15 +3119,7 @@ const Recorder = () => {},},video: {- mandatory: {- chromeMediaSource: isTab.current ? "tab" : "desktop",- chromeMediaSourceId: id,- maxWidth: width,- maxHeight: height,- width: { ideal: width, max: width },- height: { ideal: height, max: height },- maxFrameRate: fps,- },+ mandatory: videoMandatory,},};@@ -2363,8 +3128,15 @@ const Recorder = () => {let stream;+ const endGum = perfSpan("Recorder getUserMedia(desktop/tab)", {+ isTab: Boolean(isTab.current),+ });try {stream = await navigator.mediaDevices.getUserMedia(constraints);+ endGum({+ videoTracks: stream.getVideoTracks().length,+ audioTracks: stream.getAudioTracks().length,+ });if (stream.getVideoTracks().length === 0) {debugError("No video tracks returned from getUserMedia");@@ -2373,6 +3145,7 @@ const Recorder = () => {return;}} catch (err) {+ endGum({ error: String(err?.message || err).slice(0, 80) });debugError("Failed to get user media for desktop/tab capture", err);resetGateState();sendRecordingError("Failed to get user media: " + String(err));@@ -2405,29 +3178,77 @@ const Recorder = () => {chrome.runtime.sendMessage({ type: "set-surface", surface: surface });}+ perfMark("Recorder pre-audio-setup");aCtx.current = new AudioContext();destination.current = aCtx.current.createMediaStreamDestination();liveStream.current = new MediaStream();+ let mixedAudioConnected = false;- const micstream = await startAudioStream(data.defaultAudioInput);+ // Mic was kicked off in parallel above (micPromise); just await it now.+ const endMicJoin = perfSpan("Recorder startAudioStream(mic).join");+ const micstream = await micPromise;+ endMicJoin({ hasMic: Boolean(micstream) });+ endMicPar({ hasMic: Boolean(micstream) });helperAudioStream.current = micstream;if (helperAudioStream.current != null && !data.micActive) {setAudioInputVolume(0);}- // System/Tab audio+ // chrome `tab` mediaSource always returns an audio track when available;+ // gate mixing on `data.systemAudio`.const sysTracks = helperVideoStream.current.getAudioTracks();- debug("System/tab audio tracks", sysTracks.length);- if (sysTracks.length > 0) {+ debug("System/tab audio tracks", sysTracks.length, "systemAudio:", data.systemAudio);+ if (sysTracks.length > 0 && data.systemAudio) {+ const sysTrack = sysTracks[0];const sysSource = aCtx.current.createMediaStreamSource(- new MediaStream([sysTracks[0]]),+ new MediaStream([sysTrack]),);audioOutputGain.current = aCtx.current.createGain();sysSource.connect(audioOutputGain.current).connect(destination.current);+ mixedAudioConnected = true;+ // Symmetric with mic onended: detect dead system/tab audio mid-recording+ // (closed tab, OS mute, BT disconnect) instead of silently capturing dead audio.+ sysTrack.onended = () => {+ if (isFinishing.current || !isRecording.current) return;+ const info = {+ reason: "system-audio-track-ended",+ trackLabel: String(sysTrack.label || "").slice(0, 80),+ savedChunks: savedCount.current,+ };+ console.warn("[Recorder] System audio track ended", info);+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-system-audio-track-ended",+ data: info,+ });+ } catch {}+ chrome.storage.local.set({ lastTrackEndEvent: info });+ // Don't kill recording: video/mic may still be capturing.+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("audioTrackEndedToast"),+ timeout: 8000,+ }).catch(() => {});+ };+ sysTrack.onmute = () => {+ if (isFinishing.current || !isRecording.current) return;+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-system-audio-track-muted",+ data: { trackLabel: String(sysTrack.label || "").slice(0, 80) },+ });+ } catch {}+ };+ } else if (sysTracks.length > 0) {+ // Stop unused tab-audio so the captured-audio indicator doesn't show.+ try {+ sysTracks[0].stop();+ } catch {}}- // Mic audioconst micTracks = helperAudioStream.current?.getAudioTracks() ?? [];debug("Mic audio tracks", micTracks.length);if (micTracks.length > 0) {@@ -2436,7 +3257,8 @@ const Recorder = () => {);audioInputGain.current = aCtx.current.createGain();micSource.connect(audioInputGain.current).connect(destination.current);-+ mixedAudioConnected = true;+ // Gate via gain so the user can toggle the mic mid-recording without re-acquiring it.if (!data.micActive) {audioInputGain.current.gain.value = 0;}@@ -2462,15 +3284,88 @@ const Recorder = () => {stopRecording();};}- if (- (helperAudioStream.current != null &&- helperAudioStream.current.getAudioTracks().length > 0) ||- helperVideoStream.current.getAudioTracks().length > 0- ) {+ // Only attach a mixed track if at least one source (mic or sys/tab audio)+ // was connected; otherwise we'd append a silent AAC track to every recording.+ if (mixedAudioConnected) {const mixedAudioTrack = destination.current.stream.getAudioTracks()[0];if (mixedAudioTrack) {liveStream.current.addTrack(mixedAudioTrack);}+ // Silence watchdog: analyser tap detects sustained zero-energy audio+ // (perm revoke, BT cutout, OS mute). Sample 5s, fire after 30s silence.+ try {+ const analyser = aCtx.current.createAnalyser();+ analyser.fftSize = 1024;+ const buf = new Uint8Array(analyser.frequencyBinCount);+ // Parallel tap: analyser doesn't connect back, so the output graph is unaffected.+ destination.current.stream+ .getAudioTracks()+ .forEach((t) => {+ try {+ const tapSource = aCtx.current.createMediaStreamSource(+ new MediaStream([t]),+ );+ tapSource.connect(analyser);+ } catch {}+ });+ let silentSamples = 0;+ let alreadyReported = false;+ const SILENCE_THRESHOLD = 2;+ const SAMPLES_BEFORE_ALERT = 6;+ const intervalId = setInterval(() => {+ if (!isRecording.current || isFinishing.current) return;+ analyser.getByteTimeDomainData(buf);+ // Byte amplitude 0-255; 128 is silence center, deviation = energy.+ let maxDev = 0;+ for (let i = 0; i < buf.length; i += 1) {+ const dev = Math.abs(buf[i] - 128);+ if (dev > maxDev) maxDev = dev;+ }+ if (maxDev < SILENCE_THRESHOLD) {+ silentSamples += 1;+ if (silentSamples >= SAMPLES_BEFORE_ALERT && !alreadyReported) {+ alreadyReported = true;+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-audio-silent-30s",+ data: {+ elapsedRecordingMs: recordingStartTime.current+ ? Date.now() - recordingStartTime.current+ : null,+ hasMic: !!helperAudioStream.current?.getAudioTracks?.()+ ?.length,+ hasSystemAudio:+ sysTracks.length > 0 && data.systemAudio,+ },+ });+ } catch {}+ // Surface but don't stop: silence may be intentional.+ try {+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("audioSilentToast"),+ timeout: 8000,+ }).catch(() => {});+ } catch {}+ }+ } else {+ silentSamples = 0;+ if (alreadyReported) {+ alreadyReported = false;+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-audio-recovered",+ });+ } catch {}+ }+ }+ }, 5000);+ silenceWatchdogRef.current = { intervalId, analyser };+ } catch (err) {+ console.warn("[Recorder] silence watchdog setup failed", err);+ }}debug("liveStream ready", {@@ -2480,6 +3375,7 @@ const Recorder = () => {setStarted(true);streamReadyAt.current = Date.now();+ perfMark("Recorder stream-ready");slLog("stream-ready", {streamId: helperVideoStream.current?.id,videoTracks: helperVideoStream.current?.getVideoTracks().length,@@ -2487,34 +3383,43 @@ const Recorder = () => {startRequested: startRequested.current,});+ const endWarmUp = perfSpan("Recorder warmUpStream");await warmUpStream(liveStream.current);+ endWarmUp();++ beginPrewarm(liveStream.current);slLog("warmUp-done");+ perfMark("Recorder reset-active-tab.sent");chrome.runtime.sendMessage({ type: "reset-active-tab" });slLog("reset-active-tab-sent");- // If a start was already requested, honour it now that the stream is live.tryStartIfReady();}async function startStreaming(data) {+ perfMark("Recorder startStreaming.enter");startTabKeepAlive();if (document.visibilityState === "hidden") {debugWarn("Tab is hidden at recording start, requesting activation");+ const endActivate = perfSpan("Recorder activate-recorder-tab");try {await chrome.runtime.sendMessage({ type: "activate-recorder-tab" });} catch {}+ endActivate();}debug("startStreaming()", { data });slLog("startStreaming-enter", { recordingType: data?.recordingType });+ const endPerms = perfSpan("Recorder permissions.query");const permissions = await navigator.permissions.query({name: "camera",});const permissions2 = await navigator.permissions.query({name: "microphone",});+ endPerms();debug("Permissions", {camera: permissions.state,@@ -2596,6 +3501,7 @@ const Recorder = () => {);}} else {+ perfMark("Recorder path.tab-precapture");const tabStreamId = await waitForTabStreamId();debug("Streaming with pre-resolved tabID", tabStreamId);if (!tabStreamId) {@@ -2620,10 +3526,12 @@ const Recorder = () => {}, []);const getStreamID = async (id) => {+ perfMark("Recorder getStreamID.enter", { tabId: id });debug("getStreamID()", id);let streamId;if (IS_OFFSCREEN_HOST) {- // chrome.tabCapture is not callable from offscreen - delegate to SW.+ // chrome.tabCapture isn't callable from offscreen; delegate to SW.+ const endOff = perfSpan("Recorder offscreen-request-stream(tab)");const response = await chrome.runtime.sendMessage({type: "offscreen-request-stream",@@ -2631,30 +3539,75 @@ const Recorder = () => {targetTabId: id,}).catch((err) => ({ ok: false, error: String(err) }));+ endOff({ ok: Boolean(response?.ok) });if (!response?.ok || !response.streamId) {debug("Offscreen tab stream acquisition failed", response);return;}streamId = response.streamId;} else {+ const endTc = perfSpan("Recorder tabCapture.getMediaStreamId");streamId = await chrome.tabCapture.getMediaStreamId({targetTabId: id,});+ endTc({ hasStreamId: Boolean(streamId) });}debug("Resolved tabCapture streamId", streamId);tabID.current = streamId;+ perfMark("Recorder getStreamID.done");+ };++ // chromeMediaSource constraints have no "no padding" knob: any combo+ // (including no width/height) still produces the 1920x1080 padded box.+ // Only maxWidth/maxHeight matching the source aspect ratio yields a clean+ // native-aspect frame. Read the viewport in CSS pixels x DPR to size them.+ const getRecordedTabViewport = async (tabId) => {+ if (!tabId) return null;+ try {+ if (IS_OFFSCREEN_HOST) {+ const response = await chrome.runtime+ .sendMessage({+ type: "get-tab-viewport",+ tabId,+ })+ .catch(() => null);+ if (response?.ok && response.width > 0 && response.height > 0) {+ return { width: response.width, height: response.height };+ }+ return null;+ }+ const results = await chrome.scripting.executeScript({+ target: { tabId },+ func: () => ({+ w: Math.round(window.innerWidth * (window.devicePixelRatio || 1)),+ h: Math.round(window.innerHeight * (window.devicePixelRatio || 1)),+ }),+ });+ const r = results?.[0]?.result;+ if (r && r.w > 0 && r.h > 0) return { width: r.w, height: r.h };+ return null;+ } catch (err) {+ debugWarn("getRecordedTabViewport failed", err);+ return null;+ }};const waitForTabStreamId = async () => {if (tabID.current) return tabID.current;+ const endWait = perfSpan("Recorder waitForTabStreamId");+ let attempts = 0;for (let i = 0; i < 30; i += 1) {+ attempts = i + 1;await new Promise((resolve) => setTimeout(resolve, 100));- if (tabID.current) return tabID.current;+ if (tabID.current) {+ endWait({ attempts, hasId: true });+ return tabID.current;+ }}+ endWait({ attempts, hasId: false });return null;};- // Cleanup on component unmountuseEffect(() => {return () => {debug("Component unmounting - cleaning up");@@ -2677,8 +3630,7 @@ const Recorder = () => {});if (uiClosing.current || !isRecording.current) return;- // Stop recording - note: beforeunload can't reliably wait for async- // The keep-alive and session state will help with recovery if needed+ // beforeunload can't await async; keep-alive + session state aid recovery.stopRecording();e.preventDefault();@@ -2694,7 +3646,7 @@ const Recorder = () => {};}, []);- // Message handler — registered once on mount; uses refs so closure stays fresh.+ // Registered once on mount; refs keep the closure fresh.const onMessageRef = useRef(null);onMessageRef.current = (request, sender, sendResponse) => {if (DEBUG_RECORDER) {@@ -2702,26 +3654,28 @@ const Recorder = () => {}if (request.type === "loaded") {+ perfMark("Recorder loaded.received", { isTab: Boolean(request?.isTab) });slLog("msg-loaded");backupRef.current = request.backup;if (!tabPreferred.current) {isTab.current = request.isTab;if (request.isTab) {+ recordedTabId.current = request.tabID ?? null;getStreamID(request.tabID);}} else {isTab.current = false;+ recordedTabId.current = null;}requestStreamingDataWithRetry();} else if (request.type === "streaming-data") {- // Guard against duplicate delivery: streaming-data may arrive more- // than once when the SW push and the tab pull both succeed, or when- // either side retries. First arrival wins; later ones are ignored.+ // Streaming-data may arrive twice (SW push + tab pull, or retries).if (streamingDataReceivedAt.current != null) {slLog("msg-streaming-data-duplicate");return;}slLog("msg-streaming-data");+ perfMark("Recorder streaming-data.received");streamingDataReceivedAt.current = Date.now();startStreaming(JSON.parse(request.data));} else if (request.type === "start-recording-tab") {@@ -2732,33 +3686,182 @@ const Recorder = () => {docHidden: document.hidden,docVisibility: document.visibilityState,});- // Request start via the readiness gate.requestStart();} else if (request.type === "restart-recording-tab") {+ const recState = () => {+ const r = recorder.current;+ let recorderType = "none";+ if (r) {+ if (r instanceof MediaRecorder) recorderType = "MediaRecorder";+ else if (useWebCodecs.current) recorderType = "WebCodecs";+ else recorderType = "other";+ }+ return {+ attemptId: request.attemptId || null,+ hasRecorder: Boolean(r),+ recorderType,+ mediaRecorderState:+ r instanceof MediaRecorder ? r.state : null,+ isRecording: Boolean(isRecording.current),+ isRestarting: Boolean(isRestarting.current),+ isFinishing: Boolean(isFinishing.current),+ hasStream: Boolean(helperVideoStream.current),+ docHidden: document.hidden,+ };+ };+ const stateAtEntry = recState();+ lifecycle("Recorder", "restart-tab-received", stateAtEntry);+if (isRestarting.current) {- sendResponse?.({ ok: false, error: "restart-in-progress" });+ lifecycle("Recorder", "restart-tab-result", {+ ...stateAtEntry,+ ok: false,+ error: "restart-in-progress",+ });+ sendResponse?.({+ ok: false,+ error: "restart-in-progress",+ recorderState: stateAtEntry,+ });return true;}pendingStartAfterRestart.current = false;Promise.resolve(restartRecording()).then((restarted) => {+ const after = recState();if (!restarted) {- sendResponse?.({ ok: false, error: "restart-teardown-failed" });+ lifecycle("Recorder", "restart-tab-result", {+ ...after,+ ok: false,+ error: "restart-teardown-failed",+ });+ sendResponse?.({+ ok: false,+ error: "restart-teardown-failed",+ recorderState: after,+ });return;}- sendResponse?.({ ok: true, restarted: true });+ lifecycle("Recorder", "restart-tab-result", { ...after, ok: true });+ sendResponse?.({+ ok: true,+ restarted: true,+ recorderState: after,+ });}).catch((error) => {+ const reason = error?.message || String(error);+ lifecycle("Recorder", "restart-tab-result", {+ ...recState(),+ ok: false,+ error: reason,+ threw: true,+ });sendResponse?.({ok: false,- error: error?.message || String(error),+ error: reason,+ recorderState: recState(),});});return true;} else if (request.type === "stop-recording-tab") {+ perfMark("Recorder stop-recording-tab.received");stopRecording();sendResponse?.({ ok: true });return true;+ } else if (request.type === "recorder-state-snapshot") {+ // First-chunk watchdog wants to know why no data arrived before killing.+ try {+ const r = recorder.current;+ const vt = liveStream.current?.getVideoTracks?.()[0] || null;+ const at = liveStream.current?.getAudioTracks?.()[0] || null;+ const helperVt = helperVideoStream.current?.getVideoTracks?.()[0] || null;+ sendResponse?.({+ ok: true,+ ts: Date.now(),+ recorder: r+ ? {+ type:+ r instanceof MediaRecorder+ ? "MediaRecorder"+ : useWebCodecs.current+ ? "WebCodecs"+ : "other",+ state: r instanceof MediaRecorder ? r.state : null,+ mimeType: r instanceof MediaRecorder ? r.mimeType : null,+ }+ : null,+ flags: {+ isRecording: Boolean(isRecording.current),+ isRestarting: Boolean(isRestarting.current),+ isFinishing: Boolean(isFinishing.current),+ isStarting: Boolean(isStarting?.current),+ useWebCodecs: Boolean(useWebCodecs.current),+ paused: Boolean(pausedStateRef.current),+ },+ counts: {+ saved: savedCount.current,+ pending: pending.current?.length ?? 0,+ pendingBytes: pendingBytes.current ?? 0,+ hasChunks: Boolean(hasChunks.current),+ },+ stream: {+ hasLive: Boolean(liveStream.current),+ hasHelper: Boolean(helperVideoStream.current),+ liveVideoTracks:+ liveStream.current?.getVideoTracks?.()?.length ?? 0,+ liveAudioTracks:+ liveStream.current?.getAudioTracks?.()?.length ?? 0,+ videoTrack: vt+ ? {+ readyState: vt.readyState,+ muted: vt.muted,+ enabled: vt.enabled,+ label: vt.label || null,+ }+ : null,+ audioTrack: at+ ? { readyState: at.readyState, muted: at.muted, enabled: at.enabled }+ : null,+ helperVideoTrack: helperVt+ ? {+ readyState: helperVt.readyState,+ muted: helperVt.muted,+ enabled: helperVt.enabled,+ }+ : null,+ },+ docHidden: document.hidden,+ docVisibility: document.visibilityState,+ });+ } catch (err) {+ sendResponse?.({ ok: false, error: String(err) });+ }+ return true;+ } else if (request.type === "recorder-keepalive-ping") {+ // BG watchdog liveness probe; without this it can't tell slow from dead.+ sendResponse?.({ ok: true, alive: true, ts: Date.now() });+ return true;+ } else if (request.type === "recorder-wake-aggressive") {+ // BG asks the tab to prove its main thread runs by bumping lastChunkAt.+ // Check track readyState first: a tab whose JS runs but tracks died+ // (post-sleep teardown pre-onended) would otherwise paper over death.+ let trackEnded = false;+ try {+ const v = liveStream.current?.getVideoTracks?.()[0] || null;+ if (v && v.readyState === "ended") trackEnded = true;+ const a = liveStream.current?.getAudioTracks?.()[0] || null;+ if (a && a.readyState === "ended") trackEnded = true;+ } catch {}+ if (trackEnded) {+ sendResponse?.({ ok: true, woke: false, trackEnded: true });+ return true;+ }+ try {+ chrome.storage.local.set({ lastChunkAt: Date.now() });+ } catch {}+ sendResponse?.({ ok: true, woke: true });+ return true;} else if (request.type === "offscreen-shutdown") {const timeoutMs = Number(request.timeoutMs) || 20000;(async () => {@@ -2794,6 +3897,8 @@ const Recorder = () => {}const now = Date.now();pausedStateRef.current = true;+ // Local pausedAt so rapid resume avoids storage round-trip.+ pausedAtRef.current = now;void setRecordingTimingState({paused: true,pausedAt: now,@@ -2813,13 +3918,15 @@ const Recorder = () => {}const now = Date.now();pausedStateRef.current = false;+ // Local pausedAt: storage may not have propagated yet.+ const pausedAt = pausedAtRef.current;+ pausedAtRef.current = null;+ const additional = pausedAt ? Math.max(0, now - pausedAt) : 0;void (async () => {try {- const { pausedAt, totalPausedMs } = await chrome.storage.local.get([- "pausedAt",+ const { totalPausedMs } = await chrome.storage.local.get(["totalPausedMs",]);- const additional = pausedAt ? Math.max(0, now - pausedAt) : 0;await setRecordingTimingState({paused: false,pausedAt: null,@@ -2834,7 +3941,6 @@ const Recorder = () => {}};- // Stable wrapper — delegates to the ref so the listener never changes.useEffect(() => {const stableHandler = (request, sender, sendResponse) => {return onMessageRef.current?.(request, sender, sendResponse);diff --git a/src/pages/Recorder/index.html b/src/pages/Recorder/index.htmlindex ef40862..efbcdd7 100644--- a/src/pages/Recorder/index.html+++ b/src/pages/Recorder/index.html@@ -33,6 +33,15 @@font-family: Satoshi-Medium;}</style>+ <!--+ Webpack injects two <script defer> tags (chunks: ["recorderkeepalive",+ "recorder"], chunksSortMode: "manual"):+ 1. recorderkeepalive.bundle.js: audio oscillator + Web Locks ++ mediaSession signals to prevent hidden-tab throttling.+ 2. recorder.bundle.js: the React app.+ Both deferred; document-order execution keeps signals in place+ before the recorder bundle parses.+ --></head><body>diff --git a/src/pages/Recorder/recorderConfig.js b/src/pages/Recorder/recorderConfig.jsindex a6172bf..bf682cf 100644--- a/src/pages/Recorder/recorderConfig.js+++ b/src/pages/Recorder/recorderConfig.js@@ -12,7 +12,7 @@ export function getBitrates(quality) {case "4k":return { audio: 192000, video: 20000000 };case "1080p":- return { audio: 128000, video: 8000000 };+ return { audio: 128000, video: 12000000 };case "720p":return { audio: 128000, video: 5000000 };case "480p":@@ -22,7 +22,7 @@ export function getBitrates(quality) {case "240p":return { audio: 64000, video: 1000000 };default:- return { audio: 128000, video: 8000000 };+ return { audio: 128000, video: 12000000 };}}export const VIDEO_QUALITIES = {diff --git a/src/pages/Recorder/recorderKeepalive.js b/src/pages/Recorder/recorderKeepalive.jsnew file mode 100644index 0000000..da2db01--- /dev/null+++ b/src/pages/Recorder/recorderKeepalive.js@@ -0,0 +1,75 @@+// keep-alive bootstrap, loaded from recorder.html before the main bundle.+// region recordings open the tab with active:false, so chrome throttles+// JS within ~1s and stretches bundle parse from ~300ms to 3-4.5s.+// three signals (audio oscillator, navigator.locks, mediaSession) make+// the tab look active before throttling kicks in.+// external because MV3 CSP blocks inline <script>. handles stashed on+// window.__SCREENITY_KEEPALIVE so React-side startTabKeepAlive() reuses.+(function () {+ try {+ var KA = (window.__SCREENITY_KEEPALIVE =+ window.__SCREENITY_KEEPALIVE || {});+ KA.startedAt = Date.now();+ try {+ performance.mark("screenity-keepalive-start");+ } catch (e) {}++ // Silent ultrasonic sine wave; counts as "playing audio" to Chrome's+ // freeze heuristic (looks at AudioContext.state + node wiring).+ try {+ var Ctx = window.AudioContext || window.webkitAudioContext;+ if (Ctx && !KA.audioCtx) {+ var ctx = new Ctx();+ var osc = ctx.createOscillator();+ var gain = ctx.createGain();+ osc.type = "sine";+ osc.frequency.value = 20000;+ gain.gain.value = 0.0001;+ osc.connect(gain);+ gain.connect(ctx.destination);+ osc.start();+ KA.audioCtx = ctx;+ KA.oscillator = osc;+ }+ } catch (e) {}++ // Holding an exclusive lock signals "doing work".+ try {+ if (navigator.locks && !KA.lockAbort) {+ var ac = new AbortController();+ KA.lockAbort = ac;+ navigator.locks+ .request(+ "screenity-recorder-keepalive",+ { mode: "exclusive", signal: ac.signal },+ function () {+ return new Promise(function () {});+ },+ )+ .catch(function () {});+ }+ } catch (e) {}++ // Belt + braces with the audio oscillator above.+ try {+ if (navigator.mediaSession && !KA.mediaSession) {+ if (typeof window.MediaMetadata === "function") {+ navigator.mediaSession.metadata = new window.MediaMetadata({+ title: "Screenity recording",+ artist: "Screenity",+ });+ }+ navigator.mediaSession.playbackState = "playing";+ try {+ navigator.mediaSession.setActionHandler("pause", function () {});+ } catch (e) {}+ KA.mediaSession = true;+ }+ } catch (e) {}++ KA.completedAt = Date.now();+ try {+ performance.mark("screenity-keepalive-end");+ } catch (e) {}+ } catch (e) {}+})();diff --git a/src/pages/Recorder/recorderStorage/chooseReader.js b/src/pages/Recorder/recorderStorage/chooseReader.jsnew file mode 100644index 0000000..7c6be6f--- /dev/null+++ b/src/pages/Recorder/recorderStorage/chooseReader.js@@ -0,0 +1,13 @@+import { IdbChunkReader } from "./idbChunkReader";+import { OpfsChunkReader } from "./opfs/opfsChunkReader";++export const chooseReader = (backendRef) => {+ const backend = backendRef?.backend || "idb";+ switch (backend) {+ case "opfs":+ return new OpfsChunkReader();+ case "idb":+ default:+ return new IdbChunkReader();+ }+};diff --git a/src/pages/Recorder/recorderStorage/chooseWriter.js b/src/pages/Recorder/recorderStorage/chooseWriter.jsnew file mode 100644index 0000000..9844c52--- /dev/null+++ b/src/pages/Recorder/recorderStorage/chooseWriter.js@@ -0,0 +1,30 @@+/*+ * OPFS writer when available, else IDB. OPFS needs navigator.storage.getDirectory+ * and FileSystemFileHandle.createSyncAccessHandle (Chrome >=102). The+ * backendRef from close() tells the sandbox which reader to use.+ */+import { IdbChunkWriter } from "./idbChunkWriter";+import { OpfsChunkWriter } from "./opfs/opfsChunkWriter";++const isOpfsSyncSupported = () => {+ try {+ if (typeof navigator === "undefined") return false;+ if (!navigator.storage || typeof navigator.storage.getDirectory !== "function") {+ return false;+ }+ if (typeof FileSystemFileHandle === "undefined") return false;+ // createSyncAccessHandle exists only in Worker context; any Chrome+ // with OPFS on main thread has it in workers (>=102). If worker+ // open() fails, OpfsChunkWriter throws and the caller falls back.+ return true;+ } catch {+ return false;+ }+};++export const chooseWriter = async ({ preferOpfs = true } = {}) => {+ if (preferOpfs && isOpfsSyncSupported()) {+ return { writer: new OpfsChunkWriter(), backend: "opfs" };+ }+ return { writer: new IdbChunkWriter(), backend: "idb" };+};diff --git a/src/pages/Recorder/recorderStorage/chunkWriterInterface.js b/src/pages/Recorder/recorderStorage/chunkWriterInterface.jsnew file mode 100644index 0000000..a7b6141--- /dev/null+++ b/src/pages/Recorder/recorderStorage/chunkWriterInterface.js@@ -0,0 +1,12 @@+// ChunkWriter interface for WebCodecs/fMP4 recording.+// implementations: IdbChunkWriter (localforage/IDB fallback) and+// OpfsChunkWriter (worker with FileSystemSyncAccessHandle).+// single-use: one open() per recording, order kept by chunk.index.+// ChunkRecord: { chunk: Blob, index: number, timestamp: number }+// CloseResult: { byteSize, chunkCount, backendRef? }+export const ChunkWriterInterface = {+ async open(recordingId) {},+ async write(record) {},+ async close() {},+ async abort() {},+};diff --git a/src/pages/Recorder/recorderStorage/idbChunkReader.js b/src/pages/Recorder/recorderStorage/idbChunkReader.jsnew file mode 100644index 0000000..55834b8--- /dev/null+++ b/src/pages/Recorder/recorderStorage/idbChunkReader.js@@ -0,0 +1,30 @@+// Mirrors Sandbox/recorderStorage/idbChunkReader, scoped to the recorder page.+import { idbChunksStore as chunksStore } from "./idbChunkWriter";++export class IdbChunkReader {+ async open(_backendRef) {+ await chunksStore.ready();+ }++ async readBlob() {+ const items = [];+ await chunksStore.iterate((value) => {+ items.push(value);+ return undefined;+ });+ items.sort((a, b) => {+ const dt = (a.timestamp ?? 0) - (b.timestamp ?? 0);+ if (dt !== 0) return dt;+ return (a.index ?? 0) - (b.index ?? 0);+ });+ const parts = items.map((c) =>+ c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),+ );+ if (!parts.length) return { blob: null, byteSize: 0, chunkCount: 0 };+ const inferredType = parts[0]?.type || "video/mp4";+ const blob = new Blob(parts, { type: inferredType });+ return { blob, byteSize: blob.size, chunkCount: parts.length };+ }++ async close() {}+}diff --git a/src/pages/Recorder/recorderStorage/idbChunkWriter.js b/src/pages/Recorder/recorderStorage/idbChunkWriter.jsnew file mode 100644index 0000000..bd8f49c--- /dev/null+++ b/src/pages/Recorder/recorderStorage/idbChunkWriter.js@@ -0,0 +1,57 @@+// IDB-backed ChunkWriter. Fallback when OPFS unavailable.+import localforage from "localforage";++localforage.config({+ driver: localforage.INDEXEDDB,+ name: "screenity",+ version: 1,+});++const chunksStore = localforage.createInstance({+ name: "chunks",+});++export class IdbChunkWriter {+ constructor() {+ this._byteSize = 0;+ this._chunkCount = 0;+ this._closed = false;+ this._aborted = false;+ }++ async open(_recordingId) {+ // Clearing handled at recorder level (chunksStore is shared); no-op+ // here so OpfsChunkWriter's file-creation semantics don't leak in.+ return { backendRef: { backend: "idb" } };+ }++ async write({ chunk, index, timestamp }) {+ if (this._closed || this._aborted) {+ throw new Error("idb-chunk-writer-closed");+ }+ await chunksStore.setItem(`chunk_${index}`, {+ index,+ chunk,+ timestamp,+ });+ this._byteSize += chunk?.size || 0;+ this._chunkCount += 1;+ }++ async close() {+ this._closed = true;+ return {+ byteSize: this._byteSize,+ chunkCount: this._chunkCount,+ backendRef: { backend: "idb" },+ };+ }++ async abort() {+ this._aborted = true;+ // Callers decide whether to chunksStore.clear(); aborting one writer+ // doesn't imply wiping all sessions.+ }+}++export { chunksStore as idbChunksStore };diff --git a/src/pages/Recorder/recorderStorage/opfs/opfsChunkReader.js b/src/pages/Recorder/recorderStorage/opfs/opfsChunkReader.jsnew file mode 100644index 0000000..37c5de9--- /dev/null+++ b/src/pages/Recorder/recorderStorage/opfs/opfsChunkReader.js@@ -0,0 +1,35 @@+/*+ * Caller MUST close the writer's sync handle before reading: getFile()+ * returns stale/empty while the sync handle is held.+ */+const MIN_VALID_RECORDING_BYTES = 4096;++export class OpfsChunkReader {+ constructor() {+ this._fileName = null;+ }++ async open(backendRef) {+ const name = backendRef?.fileName;+ if (!name) throw new Error("opfs-chunk-reader-no-filename");+ this._fileName = name;+ }++ async readBlob() {+ if (!this._fileName) throw new Error("opfs-chunk-reader-not-opened");+ const dir = await navigator.storage.getDirectory();+ const handle = await dir.getFileHandle(this._fileName);+ const file = await handle.getFile();+ if (file.size < MIN_VALID_RECORDING_BYTES) {+ const err = new Error(+ `opfs-file-too-small: ${file.size} bytes < ${MIN_VALID_RECORDING_BYTES}`,+ );+ err.code = "opfs-file-too-small";+ throw err;+ }+ const blob = new Blob([file], { type: "video/mp4" });+ return { blob, byteSize: blob.size, chunkCount: 1 };+ }++ async close() {}+}diff --git a/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js b/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.jsnew file mode 100644index 0000000..d0fd103--- /dev/null+++ b/src/pages/Recorder/recorderStorage/opfs/opfsChunkWriter.js@@ -0,0 +1,236 @@+// main-thread ChunkWriter delegating to a worker that holds a+// FileSystemSyncAccessHandle. requestId correlates post/response and+// awaiting each write is the backpressure.+// on worker crash / timeout / quota: pending writes reject with a tagged+// error, writer marks dead, fileName kept so callers can find partial+// content. recorder stops and opens the editor on the partial; backends+// don't swap mid-recording (would orphan written chunks).++const WORKER_URL = () =>+ chrome.runtime.getURL("recorderopfsworker.bundle.js");++// Write is short (chunks ~200KB; commit fast or hung). Close is long:+// syncHandle.flush() on multi-GB recordings on slow disks can exceed+// 10s; close() scales the timeout dynamically by file size.+const WRITE_TIMEOUT_MS = 5000;+const OPEN_TIMEOUT_MS = 15000;+const CLOSE_TIMEOUT_BASE_MS = 30000;+const CLOSE_TIMEOUT_PER_GB_MS = 30000;+const CLOSE_TIMEOUT_MAX_MS = 180000;+const ABORT_TIMEOUT_MS = 10000;++// Used by Recorder.jsx's handleChunk to detect OPFS writer failure.+export const OPFS_WRITER_FAILED_CODE = "opfs-writer-failed";++const opfsDiag = (event, data = {}) => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: `opfs-${event}`,+ data,+ });+ } catch {}+};++export class OpfsChunkWriter {+ constructor() {+ this.worker = null;+ this.nextRequestId = 1;+ this.pending = new Map();+ this._byteSize = 0;+ this._chunkCount = 0;+ this._fileName = null;+ this._closed = false;+ this._aborted = false;+ // after failure (crash/timeout/quota) the writer is permanently dead;+ // file state past the failure point is unknown.+ this._dead = false;+ this._deathError = null;+ }++ _markDead(err) {+ if (this._dead) return;+ this._dead = true;+ const tagged = err instanceof Error ? err : new Error(String(err));+ tagged.code = OPFS_WRITER_FAILED_CODE;+ tagged.fileName = this._fileName;+ this._deathError = tagged;+ opfsDiag("dead", {+ errorName: tagged.errorName || tagged.name || "Error",+ message: String(tagged.message || "").slice(0, 200),+ fileName: this._fileName,+ byteSize: this._byteSize,+ chunkCount: this._chunkCount,+ pendingCount: this.pending.size,+ });+ for (const [, entry] of this.pending) entry.reject(tagged);+ this.pending.clear();+ if (this.worker) {+ try {+ this.worker.terminate();+ } catch {}+ this.worker = null;+ }+ }++ _attachWorker() {+ this.worker = new Worker(WORKER_URL());+ this.worker.onmessage = (e) => {+ const msg = e.data;+ if (!msg || !msg.requestId) return;+ const entry = this.pending.get(msg.requestId);+ if (!entry) return;+ this.pending.delete(msg.requestId);+ if (entry.timeoutId) clearTimeout(entry.timeoutId);+ if (msg.ok) {+ entry.resolve(msg);+ } else {+ const err = new Error(msg.error || "opfs-worker-error");+ err.errorName = msg.errorName || "Error";+ entry.reject(err);+ }+ };+ this.worker.onerror = (e) => {+ const err = new Error(String(e?.message || "opfs-worker-crashed"));+ err.errorName = "WorkerError";+ this._markDead(err);+ };+ }++ _request(message, timeout = WRITE_TIMEOUT_MS) {+ if (this._dead) {+ return Promise.reject(this._deathError);+ }+ if (!this.worker) this._attachWorker();+ const requestId = this.nextRequestId++;+ return new Promise((resolve, reject) => {+ const entry = { resolve, reject };+ this.pending.set(requestId, entry);+ entry.timeoutId = setTimeout(() => {+ // Terminal even if the worker eventually replies; file state is+ // unknowable past this point.+ if (this.pending.delete(requestId)) {+ const timeoutErr = new Error(+ `opfs-${message.type}-timeout after ${timeout}ms`,+ );+ timeoutErr.errorName = "TimeoutError";+ this._markDead(timeoutErr);+ }+ }, timeout);+ this.worker.postMessage({ ...message, requestId });+ });+ }++ async open(recordingId) {+ if (this._closed || this._aborted) {+ throw new Error("opfs-chunk-writer-reused");+ }+ const resp = await this._request(+ { type: "open", recordingId },+ OPEN_TIMEOUT_MS,+ );+ this._fileName = resp.fileName || null;+ opfsDiag("open-ok", { fileName: this._fileName });+ // Persist immediately so a crash before chunkBackendRef.current syncs+ // still leaves the editor a pointer to the partial OPFS file.+ if (this._fileName) {+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: {+ backend: "opfs",+ fileName: this._fileName,+ },+ });+ } catch {}+ }+ return { backendRef: { backend: "opfs", fileName: this._fileName } };+ }++ async write({ chunk, index, timestamp }) {+ if (this._closed || this._aborted) {+ throw new Error("opfs-chunk-writer-closed");+ }+ // index/timestamp accepted to match IdbChunkWriter; OPFS is ordered+ // by write position so they aren't stored.+ const resp = await this._request({+ type: "write",+ chunk,+ index,+ timestamp,+ });+ this._byteSize = resp.totalSize ?? this._byteSize;+ this._chunkCount += 1;+ }++ async close() {+ if (this._closed) {+ return {+ byteSize: this._byteSize,+ chunkCount: this._chunkCount,+ backendRef: { backend: "opfs", fileName: this._fileName },+ };+ }+ // 30s base + 30s/GB, capped at 3min. A 4GB recording on slow HDD+ // can take 90s to flush; the old fixed 30s lost bytes-on-disk recordings.+ const sizeGb = this._byteSize / (1024 * 1024 * 1024);+ const closeTimeoutMs = Math.min(+ CLOSE_TIMEOUT_BASE_MS + Math.ceil(sizeGb) * CLOSE_TIMEOUT_PER_GB_MS,+ CLOSE_TIMEOUT_MAX_MS,+ );+ opfsDiag("close-start", {+ byteSize: this._byteSize,+ chunkCount: this._chunkCount,+ timeoutMs: closeTimeoutMs,+ });+ try {+ const resp = await this._request({ type: "close" }, closeTimeoutMs);+ this._byteSize = resp.byteSize ?? this._byteSize;+ this._chunkCount = resp.chunkCount ?? this._chunkCount;+ this._fileName = resp.fileName || this._fileName;+ opfsDiag("close-ok", {+ byteSize: this._byteSize,+ chunkCount: this._chunkCount,+ });+ // signal "file is fully flushed" to the sandbox reader. kept as its+ // own key because stop cleanup rewrites lastRecordingBackendRef from+ // a few different paths and would clobber a finalized flag stored+ // there. without this signal the editor reads mid-flush and ends up+ // with a truncated blob.+ if (this._fileName) {+ try {+ await chrome.storage.local.set({+ lastRecordingFinalizedFileName: this._fileName,+ });+ } catch {}+ }+ } finally {+ this._closed = true;+ this._teardown();+ }+ return {+ byteSize: this._byteSize,+ chunkCount: this._chunkCount,+ backendRef: { backend: "opfs", fileName: this._fileName },+ };+ }++ async abort() {+ if (this._aborted) return;+ this._aborted = true;+ try {+ await this._request({ type: "abort" }, ABORT_TIMEOUT_MS);+ } catch {} finally {+ this._teardown();+ }+ }++ _teardown() {+ if (this.worker) {+ try {+ this.worker.terminate();+ } catch {}+ this.worker = null;+ }+ this.pending.clear();+ }+}diff --git a/src/pages/Recorder/recorderStorage/opfs/writerWorker.js b/src/pages/Recorder/recorderStorage/opfs/writerWorker.jsnew file mode 100644index 0000000..0d54f66--- /dev/null+++ b/src/pages/Recorder/recorderStorage/opfs/writerWorker.js@@ -0,0 +1,206 @@+// owns an OPFS file via FileSystemSyncAccessHandle. near-zero RAM, no+// IDB overhead per write. writes serial; main awaits each 'written'+// for backpressure. file persists across restarts, cleaned up by+// abort() or post-read delete in the sandbox.+// protocol: main {type, requestId, ...} -> worker {type, requestId, ok, ...}++const FILE_PREFIX = "recording-";++const devLog =+ process.env.SCREENITY_DEV_MODE === "true"+ ? (label, data) =>+ console.log("[recorder-opfs][worker]", label, data || "")+ : () => {};++let fileName = null;+let syncHandle = null;+let offset = 0;+let chunkCount = 0;+let closed = false;++// Keep exactly one recoverable recording (matches chunksStore.clear()+// on the IDB path); old recording stays until a new one actually starts.+const clearPreviousRecordings = async (exceptName = null) => {+ try {+ const dir = await navigator.storage.getDirectory();+ for await (const [name] of dir.entries()) {+ if (!name.startsWith(FILE_PREFIX)) continue;+ if (exceptName && name === exceptName) continue;+ await dir.removeEntry(name).catch(() => {});+ }+ } catch {}+};++const post = (payload) => {+ self.postMessage(payload);+};++const openFile = async (recordingId) => {+ // Create NEW before deleting old: if creation fails, the previous+ // recording remains intact for recovery, and a recovery editor+ // already loading the old file doesn't lose it mid-load.+ const dir = await navigator.storage.getDirectory();+ const name = `${FILE_PREFIX}${recordingId}.mp4`;+ const handle = await dir.getFileHandle(name, { create: true });+ const sync = await handle.createSyncAccessHandle();+ sync.truncate(0);+ fileName = name;+ syncHandle = sync;+ offset = 0;+ chunkCount = 0;+ closed = false;+ await clearPreviousRecordings(name);+ devLog("open", { fileName: name });+ return { fileName: name };+};++const writeChunk = async (blob) => {+ if (closed) throw new Error("opfs-writer-closed");+ if (!syncHandle) throw new Error("opfs-writer-not-open");+ // arrayBuffer() is async; sync handle write is synchronous once bytes are in hand.+ const buf = await blob.arrayBuffer();+ const u8 = new Uint8Array(buf);+ const written = syncHandle.write(u8, { at: offset });+ offset += typeof written === "number" ? written : u8.byteLength;+ chunkCount += 1;+ return { totalSize: offset };+};++const closeFile = () => {+ if (!syncHandle) {+ return { byteSize: offset, chunkCount, fileName };+ }+ try {+ syncHandle.flush();+ } catch {}+ const byteSize = typeof syncHandle.getSize === "function" ? syncHandle.getSize() : offset;+ syncHandle.close();+ syncHandle = null;+ closed = true;+ devLog("close", { byteSize, chunkCount, fileName });+ return { byteSize, chunkCount, fileName };+};++const abortFile = async () => {+ if (syncHandle) {+ try {+ syncHandle.close();+ } catch {}+ syncHandle = null;+ }+ if (fileName) {+ try {+ const dir = await navigator.storage.getDirectory();+ await dir.removeEntry(fileName).catch(() => {});+ } catch {}+ }+ fileName = null;+ offset = 0;+ chunkCount = 0;+ closed = true;+};++// Single promise chain: writes apply in post order, open/close/abort+// can't interleave with in-flight writes.+let queue = Promise.resolve();++const enqueue = (fn) => {+ const next = queue.then(fn).catch((err) => {+ // Error already surfaces via post(); keep chain alive for next msg.+ return { __error: err };+ });+ queue = next;+ return next;+};++self.onmessage = (e) => {+ const msg = e.data;+ if (!msg || !msg.type || !msg.requestId) return;++ // Preserve DOMException name (e.g. "QuotaExceededError") across the+ // structured-clone boundary so main can branch without substring matching.+ const errorPayload = (err) => ({+ error: String(err?.message || err),+ errorName: err?.name || "Error",+ });++ if (msg.type === "open") {+ enqueue(async () => {+ try {+ const { fileName: fn } = await openFile(msg.recordingId);+ post({ type: "ready", requestId: msg.requestId, ok: true, fileName: fn });+ } catch (err) {+ post({+ type: "ready",+ requestId: msg.requestId,+ ok: false,+ ...errorPayload(err),+ });+ }+ });+ return;+ }++ if (msg.type === "write") {+ enqueue(async () => {+ try {+ const { totalSize } = await writeChunk(msg.chunk);+ post({+ type: "written",+ requestId: msg.requestId,+ ok: true,+ totalSize,+ });+ } catch (err) {+ post({+ type: "written",+ requestId: msg.requestId,+ ok: false,+ ...errorPayload(err),+ });+ }+ });+ return;+ }++ if (msg.type === "close") {+ enqueue(async () => {+ try {+ const result = closeFile();+ post({+ type: "closed",+ requestId: msg.requestId,+ ok: true,+ byteSize: result.byteSize,+ chunkCount: result.chunkCount,+ fileName: result.fileName,+ });+ } catch (err) {+ post({+ type: "closed",+ requestId: msg.requestId,+ ok: false,+ ...errorPayload(err),+ });+ }+ });+ return;+ }++ if (msg.type === "abort") {+ enqueue(async () => {+ try {+ await abortFile();+ post({ type: "aborted", requestId: msg.requestId, ok: true });+ } catch (err) {+ post({+ type: "aborted",+ requestId: msg.requestId,+ ok: false,+ ...errorPayload(err),+ });+ }+ });+ return;+ }+};diff --git a/src/pages/Recorder/streamWarmup.js b/src/pages/Recorder/streamWarmup.jsnew file mode 100644index 0000000..bae771d--- /dev/null+++ b/src/pages/Recorder/streamWarmup.js@@ -0,0 +1,51 @@+// Keep the getDisplayMedia capture pipeline hot while we wait for the user+// (countdown, gate, etc). Without this, macOS lets the capture stream go idle+// after warm-up and the first ~1s of recording is stale frames.++export function startPrewarm(liveStream) {+ const videoTrack = liveStream?.getVideoTracks?.()[0];+ if (!videoTrack || typeof MediaStreamTrackProcessor === "undefined") {+ return null;+ }+ let cancelled = false;+ let processor;+ let reader;+ try {+ processor = new MediaStreamTrackProcessor({ track: videoTrack });+ reader = processor.readable.getReader();+ } catch {+ return null;+ }+ const loop = (async () => {+ try {+ while (!cancelled) {+ const { value, done } = await reader.read();+ if (done) break;+ try {+ value?.close?.();+ } catch {}+ }+ } catch {}+ try {+ reader.releaseLock();+ } catch {}+ })();+ return {+ cancel: async () => {+ cancelled = true;+ try {+ await reader.cancel();+ } catch {}+ try {+ await loop;+ } catch {}+ },+ };+}++export async function stopPrewarm(controller) {+ if (!controller) return;+ try {+ await controller.cancel();+ } catch {}+}diff --git a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.tsindex 83e5767..3b3c8cc 100644--- a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts+++ b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts@@ -25,9 +25,8 @@ interface Mp4MuxerWrapperOptions {debug?: boolean;}-// Flush buffered stream writes to chunksStore when we hit ~1MB or 1s,-// whichever first. Small enough that losing the last buffer on a hard crash-// only costs ~1s of video; large enough that chunksStore writes stay cheap.+// Flush buffered stream writes at ~1MB or 1s. Bounds last-buffer loss on+// hard crash to ~1s of video while keeping chunksStore writes cheap.const FLUSH_BYTES = 1 * 1024 * 1024;const FLUSH_INTERVAL_MS = 1000;@@ -50,10 +49,8 @@ export class Mp4MuxerWrapper {private _lastDecoderConfig: any = null;- // Write-buffer state: coalesces many small StreamTarget writes into- // fewer, larger IDB entries. Fragmented MP4 can emit dozens of tiny- // writes per second (per-fragment headers, sample data, trailing bytes);- // without this, IDB would get hammered with small puts.+ // Coalesces small StreamTarget writes (per-fragment headers, sample data,+ // trailing bytes) into fewer larger IDB puts.private _writeBuffer: Uint8Array[] = [];private _writeBufferBytes = 0;private _writeBufferTimer: any = null;@@ -75,16 +72,12 @@ export class Mp4MuxerWrapper {this.videoCodec = options.videoCodec || "avc";this.audioCodec = options.audioCodec || "aac";- // Fragmented MP4 via StreamTarget. Writes stream out as fragments are- // produced throughout recording, so if finalize() hangs or the recorder- // crashes, chunksStore already holds the vast majority of the file as- // self-contained fMP4 fragments (moov at start, moof+mdat pairs after).- // Playable directly in <video> and re-muxable to standard MP4 on- // download for universal compatibility.+ // Fragmented MP4: if finalize() hangs or the recorder crashes,+ // chunksStore already holds self-contained fMP4 fragments+ // (moov at start, moof+mdat pairs after) playable in <video>.const writable = new WritableStream<{ data: Uint8Array; position: number; type: string }>({write: (chunk) => {- // With an append-only fragmented output, writes arrive in byte-order- // and position is monotonic, so we ignore position and just append.+ // Append-only fragmented output: position is monotonic, ignore it.this.bufferWrite(chunk.data);},});@@ -92,9 +85,7 @@ export class Mp4MuxerWrapper {this.output = new Output({format: new Mp4OutputFormat({fastStart: "fragmented",- // Align fragment boundaries with our keyframe interval (~2s at 30fps).- // Larger fragments = fewer moof headers overhead; smaller = finer-- // grained recovery on crash. 1s is a good middle ground.+ // 1s balances moof overhead vs crash-recovery granularity.minimumFragmentDuration: 1,}),target: this.target,@@ -108,9 +99,7 @@ export class Mp4MuxerWrapper {private bufferWrite(data: Uint8Array) {if (this._closed) return;- // StreamTarget reuses its internal buffer across writes, so we must- // copy here. Storing the reference would leave us with stale bytes- // by the time the flush runs.+ // StreamTarget reuses its internal buffer across writes; must copy.const copy = new Uint8Array(data.byteLength);copy.set(data);this._writeBuffer.push(copy);@@ -145,8 +134,8 @@ export class Mp4MuxerWrapper {offset += p.byteLength;}- // Serialize emits via a promise chain so chunksStore sees writes in the- // order they were produced (critical for file byte-order integrity).+ // Serialize emits so chunksStore sees writes in produced order+ // (critical for file byte-order integrity).this._pendingFlush = this._pendingFlush.catch(() => {}).then(() => this.emitChunk(merged, null));@@ -165,7 +154,7 @@ export class Mp4MuxerWrapper {this._lastDecoderConfig = meta.decoderConfig;}- // Meta is read-only — supply cached decoderConfig when the chunk lacks one.+ // Supply cached decoderConfig when chunk lacks one.const effectiveMeta =!meta?.decoderConfig && this._lastDecoderConfig? { ...meta, decoderConfig: this._lastDecoderConfig }@@ -194,28 +183,26 @@ export class Mp4MuxerWrapper {try {await this.output.finalize();} finally {- // Whatever finalize did (or didn't) write, flush the coalescing- // buffer and mark closed so late writes are dropped rather than- // leaking into a future recording.+ // Flush coalescing buffer and close so late writes don't leak+ // into a future recording.this.flushWriteBuffer();this._closed = true;- // Let any in-flight emitChunk calls settle before returning. The- // caller's onFinalized depends on chunksStore being consistent.+ // Let in-flight emitChunk calls settle; caller's onFinalized+ // depends on chunksStore being consistent.await this._pendingFlush;}}- // Force-flush pending writes without running output.finalize(). Called- // when the muxer hangs, to preserve whatever fragments have already- // streamed out so the recording is still recoverable.+ // Force-flush without finalize(). Used when the muxer hangs to preserve+ // already-streamed fragments for recovery.async flushPending() {this.flushWriteBuffer();this._closed = true;await this._pendingFlush;}- // No-op: WebCodecsRecorder already subtracts paused time from timestamps,- // so a second subtraction here would break monotonicity. Kept for API compat.+ // No-op: WebCodecsRecorder already subtracts paused time; double-subtract+ // would break monotonicity. Kept for API compat.setPausedOffset(_offsetUs: number) {}setAudioOffset(offsetUs: number) {@@ -256,8 +243,7 @@ export class Mp4MuxerWrapper {const last = (this as any)[key] ?? 0;if (type === "audio") {- // Audio ts is already monotonic from WebCodecsRecorder's sample counter.- // Just accumulate for logging.+ // Audio ts is monotonic from WebCodecsRecorder's sample counter.const next = last + durationUs;(this as any)[key] = next;this.log(`[MUX] audio ts +${durationUs} => ${next}`);@@ -271,9 +257,8 @@ export class Mp4MuxerWrapper {return fallback;}- // Pin offset to the first frame so output starts at 0.- // Don't subtract pausedOffsetUs — WebCodecsRecorder already excludes- // paused time, and double-subtracting breaks monotonicity.+ // Pin offset to first frame so output starts at 0. Don't subtract+ // pausedOffsetUs: WebCodecsRecorder already excludes paused time.if (this.videoTimestampOffsetUs == null) {this.videoTimestampOffsetUs = timestampUs;}diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.jsindex 19b554e..6b100c4 100644--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js@@ -9,7 +9,24 @@* Handles H.264 video, AAC audio, timestamp safety,* canvas resizing, pause/resume, and chunked output.*/-import { Mp4MuxerWrapper } from "./Mp4MuxerWrapper";+import { perfMark, perfSpan } from "../../utils/perfMarks";+// Lazy-load Mp4MuxerWrapper so its ~3MB mediabunny static import doesn't+// drag into recorder.bundle.js cold start (dominates click-record latency).+let _mp4MuxerWrapperPromise = null;+const loadMp4MuxerWrapper = () => {+ if (!_mp4MuxerWrapperPromise) {+ _mp4MuxerWrapperPromise = import("./Mp4MuxerWrapper").then(+ (m) => m.Mp4MuxerWrapper,+ );+ }+ return _mp4MuxerWrapperPromise;+};++// Warm the mediabunny muxer chunk before start() so its first import doesn't+// add latency between the countdown ending and the recorder firing.+export function preloadWebCodecsModules() {+ loadMp4MuxerWrapper().catch(() => {});+}export class WebCodecsRecorder {constructor(stream, options) {@@ -46,9 +63,9 @@ export class WebCodecsRecorder {this.videoTimestampOffsetUs = null;this.videoFallbackStartMs = null;this.selectedVideoCodec = null;+ this.actualVideoCodec = null;this.firstVideoFrame = undefined;this.frameCount = 0;- // Monotonic video frame index for safe timestampsthis._videoFrameIndex = 0;this._videoStartUs = null;this._frameDurationUs = null;@@ -78,6 +95,24 @@ export class WebCodecsRecorder {}async _probeRealResolution() {+ // Prefer track settings: on macOS getDisplayMedia, the first frame from+ // MediaStreamTrackProcessor can be delayed several seconds by VideoToolbox+ // capture cold-start, which would block start() and freeze the toolbar.+ try {+ const settings =+ typeof this.videoTrack.getSettings === "function"+ ? this.videoTrack.getSettings()+ : null;+ const w = settings && Number(settings.width);+ const h = settings && Number(settings.height);+ if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {+ this.log("[WCR] Resolution from track settings:", w, "x", h);+ return { width: w, height: h };+ }+ } catch (err) {+ this.warn("[WCR] getSettings() failed; falling back to frame probe", err);+ }+const processor = new MediaStreamTrackProcessor({ track: this.videoTrack });const reader = processor.readable.getReader();@@ -143,16 +178,34 @@ export class WebCodecsRecorder {}try {+ perfMark("WCR.start.enter");+ const endProbe = perfSpan("WCR.probeResolution");const { width, height } = await this._probeRealResolution();+ endProbe({ width, height });this.actualWidth = width;this.actualHeight = height;- let targetWidth = Math.min(width, 1920);+ // User quality (options.width/height) caps target; never upscale+ // beyond capture. 3840 hard cap stops pathological inputs.+ const HARD_CAP = 3840;+ const userMaxWidth = Number.isFinite(this.options?.width)+ ? this.options.width+ : HARD_CAP;+ const userMaxHeight = Number.isFinite(this.options?.height)+ ? this.options.height+ : HARD_CAP;+ const effectiveCapWidth = Math.min(userMaxWidth, HARD_CAP);+ const effectiveCapHeight = Math.min(userMaxHeight, HARD_CAP);++ let targetWidth = Math.min(width, effectiveCapWidth);let targetHeight = Math.round((height / width) * targetWidth);- if (targetHeight > 1080) {- targetHeight = 1080;+ if (targetHeight > effectiveCapHeight) {+ targetHeight = effectiveCapHeight;targetWidth = Math.round((width / height) * targetHeight);}+ // H.264/HEVC require even dimensions; min 32 for tiny regions.+ targetWidth = Math.max(32, targetWidth - (targetWidth % 2));+ targetHeight = Math.max(32, targetHeight - (targetHeight % 2));this.targetWidth = targetWidth;this.targetHeight = targetHeight;@@ -177,7 +230,6 @@ export class WebCodecsRecorder {};this.log("[WCR] Using override encoder config", config);try {- // Verify override is still supported at runtimeconst support = await VideoEncoder.isConfigSupported(config);if (support?.supported) {videoConfig = {@@ -192,16 +244,20 @@ export class WebCodecsRecorder {}if (!videoConfig) {+ const endChoose = perfSpan("WCR.chooseVideoEncoderConfig");videoConfig = await this.chooseVideoEncoderConfig({width: this.targetWidth,height: this.targetHeight,fps,bitrate: safeBitrate,});+ endChoose({ codec: videoConfig?.codec });}this.selectedVideoCodec = videoConfig.codec;+ const endAudioCfg = perfSpan("WCR.prepareAudioEncoderConfig");const audioConfig = await this.prepareAudioEncoderConfig();+ endAudioCfg({ ok: Boolean(audioConfig) });this._pendingAudioConfig = audioConfig;this.log("[WCR] Audio config:", audioConfig);@@ -220,11 +276,13 @@ export class WebCodecsRecorder {this.audioReader = this.audioProcessor.readable.getReader();}- // Init audio encoder first so _audioReady=true when both loops- // launch together — avoids audio prebuffering before video starts.+ // Init audio first so _audioReady=true when both loops launch+ // together, avoiding audio prebuffer before video starts.if (this._pendingAudioConfig) {+ const endAudioInit = perfSpan("WCR.initAudioEncoder");await this.initAudioEncoder(this._pendingAudioConfig);this._audioReady = true;+ endAudioInit();}this.videoProcessor = new MediaStreamTrackProcessor({@@ -233,6 +291,9 @@ export class WebCodecsRecorder {this.videoReader = this.videoProcessor.readable.getReader();this.log("[WCR] creating muxer...");+ const endLoadMuxer = perfSpan("WCR.loadMp4MuxerWrapper");+ const Mp4MuxerWrapper = await loadMp4MuxerWrapper();+ endLoadMuxer();this.muxer = new Mp4MuxerWrapper({width: this.targetWidth,height: this.targetHeight,@@ -248,15 +309,21 @@ export class WebCodecsRecorder {this.muxer.enableAudio();}+ const endMuxerStart = perfSpan("WCR.muxer.start");await this.muxer.start();+ endMuxerStart();this.log("[WCR] muxer started");+ const endVidInit = perfSpan("WCR.initVideoEncoder");await this.initVideoEncoder(videoConfig.config, videoConfig.codec);+ endVidInit();await Promise.resolve();- setTimeout(() => {- // Start both loops together so t=0 is aligned.+ this._startAlignTimer = setTimeout(() => {+ this._startAlignTimer = null;+ if (!this.running) return;+ // Launch loops together so t=0 aligns.this._videoLoopPromise = this.readVideoLoop();if (this.audioReader && this.options.enableAudio) {this.log("[WCR] start audio loop (aligned with video)");@@ -311,7 +378,12 @@ export class WebCodecsRecorder {return;}- // Soft stop: let loops finish current work+ if (this._startAlignTimer) {+ clearTimeout(this._startAlignTimer);+ this._startAlignTimer = null;+ }++ // Soft stop: let loops finish current work.this.running = false;this.paused = true;@@ -324,16 +396,15 @@ export class WebCodecsRecorder {this.log("[WCR] Waiting for read loops to finish before flush...");await Promise.race([Promise.allSettled(loopPromises),- new Promise((res) => setTimeout(res, 500)), // safety timeout+ new Promise((res) => setTimeout(res, 500)),]);}} catch (err) {this.err("[WCR] Error while waiting for loops:", err);}- // First flush: drain all queued audio and video from the main recording.- // This is what makes audioSamplesWritten a reliable basis for computing- // the final audio track duration below.+ // First flush: drain queued audio/video so audioSamplesWritten is a+ // reliable basis for final track duration.try {if (this.videoEncoder && this.videoEncoder.state !== "closed") {await this.videoEncoder.flush();@@ -346,18 +417,11 @@ export class WebCodecsRecorder {this.options.onError?.(err);}- // Now encode trailing hold frames sized to cover the final audio track- // end. Done after the first flush so all queued audio has been emitted and- // audioSamplesWritten reflects the true audio track duration. Without- // these, the audio track extends past the last video sample and players- // render the gap as a black frame at the very end.- //- // We encode MULTIPLE hold frames (not one long-duration frame) because- // encoders don't always preserve VideoFrame.duration on the output chunk —- // a single hold frame with claimed duration=150ms may get written to MP4- // with duration=0 or the default frameDuration, leaving the track at its- // pre-hold end. With multiple frames, the muxer derives each sample's- // duration from the NEXT sample's timestamp, which is naturally correct.+ // Encode trailing hold frames to cover the final audio end. Without+ // these, audio extends past the last video sample and players render a+ // trailing black frame. Multiple frames (not one long-duration frame):+ // encoders don't always preserve VideoFrame.duration on the output+ // chunk, so a single 150ms hold may get written with duration=0.if (this.videoEncoder &&this.videoEncoder.state !== "closed" &&@@ -372,9 +436,7 @@ export class WebCodecsRecorder {? Math.round((this.audioSamplesWritten * 1_000_000) / sampleRate): 0;const holdStartUs = this._videoFrameIndex * this._frameDurationUs;- // Generous cushion covers both audio-encoder drain lag and any- // muxer-side rounding. 150ms is imperceptible to a user scrubbing to- // the end; they see the last captured frame held briefly.+ // Cushion for audio drain lag + muxer rounding; 150ms is imperceptible.const cushionUs = 150_000;const targetEndUs = Math.max(holdStartUs + this._frameDurationUs,@@ -397,7 +459,6 @@ export class WebCodecsRecorder {hold.close();this._videoFrameIndex += 1;}- // Second flush: drain the hold frames.await this.videoEncoder.flush();this.log("[WCR] trailing hold frames encoded", {holdStartUs,@@ -409,13 +470,10 @@ export class WebCodecsRecorder {}}- // Finalize the muxer with a hard timeout. On abrupt stream end (e.g. user- // clicks Chrome's "Stop sharing" bar and the video track is torn down- // mid-pipeline), output.finalize() can hang. With fragmented MP4 +- // StreamTarget the vast majority of the file has already been streamed- // to chunksStore throughout the recording, so a hung finalize at most- // costs us the last fragment (~1s). flushPending() drops the muxer into- // a closed state and flushes any buffered writes, preserving what we have.+ // Finalize with hard timeout: abrupt stream end (Chrome "Stop sharing"+ // tearing down the video track) can hang output.finalize(). Fragmented+ // MP4 + StreamTarget means most of the file is already in chunksStore;+ // a hung finalize costs at most ~1s. flushPending() preserves what we have.let muxerFinalizeOk = false;if (this.muxer) {try {@@ -439,10 +497,9 @@ export class WebCodecsRecorder {}}- // Always invoke onFinalized so the Recorder layer can decide what to do- // next (validate whatever chunks landed, mark the recording as failed,- // send video-ready to unblock the editor). Skipping this on finalize- // failure is what caused the stuck-at-90% bug on stream-end.+ // Always invoke onFinalized: skipping on finalize-fail caused the+ // stuck-at-90% bug on stream-end. Recorder layer decides next steps+ // (validate chunks, mark failed, send video-ready).if (this.options.onFinalized) {try {await this.options.onFinalized({ muxerFinalizeOk });@@ -494,9 +551,8 @@ export class WebCodecsRecorder {this.audioEncoder?.close();} catch {}- // Release any AudioData objects that were queued before the audio encoder- // was ready. If encoder init failed, these would otherwise be held in- // memory indefinitely because readAudioLoop never drained the buffer.+ // Release pre-encoder-ready AudioData; if encoder init failed,+ // readAudioLoop never drains the buffer and these would leak.for (const item of this._prebufferedAudio) {try { item.close?.(); } catch {}}@@ -515,6 +571,7 @@ export class WebCodecsRecorder {this.videoFallbackStartMs = null;this.firstVideoFrame = undefined;this.selectedVideoCodec = null;+ this.actualVideoCodec = null;this._videoFrameIndex = 0;this._videoStartUs = null;this._frameDurationUs = null;@@ -536,6 +593,32 @@ export class WebCodecsRecorder {this.videoEncoder = new VideoEncoder({output: (chunk, meta) => {+ // decoderConfig.codec can overstate the level vs the SPS (Chrome+ // reports avc1.64002A when the bitstream is L4.0 / 0x28). Parse+ // from the avcC description when possible, fall back to the+ // reported codec. avcC bytes: [0] version, [1] profile,+ // [2] profile_compat, [3] level.+ if (!this.actualVideoCodec) {+ const desc = meta?.decoderConfig?.description;+ const reported = meta?.decoderConfig?.codec;+ let parsed = null;+ if (desc instanceof Uint8Array || desc instanceof ArrayBuffer) {+ const view = new Uint8Array(+ desc instanceof ArrayBuffer ? desc : desc.buffer,+ desc instanceof ArrayBuffer ? 0 : desc.byteOffset,+ desc instanceof ArrayBuffer ? desc.byteLength : desc.byteLength,+ );+ if (view[0] === 1 && view.length >= 4) {+ const hex = (n) => n.toString(16).padStart(2, "0").toUpperCase();+ parsed = `avc1.${hex(view[1])}${hex(view[2])}${hex(view[3])}`;+ }+ }+ if (parsed) {+ this.actualVideoCodec = parsed;+ } else if (typeof reported === "string" && reported.length > 0) {+ this.actualVideoCodec = reported;+ }+ }this.muxer.addVideoChunk(chunk, meta);},error: (err) => {@@ -544,7 +627,19 @@ export class WebCodecsRecorder {},});- this.videoEncoder.configure(config);+ // configure() can throw sync on invalid configs (Chrome removing a+ // codec profile, validation changes). Tag with codec context for triage.+ try {+ this.videoEncoder.configure(config);+ } catch (err) {+ const tagged = new Error(+ `VideoEncoder.configure failed for ${codecLabel}: ${err?.message || err}`,+ );+ tagged.cause = err;+ tagged.codec = codecLabel;+ tagged.code = "video-encoder-configure-failed";+ throw tagged;+ }this.log("[WCR] VideoEncoder configured");}@@ -562,7 +657,16 @@ export class WebCodecsRecorder {},});- this.audioEncoder.configure(config);+ try {+ this.audioEncoder.configure(config);+ } catch (err) {+ const tagged = new Error(+ `AudioEncoder.configure failed: ${err?.message || err}`,+ );+ tagged.cause = err;+ tagged.code = "audio-encoder-configure-failed";+ throw tagged;+ }}async prepareAudioEncoderConfig() {@@ -614,13 +718,9 @@ export class WebCodecsRecorder {for (const c of candidates) {const config = { ...base, codec: c.codec, hardwareAcceleration: c.hw };+ const test = new VideoEncoder({ output() {}, error() {} });try {- const test = new VideoEncoder({- output() {},- error() {},- });test.configure(config);- test.close();this.log("[WCR] Selected encoder:", c.codec, c.hw);try {chrome.storage.local.set({@@ -641,7 +741,10 @@ export class WebCodecsRecorder {codec: c.codec,containerCodec: c.containerCodec,};- } catch (e) {}+ } catch (e) {+ } finally {+ try { test.close(); } catch {}+ }}throw new Error("WebCodecsRecorder: No supported H.264 encoder");}@@ -688,7 +791,10 @@ export class WebCodecsRecorder {this.targetHeight);- if (!this._videoStartUs) this._videoStartUs = performance.now() * 1000;+ if (!this._videoStartUs) {+ this._videoStartUs = performance.now() * 1000;+ perfMark("WCR.firstSourceFrame", { w: frame.codedWidth, h: frame.codedHeight });+ }const nowUs = performance.now() * 1000;const elapsedUs = Math.max(@@ -698,20 +804,17 @@ export class WebCodecsRecorder {const frameDurationUs = this._frameDurationUs || Math.round(1_000_000 / 30);const targetIndex = Math.max(0, Math.floor(elapsedUs / frameDurationUs));- // If we're ahead of wall-clock, drop this frame.+ // Drop frames ahead of wall-clock.if (targetIndex < this._videoFrameIndex) {frame.close();continue;}- // If the tab was hidden or the system was heavily loaded, we can end- // up many frames behind wall-clock. Filling the entire gap in one- // iteration would create hundreds of VideoFrames synchronously and- // overflow the encoder's internal queue. Instead, skip ahead to at- // most MAX_GAP_FRAMES behind the target so the burst is bounded.- // The skipped indices advance _videoFrameIndex, preventing repeated- // catch-up attempts on the next iteration.- const MAX_GAP_FRAMES = 8; // ≈ 267 ms at 30 fps+ // Hidden tab / heavy load can leave us many frames behind wall-clock.+ // Filling the gap synchronously would overflow the encoder queue, so+ // skip ahead to at most MAX_GAP_FRAMES behind. Skipped indices+ // advance _videoFrameIndex to prevent repeated catch-up attempts.+ const MAX_GAP_FRAMES = 8;const gap = targetIndex - this._videoFrameIndex;if (gap > MAX_GAP_FRAMES) {this.warn(`[WCR] skipping ${gap - MAX_GAP_FRAMES} frames (tab gap)`);@@ -760,10 +863,9 @@ export class WebCodecsRecorder {}this.log("[WCR] video loop exit", this.frameCount, "running=", this.running);- // If the loop exits while we still think we're recording, the video source- // died unexpectedly. Stop the audio loop too so the output file's audio- // track doesn't extend past the last video frame. Don't fire onError —- // the partial recording is still valid; let the user's stop flow finalize.+ // Loop exited while still running: video source died. Stop the audio+ // loop so audio doesn't extend past last video frame. Don't fire+ // onError, partial recording is valid.if (this.running) {this.warn("[WCR] video loop exited early while running; stopping audio loop",@@ -824,10 +926,9 @@ export class WebCodecsRecorder {continue;}- // Drop audio data while the recording is paused. The sample counter- // is not advanced, so audio timestamps resume from the correct- // active-recording position when resume() is called — keeping audio- // and video aligned across any number of pause/resume cycles.+ // Drop audio while paused; sample counter doesn't advance so+ // timestamps resume from the correct position, keeping audio/video+ // aligned across pause/resume cycles.if (this.paused) {audioData.close?.();continue;diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsxindex ee863ce..f76039c 100644--- a/src/pages/Region/Recorder.jsx+++ b/src/pages/Region/Recorder.jsx@@ -1,6 +1,10 @@import React, { useEffect, useRef, useCallback } from "react";import { getUserMediaWithFallback } from "../utils/mediaDeviceFallback";-import { WebCodecsRecorder } from "../Recorder/webcodecs/WebCodecsRecorder";+import {+ WebCodecsRecorder,+ preloadWebCodecsModules,+} from "../Recorder/webcodecs/WebCodecsRecorder";+import { startPrewarm, stopPrewarm } from "../Recorder/streamWarmup";import {debugRecordingEvent,resetRecordingDebugSession,@@ -13,7 +17,12 @@ import {getFastRecorderStickyState,markFastRecorderFailure,validateFastRecorderOutputBlob,+ isTransientFastRecorderError,} from "../../media/fastRecorderGate";+import { chooseWriter } from "../Recorder/recorderStorage/chooseWriter";+import { chooseReader } from "../Recorder/recorderStorage/chooseReader";+import { lifecycle } from "../utils/lifecycleLog";+import { perfMark, perfSpan } from "../utils/perfMarks";import localforage from "localforage";@@ -23,13 +32,10 @@ localforage.config({version: 1,});-// Get chunks storeconst chunksStore = localforage.createInstance({name: "chunks",});-// Debug flag for logging-// window.SCREENITY_DEBUG_RECORDER = true;const DEBUG_RECORDER =typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;const logPrefix = "[Screenity Region Recorder]";@@ -114,16 +120,14 @@ const Recorder = () => {const recordingStartTimeRef = useRef(null);const recordingTick = useRef(null);- // Main stream (recording)const liveStream = useRef(null);+ const prewarmRef = useRef(null);- // Helper streamsconst helperVideoStream = useRef(null);const helperAudioStream = useRef(null);const startRetryTimer = useRef(null);const startRetryAttempts = useRef(0);- // Audio controls, with refs to persist across rendersconst aCtx = useRef(null);const destination = useRef(null);const audioInputSource = useRef(null);@@ -135,10 +139,8 @@ const Recorder = () => {const useWebCodecs = useRef(false);const recdbgSessionRef = useRef(null);- // Targetconst target = useRef(null);- // Recording refconst recordingRef = useRef();const regionRef = useRef();const backupRef = useRef(false);@@ -151,10 +153,12 @@ const Recorder = () => {const streamingDataHandled = useRef(false);const streamingDataRetryTimer = useRef(null);- // Retry get-streaming-data from the SW with backoff. The initial- // sendMessage can fail silently if the SW is mid-wakeup; this retry- // plus SW-side retry plus the handler's idempotency guard cover the- // handshake reliably on slow Windows cold-starts.+ const chunkWriter = useRef(null);+ const chunkBackendRef = useRef(null);++ // Retry with backoff: SW mid-wakeup can drop the initial sendMessage+ // silently. Combined with SW-side retry and handler idempotency, this+ // covers slow Windows cold-starts.const requestStreamingDataWithRetry = (attempt = 0) => {if (streamingDataHandled.current) return;const backoffMs = [0, 250, 500, 1000, 2000];@@ -300,50 +304,98 @@ const Recorder = () => {async function saveChunk(e, i) {const ts = e.timecode ?? 0;- // FLAG: disabled duplicate chunk check due to issues with some devices- // if (- // savedCount.current > 0 &&- // ts === lastTimecode.current &&- // e.data.size === lastSize.current- // ) {- // return false;- // }-if (!(await canFitChunk(e.data.size))) {- if (!lowStorageAbort.current) {- chrome.runtime.sendMessage({- type: "show-toast",- message: chrome.i18n.getMessage("toastStorageCritical"),- timeout: 8000,+ // Post-stop, navigator.storage.estimate() can read false-low.+ // Don't surface "Memory limit reached"; save the tail chunk.+ if (isFinishing.current || !recordingRef.current) {+ lifecycle("Region.Recorder", "saveChunk-canFitChunk-suppressed", {+ isFinishing: Boolean(isFinishing.current),+ recordingRef: Boolean(recordingRef.current),+ savedCount: savedCount.current,+ size: e?.data?.size ?? null,+ });+ } else {+ if (!lowStorageAbort.current) {+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("toastStorageCritical"),+ timeout: 8000,+ });+ }+ lifecycle("Region.Recorder", "memory-error-flag-set", {+ reason: "saveChunk-canFitChunk",+ size: e?.data?.size ?? null,+ savedCount: savedCount.current,});+ lowStorageAbort.current = true;+ chrome.storage.local.set({+ recording: false,+ restarting: false,+ tabRecordedID: null,+ memoryError: true,+ });+ sendStopWithReason("region-low-storage-headroom");+ window.location.reload();+ return false;}- lowStorageAbort.current = true;- chrome.storage.local.set({- recording: false,- restarting: false,- tabRecordedID: null,- memoryError: true,- });- sendStopWithReason("region-low-storage-headroom");- // Reload this iframe- window.location.reload();- return false;}+ lifecycle("Region.Recorder", "saveChunk-enter", {+ i,+ size: e?.data?.size ?? null,+ timecode: ts,+ hasWriter: Boolean(chunkWriter.current),+ lowStorageAbort: lowStorageAbort.current,+ });try {- await chunksStore.setItem(`chunk_${i}`, {- index: i,- chunk: e.data,- timestamp: ts,- });+ if (chunkWriter.current) {+ await chunkWriter.current.write({+ chunk: e.data,+ index: i,+ timestamp: ts,+ });+ } else {+ await chunksStore.setItem(`chunk_${i}`, {+ index: i,+ chunk: e.data,+ timestamp: ts,+ });+ }} catch (err) {+ lifecycle("Region.Recorder", "saveChunk-write-failed", {+ i,+ err: String(err?.message || err).slice(0, 120),+ code: err?.code || null,+ });+ // OPFS writer death preserves the partial file; quota fail uses a generic toast.+ const isOpfsWriterDead = err?.code === "opfs-writer-failed";+ if (isOpfsWriterDead && err?.fileName) {+ chunkBackendRef.current = {+ backend: "opfs",+ fileName: err.fileName,+ };+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: chunkBackendRef.current,+ });+ } catch {}+ }if (!lowStorageAbort.current) {+ const toastMessage = isOpfsWriterDead+ ? chrome.i18n.getMessage("recordingWriterFailedToast")+ : chrome.i18n.getMessage("toastStorageCritical");chrome.runtime.sendMessage({type: "show-toast",- message: chrome.i18n.getMessage("toastStorageCritical"),+ message: toastMessage,timeout: 8000,});}+ lifecycle("Region.Recorder", "memory-error-flag-set", {+ reason: "saveChunk-write-failed",+ isOpfsWriterDead,+ err: String(err?.message || err).slice(0, 120),+ savedCount: savedCount.current,+ });lowStorageAbort.current = true;chrome.storage.local.set({recording: false,@@ -351,8 +403,9 @@ const Recorder = () => {tabRecordedID: null,memoryError: true,});- sendStopWithReason("region-save-chunk-failed");- // Reload this iframe+ sendStopWithReason(+ isOpfsWriterDead ? "opfs-writer-failed" : "region-save-chunk-failed",+ );window.location.reload();return false;}@@ -360,6 +413,10 @@ const Recorder = () => {lastTimecode.current = ts;lastSize.current = e.data.size;savedCount.current += 1;+ lifecycle("Region.Recorder", "saveChunk-ok", {+ i,+ savedCount: savedCount.current,+ });if (backupRef.current) {chrome.runtime.sendMessage({ type: "write-file", index: i });@@ -368,17 +425,18 @@ const Recorder = () => {}const rebuildBlobFromChunks = async () => {- const items = [];- await chunksStore.ready();- await chunksStore.iterate((value) => (items.push(value), undefined));- items.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));- const parts = items.map((c) =>- c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),- );- if (!parts.length) return null;- const first = parts[0];- const inferredType = first?.type || "video/mp4";- return new Blob(parts, { type: inferredType });+ const backendRef = chunkBackendRef.current || { backend: "idb" };+ const reader = chooseReader(backendRef);+ try {+ await reader.open(backendRef);+ const { blob, chunkCount } = await reader.readBlob();+ if (!blob || chunkCount === 0) return null;+ return blob;+ } finally {+ try {+ await reader.close();+ } catch {}+ }};const updateFreeFinalizeStatus = async (stage, percent = 0, error = null) => {@@ -411,8 +469,15 @@ const Recorder = () => {};async function drainQueue() {- if (draining.current) return;+ if (draining.current) {+ lifecycle("Region.Recorder", "drainQueue-skip-busy", {+ pendingLen: pending.current.length,+ });+ return;+ }draining.current = true;+ const drainStartedAt = Date.now();+ const initialPending = pending.current.length;try {while (pending.current.length) {@@ -426,6 +491,15 @@ const Recorder = () => {pendingBytes.current -= e.data.size;if (!(await canFitChunk(e.data.size))) {+ if (isFinishing.current || !recordingRef.current) {+ lifecycle("Region.Recorder", "drainQueue-canFitChunk-suppressed", {+ isFinishing: Boolean(isFinishing.current),+ recordingRef: Boolean(recordingRef.current),+ savedCount: savedCount.current,+ size: e?.data?.size ?? null,+ });+ // Keep the chunk to avoid losing the tail; skip memoryError abort.+ } else {if (!lowStorageAbort.current) {chrome.runtime.sendMessage({type: "show-toast",@@ -433,6 +507,12 @@ const Recorder = () => {timeout: 8000,});}+ lifecycle("Region.Recorder", "memory-error-flag-set", {+ reason: "drainQueue-canFitChunk",+ size: e?.data?.size ?? null,+ savedCount: savedCount.current,+ recorderState: recorder.current?.state || null,+ });lowStorageAbort.current = true;chrome.storage.local.set({recording: false,@@ -443,9 +523,9 @@ const Recorder = () => {sendStopWithReason("region-drainqueue-low-storage");pending.current.length = 0;pendingBytes.current = 0;- // Reload this iframewindow.location.reload();break;+ }}const i = index.current;@@ -454,11 +534,26 @@ const Recorder = () => {}} finally {draining.current = false;+ lifecycle("Region.Recorder", "drainQueue-done", {+ elapsedMs: Date.now() - drainStartedAt,+ initialPending,+ savedCount: savedCount.current,+ finalPending: pending.current.length,+ });}}async function waitForDrain() {+ // Cap so a wedged drain doesn't block stop forever.+ const deadline = Date.now() + 30000;while (draining.current || pending.current.length) {+ if (Date.now() > deadline) {+ console.warn("[Region] waitForDrain timed out", {+ pending: pending.current.length,+ draining: draining.current,+ });+ break;+ }await new Promise((r) => setTimeout(r, 10));}}@@ -472,7 +567,6 @@ const Recorder = () => {);}, []);- // Receive post message from parent (this is an iframe)useEffect(() => {const onMessage = (event) => {if (event.data.type === "crop-target") {@@ -490,10 +584,24 @@ const Recorder = () => {}, []);async function startRecording() {- // Check that a recording is not already in progressif (recorder.current !== null) return;+ // Bail out if this iframe isn't actually the recording target. Without+ // this guard, a stale state (e.g. start-recording-tab arriving by some+ // unexpected path) makes the iframe spin its 5s preflight retry loop,+ // then fire "Capture stream is not ready yet" - which tears down a+ // legitimate recording happening in a different tab.+ if (!regionRef.current && !target.current) {+ persistRegionStartDebug({+ stage: "start-recording-bailout",+ reason: "not-region-target-for-this-iframe",+ });+ return;+ }persistRegionStartDebug({ stage: "start-recording-enter" });+ await stopPrewarm(prewarmRef.current);+ prewarmRef.current = null;+const hasHelperVideoTrack =!!helperVideoStream.current &&typeof helperVideoStream.current.getVideoTracks === "function" &&@@ -528,7 +636,8 @@ const Recorder = () => {error: "stream-error",why: "Capture stream is not ready yet",});- window.location.reload();+ // Don't location.reload(): active getDisplayMedia triggers a+ // beforeunload prompt. BG teardown handles cleanup.return;}@@ -545,7 +654,6 @@ const Recorder = () => {draining.current = false;lowStorageAbort.current = false;pendingBytes.current = 0;- // Check if the stream actually has data in ittry {if (helperVideoStream.current.getVideoTracks().length === 0) {persistRegionStartDebug({@@ -564,7 +672,6 @@ const Recorder = () => {why: "No video tracks available",});- // Reload this iframewindow.location.reload();return;}@@ -596,7 +703,6 @@ const Recorder = () => {why: String(err),});- // Reload this iframewindow.location.reload();return;}@@ -653,7 +759,6 @@ const Recorder = () => {videoBitsPerSecond = 500000;}- // List all mimeTypesconst mimeTypes = ["video/webm;codecs=avc1","video/webm;codecs=vp8,opus",@@ -664,7 +769,6 @@ const Recorder = () => {"video/webm",];- // Check if the browser supports any of the mimeTypes, make sure to select the first one that is supported from the listlet mimeType = mimeTypes.find((mimeType) =>MediaRecorder.isTypeSupported(mimeType),);@@ -684,7 +788,7 @@ const Recorder = () => {const { useWebCodecsRecorder } = await chrome.storage.local.get(["useWebCodecsRecorder",]);- // Default-on: treat undefined as enabled; only explicit `false` opts out.+ // undefined defaults to enabled; only explicit `false` opts out.const userSetting = useWebCodecsRecorder === false ? false : true;const stickyState = await getFastRecorderStickyState();const probeResult = await probeFastRecorderSupport();@@ -814,6 +918,57 @@ const Recorder = () => {useWebCodecs.current = true;await chrome.storage.local.set({ fastRecorderInUse: true });+ // Fall back to IDB if OPFS open() fails.+ chunkWriter.current = null;+ const writerRecordingId = `region-${Date.now()}-${Math.random()+ .toString(36)+ .slice(2, 8)}`;+ try {+ let selection = await chooseWriter({ preferOpfs: true });+ let openResult = null;+ try {+ openResult = await selection.writer.open(writerRecordingId);+ } catch (openErr) {+ if (selection.backend === "opfs") {+ try {+ await selection.writer.abort();+ } catch {}+ selection = await chooseWriter({ preferOpfs: false });+ openResult = await selection.writer.open(writerRecordingId);+ } else {+ throw openErr;+ }+ }+ chunkWriter.current = selection.writer;+ const backendRefAtOpen = openResult?.backendRef || {+ backend: selection.backend,+ };+ chunkBackendRef.current = backendRefAtOpen;+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: backendRefAtOpen,+ });+ } catch {}+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][region] writer-open", {+ backend: selection.backend,+ path: "webcodecs",+ backendRef: backendRefAtOpen,+ });+ }+ } catch (err) {+ persistRegionStartDebug({+ stage: "chunk-writer-init-failed",+ err: String(err?.message || err).slice(0, 120),+ });+ chunkBackendRef.current = { backend: "idb" };+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: { backend: "idb" },+ });+ } catch {}+ }+recorder.current = new WebCodecsRecorder(liveStream.current, {width,height,@@ -840,13 +995,33 @@ const Recorder = () => {});return;}+ // OPFS holds an exclusive handle; close before reading.+ if (chunkWriter.current) {+ try {+ const closeResult = await chunkWriter.current.close();+ chunkBackendRef.current =+ closeResult?.backendRef || { backend: "idb" };+ } catch (err) {+ if (err?.code === "opfs-writer-failed" && err?.fileName) {+ // Close failed; partial file is still on disk.+ chunkBackendRef.current = {+ backend: "opfs",+ fileName: err.fileName,+ };+ } else {+ chunkBackendRef.current = { backend: "idb" };+ }+ }+ chunkWriter.current = null;+ }await updateFreeFinalizeStatus("chunks_ready", 95);let validation = null;try {const blob = await rebuildBlobFromChunks();validation = await validateFastRecorderOutputBlob(blob, {minBytes: 64 * 1024,- timeoutMs: 4000,+ // 15s for multi-GB demuxer scans on slow disks.+ timeoutMs: 15000,videoCodec: recorder.current?.selectedVideoCodec || undefined,audioCodec: hasAudioTrack ? "mp4a.40.2" : null,recordingId,@@ -906,13 +1081,29 @@ const Recorder = () => {});}+ await chrome.storage.local.set({+ lastRecordingBackendRef: chunkBackendRef.current || {+ backend: "idb",+ },+ });await updateFreeFinalizeStatus("ready", 100);if (!sentLast.current) {sentLast.current = true;isFinished.current = true;isFinishing.current = false;if (!isRestarting.current) {- chrome.runtime.sendMessage({ type: "video-ready" });+ // Verify ≥1 chunk persisted before claiming ready;+ // zero-output encoder (config mismatch, immediate close)+ // would otherwise produce 0-byte video.+ if (savedCount.current === 0 && !hasChunks.current) {+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "stream-error",+ why: "No recording data was generated",+ });+ } else {+ chrome.runtime.sendMessage({ type: "video-ready" });+ }}}},@@ -921,23 +1112,31 @@ const Recorder = () => {handleWebCodecsChunk(blob, timestampUs);},onError: (err) => {- markFastRecorderFailure("webcodecs-error", {- error: String(err),- });- chrome.storage.local.set({- useWebCodecsRecorder: false,+ const errStr = String(err);+ const transient = isTransientFastRecorderError(errStr);+ markFastRecorderFailure("webcodecs-error", { error: errStr });+ // Keep useWebCodecsRecorder on for transient stream errors.+ const persisted = {lastWebCodecsFailureAt: Date.now(),- lastWebCodecsFailureCode: "webcodecs-error",- });- updateFreeFinalizeStatus("failed", 100, String(err));- chrome.runtime.sendMessage({- type: "show-toast",- message: chrome.i18n.getMessage("webcodecsFailedOffToast"),- });+ lastWebCodecsFailureCode: transient+ ? "webcodecs-transient"+ : "webcodecs-error",+ };+ if (!transient) persisted.useWebCodecsRecorder = false;+ chrome.storage.local.set(persisted);+ updateFreeFinalizeStatus("failed", 100, errStr);+ if (!transient) {+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("webcodecsFailedOffToast"),+ });+ }chrome.runtime.sendMessage({type: "recording-error",error: "stream-error",- why: "Fast recorder failed. Please try compatibility mode.",+ why: transient+ ? errStr+ : "Fast recorder failed. Please try compatibility mode.",});},onStop: async () => {@@ -979,6 +1178,12 @@ const Recorder = () => {const startMediaRecorderWithCodec = async (codec) => {const mimeType = selectMimeType(codec);+ lifecycle("Region.Recorder", "startMediaRecorderWithCodec", {+ codec,+ mimeType,+ hasExistingRecorder: Boolean(recorder.current),+ hasChunkWriter: Boolean(chunkWriter.current),+ });if (!mimeType) {chrome.runtime.sendMessage({type: "recording-error",@@ -986,7 +1191,6 @@ const Recorder = () => {why: `No supported mimeTypes available for ${codec}`,});- // Reload this iframewindow.location.reload();return false;}@@ -1002,6 +1206,30 @@ const Recorder = () => {audioBitsPerSecond: audioBitsPerSecond,videoBitsPerSecond: videoBitsPerSecond,});++ // Force IDB: MediaRecorder chunks must relay to null-origin sandbox.+ if (!chunkWriter.current) {+ try {+ const selection = await chooseWriter({ preferOpfs: false });+ chunkWriter.current = selection.writer;+ const openResult = await chunkWriter.current.open(+ `region-mr-${Date.now()}-${Math.random()+ .toString(36)+ .slice(2, 8)}`,+ );+ const backendRefAtOpen = openResult?.backendRef || {+ backend: "idb",+ };+ chunkBackendRef.current = backendRefAtOpen;+ try {+ await chrome.storage.local.set({+ lastRecordingBackendRef: backendRefAtOpen,+ });+ } catch {}+ } catch (err) {+ chunkWriter.current = null;+ }+ }debug("MediaRecorder config", {mimeType: recorder.current?.mimeType,audioBitsPerSecond,@@ -1040,11 +1268,21 @@ const Recorder = () => {recorder.current.onerror = (ev) => {if (token !== recorderToken) return;- chrome.runtime.sendMessage({- type: "recording-error",- error: "mediarecorder",- why: String(ev?.error || "unknown"),- });+ const errStr = String(ev?.error || ev?.error?.name || "unknown");+ const isTransient =+ /invalidstateerror/i.test(errStr) ||+ /not in recording state/i.test(errStr) ||+ /already (stopped|inactive)/i.test(errStr);+ if (!isTransient) {+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "mediarecorder",+ why: errStr,+ });+ }+ if (!isFinishing.current) {+ stopRecording().catch(() => {});+ }};recorder.current.onstop = async () => {@@ -1078,6 +1316,10 @@ const Recorder = () => {savedCount: savedCount.current,pending: pending.current.length,});+ // Mark terminal so 15s watchdog can't re-fire recording-error.+ sentLast.current = true;+ isFinished.current = true;+ isFinishing.current = false;chrome.runtime.sendMessage({type: "recording-error",error: "stream-error",@@ -1097,6 +1339,12 @@ const Recorder = () => {recorder.current.ondataavailable = async (e) => {if (token !== recorderToken) return;if (!e || !e.data || !e.data.size) {+ lifecycle("Region.Recorder", "ondataavailable-empty", {+ hasEvent: Boolean(e),+ hasData: Boolean(e?.data),+ size: e?.data?.size ?? null,+ recorderState: recorder.current?.state || null,+ });if (recorder.current && recorder.current.state === "inactive") {chrome.storage.local.set({recording: false,@@ -1107,6 +1355,14 @@ const Recorder = () => {}return;}+ // Avoid spamming logs on long recordings.+ if (recdbgChunkCount < 3) {+ lifecycle("Region.Recorder", "ondataavailable", {+ index: recdbgChunkCount,+ size: e.data.size,+ timecode: e.timecode ?? 0,+ });+ }if (lowStorageAbort.current) {return;@@ -1140,10 +1396,22 @@ const Recorder = () => {if (!codecFallbackTriggered &&- (recdbgChunkCount >= 3 || elapsedSec >= 3)+ recdbgChunkCount >= 3 &&+ elapsedSec >= 3 &&+ recordingRef.current &&+ !isFinishing.current &&+ !isRestarting.current) {if (derivedMbps < 5 && getCodecLabel(mimeType) !== "vp8") {codecFallbackTriggered = true;+ lifecycle("Region.Recorder", "codec-fallback", {+ from: getCodecLabel(mimeType),+ to: "vp8",+ derivedMbps,+ recdbgChunkCount,+ elapsedSec,+ savedCount: savedCount.current,+ });debugRecordingEvent(recdbgSessionRef, "codec-fallback", {from: getCodecLabel(mimeType),to: "vp8",@@ -1238,7 +1506,6 @@ const Recorder = () => {why: String(err),});- // Reload this iframewindow.location.reload();return;}@@ -1251,9 +1518,25 @@ const Recorder = () => {const isMediaRecorder = recorder.current instanceof MediaRecorder;if (isMediaRecorder) {try {+ // Snapshot stream/track health pre-start to attribute zero-chunk+ // recordings to a dead-at-start stream.+ const vTracks = liveStream.current?.getVideoTracks?.() || [];+ const aTracks = liveStream.current?.getAudioTracks?.() || [];+ lifecycle("Region.Recorder", "mediarecorder-start", {+ videoTracks: vTracks.length,+ audioTracks: aTracks.length,+ videoState: vTracks[0]+ ? {+ readyState: vTracks[0].readyState,+ muted: vTracks[0].muted,+ enabled: vTracks[0].enabled,+ }+ : null,+ mimeType: recorder.current?.mimeType || null,+ recorderState: recorder.current?.state || null,+ });recorder.current.start(5000);- // Force an early first chunk so even very short recordings have- // data in IndexedDB before the user can navigate away.+ // Force early first chunk so short recordings persist before nav.setTimeout(() => {try { recorder.current?.requestData?.(); } catch (_) {}}, 250);@@ -1269,6 +1552,10 @@ const Recorder = () => {liveStream.current?.getVideoTracks?.()[0] || null,),});+ lifecycle("Region.Recorder", "memory-error-flag-set", {+ reason: "mediarecorder-start-throw",+ err: String(err).slice(0, 120),+ });chrome.storage.local.set({recording: false,restarting: false,@@ -1277,7 +1564,6 @@ const Recorder = () => {});sendStopWithReason("region-mediarecorder-start-throw");- // Reload this iframewindow.location.reload();return;}@@ -1346,6 +1632,33 @@ const Recorder = () => {why: "Audio track became inactive",});};+ // Mirrors Recorder.jsx sysTrack.onended; surfaces mid-recording+ // mic disconnects.+ aTrack.onended = () => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-region-audio-track-ended",+ data: {+ trackLabel: String(aTrack.label || "").slice(0, 80),+ },+ });+ } catch {}+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("audioTrackEndedToast"),+ timeout: 8000,+ }).catch(() => {});+ };+ aTrack.onmute = () => {+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "recorder-region-audio-track-muted",+ data: { trackLabel: String(aTrack.label || "").slice(0, 80) },+ });+ } catch {}+ };}const helperVideoTrack =@@ -1369,6 +1682,11 @@ const Recorder = () => {recordingStartTimeRef.current = null;isFinishing.current = true;regionRef.current = false;+ // Reset customRegion crop target: otherwise it sticks for the iframe's+ // life and a later regular screen recording (stream in a separate+ // recorder tab) hits "Capture stream is not ready yet" at 5s.+ target.current = null;+ streamingDataHandled.current = false;await updateFreeFinalizeStatus("stopping", 0);await setRecordingTimingState({recording: false,@@ -1401,8 +1719,45 @@ const Recorder = () => {}} catch {}+ // Watchdog: if onstop never fires, force finalize so the editor+ // isn't stuck waiting for video-ready.+ setTimeout(() => {+ if (sentLast.current || isFinished.current) return;+ // Mark terminal in both branches so a late onstop can't double-+ // fire recording-error / video-ready.+ sentLast.current = true;+ isFinished.current = true;+ isFinishing.current = false;+ if (!hasChunks.current || savedCount.current === 0) {+ chrome.runtime.sendMessage({+ type: "recording-error",+ error: "stream-error",+ why: "Recorder stop timed out with no data",+ });+ return;+ }+ chrome.runtime.sendMessage({ type: "video-ready" });+ }, 15000);+await waitForDrain();recorder.current = null;+ // Capture backendRef for the sandbox.+ if (chunkWriter.current) {+ try {+ const closeResult = await chunkWriter.current.close();+ // Prefer close-result backendRef; never hardcode "idb",+ // would misroute editor reads when chunks are in OPFS.+ if (closeResult?.backendRef) {+ chunkBackendRef.current = closeResult.backendRef;+ }+ if (chunkBackendRef.current) {+ await chrome.storage.local.set({+ lastRecordingBackendRef: chunkBackendRef.current,+ });+ }+ } catch {}+ chunkWriter.current = null;+ }await updateFreeFinalizeStatus("chunks_ready", 100);}}@@ -1436,6 +1791,8 @@ const Recorder = () => {stopRecordingTick();recordingStartTimeRef.current = null;regionRef.current = false;+ target.current = null;+ streamingDataHandled.current = false;useWebCodecs.current = false;await setRecordingTimingState({recording: false,@@ -1449,7 +1806,12 @@ const Recorder = () => {isRestarting.current = true;isDismissing.current = true;if (recorder.current !== null) {- recorder.current.stop();+ // Detach handlers before stop(); queued onstop microtask would+ // otherwise fire post-dismiss and open the editor on a discarded recording.+ try { recorder.current.onstop = null; } catch {}+ try { recorder.current.ondataavailable = null; } catch {}+ try { recorder.current.onerror = null; } catch {}+ try { recorder.current.stop(); } catch {}recorder.current = null;}if (liveStream.current !== null) {@@ -1472,6 +1834,11 @@ const Recorder = () => {});helperAudioStream.current = null;}+ // dismissRecording reuses isRestarting as an "incoming-chunks shield"+ // during teardown; release here or a later restartRecording sees a+ // stuck-true flag and early-returns false.+ isRestarting.current = false;+ isDismissing.current = false;};const restartRecording = async () => {@@ -1592,7 +1959,7 @@ const Recorder = () => {return stream;}).catch((err) => {- // Try again without the device ID+ // Retry without device ID.const audioStreamOptions = {mimeType: "video/webm;codecs=vp8,opus",audio: true,@@ -1610,21 +1977,24 @@ const Recorder = () => {return result;}- // Set audio input volumefunction setAudioInputVolume(volume) {if (!audioInputGain.current) return;audioInputGain.current.gain.value = volume;}- // Set audio output volumefunction setAudioOutputVolume(volume) {if (!audioOutputGain.current) return;audioOutputGain.current.gain.value = volume;}async function startStreaming(data) {+ perfMark("Region.Recorder startStreaming.enter", {+ hasTarget: Boolean(target.current),+ systemAudio: Boolean(data?.systemAudio),+ hasMic: Boolean(data?.defaultAudioInput && data.defaultAudioInput !== "none"),+ });try {- // Get quality value+ const endStorageReads = perfSpan("Region.Recorder storage.reads");const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);let width = 1920;@@ -1653,15 +2023,19 @@ const Recorder = () => {const { fpsValue } = await chrome.storage.local.get(["fpsValue"]);let fps = parseInt(fpsValue);- // Check if fps is a numberif (isNaN(fps)) {fps = 30;}+ endStorageReads();let stream;const constraints = {preferCurrentTab: true,+ // Suppress Chrome's "Share this tab instead" banner: the crop target+ // is a RestrictionTarget tied to this tab's DOM; switching surfaces+ // mid-session breaks the crop.+ surfaceSwitching: "exclude",audio: data.systemAudio,video: {frameRate: fps,@@ -1673,7 +2047,12 @@ const Recorder = () => {},},};+ const endGetDisplayMedia = perfSpan("Region.Recorder getDisplayMedia");stream = await navigator.mediaDevices.getDisplayMedia(constraints);+ endGetDisplayMedia({+ videoTracks: stream?.getVideoTracks?.()?.length ?? 0,+ audioTracks: stream?.getAudioTracks?.()?.length ?? 0,+ });if (!stream || typeof stream.getVideoTracks !== "function") {chrome.runtime.sendMessage({type: "recording-error",@@ -1695,16 +2074,19 @@ const Recorder = () => {helperVideoStream.current = stream;- // Create an audio context, destination, and stream+ stopPrewarm(prewarmRef.current);+ prewarmRef.current = startPrewarm(helperVideoStream.current);+ preloadWebCodecsModules();+aCtx.current = new AudioContext();destination.current = aCtx.current.createMediaStreamDestination();liveStream.current = new MediaStream();+ const endMic = perfSpan("Region.Recorder startAudioStream(mic)");const micstream = await startAudioStream(data.defaultAudioInput);+ endMic({ hasMic: Boolean(micstream) });- // Save the helper streamshelperAudioStream.current = micstream;- // Check if micstream has an audio trackif (helperAudioStream.current != null &&helperAudioStream.current.getAudioTracks().length > 0@@ -1716,15 +2098,12 @@ const Recorder = () => {audioInputSource.current.connect(audioInputGain.current).connect(destination.current);- } else {- // No microphone available}if (helperAudioStream.current != null && !data.micActive) {setAudioInputVolume(0);}- // Check if stream has an audio trackif (helperVideoStream.current.getAudioTracks().length > 0) {audioOutputGain.current = aCtx.current.createGain();audioOutputSource.current = aCtx.current.createMediaStreamSource(@@ -1733,11 +2112,8 @@ const Recorder = () => {audioOutputSource.current.connect(audioOutputGain.current).connect(destination.current);- } else {- // No system audio available}- // Add the tracks to the streamconst helperVideoTrack = helperVideoStream.current.getVideoTracks()[0];if (!helperVideoTrack) {chrome.runtime.sendMessage({@@ -1773,16 +2149,16 @@ const Recorder = () => {window.location.reload();return;}+ const endCropTo = perfSpan("Region.Recorder cropTo");await track.cropTo(target.current);+ endCropTo();} else {- // No targetchrome.runtime.sendMessage({type: "recording-error",error: "cancel-modal",why: "No target",});- // Reload this iframewindow.location.reload();}} catch (err) {@@ -1792,11 +2168,10 @@ const Recorder = () => {why: String(err),});- // Reload this iframewindow.location.reload();}- // Send message to go back to the previously active tab+ perfMark("Region.Recorder reset-active-tab.sent");chrome.runtime.sendMessage({ type: "reset-active-tab" });} catch (err) {chrome.runtime.sendMessage({@@ -1805,7 +2180,6 @@ const Recorder = () => {why: String(err),});- // Reload this iframewindow.location.reload();}}@@ -1823,9 +2197,8 @@ const Recorder = () => {useEffect(() => {const handleBeforeUnload = (e) => {if (recordingRef.current && regionRef.current) {- // Flush any buffered data from the MediaRecorder into IndexedDB.- // The "Leave page?" dialog gives the ondataavailable handler enough- // time to persist the chunk before the frame is torn down.+ // The "Leave page?" dialog gives ondataavailable enough time to+ // persist the chunk before the frame is torn down.try {recorder.current?.requestData?.();} catch (_) {}@@ -1835,20 +2208,15 @@ const Recorder = () => {};window.addEventListener("beforeunload", handleBeforeUnload);- // When the iframe is actually being destroyed (user clicked "Leave" or- // the parent page navigated), fire a message to the background to force- // stop the recording. pagehide fires synchronously during teardown and- // chrome.runtime.sendMessage from an extension page is delivered via IPC- // before the frame is gone — no async race.+ // pagehide fires synchronously during iframe teardown; the IPC+ // sendMessage is delivered before the frame is gone (no async race).const handlePageHide = () => {if (recordingRef.current && regionRef.current) {try {chrome.runtime.sendMessage({type: "region-iframe-destroyed",});- } catch (_) {- // Extension context may already be invalidated- }+ } catch (_) {}}};window.addEventListener("pagehide", handlePageHide);@@ -1866,25 +2234,37 @@ const Recorder = () => {} else {setAudioInputVolume(0);}- } else {- // No microphone available}};const onMessage = useCallback((request, sender, sendResponse) => {if (request.type === "loaded") {+ perfMark("Region.Recorder loaded.received", {+ isRegion: Boolean(request.region),+ });backupRef.current = request.backup;if (request.region) {requestStreamingDataWithRetry();}+ // Ack so BG's sendMessageRecord doesn't reject + trigger retries.+ try { sendResponse?.({ ok: true }); } catch {}+ return true;}if (request.type === "streaming-data") {- if (streamingDataHandled.current) return;- streamingDataHandled.current = true;- if (regionRef.current) {- startStreaming(JSON.parse(request.data));+ perfMark("Region.Recorder streaming-data.received", {+ duplicate: streamingDataHandled.current,+ regionMode: Boolean(regionRef.current),+ });+ const wasDuplicate = streamingDataHandled.current;+ if (!wasDuplicate) {+ streamingDataHandled.current = true;+ if (regionRef.current) {+ startStreaming(JSON.parse(request.data));+ }}+ try { sendResponse?.({ ok: true, duplicate: wasDuplicate }); } catch {}+ return true;} else if (request.type === "start-recording-tab") {setRegionRestartPhase("restart-start-message-received", {regionMode: Boolean(regionRef.current),@@ -1896,24 +2276,88 @@ const Recorder = () => {startRecording();}} else if (request.type === "restart-recording-tab") {+ const recState = () => {+ const r = recorder.current;+ let recorderType = "none";+ if (r) {+ if (r instanceof MediaRecorder) recorderType = "MediaRecorder";+ else if (useWebCodecs.current) recorderType = "WebCodecs";+ else recorderType = "other";+ }+ return {+ attemptId: request.attemptId || null,+ hasRecorder: Boolean(r),+ recorderType,+ mediaRecorderState:+ r instanceof MediaRecorder ? r.state : null,+ recordingRef: Boolean(recordingRef.current),+ isRestarting: Boolean(isRestarting.current),+ isFinishing: Boolean(isFinishing.current),+ hasLiveStream: Boolean(liveStream.current),+ regionMode: Boolean(regionRef.current),+ hasTarget: Boolean(target.current),+ docHidden: document.hidden,+ };+ };+ const stateAtEntry = recState();+ lifecycle("Region.Recorder", "restart-tab-received", stateAtEntry);+Promise.resolve(restartRecording()).then((restarted) => {+ const after = recState();if (!restarted) {- sendResponse?.({ ok: false, error: "restart-teardown-failed" });+ lifecycle("Region.Recorder", "restart-tab-result", {+ ...after,+ ok: false,+ error: "restart-teardown-failed",+ });+ sendResponse?.({+ ok: false,+ error: "restart-teardown-failed",+ recorderState: after,+ });return;}- sendResponse?.({ ok: true, restarted: true });+ lifecycle("Region.Recorder", "restart-tab-result", {+ ...after,+ ok: true,+ });+ sendResponse?.({+ ok: true,+ restarted: true,+ recorderState: after,+ });}).catch((error) => {+ const reason = error?.message || String(error);+ lifecycle("Region.Recorder", "restart-tab-result", {+ ...recState(),+ ok: false,+ error: reason,+ threw: true,+ });sendResponse?.({ok: false,- error: error?.message || String(error),+ error: reason,+ recorderState: recState(),});});return true;} else if (request.type === "stop-recording-tab") {+ // Ack BG so it doesn't surface stopAckTimeoutToast; ack is just "received".+ try { sendResponse?.({ ok: true, received: true }); } catch {}if (isFinishing.current) return;stopRecording();+ } else if (request.type === "recorder-keepalive-ping") {+ try { sendResponse?.({ ok: true, alive: true, ts: Date.now() }); } catch {}+ return true;+ } else if (request.type === "recorder-wake-aggressive") {+ // Bumping lastChunkAt proves the main thread is responsive.+ try {+ chrome.storage.local.set({ lastChunkAt: Date.now() });+ } catch {}+ try { sendResponse?.({ ok: true, woke: true }); } catch {}+ return true;} else if (request.type === "set-mic-active-tab") {setMic(request);} else if (request.type === "set-audio-output-volume") {@@ -1961,12 +2405,20 @@ const Recorder = () => {);useEffect(() => {- // Event listener (extension messaging)chrome.runtime.onMessage.addListener(onMessage);+ perfMark("Region.Recorder mount.useEffect");+ lifecycle("Region.Recorder", "iframe-mount", {+ href: typeof window !== "undefined" ? window.location?.href?.slice(0, 200) : null,+ });return () => {clearStartRetry();chrome.runtime.onMessage.removeListener(onMessage);+ lifecycle("Region.Recorder", "iframe-unmount", {+ regionRef: regionRef.current,+ hasTarget: Boolean(target.current),+ hasRecorder: Boolean(recorder.current),+ });};}, []);diff --git a/src/pages/Region/index.jsx b/src/pages/Region/index.jsxindex 69ea2d7..f33e4eb 100644--- a/src/pages/Region/index.jsx+++ b/src/pages/Region/index.jsx@@ -1,16 +1,21 @@+import { perfMark } from "../utils/perfMarks";++// Distinguishes iframe-mount from message latency.+perfMark("Region.Recorder bundle.start");+import React from "react";import { createRoot } from "react-dom/client";import Recorder from "./Recorder";-// Find the container to render intoconst container = window.document.querySelector("#app-container");if (container) {+ perfMark("Region.Recorder render.start");const root = createRoot(container);root.render(<Recorder />);+ perfMark("Region.Recorder render.dispatched");}-// Hot Module Replacementif (module.hot) {module.hot.accept();}diff --git a/src/pages/RemuxOffscreen/opfsTarget.js b/src/pages/RemuxOffscreen/opfsTarget.jsindex 077b3e5..5c80ffe 100644--- a/src/pages/RemuxOffscreen/opfsTarget.js+++ b/src/pages/RemuxOffscreen/opfsTarget.js@@ -1,20 +1,13 @@-/*- * Wraps a FileSystemSyncAccessHandle as a WritableStream, so mediabunny's- * StreamTarget can write to OPFS directly. Keeps zero bytes in memory past- * the last write. Supports positioned writes (required for fastStart: false- * MP4, which patches the mdat size header after samples are written).- *- * Must run inside a Dedicated Worker: createSyncAccessHandle() is not- * available on the main thread.- */+// wraps a FileSystemSyncAccessHandle as a WritableStream so mediabunny's+// StreamTarget writes to OPFS directly with zero buffered bytes. supports+// positioned writes (fastStart:false patches the mdat size header after+// samples). worker-only since createSyncAccessHandle isn't on the main thread.export function createOpfsWritable(syncHandle) {let writtenBytes = 0;return new WritableStream({write(chunk) {- // Mediabunny's StreamTarget emits chunks shaped as- // { data: Uint8Array | ArrayBuffer, position: number, type: string }.- // Fall back to append-mode for plain bytes so the writable is also- // usable outside StreamTarget.+ // Mediabunny StreamTarget emits { data, position, type }; fall back+ // to append-mode for plain bytes so the writable works elsewhere.const data = chunk?.data ?? chunk;const position = chunk?.position ?? writtenBytes;const buf =@@ -22,6 +15,16 @@ export function createOpfsWritable(syncHandle) {? data: new Uint8Array(data);const bytesWritten = syncHandle.write(buf, { at: position });+ // Short write = OPFS quota hit mid-buffer. Hard error so the caller+ // falls back to the in-sandbox tier instead of silently truncating.+ if (+ typeof bytesWritten === "number" &&+ bytesWritten < buf.byteLength+ ) {+ throw new Error(+ `opfs-write-short:${bytesWritten}/${buf.byteLength}`,+ );+ }const end = position + (bytesWritten ?? buf.byteLength);if (end > writtenBytes) writtenBytes = end;},diff --git a/src/pages/RemuxOffscreen/worker.js b/src/pages/RemuxOffscreen/worker.jsindex 30bac45..aa93b31 100644--- a/src/pages/RemuxOffscreen/worker.js+++ b/src/pages/RemuxOffscreen/worker.js@@ -1,26 +1,9 @@-/*- * Dedicated worker that re-muxes a fragmented MP4 file from OPFS to a- * standard (non-fragmented) MP4, also written to OPFS. Keeps peak RAM- * near zero regardless of recording length.- *- * Input and output are exchanged as OPFS filenames (strings) rather than- * Blobs, because chrome.runtime.sendMessage across the service worker- * loses Blob identity ("blob must be a Blob." errors). OPFS is shared- * between the sandbox and the worker since both live at the same- * chrome-extension origin.- *- * Flow:- * 1. Sweep OPFS remux-*.mp4 files older than STALE_AGE_MS.- * 2. Receive inputFileName + outputFileName from the offscreen doc.- * 3. Open the input OPFS file, read as a Blob via getFile().- * 4. Open the output OPFS file with a sync access handle.- * 5. Run mediabunny Conversion (fastStart: false) streaming through- * a WritableStream backed by the sync handle.- * 6. Flush + close the handle. Return the output filename.- * 7. Caller (sandbox) reads the output from OPFS and triggers the- * download, then cleans up the input file. Output file lingers;- * the next run's sweep removes it.- */+// re-muxes fMP4 from OPFS to a standard MP4 in OPFS. near-zero RAM.+// in/out are passed as OPFS filenames (strings) since sendMessage+// across the SW drops Blob identity ("blob must be a Blob"). OPFS is+// shared with the sandbox (same chrome-extension origin).+// output lingers after success so the sandbox can stream to+// chrome.downloads without a delete-race. next run's sweep removes it.import {Input,Output,@@ -28,7 +11,9 @@ import {StreamTarget,Mp4OutputFormat,ALL_FORMATS,- Conversion,+ EncodedPacketSink,+ EncodedVideoPacketSource,+ EncodedAudioPacketSource,} from "mediabunny";import { createOpfsWritable } from "./opfsTarget";@@ -56,10 +41,7 @@ const postError = (requestId, error) => {});};-// Sweep stale remux-*.mp4 files from prior runs, but only those older than-// STALE_AGE_MS. Previous remuxes intentionally leave their file around so-// the sandbox can stream it to chrome.downloads without racing a delete;-// the age window is plenty for a download to complete.+// STALE_AGE_MS gives prior remuxes time to be downloaded by the sandbox.const sweepOpfsStaleFiles = async () => {try {const dir = await navigator.storage.getDirectory();@@ -71,13 +53,9 @@ const sweepOpfsStaleFiles = async () => {if (now - file.lastModified > STALE_AGE_MS) {await dir.removeEntry(name).catch(() => {});}- } catch {- // Unable to stat the file; leave it alone.- }+ } catch {}}- } catch {- // best-effort- }+ } catch {}};const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {@@ -94,9 +72,8 @@ const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {try {dir = await navigator.storage.getDirectory();- // Load the input as a Blob via getFile(). The Blob is disk-backed by- // Chrome; reads during mediabunny's processing stream from the OPFS- // file on demand without pulling all bytes into memory at once.+ // getFile() returns a disk-backed Blob; mediabunny streams reads+ // on demand without pulling all bytes into memory.const inputHandle = await dir.getFileHandle(inputFileName);const inputFile = await inputHandle.getFile();@@ -110,32 +87,120 @@ const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {formats: ALL_FORMATS,source: new BlobSource(inputFile),});++ // Pipe encoded packets through the muxer for bounded memory (~8 MiB+ // cache); the Conversion API buffers a full sample table upfront.+ const videoTrack = await input.getPrimaryVideoTrack();+ const audioTrack = await input+ .getPrimaryAudioTrack()+ .catch(() => null);++ if (!videoTrack) {+ throw new Error("remux-no-video-track");+ }++ const videoCodec = videoTrack.codec;+ const videoDecoderConfig = await videoTrack.getDecoderConfig();+ const videoSource = new EncodedVideoPacketSource(videoCodec);++ let audioCodec = null;+ let audioDecoderConfig = null;+ let audioSource = null;+ if (audioTrack) {+ try {+ audioCodec = audioTrack.codec;+ audioDecoderConfig = await audioTrack.getDecoderConfig();+ audioSource = new EncodedAudioPacketSource(audioCodec);+ } catch (audioErr) {+ // Unreadable audio: proceed video-only.+ devLog("audio-skip", {+ reason: String(audioErr?.message || audioErr).slice(0, 120),+ });+ audioCodec = null;+ audioDecoderConfig = null;+ audioSource = null;+ }+ }+const output = new Output({target: new StreamTarget(writable),format: new Mp4OutputFormat({ fastStart: false }),});+ output.addVideoTrack(videoSource);+ if (audioSource) output.addAudioTrack(audioSource);++ await output.start();++ // Not all formats expose every field.+ const totalDuration = (() => {+ const candidates = [+ videoTrack?.duration,+ audioTrack?.duration,+ input?.duration,+ ];+ for (const v of candidates) {+ if (typeof v === "number" && Number.isFinite(v) && v > 0) return v;+ }+ return 0;+ })();++ const pipeVideo = async () => {+ const sink = new EncodedPacketSink(videoTrack);+ let isFirst = true;+ for await (const packet of sink.packets()) {+ if (isFirst) {+ await videoSource.add(packet, {+ decoderConfig: videoDecoderConfig,+ });+ isFirst = false;+ } else {+ await videoSource.add(packet);+ }+ if (totalDuration > 0) {+ const pct = Math.min(1, packet.timestamp / totalDuration);+ postProgress(requestId, pct);+ const decile = Math.floor(pct * 10);+ if (decile !== lastProgressLogged) {+ lastProgressLogged = decile;+ devLog("progress", { pct: Math.round(pct * 100) });+ }+ }+ }+ };- const conversion = await Conversion.init({- input,- output,- video: { forceTranscode: false },- audio: { forceTranscode: false },- });- conversion.onProgress = (p) => {- postProgress(requestId, p);- const decile = Math.floor(p * 10);- if (decile !== lastProgressLogged) {- lastProgressLogged = decile;- devLog("progress", { pct: Math.round(p * 100) });+ const pipeAudio = async () => {+ if (!audioSource || !audioTrack) return;+ const sink = new EncodedPacketSink(audioTrack);+ let isFirst = true;+ for await (const packet of sink.packets()) {+ if (isFirst) {+ await audioSource.add(packet, {+ decoderConfig: audioDecoderConfig,+ });+ isFirst = false;+ } else {+ await audioSource.add(packet);+ }}};- await conversion.execute();++ // allSettled so a transient audio decode failure doesn't kill video.+ const pipeResults = await Promise.allSettled([pipeVideo(), pipeAudio()]);+ const videoResult = pipeResults[0];+ if (videoResult.status === "rejected") {+ throw videoResult.reason;+ }+ if (pipeResults[1].status === "rejected") {+ devLog("audio-pipe-failed", {+ err: String(pipeResults[1].reason?.message || pipeResults[1].reason).slice(0, 200),+ });+ }++ await output.finalize();try {await writable.close();- } catch {- // close is best-effort; the sync handle already has the data.- }+ } catch {}syncHandle.flush();const finalSize = syncHandle.getSize();syncHandle.close();@@ -155,16 +220,12 @@ const remuxToOpfs = async ({ requestId, inputFileName, outputFileName }) => {if (syncHandle && !handleReleased) {try {syncHandle.close();- } catch {- // already closed- }+ } catch {}}if (dir && outputFileName) {try {await dir.removeEntry(outputFileName).catch(() => {});- } catch {- // best-effort- }+ } catch {}}}};diff --git a/src/pages/Sandbox/DevHUD.jsx b/src/pages/Sandbox/DevHUD.jsxindex 97c472a..c0839d6 100644--- a/src/pages/Sandbox/DevHUD.jsx+++ b/src/pages/Sandbox/DevHUD.jsx@@ -13,7 +13,12 @@ const BTN = {const BTN_RESET = { ...BTN, background: "rgba(200,50,50,0.7)" };const Z = 2147483647;-const DevHUD = ({ setContentState, contentStateRef, lastDownloadInfo }) => {+const DevHUD = ({+ setContentState,+ contentStateRef,+ lastDownloadInfo,+ lastRecordingBackend,+}) => {const [collapsed, setCollapsed] = useState(true);if (collapsed) {@@ -143,6 +148,24 @@ const DevHUD = ({ setContentState, contentStateRef, lastDownloadInfo }) => {fallback: false,})),},+ {+ label: "Edit audio too large",+ fn: () =>+ setContentState((p) => ({+ ...p,+ editErrorType: "audio-too-large",+ fallback: false,+ mode: "audio",+ })),+ },+ {+ label: "Player loading (toggle)",+ fn: () =>+ setContentState((p) => ({+ ...p,+ playerLoading: !p.playerLoading,+ })),+ },{label: "Offline",fn: () =>@@ -215,6 +238,22 @@ const DevHUD = ({ setContentState, contentStateRef, lastDownloadInfo }) => {x</span></div>+ {lastRecordingBackend && (+ <div+ style={{+ color: "#0ff",+ fontSize: "9px",+ background: "rgba(0,30,40,0.4)",+ padding: "4px 6px",+ borderRadius: "3px",+ lineHeight: 1.4,+ whiteSpace: "normal",+ }}+ >+ <div>Recording backend</div>+ <div style={{ color: "#8ff" }}>{lastRecordingBackend}</div>+ </div>+ )}{lastDownloadInfo && (<divstyle={{diff --git a/src/pages/Sandbox/Sandbox.jsx b/src/pages/Sandbox/Sandbox.jsxindex 79a5273..196f538 100644--- a/src/pages/Sandbox/Sandbox.jsx+++ b/src/pages/Sandbox/Sandbox.jsx@@ -2,19 +2,19 @@ import "./styles/edit/_VideoPlayer.scss";import "./styles/global/_app.scss";import React, { useEffect, useRef, useContext } from "react";-// Layoutimport Editor from "./layout/editor/Editor";import Player from "./layout/player/Player";import Modal from "./components/global/Modal";+import Toast from "./components/global/Toast";import HelpButton from "./components/player/HelpButton";-// Context-import { ContentStateContext } from "./context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "./context/ContentState";import { diagForward } from "../utils/diagForward";+import { perfMark } from "../utils/perfMarks";const Sandbox = () => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const parentRef = useRef(null);const progress = useRef("");@@ -42,16 +42,13 @@ const Sandbox = () => {useEffect(() => {if (!contentState.blob || !contentState.ffmpeg) return;if (contentState.frame) return;- // Frame extraction now works in fallback mode using Canvas APIcontentState.getFrame();}, [contentState.blob, contentState.ffmpeg]);- // Programmatically add custom scrollbarsuseEffect(() => {if (!parentRef) return;if (!parentRef.current) return;- // Check if on macconst isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;if (isMac) return;@@ -100,7 +97,6 @@ const Sandbox = () => {}, [contentState.chunkIndex, contentState.chunkCount]);useEffect(() => {- // Check if we need to show support bannerchrome.runtime.sendMessage({ type: "check-banner-support" }, (response) => {if (response && response.bannerSupport) {setContentState((prev) => ({@@ -111,35 +107,82 @@ const Sandbox = () => {});}, []);- // If editor was opened manually and we don't yet have a blob/ready state,- // proactively ask the background to send chunks to this sandbox tab.+ // Editor opened without a blob/ready state: ask BG to send chunks.+ // Retry because BG may be dormant on first wake, and a single dropped+ // message would leave the editor stuck at "Preparing recording..." forever.useEffect(() => {- let requested = false;- if (requested) return; // guard- requested = true;+ const RETRY_DELAYS_MS = [400, 2000, 6000, 14000];+ let cancelled = false;+ const timers = [];- const tryRequest = () => {+ const tryRequest = async (attempt) => {+ if (cancelled) return;try {- if (!contentState.blob && !contentState.ready) {+ if (contentState.blob || contentState.ready) return;+ // OPFS-backed: sandbox reads the file directly in makeVideoTab.+ const { lastRecordingBackendRef } = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ if (lastRecordingBackendRef?.backend === "opfs") {console.debug(- "[Screenity][Sandbox] requesting chunks from background (send-chunks-to-sandbox)",- );- // Ask background to send chunks to this tab (background will- // determine the target tab or use this sender)- chrome.runtime.sendMessage(- { type: "send-chunks-to-sandbox" },- () => {},+ "[Screenity][Sandbox] OPFS-backed recording; skipping SW chunk relay request",);+ return;}+ console.debug(+ "[Screenity][Sandbox] requesting chunks from background",+ { attempt: attempt + 1 },+ );+ perfMark("Sandbox send-chunks-to-sandbox.requested", {+ attempt: attempt + 1,+ });+ chrome.runtime.sendMessage(+ { type: "send-chunks-to-sandbox" },+ () => {},+ );} catch (err) {}};- // Delay slightly to allow initial message listeners to be registered- const t = setTimeout(tryRequest, 400);- return () => clearTimeout(t);+ perfMark("Sandbox boot");+ RETRY_DELAYS_MS.forEach((ms, i) => {+ timers.push(setTimeout(() => tryRequest(i), ms));+ });++ // Surface recovery modal if "Preparing recording..." sits 60s with no+ // blob/ready/editorRecordingError; writing editorRecordingError reuses+ // the ContentState consumer.+ const STUCK_TIMEOUT_MS = 60_000;+ const stuckTimer = setTimeout(() => {+ try {+ if (cancelled) return;+ // editorRecordingError's own filter (ready=true → suppress) makes+ // a stale write harmless if the editor already loaded.+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "sandbox-stuck-timeout",+ data: { afterMs: STUCK_TIMEOUT_MS },+ })+ .catch(() => {});+ chrome.storage.local.set({+ editorRecordingError: {+ ts: Date.now(),+ sandboxTab: null,+ error: "editor-stuck",+ why: chrome.i18n.getMessage("editorStuckDescription"),+ errorCode: "EDITOR_STUCK_TIMEOUT",+ },+ });+ } catch {}+ }, STUCK_TIMEOUT_MS);+ timers.push(stuckTimer);++ return () => {+ cancelled = true;+ timers.forEach((t) => clearTimeout(t));+ };}, []);- // Regenerate frame when entering crop mode to reflect current blobuseEffect(() => {if (contentState.mode === "crop" &&@@ -147,7 +190,7 @@ const Sandbox = () => {contentState.blob &&contentState.ffmpeg) {- // Small delay to ensure state updates have propagated+ // Let state updates propagate first.setTimeout(() => {contentState.getFrame();}, 50);@@ -157,8 +200,8 @@ const Sandbox = () => {return (<div ref={parentRef}><Modal />+ <Toast /><video></video>- {/* Render the WaveformGenerator component and pass the ffmpeg instance as a prop */}{contentState.ffmpeg &&contentState.ready &&contentState.mode === "edit" && <Editor />}@@ -200,10 +243,10 @@ const Sandbox = () => {() => {chrome.runtime.sendMessage({ type: "report-bug" });},- null, // image- null, // learnMore- null, // learnMoreLink- false, // colorSafe+ null,+ null,+ null,+ false,chrome.i18n.getMessage("getHelpButton"),() => {chrome.runtime.sendMessage({diff --git a/src/pages/Sandbox/components/editor/CropperWrap.jsx b/src/pages/Sandbox/components/editor/CropperWrap.jsxindex e930253..fa47601 100644--- a/src/pages/Sandbox/components/editor/CropperWrap.jsx+++ b/src/pages/Sandbox/components/editor/CropperWrap.jsx@@ -2,24 +2,28 @@ import React, { useState, useEffect, useContext, useRef } from "react";import { CropperRef, Cropper } from "react-advanced-cropper";import "react-advanced-cropper/dist/style.css";-// Context-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const CropperWrap = () => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const [image, setImage] = useState(null);const cropperRef = useRef(null);+ // Guards against onChange firing during setCoordinates push: stale cropper+ // coords would otherwise overwrite state and revert CropUI inputs.+ const pushingToCropperRef = useRef(false);useEffect(() => {if (!cropperRef.current) return;if (!cropperRef.current.getCoordinates()) return;if (contentState.fromCropper) return;+ pushingToCropperRef.current = true;cropperRef.current.setCoordinates({top: contentState.top,left: contentState.left,width: contentState.width,height: contentState.height,});+ pushingToCropperRef.current = false;if (contentState.top != cropperRef.current.getCoordinates().top) {setContentState((prevState) => ({...prevState,@@ -53,6 +57,7 @@ const CropperWrap = () => {const onChange = (cropper) => {if (!cropper) return;+ if (pushingToCropperRef.current) return;setContentState((prevState) => ({...prevState,top: cropper.getCoordinates().top,diff --git a/src/pages/Sandbox/components/editor/Trimmer.jsx b/src/pages/Sandbox/components/editor/Trimmer.jsxindex c706e7d..5151f06 100644--- a/src/pages/Sandbox/components/editor/Trimmer.jsx+++ b/src/pages/Sandbox/components/editor/Trimmer.jsx@@ -2,75 +2,96 @@ import React, { useRef, useEffect, useState, useContext } from "react";import styles from "../../styles/edit/_Trimmer.module.scss";import WaveformGenerator from "./Waveform";-// Context-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const Trimmer = (props) => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const trimmerRef = useRef(null);const startHandleRef = useRef(null);const endHandleRef = useRef(null);const isDragging = useRef(false);const activeHandle = useRef(null);+ // Refs so doc-level mousemove/mouseup don't re-bind per render and leak+ // listeners with stale bounds.+ const setContentStateRef = useRef(setContentState);+ const addToHistoryRef = useRef(null);+ const startBoundRef = useRef(0);+ const endBoundRef = useRef(1);- const handleMouseDown = (e, handle) => {- e.preventDefault();- isDragging.current = true;- activeHandle.current = handle;-- document.addEventListener("mousemove", handleMouseMove);- document.addEventListener("mouseup", handleMouseUp);- };+ useEffect(() => {+ setContentStateRef.current = setContentState;+ addToHistoryRef.current = contentState.addToHistory;+ startBoundRef.current = contentState.start;+ endBoundRef.current = contentState.end;+ });- const handleMouseMove = (e) => {- if (!isDragging.current) return;+ const handleMouseMoveRef = useRef(null);+ const handleMouseUpRef = useRef(null);- const trimmerRect = trimmerRef.current.getBoundingClientRect();- const trimmerWidth = trimmerRect.width;- const mouseX = e.clientX - trimmerRect.left;- let newPosition = mouseX / trimmerWidth;+ if (!handleMouseMoveRef.current) {+ handleMouseMoveRef.current = (e) => {+ if (!isDragging.current) return;+ const trimmerRect = trimmerRef.current?.getBoundingClientRect();+ if (!trimmerRect) return;+ const trimmerWidth = trimmerRect.width;+ const mouseX = e.clientX - trimmerRect.left;+ const newPosition = mouseX / trimmerWidth;- if (activeHandle.current === "start") {- newPosition += 0;- const validPosition = Math.max(- Math.min(newPosition, contentState.end - 0.02),- 0- );- setContentState((prevContentState) => ({- ...prevContentState,- start: validPosition,- }));- } else if (activeHandle.current === "end") {- newPosition -= 0;- const validPosition = Math.min(- Math.max(newPosition, contentState.start + 0.02),- 1- );- setContentState((prevContentState) => ({- ...prevContentState,- end: validPosition,+ if (activeHandle.current === "start") {+ const validPosition = Math.max(+ Math.min(newPosition, endBoundRef.current - 0.02),+ 0,+ );+ setContentStateRef.current((prev) => ({+ ...prev,+ start: Math.min(validPosition, prev.end - 0.02),+ }));+ } else if (activeHandle.current === "end") {+ const validPosition = Math.min(+ Math.max(newPosition, startBoundRef.current + 0.02),+ 1,+ );+ setContentStateRef.current((prev) => ({+ ...prev,+ end: Math.max(validPosition, prev.start + 0.02),+ }));+ }+ };+ }+ if (!handleMouseUpRef.current) {+ handleMouseUpRef.current = () => {+ isDragging.current = false;+ activeHandle.current = null;+ try {+ addToHistoryRef.current?.();+ } catch {}+ setContentStateRef.current((prev) => ({+ ...prev,+ dragInteracted: true,}));- }- };-- const handleMouseUp = () => {- isDragging.current = false;- activeHandle.current = null;+ document.removeEventListener("mousemove", handleMouseMoveRef.current);+ document.removeEventListener("mouseup", handleMouseUpRef.current);+ };+ }- contentState.addToHistory();-- setContentState((prevContentState) => ({- ...prevContentState,- dragInteracted: true,- }));+ // Cleanup if component unmounts mid-drag.+ useEffect(() => {+ return () => {+ document.removeEventListener("mousemove", handleMouseMoveRef.current);+ document.removeEventListener("mouseup", handleMouseUpRef.current);+ };+ }, []);- document.removeEventListener("mousemove", handleMouseMove);- document.removeEventListener("mouseup", handleMouseUp);+ const handleMouseDown = (e, handle) => {+ e.preventDefault();+ isDragging.current = true;+ activeHandle.current = handle;+ document.addEventListener("mousemove", handleMouseMoveRef.current);+ document.addEventListener("mouseup", handleMouseUpRef.current);};useEffect(() => {- // Update the handle positions when the start and end values changestartHandleRef.current.style.left = `calc(${contentState.start * 100}%)`;endHandleRef.current.style.left = `${contentState.end * 100}%`;}, [contentState.start, contentState.end]);diff --git a/src/pages/Sandbox/components/editor/VideoPlayer.jsx b/src/pages/Sandbox/components/editor/VideoPlayer.jsxindex d8e3c93..1fd7598 100644--- a/src/pages/Sandbox/components/editor/VideoPlayer.jsx+++ b/src/pages/Sandbox/components/editor/VideoPlayer.jsx@@ -9,6 +9,9 @@ const VideoPlayer = (props) => {const [url, setUrl] = useState(null);const [source, setSource] = useState(null);const [isSet, setIsSet] = useState(false);+ // Probed from the blob's intrinsic dimensions; a fixed "16:9" would+ // pillarbox recordings of square-ish tabs.+ const [videoRatio, setVideoRatio] = useState("16:9");useEffect(() => {if (@@ -23,7 +26,7 @@ const VideoPlayer = (props) => {const options = useMemo(() => ({controls: ["play", "mute", "captions", "settings", "pip", "fullscreen"],- ratio: "16:9",+ ratio: videoRatio,blankVideo:"chrome-extension://" +chrome.i18n.getMessage("@@extension_id") +@@ -32,9 +35,33 @@ const VideoPlayer = (props) => {global: true,},}),- []+ [videoRatio]);+ useEffect(() => {+ if (!contentState.blob) return;+ const probeUrl = URL.createObjectURL(contentState.blob);+ const probe = document.createElement("video");+ probe.preload = "metadata";+ probe.muted = true;+ probe.src = probeUrl;+ const onMeta = () => {+ const w = probe.videoWidth;+ const h = probe.videoHeight;+ if (w > 0 && h > 0) setVideoRatio(`${w}:${h}`);+ cleanup();+ };+ const onErr = () => cleanup();+ const cleanup = () => {+ probe.removeEventListener("loadedmetadata", onMeta);+ probe.removeEventListener("error", onErr);+ URL.revokeObjectURL(probeUrl);+ };+ probe.addEventListener("loadedmetadata", onMeta);+ probe.addEventListener("error", onErr);+ return cleanup;+ }, [contentState.blob]);+useEffect(() => {if (contentState.blob) {const objectURL = URL.createObjectURL(contentState.blob);diff --git a/src/pages/Sandbox/components/editor/Waveform.jsx b/src/pages/Sandbox/components/editor/Waveform.jsxindex d76ad44..a4dc8ff 100644--- a/src/pages/Sandbox/components/editor/Waveform.jsx+++ b/src/pages/Sandbox/components/editor/Waveform.jsx@@ -1,10 +1,10 @@import React, { useContext, useRef, useEffect, useState } from "react";import WaveSurfer from "wavesurfer.js";import styles from "../../styles/edit/_Waveform.module.scss";-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const WaveformGenerator = (props) => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const wavesurferRef = useRef(null);const waveformContainerRef = useRef(null);const customCursorRef = useRef(null);@@ -113,6 +113,11 @@ const WaveformGenerator = (props) => {return () => {if (wavesurferRef.current) {wavesurferRef.current.destroy();+ wavesurferRef.current = null;+ }+ // WaveSurfer 7 leaves old canvas behind on destroy.+ if (container) {+ container.innerHTML = "";}container.removeEventListener("mouseenter", handleMouseEnter);container.removeEventListener("mousemove", handleMouseMove);diff --git a/src/pages/Sandbox/components/global/Modal.jsx b/src/pages/Sandbox/components/global/Modal.jsxindex b42e536..82bb0aa 100644--- a/src/pages/Sandbox/components/global/Modal.jsx+++ b/src/pages/Sandbox/components/global/Modal.jsx@@ -1,7 +1,6 @@import React, { useState, useEffect, useContext, useCallback } from "react";import * as AlertDialog from "@radix-ui/react-alert-dialog";-// Contextimport { ContentStateContext } from "../../context/ContentState";const Modal = (props) => {@@ -35,6 +34,19 @@ const Modal = (props) => {sideButton = false,sideButtonAction = () => {}) => {+ // Surface which error/info modal the user saw (title is i18n-resolved here).+ try {+ chrome.runtime+ .sendMessage({+ type: "diag-forward",+ event: "sandbox-modal-open",+ data: {+ title: String(title || "").slice(0, 120),+ description: String(description || "").slice(0, 240),+ },+ })+ .catch(() => {});+ } catch {}setTitle(title);setDescription(description);setButton1(button1);diff --git a/src/pages/Sandbox/components/global/Toast.jsx b/src/pages/Sandbox/components/global/Toast.jsxnew file mode 100644index 0000000..67643ed--- /dev/null+++ b/src/pages/Sandbox/components/global/Toast.jsx@@ -0,0 +1,78 @@+import React, {+ useState,+ useEffect,+ useContext,+ useCallback,+ useRef,+} from "react";++import * as ToastEl from "@radix-ui/react-toast";++import { ContentStateContext } from "../../context/ContentState";++const Toast = () => {+ const [contentState, setContentState] = useContext(ContentStateContext);+ const [open, setOpen] = useState(false);+ const [title, setTitle] = useState("");+ const [duration, setDuration] = useState(2200);+ const actionRef = useRef(null);++ const openToast = useCallback((nextTitle, action = null, durationMs = 2200) => {+ setTitle(nextTitle);+ setDuration(durationMs);+ actionRef.current = typeof action === "function" ? action : null;+ setOpen(false);+ requestAnimationFrame(() => setOpen(true));+ }, []);++ useEffect(() => {+ setContentState((prev) => ({ ...prev, openToast }));+ return () => {+ setContentState((prev) => ({ ...prev, openToast: null }));+ };+ }, []);++ const fireAction = () => {+ const fn = actionRef.current;+ actionRef.current = null;+ setOpen(false);+ if (fn) {+ try {+ fn();+ } catch {}+ }+ };++ return (+ <ToastEl.Provider swipeDirection="down" duration={duration}>+ <ToastEl.Root+ className="ToastRoot"+ open={open}+ onOpenChange={setOpen}+ onEscapeKeyDown={(e) => {+ if (!actionRef.current) return;+ e.preventDefault();+ fireAction();+ }}+ >+ <ToastEl.Title className="ToastTitle">{title}</ToastEl.Title>+ {actionRef.current && (+ <ToastEl.Action className="ToastAction" asChild altText="Esc">+ <button+ className="ToastEscButton"+ onClick={(e) => {+ e.stopPropagation();+ fireAction();+ }}+ >+ Esc+ </button>+ </ToastEl.Action>+ )}+ </ToastEl.Root>+ <ToastEl.Viewport className="ToastViewport" />+ </ToastEl.Provider>+ );+};++export default Toast;diff --git a/src/pages/Sandbox/components/player/VideoPlayer.jsx b/src/pages/Sandbox/components/player/VideoPlayer.jsxindex e8b75be..37e8c4f 100644--- a/src/pages/Sandbox/components/player/VideoPlayer.jsx+++ b/src/pages/Sandbox/components/player/VideoPlayer.jsx@@ -1,17 +1,18 @@import React, { useContext, useEffect, useState, useRef, useMemo } from "react";+import { createPortal } from "react-dom";import Plyr from "plyr-react";import "../../styles/plyr.css";-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";-// Componentsimport Title from "./Title";const VideoPlayer = (props) => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const playerRef = useRef(null);const [url, setUrl] = useState(null);const [source, setSource] = useState(null);+ const [overlayHost, setOverlayHost] = useState(null);const contentStateRef = useRef(contentState);const bannerRef = useRef(null);@@ -66,28 +67,6 @@ const VideoPlayer = (props) => {[]);- /*- useEffect(() => {- if (contentState.blob) {- const objectURL = URL.createObjectURL(contentState.blob);- setSource({- type: "video",- sources: [- {- src: objectURL,- type: "video/mp4",- },- ],- });- setUrl(objectURL);-- return () => {- URL.revokeObjectURL(objectURL);- };- }- }, [contentState.blob, playerRef]);- */-useEffect(() => {if (contentState.webm || contentState.blob) {let vid;@@ -101,6 +80,8 @@ const VideoPlayer = (props) => {vid = contentState.webm;}const objectURL = URL.createObjectURL(vid);+ // Long recordings can take seconds to parse metadata.+ setContentState((prev) => ({ ...prev, playerLoading: true }));setSource({type: "video",sources: [@@ -116,14 +97,83 @@ const VideoPlayer = (props) => {URL.revokeObjectURL(objectURL);};}- }, [- contentState.webm,- contentState.blob,- contentState.hasBeenEdited,- playerRef,- ]);-- // Use a mutation observer to check if .plyr--video is added to the DOM+ }, [contentState.webm, contentState.blob, playerRef]);++ // plyr-react ref shape varies; bind directly to <video>. 15s safety+ // timeout in case events never fire.+ useEffect(() => {+ if (!source) return;+ let cleared = false;+ const clear = () => {+ if (cleared) return;+ cleared = true;+ setContentState((prev) =>+ prev.playerLoading ? { ...prev, playerLoading: false } : prev,+ );+ };+ let videoEl = null;+ let safetyId = null;+ let retryId = null;+ let errorSurfaced = false;+ // Corrupt/zero-byte/header-only OPFS file (recorder died before chunks+ // landed, or quota hit past moov) fires MediaError. Without this,+ // playerLoading only clears via the 15s safety timeout, leaving a black+ // <video>. Surface a toast and clear loading immediately.+ const onVideoError = () => {+ if (errorSurfaced) return;+ errorSurfaced = true;+ try {+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("recordingCorruptToast"),+ timeout: 8000,+ });+ } catch {}+ try {+ chrome.runtime.sendMessage({+ type: "diag-forward",+ event: "editor-video-decode-error",+ data: {+ mediaError: videoEl?.error?.code ?? null,+ mediaErrorMessage:+ String(videoEl?.error?.message || "").slice(0, 120) || null,+ blobSize: contentStateRef.current?.blob?.size ?? null,+ },+ });+ } catch {}+ clear();+ };+ const tryAttach = () => {+ videoEl =+ document.querySelector("#plyr-player") ||+ document.querySelector(".plyr video");+ const plyrEl = document.querySelector(".plyr");+ if (plyrEl) setOverlayHost(plyrEl);+ if (!videoEl) return false;+ videoEl.addEventListener("loadedmetadata", clear);+ videoEl.addEventListener("canplay", clear);+ videoEl.addEventListener("error", onVideoError);+ if (videoEl.readyState >= 1) clear();+ // Error may have already fired pre-attach.+ if (videoEl.error) onVideoError();+ return true;+ };+ if (!tryAttach()) {+ retryId = setTimeout(tryAttach, 50);+ }+ safetyId = setTimeout(clear, 15000);+ return () => {+ if (retryId) clearTimeout(retryId);+ if (safetyId) clearTimeout(safetyId);+ if (videoEl) {+ videoEl.removeEventListener("loadedmetadata", clear);+ videoEl.removeEventListener("canplay", clear);+ videoEl.removeEventListener("error", onVideoError);+ }+ setOverlayHost(null);+ };+ }, [source]);+useEffect(() => {if (contentStateRef.current.mp4ready || contentStateRef.current.blob)return;@@ -192,6 +242,49 @@ const VideoPlayer = (props) => {options={options}/>)}+ {(contentState.playerLoading || contentState.finalizingRecording) &&+ overlayHost &&+ createPortal(+ <div+ className="screenity-player-loading"+ style={{+ position: "absolute",+ inset: 0,+ background: "rgba(0,0,0,0.55)",+ display: "flex",+ flexDirection: "column",+ gap: "12px",+ alignItems: "center",+ justifyContent: "center",+ zIndex: 5,+ pointerEvents: "none",+ }}+ >+ <div+ style={{+ width: "32px",+ height: "32px",+ border: "3px solid rgba(255,255,255,0.2)",+ borderTopColor: "#fff",+ borderRadius: "50%",+ animation: "screenity-spin 0.9s linear infinite",+ }}+ />+ {contentState.finalizingRecording && (+ <div+ style={{+ color: "#fff",+ fontSize: "13px",+ fontWeight: 500,+ opacity: 0.9,+ }}+ >+ {chrome.i18n.getMessage("sandboxFinalizingRecording")}+ </div>+ )}+ </div>,+ overlayHost+ )}{contentState.mode === "player" && <Title />}</div><style>@@ -201,6 +294,9 @@ const VideoPlayer = (props) => {position: relative!important;}}+ @keyframes screenity-spin {+ to { transform: rotate(360deg); }+ }`}</style></div>diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsxindex ac7b29f..a55df2a 100644--- a/src/pages/Sandbox/context/ContentState.jsx+++ b/src/pages/Sandbox/context/ContentState.jsx@@ -22,6 +22,8 @@ import {isRecordingDebugEnabled,} from "../../utils/recordingDebug";import { diagForward } from "../../utils/diagForward";+import { perfMark, perfSpan } from "../../utils/perfMarks";+import { chooseReader } from "../recorderStorage/chooseReader";import {Input,Output,@@ -47,7 +49,6 @@ export const ContentStateContext = createContext();const DEBUG_RECORDER =typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;-// Enable post-stop debug logs for sandboxconst DEBUG_POSTSTOP = DEBUG_RECORDER;const ContentState = (props) => {@@ -56,7 +57,6 @@ const ContentState = (props) => {const chunkCount = useRef(0);const recdbgSessionRef = useRef(null);const tabIdRef = useRef(null);- // Stale-result guard + stuck-edit watchdog.const opIdRef = useRef(0);const editWatchdogRef = useRef(null);@@ -146,13 +146,20 @@ const ContentState = (props) => {chrome.runtime.sendMessage({ type: "recdbg-ping" });}, []);+ // legacy ffmpeg editor loads entire blob into WASM (~3x peak RAM); cap edit length+ const isLegacyFfmpegEditor =+ typeof window !== "undefined" &&+ typeof window.location !== "undefined" &&+ /\/editor\.html(?:[?#]|$)/.test(window.location.pathname + window.location.search);+ const MAX_EDIT_LIMIT_S = isLegacyFfmpegEditor ? 600 : 3600;+const defaultState = {time: 0,editLimit: 420,- // Last successful (or failed) download remux outcome. Populated at- // the end of download(); consumed by DevHUD in dev builds to show- // which tier ran and how long it took.+ playerLoading: false,+ finalizingRecording: false,lastDownloadInfo: null,+ lastRecordingBackend: null,blob: null,webm: null,originalBlob: null,@@ -162,7 +169,7 @@ const ContentState = (props) => {trimming: false,cutting: false,muting: false,- editErrorType: null, // null | "too-long" | "timeout" | "failed"+ editErrorType: null, // null | "too-long" | "timeout" | "failed" | "audio-too-large"history: [{}], // Initialize history with a default stateredoHistory: [],undoDisabled: true,@@ -171,7 +178,9 @@ const ContentState = (props) => {mode: "player",ffmpegLoaded: false,frame: null,+ pendingCropEntry: false,getFrame: null,+ openToast: null,isFfmpegRunning: false,reencoding: false,prevWidth: 0,@@ -221,6 +230,8 @@ const ContentState = (props) => {const pseudoProgressStartAtRef = useRef(null);const diagMountAtRef = useRef(null);const diagMakeVideoAtRef = useRef(null);+ const editorReadyDiagSentRef = useRef(false);+ const editorErrorShownRef = useRef(false);const diagHeartbeatCountRef = useRef(0);const setContentState = useCallback((updater) => {@@ -239,6 +250,20 @@ const ContentState = (props) => {} catch {}}, []);+ useEffect(() => {+ // emit diag-editor-ready once; WebM has many "ready:true" branches+ if (!contentState.ready) return;+ if (editorReadyDiagSentRef.current) return;+ editorReadyDiagSentRef.current = true;+ const blobType = contentStateRef.current?.blob?.type+ || contentStateRef.current?.rawBlob?.type+ || null;+ const path = blobType?.includes("mp4") ? "mp4-fast" : "webm";+ chrome.runtime+ .sendMessage({ type: "diag-editor-ready", path })+ .catch(() => {});+ }, [contentState.ready]);+useEffect(() => {if (launchModeRef.current !== "postStop") return;if (contentState.ready) {@@ -397,68 +422,42 @@ const ContentState = (props) => {}, [contentState.chunkIndex, contentState.chunkCount]);const buildBlobFromChunks = async () => {- const items = [];-- await chunksStore.ready();- if (DEBUG_POSTSTOP)- console.debug(- "[Screenity][Sandbox] buildBlobFromChunks: chunksStore ready, iterating",- );-- await chunksStore.iterate((value) => (items.push(value), undefined));- if (DEBUG_POSTSTOP)- console.debug("[Screenity][Sandbox] buildBlobFromChunks: items loaded", {- count: items.length,- });-- items.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));- const parts = items.map((c) =>- c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),- );-- if (!parts.length) {- debug("No chunks found in IndexedDB");+ const { lastRecordingBackendRef } = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ const reader = chooseReader(lastRecordingBackendRef);+ await reader.open(lastRecordingBackendRef);+ let readResult;+ try {+ readResult = await reader.readBlob();+ } finally {+ await reader.close().catch(() => {});+ }+ if (!readResult || readResult.chunkCount === 0) {+ debug("No chunks found in chunk reader");if (DEBUG_POSTSTOP)console.warn(- "[Screenity][Sandbox] buildBlobFromChunks: no parts found in IndexedDB",+ "[Screenity][Sandbox] buildBlobFromChunks: no parts found",);debugRecordingEventWithSession(recdbgSessionRef.current, "blob-empty", {chunkCount: 0,});return null;}-- const first = parts[0];- const inferredType = first?.type || "video/webm";-- const blob = new Blob(parts, { type: inferredType });+ const blob = readResult.blob;if (DEBUG_POSTSTOP)console.debug("[Screenity][Sandbox] buildBlobFromChunks: reconstructed blob",{size: blob.size,type: blob.type,+ chunkCount: readResult.chunkCount,},);reconstructVideo(blob);return blob;};- // useEffect(() => {- // contentStateRef.current = contentState;- // }, [contentState]);-- // Check if the user is offline- // useEffect(() => {- // if (!navigator.onLine) {- // setContentState((prevState) => ({- // ...prevState,- // offline: true,- // }));- // }- // }, []);-- // Generate a title based on the current time unless this is a tab recordinguseEffect(() => {const loadInitialTitle = async () => {const date = new Date();@@ -505,7 +504,6 @@ const ContentState = (props) => {loadInitialTitle();}, []);- // Show a popup when attempting to close the tab if the user has not downloaded their videouseEffect(() => {if (!contentState.saved) {window.onbeforeunload = function () {@@ -541,14 +539,35 @@ const ContentState = (props) => {}));};+ // each entry pins a blob (multi-GB on long recordings); cap to bound memory+ const MAX_HISTORY_DEPTH = 20;const addToHistory = useCallback(() => {- setContentState((prevState) => ({- ...prevState,- history: [...prevState.history, prevState],- redoHistory: [], // Clear redo history when a new state is added- }));+ setContentState((prevState) => {+ const next = [...prevState.history, prevState];+ if (next.length > MAX_HISTORY_DEPTH) {+ next.splice(0, next.length - MAX_HISTORY_DEPTH);+ }+ return {+ ...prevState,+ history: next,+ redoHistory: [],+ };+ });}, [contentState]);+ // History snapshots taken mid-edit can carry isFfmpegRunning:true and+ // edit-mode flags. Restoring such a snapshot leaves redo greyed out and+ // edit buttons disabled. The action gate already confirms no FFmpeg+ // is in flight by the time undo/redo can fire, so reset on every restore.+ const RESET_RUNTIME_FLAGS = {+ isFfmpegRunning: false,+ trimming: false,+ cutting: false,+ muting: false,+ cropping: false,+ reencoding: false,+ };+const undo = useCallback(() => {if (contentState.history.length > 1) {const previousState =@@ -559,6 +578,7 @@ const ContentState = (props) => {...previousState,history: newHistory,redoHistory: [contentState, ...contentState.redoHistory],+ ...RESET_RUNTIME_FLAGS,}));}}, [contentState]);@@ -572,6 +592,7 @@ const ContentState = (props) => {...nextState,history: [...contentState.history, contentState],redoHistory: newRedoHistory,+ ...RESET_RUNTIME_FLAGS,}));}}, [contentState]);@@ -602,13 +623,38 @@ const ContentState = (props) => {useEffect(() => {if (!contentState.blob) return;- // Get duration of video blobconst video = document.createElement("video");video.preload = "metadata";video.onloadedmetadata = async () => {+ // fragmented MP4 mvhd can be wrong; cross-check storage but only on original+ // (edited blobs are shorter than recordingDuration)+ const isOriginalBlob =+ !contentState.originalBlob ||+ contentState.blob === contentState.originalBlob;+ let durationSec = video.duration;+ if (isOriginalBlob) {+ try {+ const { recordingDuration } = await chrome.storage.local.get([+ "recordingDuration",+ ]);+ const recSec = Number(recordingDuration) > 0+ ? Number(recordingDuration) / 1000+ : 0;+ const probedSec = Number.isFinite(video.duration) && video.duration > 0+ ? video.duration+ : 0;+ if (recSec > probedSec + 0.3) {+ durationSec = recSec;+ } else if (probedSec > 0) {+ durationSec = probedSec;+ } else if (recSec > 0) {+ durationSec = recSec;+ }+ } catch {}+ }setContentState((prevState) => ({...prevState,- duration: video.duration,+ duration: durationSec,width: video.videoWidth,height: video.videoHeight,prevWidth: video.videoWidth,@@ -622,9 +668,8 @@ const ContentState = (props) => {}, [contentState.blob]);const reconstructVideo = async (withBlob) => {- // Sniff MIME type from magic bytes (WebCodecs chunks are MP4, not WebM).- // `base64ToUint8Array` returns Blob for data-URL inputs and Uint8Array for- // raw base64 — handle both. A Blob has .size; a Uint8Array has .length.+ // sniff magic bytes; WebCodecs chunks are MP4 not WebM.+ // base64ToUint8Array returns Blob for data-URL, Uint8Array for rawlet inferredType = "video/webm; codecs=vp8,opus";if (!withBlob && videoChunks.current.length > 0) {try {@@ -667,9 +712,34 @@ const ContentState = (props) => {let blob;try {- blob = withBlob- ? withBlob- : new Blob(videoChunks.current, { type: inferredType });+ if (withBlob) {+ blob = withBlob;+ } else {+ // trim at first gap; sparse holes from out-of-order arrivals corrupt video+ let firstGap = -1;+ for (let i = 0; i < videoChunks.current.length; i += 1) {+ if (videoChunks.current[i] == null) {+ firstGap = i;+ break;+ }+ }+ const safeChunks =+ firstGap >= 0+ ? videoChunks.current.slice(0, firstGap)+ : videoChunks.current;+ if (firstGap >= 0) {+ diagForward("sandbox-reconstruct-trimmed-at-gap", {+ firstGap,+ haveCount: safeChunks.length,+ totalSlots: videoChunks.current.length,+ });+ }+ blob = new Blob(safeChunks, { type: inferredType });+ }+ perfMark("Sandbox blob-built", {+ bytes: blob?.size ?? 0,+ chunks: videoChunks.current.length,+ });} catch (err) {diagForward("sandbox-reconstruct-error", {error: String(err?.message || err).slice(0, 200),@@ -689,35 +759,6 @@ const ContentState = (props) => {console.log("[Screenity][Sandbox] reconstructVideo: fast MP4 path taken", {size: blob.size,});- //const TOO_BIG_BYTES = 200 * 1024 * 1024;- // const TOO_BIG_BYTES = 0;- // if (blob.size > TOO_BIG_BYTES) {- // // Convert Blob → base64 first so we can pass to sandbox- // const reader = new FileReader();- // reader.onloadend = () => {- // const base64 = reader.result;-- // setContentState((prev) => ({- // ...prev,- // base64,- // compressing: true,- // mp4ready: false,- // ready: false,- // rawBlob: prev.rawBlob || blob,- // }));-- // // Send to sandbox for compression- // sendMessage({- // type: "compress-video",- // base64,- // topLevel: true,- // });- // };- // reader.readAsDataURL(blob);-- // return;- // }-setContentState((prev) => ({...prev,blob: blob,@@ -725,18 +766,20 @@ const ContentState = (props) => {mp4ready: true,ready: true,rawBlob: blob,+ originalBlob: prev.originalBlob || blob,isFfmpegRunning: false,noffmpeg: false,- // Native MP4 from WebCodecs: trim/crop go through mediabunny streaming- // ops, and mute/add-audio have their own 15-min cap. 7 min is a- // leftover from the ffmpeg.wasm era — bump to 15 min to match.- editLimit: Math.max(prev.editLimit || 0, 900),+ editLimit: Math.max(prev.editLimit || 0, MAX_EDIT_LIMIT_S),}));- // Extract duration, width, heightconst video = document.createElement("video");video.preload = "metadata";video.onloadedmetadata = () => {+ perfMark("Sandbox video-loadedmetadata", {+ duration: video.duration,+ w: video.videoWidth,+ h: video.videoHeight,+ });setContentState((prev) => ({...prev,duration: video.duration,@@ -812,7 +855,6 @@ const ContentState = (props) => {}}- // Check if token is presentconst { token } = await chrome.storage.local.get("token");let driveEnabled = false;@@ -828,7 +870,6 @@ const ContentState = (props) => {duration: safeDuration / 1000,}));- // Check if user is in Windows 10const isWindows10 = navigator.userAgent.match(/Windows NT 10.0/);try {@@ -838,7 +879,6 @@ const ContentState = (props) => {blob,safeDuration,async (fixedWebm) => {- // Skip conversion only if Chrome is outdated or recording exceeds edit limitif (contentStateRef.current.updateChrome ||contentStateRef.current.noffmpeg ||@@ -873,7 +913,6 @@ const ContentState = (props) => {const fixedWebm = await fixWebmDurationFallback(blob, {type: "video/webm; codecs=vp8, opus",});- // Skip conversion only if Chrome is outdated or recording exceeds edit limitif (contentStateRef.current.updateChrome ||contentStateRef.current.noffmpeg ||@@ -903,11 +942,9 @@ const ContentState = (props) => {reader.readAsDataURL(fixedWebm);}} else {- // Duration unknown — skip fixing, use raw blob as-isconsole.warn("[Screenity][WebM] skipping duration fix: safeDuration=0, blob will have broken seek metadata",);- // Skip conversion only if Chrome is outdated or recording exceeds edit limitif (contentStateRef.current.updateChrome ||contentStateRef.current.noffmpeg ||@@ -950,8 +987,7 @@ const ContentState = (props) => {chrome.runtime.sendMessage({ type: "recording-complete" });}- // 45s safety timeout for the direct-blob path — force ready if- // fixWebmDuration or readAsDataURL hangs.+ // 45s safety timeout for direct-blob path; fixWebmDuration/readAsDataURL can hangif (withBlob) {setTimeout(() => {const s = contentStateRef.current;@@ -1011,6 +1047,9 @@ const ContentState = (props) => {}, [contentState.chunkCount]);const handleBatch = (chunks, sendResponse) => {+ if (videoChunks.current.length === 0) {+ perfMark("Sandbox first-chunk-batch", { batchLen: chunks?.length });+ }if (DEBUG_POSTSTOP)console.debug("[Screenity][Sandbox] handleBatch called", {chunksLen: chunks?.length,@@ -1061,10 +1100,9 @@ const ContentState = (props) => {}})();- return true; // Keep the messaging channel open for the response+ return true;};- // Check Chrome versionuseEffect(() => {const version = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);@@ -1079,9 +1117,10 @@ const ContentState = (props) => {}}, []);- const makeVideoTab = (sendResponse = null, message) => {+ const makeVideoTab = async (sendResponse = null, message) => {if (makeVideoCheck.current) return;makeVideoCheck.current = true;+ perfMark("Sandbox makeVideoTab.enter", { override: message?.override });if (DEBUG_POSTSTOP)console.debug("[Screenity][Sandbox] makeVideoTab invoked", {override: message?.override,@@ -1090,12 +1129,119 @@ const ContentState = (props) => {...prevState,override: message.override,}));- // All chunks received, reconstruct video- checkMemory();- reconstructVideo();+ // clear leftover memoryError without surfacing modal; recording-time toast already fired+ try {+ chrome.storage.local.set({ memoryError: false });+ } catch {}+ let directBlob = null;+ let opfsReadFailed = false;+ let backendRefForThisLoad = null;+ try {+ const { lastRecordingBackendRef } = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ backendRefForThisLoad = lastRecordingBackendRef;+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log(+ "[recorder-opfs][sandbox] makeVideoTab backend",+ lastRecordingBackendRef || { backend: "idb" },+ );+ }+ setContentState((prev) => ({+ ...prev,+ lastRecordingBackend: lastRecordingBackendRef?.backend || "idb",+ }));+ if (lastRecordingBackendRef?.backend === "opfs") {+ const reader = chooseReader(lastRecordingBackendRef);+ await reader.open(lastRecordingBackendRef);+ const { blob: rawBlob } = await reader.readBlob({+ // OPFS file isn't ready yet, recorder still flushing under load.+ // Surface a labeled loading state so the user knows it's progressing.+ onSlowFinalize: () => {+ setContentState((prev) =>+ prev.finalizingRecording ? prev : { ...prev, finalizingRecording: true },+ );+ },+ });+ setContentState((prev) =>+ prev.finalizingRecording ? { ...prev, finalizingRecording: false } : prev,+ );+ await reader.close().catch(() => {});+ // materialize so Blob URL doesn't break when mtime changes+ let blob = rawBlob;+ if (rawBlob && rawBlob.size <= 1_500_000_000) {+ try {+ const buf = await rawBlob.arrayBuffer();+ blob = new Blob([buf], { type: rawBlob.type || "video/mp4" });+ } catch {+ blob = rawBlob;+ }+ }+ if (blob) {+ directBlob = blob;+ diagForward("sandbox-opfs-direct-read", {+ outputBytes: blob.size,+ });+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[recorder-opfs][sandbox] opfs-direct-read-ok", {+ bytes: blob.size,+ });+ }+ } else {+ opfsReadFailed = true;+ }+ }+ } catch (err) {+ opfsReadFailed = true;+ diagForward("sandbox-opfs-direct-read-fail", {+ err: String(err?.message || err).slice(0, 200),+ });+ console.warn(+ "[Screenity][Sandbox] OPFS direct read failed",+ err,+ );+ }++ if (opfsReadFailed && !directBlob) {+ try {+ const idbReader = chooseReader({ backend: "idb" });+ await idbReader.open({ backend: "idb" });+ const { blob, chunkCount } = await idbReader.readBlob();+ await idbReader.close().catch(() => {});+ if (blob && chunkCount > 0) {+ directBlob = blob;+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log(+ "[recorder-opfs][sandbox] OPFS failed but IDB fallback succeeded",+ { bytes: blob.size, chunkCount },+ );+ }+ }+ } catch {}+ if (!directBlob) {+ if (typeof contentStateRef.current?.openModal === "function") {+ contentStateRef.current.openModal(+ chrome.i18n.getMessage("opfsLoadErrorTitle"),+ chrome.i18n.getMessage("opfsLoadErrorDescription"),+ null,+ chrome.i18n.getMessage("permissionsModalDismiss"),+ () => {},+ () => {},+ null,+ null,+ null,+ true,+ false,+ );+ }+ diagForward("sandbox-recording-load-failed", {+ backend: backendRefForThisLoad?.backend || "unknown",+ });+ }+ }+ reconstructVideo(directBlob);- // Timeout: if duration-fix hasn't finished, mark ready so the user- // isn't stuck forever. Don't overwrite an already-fixed webm.+ // mark ready if duration-fix hangs; don't overwrite an already-fixed webmconst safetyCheck = () => {const s = contentStateRef.current;if (DEBUG_POSTSTOP)@@ -1117,11 +1263,10 @@ const ContentState = (props) => {? Date.now() - diagMakeVideoAtRef.current: null,});- if (s?.ready) return; // Fix already completed, nothing to do+ if (s?.ready) return;const complete = s?.chunkCount > 0 && s?.chunkIndex >= s?.chunkCount;if (complete && s?.rawBlob) {- // Keep the fixed webm if it landed between checks.if (s?.webm) {if (DEBUG_RECORDER)console.log(@@ -1148,7 +1293,6 @@ const ContentState = (props) => {chrome.runtime.sendMessage({ type: "recording-complete" });}};- // First check at 30s; if still not ready, final check at 60ssetTimeout(() => {if (!contentStateRef.current?.ready) {safetyCheck();@@ -1207,6 +1351,49 @@ const ContentState = (props) => {}));} else if (message.type === "ping") {sendResponse({ status: "ready" });+ } else if (message.type === "editor-force-close") {+ // BG closes this tab when a new recording starts. the OPFS file+ // backing this editor is about to be deleted, so the unsaved-changes+ // prompt would just block the start flow.+ try {+ window.onbeforeunload = null;+ } catch {}+ sendResponse?.({ ok: true });+ } else if (message.type === "recording-error") {+ // suppress when this editor already loaded; error belongs to a later attempt+ const editorAlreadyLoaded =+ Boolean(contentStateRef.current?.ready) ||+ Boolean(contentStateRef.current?.blob);+ if (editorAlreadyLoaded) return;+ diagForward("sandbox-recording-error-received", {+ error: String(message?.error || "").slice(0, 120),+ why: String(message?.why || "").slice(0, 240),+ errorCode: message?.errorCode || null,+ });+ if (+ !editorErrorShownRef.current &&+ typeof contentStateRef.current?.openModal === "function"+ ) {+ editorErrorShownRef.current = true;+ contentStateRef.current.openModal(+ chrome.i18n.getMessage("opfsLoadErrorTitle"),+ message?.why || chrome.i18n.getMessage("opfsLoadErrorDescription"),+ null,+ chrome.i18n.getMessage("permissionsModalDismiss"),+ () => {},+ () => {},+ null,+ null,+ null,+ true,+ false,+ );+ }+ setContentState((prev) => ({+ ...prev,+ ready: true,+ recordingFailed: true,+ }));} else if (message.type === "new-chunk-tab") {if (DEBUG_POSTSTOP)console.debug("[Screenity][Sandbox] received new-chunk-tab", {@@ -1232,9 +1419,9 @@ const ContentState = (props) => {setContentState((prevContentState) => ({...prevContentState,fallback: true,- noffmpeg: false, // Pretending FFmpeg is loaded (using Mediabunny)+ noffmpeg: false, // mediabunny stands in for FFmpeg hereisFfmpegRunning: false,- editLimit: 3600, // Set high edit limit (1 hour) for recovery mode+ editLimit: MAX_EDIT_LIMIT_S,}));buildBlobFromChunks()@@ -1250,7 +1437,7 @@ const ContentState = (props) => {sendResponse({ status: "error", error: error.message });});- return true; // Keep message port open for async response+ return true;} else if (message.type === "large-recording") {setContentState((prevContentState) => ({...prevContentState,@@ -1271,7 +1458,6 @@ const ContentState = (props) => {ffmpegLoaded: true,processingProgress: 0,}));- // Try to recover chunks.buildBlobFromChunks().then((blob) => {if (!blob) {@@ -1315,14 +1501,14 @@ const ContentState = (props) => {sendResponse({ status: "error", error: error.message });});- return true; // Keep message port open for async response+ return true;} else if (message.type === "fallback-recording") {setContentState((prevContentState) => ({...prevContentState,fallback: true,noffmpeg: false,isFfmpegRunning: true,- editLimit: 3600,+ editLimit: MAX_EDIT_LIMIT_S,}));const shouldGate =launchModeRef.current === "postStop" &&@@ -1337,7 +1523,6 @@ const ContentState = (props) => {ffmpegLoaded: true,processingProgress: 0,}));- // Try to recover chunks.buildBlobFromChunks().then((blob) => {if (!blob) {@@ -1403,7 +1588,6 @@ const ContentState = (props) => {ffmpegLoaded: true,processingProgress: 0,}));- // Try to recover chunks.buildBlobFromChunks().catch(() => {});sendResponse({ status: "error", error: result.error });return;@@ -1441,6 +1625,56 @@ const ContentState = (props) => {],);+ // sandbox self-triggers reconstruct on OPFS; recovery mode is driven by restore-recording+ useEffect(() => {+ let cancelled = false;+ const params = new URLSearchParams(window.location.search || "");+ const isRecoveryMode = params.get("mode") === "recover";+ if (isRecoveryMode) return;++ // 500ms retry in case backendRef hasn't propagated yet+ const attemptSelfTrigger = async (isRetry = false) => {+ try {+ const { lastRecordingBackendRef } = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ if (cancelled) return true;+ if (lastRecordingBackendRef?.backend === "opfs") {+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log(+ "[recorder-opfs][sandbox] self-trigger makeVideoTab for OPFS backend",+ isRetry ? "(retry)" : "",+ );+ }+ makeVideoTab(null, { override: false });+ return true;+ }+ return false;+ } catch (err) {+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.warn(+ "[recorder-opfs][sandbox] self-trigger failed",+ err,+ );+ }+ return false;+ }+ };++ (async () => {+ const hit = await attemptSelfTrigger(false);+ if (!hit && !cancelled) {+ setTimeout(() => {+ if (!cancelled) attemptSelfTrigger(true);+ }, 500);+ }+ })();++ return () => {+ cancelled = true;+ };+ }, []);+useEffect(() => {const messageListener = (message, sender, sendResponse) => {const shouldKeepPortOpen = onChromeMessage(message, sender, sendResponse);@@ -1449,21 +1683,109 @@ const ContentState = (props) => {chrome.runtime.onMessage.addListener(messageListener);- // Storage fallback listener: watch for background writing a `chunks_ready_for:<tabId>` keyconst storageListener = (changes, areaName) => {if (areaName !== "local") return;try {const tabId = tabIdRef.current;+ // BG writes editorRecordingError; sandboxed context can't use runtime.onMessage+ if (changes.editorRecordingError && changes.editorRecordingError.newValue) {+ const payload = changes.editorRecordingError.newValue;+ // suppress when THIS editor already loaded; error belongs to a later attempt+ const editorAlreadyLoaded =+ Boolean(contentStateRef.current?.ready) ||+ Boolean(contentStateRef.current?.blob);+ if (+ !editorAlreadyLoaded &&+ (tabId == null ||+ payload?.sandboxTab == null ||+ payload.sandboxTab === tabId)+ ) {+ diagForward("sandbox-recording-error-received", {+ error: String(payload?.error || "").slice(0, 120),+ why: String(payload?.why || "").slice(0, 240),+ errorCode: payload?.errorCode || null,+ });+ if (+ !editorErrorShownRef.current &&+ typeof contentStateRef.current?.openModal === "function"+ ) {+ editorErrorShownRef.current = true;+ // prefer i18n over raw codes like "REC_STOP_NO_CHUNKS"+ const rawWhy = payload?.why;+ const whyIsCode =+ typeof rawWhy === "string" && /^[A-Z][A-Z0-9_]+$/.test(rawWhy);+ // pipeline failures get copy that says the recording may still be on-device+ const pipelineFailureCodes = new Set([+ "EDITOR_TAB_LOAD_TIMEOUT",+ "EDITOR_CONTENT_SCRIPT_TIMEOUT",+ "EDITOR_MESSAGE_DELIVERY_FAILED",+ ]);+ const isPipelineFailure = pipelineFailureCodes.has(+ payload?.errorCode,+ );+ const isStuckTimeout =+ payload?.errorCode === "EDITOR_STUCK_TIMEOUT";+ let title;+ let description;+ if (isStuckTimeout) {+ title = chrome.i18n.getMessage("editorStuckTitle");+ description = chrome.i18n.getMessage("editorStuckDescription");+ } else if (isPipelineFailure) {+ title = chrome.i18n.getMessage("editorRecoveryFailedTitle");+ description = chrome.i18n.getMessage(+ "editorRecoveryFailedDescription",+ );+ } else {+ title = chrome.i18n.getMessage("opfsLoadErrorTitle");+ description =+ whyIsCode || !rawWhy+ ? chrome.i18n.getMessage("opfsLoadErrorDescription")+ : rawWhy;+ }+ contentStateRef.current.openModal(+ title,+ description,+ chrome.i18n.getMessage("editorStuckTryRecover"),+ chrome.i18n.getMessage("permissionsModalDismiss"),+ () => {+ try {+ chrome.runtime.sendMessage({ type: "restore-recording" });+ } catch {}+ },+ () => {},+ null,+ null,+ null,+ false,+ chrome.i18n.getMessage("editorStuckGetHelp"),+ () => {+ try {+ chrome.runtime.sendMessage({+ type: "report-error",+ source: "editor-recovery-failed",+ errorCode: payload?.errorCode || null,+ });+ } catch {}+ },+ );+ setContentState((prev) => ({+ ...prev,+ ready: true,+ recordingFailed: true,+ }));+ }+ }+ }if (!tabId) return;+ // sandboxed ffmpeg iframes may not expose indexedDB; only run in top+ if (window.top !== window.self) return;const key = `chunks_ready_for:${tabId}`;if (changes[key]) {if (DEBUG_POSTSTOP)console.debug("[Screenity][Sandbox] storage fallback triggered", {key,});- // Ensure IndexedDB is available in this frame before attempting- // to read chunks. Some sandboxed/iframe contexts (ffmpeg iframe)- // may not expose IndexedDB; guard to avoid localforage throwing.+ // sandboxed iframes may not expose IndexedDB; guard against localforage throwingif (!window.indexedDB) {if (DEBUG_POSTSTOP)console.warn(@@ -1472,7 +1794,6 @@ const ContentState = (props) => {return;}- // Asynchronously attempt to build the blob from IndexedDBbuildBlobFromChunks().then((blob) => {if (!blob) {@@ -1504,18 +1825,11 @@ const ContentState = (props) => {}};- // Only attach the storage fallback listener in the top-level window- // (editor/page) — avoid running this inside sandboxed iframes used for- // FFmpeg which may not expose IndexedDB.+ // attach in both contexts; iframe needs editorRecordingError modal trigger,+ // chunks-ready fallback below self-guards on window.top===window.selflet storageListenerAttached = false;- if (window.top === window.self) {- chrome.storage.onChanged.addListener(storageListener);- storageListenerAttached = true;- } else if (DEBUG_POSTSTOP) {- console.debug(- "[Screenity][Sandbox] running inside an iframe; skipping storage fallback listener",- );- }+ chrome.storage.onChanged.addListener(storageListener);+ storageListenerAttached = true;return () => {chrome.runtime.onMessage.removeListener(messageListener);@@ -1526,8 +1840,46 @@ const ContentState = (props) => {}, []);const onMessage = async (event) => {+ if (event.data.type === "recording-error-from-parent") {+ const payload = event.data.payload || {};+ // suppress when this editor already loaded; parent forwards every error+ const editorAlreadyLoaded =+ Boolean(contentStateRef.current?.ready) ||+ Boolean(contentStateRef.current?.blob);+ if (editorAlreadyLoaded) return;+ diagForward("sandbox-recording-error-received-via-parent", {+ error: String(payload?.error || "").slice(0, 120),+ why: String(payload?.why || "").slice(0, 240),+ errorCode: payload?.errorCode || null,+ });+ if (+ !editorErrorShownRef.current &&+ typeof contentStateRef.current?.openModal === "function"+ ) {+ editorErrorShownRef.current = true;+ contentStateRef.current.openModal(+ chrome.i18n.getMessage("opfsLoadErrorTitle"),+ payload?.why || chrome.i18n.getMessage("opfsLoadErrorDescription"),+ null,+ chrome.i18n.getMessage("permissionsModalDismiss"),+ () => {},+ () => {},+ null,+ null,+ null,+ true,+ false,+ );+ setContentState((prev) => ({+ ...prev,+ ready: true,+ recordingFailed: true,+ }));+ }+ return;+ }if (event.data.type === "updated-blob") {- // Discard results from a timed-out or superseded operation.+ // discard timed-out/superseded opsconst msgOpId = event.data._opId;if (msgOpId != null && msgOpId !== opIdRef.current) return;@@ -1539,9 +1891,8 @@ const ContentState = (props) => {const isTopLevel = event.data.topLevel === true;const isFromAudio = event.data.fromAudio === true;- if (isFromAudio) {- // Mid-chain: add-audio succeeded; reencode is still pending.- // Forward the same opId so the reencode result is also validated.+ if (isFromAudio && !event.data.skipReencode) {+ // legacy ffmpeg path needs a follow-up reencode; webcodecs skipssendMessage({type: "reencode-video",blob,@@ -1582,6 +1933,21 @@ const ContentState = (props) => {const video = document.createElement("video");video.preload = "metadata";video.onloadedmetadata = async () => {+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[Screenity][cut-debug] updated-blob received", {+ blobSize: blob?.length ?? blob?.size,+ blobIsBlob: blob instanceof Blob,+ measuredDuration: video.duration,+ previousDuration: contentState.duration,+ isFromAudio,+ wasCropping,+ wasCutting: contentState.cutting,+ wasMuting: contentState.muting,+ wasTrimming: contentState.trimming,+ videoWidth: video.videoWidth,+ videoHeight: video.videoHeight,+ });+ }setContentState((prev) => ({...prev,duration: video.duration,@@ -1612,7 +1978,6 @@ const ContentState = (props) => {const base64 = event.data.base64;const blob = base64ToUint8Array(base64);- // Download the blobconst url = URL.createObjectURL(blob);await requestDownload(url, ".mp4");setContentState((prevContentState) => ({@@ -1623,11 +1988,7 @@ const ContentState = (props) => {}));} else if (event.data.type === "download-gif") {const base64 = event.data.base64;- // const blob = new Blob([base64ToUint8Array(base64)], {- // type: "image/gif",- // });const blob = base64ToUint8Array(base64);- // Download the blobconst url = URL.createObjectURL(blob);await requestDownload(url, ".gif");setContentState((prevContentState) => ({@@ -1637,11 +1998,23 @@ const ContentState = (props) => {downloadingGIF: false,}));} else if (event.data.type === "new-frame") {+ // crop entries leak blob URLs otherwise+ const prevFrame = contentStateRef.current?.frame;+ if (typeof prevFrame === "string" && prevFrame.startsWith("blob:")) {+ try {+ URL.revokeObjectURL(prevFrame);+ } catch {}+ }const url = URL.createObjectURL(event.data.frame);setContentState((prevContentState) => ({...prevContentState,frame: url,isFfmpegRunning: false,+ // Defer the mode flip until the frame is in hand so the cropper+ // doesn't mount over an empty stage (causing a black flash).+ ...(prevContentState.pendingCropEntry+ ? { mode: "crop", pendingCropEntry: false }+ : {}),}));} else if (event.data.type === "ffmpeg-loaded") {setContentState((prevContentState) => ({@@ -1660,34 +2033,22 @@ const ContentState = (props) => {}));console.log("[Screenity][Editor] recording-complete sent from ffmpeg-load-error fallback");chrome.runtime.sendMessage({ type: "recording-complete" });-- // if (!navigator.onLine) {- // setContentState((prevState) => ({- // ...prevState,- // offline: true,- // }));-- // // Try loading ffmpeg again when reconnected to the internet- // window.addEventListener("online", () => {- // setContentState((prevState) => ({- // ...prevState,- // offline: false,- // }));- // contentState.loadFFmpeg();- // });- // }} else if (event.data.type === "ffmpeg-error") {- console.warn("FFmpeg error:", event.data.error);+ console.warn("FFmpeg error:", {+ error: event.data.error,+ errorMessage: event.data.errorMessage,+ opType: event.data.opType,+ errorStack: event.data.errorStack,+ });clearEditOp();- // Fallback: allow playback/download using webm/rawBlob even if conversion fails+ // fall back to webm/rawBlob even if conversion failssetContentState((prev) => {- // If an edit was actively running, surface the failure to the userconst wasEditing = prev.isFfmpegRunning && (prev.cutting || prev.trimming || prev.muting || prev.cropping || prev.reencoding);return {...prev,noffmpeg: true,- ffmpegLoaded: true, // treat as "done trying"+ ffmpegLoaded: true,isFfmpegRunning: false,muting: false,cutting: false,@@ -1703,8 +2064,21 @@ const ContentState = (props) => {});chrome.runtime.sendMessage({ type: "recording-complete" });+ } else if (event.data.type === "audio-too-large") {+ clearEditOp();+ setContentState((prev) => ({+ ...prev,+ isFfmpegRunning: false,+ muting: false,+ cutting: false,+ trimming: false,+ reencoding: false,+ cropping: false,+ processingProgress: 0,+ editErrorType: "audio-too-large",+ }));} else if (event.data.type === "edit-too-long") {- // Too long for in-browser processing — reset so user can retry or trim.+ // Too long for in-browser processing, reset so user can retry or trim.clearEditOp();setContentState((prev) => ({...prev,@@ -1743,9 +2117,6 @@ const ContentState = (props) => {}));} else if (event.data.type === "download-webm") {const base64 = event.data.base64;- // const blob = new Blob([base64ToUint8Array(base64)], {- // type: "video/webm",- // });const blob = base64ToUint8Array(base64);const url = URL.createObjectURL(blob);@@ -1760,18 +2131,26 @@ const ContentState = (props) => {}};- // Listen to PostMessage eventsuseEffect(() => {window.addEventListener("message", onMessage);return () => window.removeEventListener("message", onMessage);}, [onMessage]);+ // covers the race where parent received the storage change before this iframe mounted+ useEffect(() => {+ try {+ window.parent.postMessage(+ { type: "request-recording-error-state" },+ "*",+ );+ } catch {}+ }, []);+const sendMessage = (message) => {window.parent.postMessage(message, "*");};const getBlob = async () => {- // Skip conversion only if Chrome is outdated or recording exceeds edit limitif (contentState.noffmpeg ||(contentState.duration > contentState.editLimit && !contentState.override)@@ -1779,10 +2158,6 @@ const ContentState = (props) => {return;}- // const webmVideo = new Blob([base64ToUint8Array(contentState.base64)], {- // type: "video/webm",- // });-const webmVideo = base64ToUint8Array(contentState.base64);setContentState((prevState) => ({@@ -1792,12 +2167,10 @@ const ContentState = (props) => {}));if (contentState.offline && contentState.ffmpeg === true) {- // Offline (if I need to do anything differently)} else if (!contentState.updateChrome &&(contentState.duration <= contentState.editLimit || contentState.override)) {- // Set isFfmpegRunning to true when starting conversionsetContentState((prevState) => ({...prevState,isFfmpegRunning: true,@@ -1820,24 +2193,20 @@ const ContentState = (props) => {getBlob();}, [contentState.base64, contentState.ffmpeg, contentState.ffmpegLoaded]);- // 30s fallback: if FFmpeg never loads (blocked CDN, worker crash, etc.),- // force recovery mode so the user can still download their recording.+ // 30s fallback for blocked CDN / worker crash; force recovery modeuseEffect(() => {if (!contentState.base64) return;if (!contentState.ffmpeg) return;- if (contentState.ffmpegLoaded) return; // FFmpeg loaded normally — nothing to do- if (contentState.noffmpeg) return; // already in fallback — nothing to do+ if (contentState.ffmpegLoaded) return;+ if (contentState.noffmpeg) return;const timer = setTimeout(() => {- // Re-check via ref in case state changed since the effect ran.const current = contentStateRef.current;if (current.ffmpegLoaded || current.noffmpeg) return;chrome.storage.local.set({ editorLoadTimeoutAt: Date.now() });setContentState((prev) => {- // Double-check inside the updater for concurrent state races.if (prev.ffmpegLoaded || prev.noffmpeg) return prev;- // Also set ready when falling back — getBlob() early-returns- // when noffmpeg is true, so ready would never be set otherwise.+ // also set ready: getBlob early-returns on noffmpeg so ready wouldn't fireconst fallbackWebm = prev.webm || prev.rawBlob;return {...prev,@@ -1863,13 +2232,12 @@ const ContentState = (props) => {setContentState((prevState) => ({...prevState,- isFfmpegRunning: true, // Set isFfmpegRunning to true to indicate that ffmpeg is running+ isFfmpegRunning: true,}));sendMessage({ type: "get-frame", time: 0, blob: contentState.blob });}, [contentState.blob, contentState.ffmpeg, contentState.isFfmpegRunning]);- // Returns the opId to include in outgoing messages for stale-result validation.const beginEditOp = () => {if (editWatchdogRef.current) {clearTimeout(editWatchdogRef.current);@@ -1878,7 +2246,7 @@ const ContentState = (props) => {const id = opIdRef.current;editWatchdogRef.current = setTimeout(() => {editWatchdogRef.current = null;- opIdRef.current += 1; // invalidate any late-arriving result+ opIdRef.current += 1;setContentState((prev) => ({...prev,isFfmpegRunning: false,@@ -1890,11 +2258,10 @@ const ContentState = (props) => {processingProgress: 0,editErrorType: "timeout",}));- }, 5 * 60 * 1000); // 5-minute ceiling+ }, 5 * 60 * 1000);return id;};- // Clears the watchdog when an op completes or fails normally.const clearEditOp = () => {if (editWatchdogRef.current) {clearTimeout(editWatchdogRef.current);@@ -1902,6 +2269,21 @@ const ContentState = (props) => {}};+ const cancelEditOp = () => {+ opIdRef.current += 1;+ clearEditOp();+ setContentState((prev) => ({+ ...prev,+ isFfmpegRunning: false,+ muting: false,+ cutting: false,+ trimming: false,+ reencoding: false,+ cropping: false,+ processingProgress: 0,+ }));+ };+const addAudio = async (videoBlob, audioBlob, volume) => {if (contentState.isFfmpegRunning) return;if (@@ -1939,10 +2321,42 @@ const ContentState = (props) => {!contentState.override)return;+ // undo/redo/keyboard/programmatic restore can leave start>=end; bail clearly+ if (+ !Number.isFinite(contentState.start) ||+ !Number.isFinite(contentState.end) ||+ contentState.start >= contentState.end+ ) {+ setContentState((prev) => ({+ ...prev,+ editErrorType: "invalid-trim-range",+ }));+ return;+ }const sourceBlob = contentState.blob;const opId = beginEditOp();+ if (process.env.SCREENITY_DEV_MODE === "true") {+ console.log("[Screenity][cut-debug] handleTrim dispatch", {+ cut,+ opId,+ sourceBlobSize: sourceBlob?.size,+ sourceBlobType: sourceBlob?.type,+ duration: contentState.duration,+ start: contentState.start,+ end: contentState.end,+ startTime: contentState.start * contentState.duration,+ endTime: contentState.end * contentState.duration,+ expectedOutputDuration: cut+ ? contentState.duration -+ (contentState.end * contentState.duration -+ contentState.start * contentState.duration)+ : contentState.end * contentState.duration -+ contentState.start * contentState.duration,+ });+ }+setContentState((prev) => ({...prev,isFfmpegRunning: true,@@ -1971,6 +2385,17 @@ const ContentState = (props) => {!contentState.override)return;+ if (+ !Number.isFinite(contentState.start) ||+ !Number.isFinite(contentState.end) ||+ contentState.start >= contentState.end+ ) {+ setContentState((prev) => ({+ ...prev,+ editErrorType: "invalid-trim-range",+ }));+ return;+ }const sourceBlob = contentState.blob;const opId = beginEditOp();@@ -2067,18 +2492,35 @@ const ContentState = (props) => {};const requestDownload = async (url, ext) => {+ // rapid double-click would otherwise create two downloads + double-revoke+ if (contentStateRef.current?.downloadInProgress) {+ console.warn("[Screenity] download already in progress, ignoring");+ return;+ }+ setContentState((prev) => ({+ ...prev,+ downloadInProgress: true,+ downloadError: null,+ }));+const rawTitle = contentStateRef.current.title || "Screenity recording";const base = sanitizeDownloadFilename(rawTitle);const filename = `${base}${ext}`;+ let revoked = false;const revoke = () => {+ if (revoked) return;+ revoked = true;try {URL.revokeObjectURL(url);} catch {}+ try {+ setContentState((prev) => ({ ...prev, downloadInProgress: false }));+ } catch {}};- // Brave fallback: send base64 to background for download+ // Brave: route via background for downloadif ((navigator.brave && (await navigator.brave.isBrave())) || false) {const resp = await fetch(url);const blob = await resp.blob();@@ -2100,19 +2542,55 @@ const ContentState = (props) => {const downloadId = await new Promise((resolve, reject) => {chrome.downloads.download({ url, filename, saveAs: true }, (id) => {- if (chrome.runtime.lastError || !id) {- reject(chrome.runtime.lastError || new Error("Download failed"));+ const lastErr = chrome.runtime.lastError;+ // user cancelled Save-As; don't show "Download failed"+ const errMsg = String(lastErr?.message || "");+ if (errMsg.includes("USER_CANCELED") || errMsg.includes("canceled")) {+ revoke();+ resolve(null);+ return;+ }+ if (lastErr || !id) {+ reject(lastErr || new Error("Download failed"));} else {resolve(id);}});});+ if (downloadId == null) return;await new Promise((resolve) => {+ let settled = false;+ const timeoutMs = 10 * 60 * 1000;+ const timeoutId = setTimeout(() => {+ if (settled) return;+ settled = true;+ try {+ chrome.downloads.onChanged.removeListener(handler);+ } catch {}+ revoke();+ console.warn(+ "[Screenity] download status listener timed out, releasing handle",+ { downloadId, filename, timeoutMs },+ );+ // surface error so editor toasts fire; silent resolve would mask as success+ try {+ setContentState((prev) => ({+ ...prev,+ downloadError: "timeout",+ downloadInProgress: false,+ }));+ } catch {}+ resolve();+ }, timeoutMs);+const handler = async (delta) => {if (delta.id !== downloadId || !delta.state) return;const done = () => {+ if (settled) return;+ settled = true;+ clearTimeout(timeoutId);chrome.downloads.onChanged.removeListener(handler);revoke();resolve();@@ -2125,18 +2603,39 @@ const ContentState = (props) => {try {const resp = await fetch(url);const blob = await resp.blob();- await new Promise((res) => {- const reader = new FileReader();- reader.onloadend = () => {+ // sendMessage caps at ~64MB; base64 inflates 4/3, so cap at 30MB+ const BASE64_FALLBACK_MAX_BYTES = 30 * 1024 * 1024;+ if (blob.size > BASE64_FALLBACK_MAX_BYTES) {+ try {+ setContentState((prev) => ({+ ...prev,+ downloadError: "interrupted-too-large",+ downloadInProgress: false,+ }));+ } catch {}+ try {chrome.runtime.sendMessage({- type: "request-download",- base64: reader.result,- title: filename,+ type: "show-toast",+ message: chrome.i18n.getMessage(+ "downloadInterruptedLargeToast",+ ),+ timeout: 8000,});- res();- };- reader.readAsDataURL(blob);- });+ } catch {}+ } else {+ await new Promise((res) => {+ const reader = new FileReader();+ reader.onloadend = () => {+ chrome.runtime.sendMessage({+ type: "request-download",+ base64: reader.result,+ title: filename,+ });+ res();+ };+ reader.readAsDataURL(blob);+ });+ }} finally {done();}@@ -2152,19 +2651,9 @@ const ContentState = (props) => {});};- // Re-mux a fragmented MP4 blob to a standard (non-fragmented) MP4 blob- // via container copy (no re-decode, no re-encode). The recorder writes- // fMP4 for crash safety, but users expect a standard MP4 on download- // for universal compatibility (QuickTime seeking, editors, etc.).- // Typical cost: ~1-3 seconds for a 10-min recording.- //- // Uses BufferTarget despite the memory cost. fastStart: false is NOT a- // pure append-only write: mediabunny writes an mdat header placeholder- // up front, then samples, then patches the mdat size at the end via a- // positioned write. A naive stream-to-blob pipe drops those positioned- // patches, producing a file with an empty mdat and orphan samples that- // no player can open. A positioned StreamTarget would need a random-- // access backing store (a buffer), so BufferTarget is the right tool.+ // fMP4 -> standard MP4 via container copy. QuickTime/editors need fastStart.+ // BufferTarget is required: fastStart:false patches the mdat size with a+ // positioned write at the end, which a stream-to-blob pipe would drop.const remuxFragmentedToStandardMp4 = async (fragmentedBlob, onProgress) => {const input = new Input({formats: ALL_FORMATS,@@ -2188,12 +2677,7 @@ const ContentState = (props) => {return new Blob([target.buffer], { type: "video/mp4" });};- // Route the remux through an offscreen document that spawns a dedicated- // worker and writes the output to OPFS via a sync access handle. Keeps- // peak RAM near zero regardless of recording length, and avoids the- // 2 GB ArrayBuffer ceiling that BufferTarget hits on very long clips.- // Falls back silently: if any hop fails, the caller tries the in-sandbox- // BufferTarget path instead.+ // OPFS sync access handle in an offscreen worker; bypasses BufferTarget's 2 GB capconst remuxViaOffscreenOpfs = async (fragmentedBlob, onProgress) => {const requestId =(typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"@@ -2220,14 +2704,8 @@ const ContentState = (props) => {};chrome.runtime.onMessage.addListener(progressListener);- // Transport via OPFS rather than passing the Blob through- // chrome.runtime.sendMessage. Chrome's structured clone for extension- // messaging is lossy for Blobs crossing the service worker: the Blob- // arrives as a plain object and BlobSource rejects it with- // "blob must be a Blob.". Writing the input to OPFS first and passing- // a filename (string) sidesteps the issue entirely; the worker reads- // back via navigator.storage.getDirectory() in its own context.- const inputFileName = `remux-in-${requestId}.mp4`;+ // sendMessage's structured clone is lossy for Blobs across the SW+ // (BlobSource rejects with "blob must be a Blob"); transport via OPFS+filenameconst outputFileName = `remux-${requestId}.mp4`;let opfsDir;try {@@ -2239,16 +2717,52 @@ const ContentState = (props) => {);}+ // reuse OPFS input when size matches; edits diverge so fall back to staging+ let stagedInputFileName = null;+ let inputFileName;try {- // Stage the input in OPFS. createWritable is async and streams to- // disk without blocking the main thread for the full duration.- const inputHandle = await opfsDir.getFileHandle(inputFileName, {- create: true,- });- const writable = await inputHandle.createWritable();- await writable.write(fragmentedBlob);- await writable.close();- devLog("staged-input-in-opfs", { inputFileName });+ const { lastRecordingBackendRef } = await chrome.storage.local.get([+ "lastRecordingBackendRef",+ ]);+ if (+ lastRecordingBackendRef?.backend === "opfs" &&+ typeof lastRecordingBackendRef.fileName === "string" &&+ lastRecordingBackendRef.fileName.length > 0+ ) {+ try {+ const handle = await opfsDir.getFileHandle(+ lastRecordingBackendRef.fileName,+ );+ const opfsFile = await handle.getFile();+ if (+ fragmentedBlob &&+ typeof fragmentedBlob.size === "number" &&+ opfsFile.size === fragmentedBlob.size+ ) {+ inputFileName = lastRecordingBackendRef.fileName;+ devLog("reused-opfs-input", { inputFileName });+ } else {+ devLog("opfs-input-size-mismatch-skipping-reuse", {+ opfsBytes: opfsFile.size,+ blobBytes: fragmentedBlob?.size,+ });+ }+ } catch {}+ }+ } catch {}++ try {+ if (!inputFileName) {+ stagedInputFileName = `remux-in-${requestId}.mp4`;+ const inputHandle = await opfsDir.getFileHandle(stagedInputFileName, {+ create: true,+ });+ const writable = await inputHandle.createWritable();+ await writable.write(fragmentedBlob);+ await writable.close();+ inputFileName = stagedInputFileName;+ devLog("staged-input-in-opfs", { inputFileName });+ }const response = await chrome.runtime.sendMessage({type: "remux-request",@@ -2268,18 +2782,20 @@ const ContentState = (props) => {return outputBlob;} finally {chrome.runtime.onMessage.removeListener(progressListener);- // Input file is no longer needed once the worker finished (or failed).- try {- await opfsDir.removeEntry(inputFileName).catch(() => {});- } catch {}- // Output file is left in place; the Blob we just returned may still- // be streaming to chrome.downloads. The worker's age-based sweep- // cleans it up on the next remux.+ // never delete the recording itself+ if (stagedInputFileName) {+ try {+ await opfsDir.removeEntry(stagedInputFileName).catch(() => {});+ } catch {}+ }+ // output left in place; worker's age-based sweep cleans next remux}};const download = async () => {- if (contentState.isFfmpegRunning || contentState.downloading) return;+ // ref: rapid clicks fire before state propagates+ const latest = contentStateRef.current || contentState;+ if (latest.isFfmpegRunning || latest.downloading) return;setContentState((prev) => ({...prev,@@ -2298,7 +2814,8 @@ const ContentState = (props) => {const remuxStartedAt = Date.now();let remuxedBlob = null;let remuxPath = null;- // Tier 1: offscreen + OPFS. Flat memory, works for any recording size.++ // tier 1: offscreen+OPFS, bounded memorytry {diagForward("remux-offscreen-start", { inputBytes: inputSize });remuxedBlob = await remuxViaOffscreenOpfs(@@ -2315,8 +2832,7 @@ const ContentState = (props) => {});}- // Tier 2: in-sandbox BufferTarget. Costs ~recording size in RAM; hits- // a 2 GB ArrayBuffer ceiling on very long clips.+ // tier 2: in-sandbox BufferTarget, capped at ~2 GBif (!remuxedBlob) {try {remuxedBlob = await remuxFragmentedToStandardMp4(@@ -2326,7 +2842,10 @@ const ContentState = (props) => {remuxPath = "buffer-target";diagForward("remux-buffer-target-ok", { inputBytes: inputSize });} catch (err) {- console.warn("[Screenity] buffer-target remux failed, falling back", err);+ console.warn(+ "[Screenity] buffer-target remux failed, falling back",+ err,+ );diagForward("remux-buffer-target-fail", {inputBytes: inputSize,err: String(err?.message || err).slice(0, 200),@@ -2335,9 +2854,10 @@ const ContentState = (props) => {}const remuxDurationMs = Date.now() - remuxStartedAt;+ const finalPath = remuxPath || "fmp4-fallback";if (process.env.SCREENITY_DEV_MODE === "true") {console.log("[remux][sandbox] summary", {- path: remuxPath || "fmp4-fallback",+ path: finalPath,durationMs: remuxDurationMs,inputBytes: inputSize,outputBytes: remuxedBlob?.size || 0,@@ -2346,7 +2866,7 @@ const ContentState = (props) => {setContentState((prev) => ({...prev,lastDownloadInfo: {- path: remuxPath || "fmp4-fallback",+ path: finalPath,durationMs: remuxDurationMs,inputBytes: inputSize,outputBytes: remuxedBlob?.size || 0,@@ -2366,15 +2886,11 @@ const ContentState = (props) => {path: remuxPath,});} else {- // Tier 3: serve the fMP4 as-is. Plays in Chrome/VLC/most modern- // players; some older editors may have seeking quirks.throw new Error("both-remux-paths-failed");}} catch (err) {console.error("MP4 download failed:", err);- // Fallback: serve the fMP4 as-is so the user doesn't lose the- // recording if re-mux fails. Chrome/VLC/most modern players read it- // fine; older tools may struggle with seeking.+ // tier 3: serve fMP4 as-is so the user doesn't lose the recordingtry {const url = URL.createObjectURL(contentState.blob);await requestDownload(url, ".mp4");@@ -2418,7 +2934,6 @@ const ContentState = (props) => {return;}- // ➜ ADD THIS: If untouched + already webm → skip FFmpeg entirelyif (!contentState.hasBeenEdited && contentState.webm) {const url = URL.createObjectURL(contentState.webm);await requestDownload(url, ".webm");@@ -2459,7 +2974,16 @@ const ContentState = (props) => {if (contentState.isFfmpegRunning || contentState.downloading) {return;}- if (contentState.duration > 30) return;+ if (contentState.duration > 30) {+ try {+ chrome.runtime.sendMessage({+ type: "show-toast",+ message: chrome.i18n.getMessage("downloadGIFTooLongToast"),+ timeout: 6000,+ });+ } catch {}+ return;+ }setContentState((prevState) => ({...prevState,@@ -2506,6 +3030,7 @@ const ContentState = (props) => {contentState.createBackup = createBackup;contentState.restoreBackup = restoreBackup;contentState.clearBackup = clearBackup;+ contentState.cancelEditOp = cancelEditOp;return (<ContentStateContext.Provider value={[contentState, setContentState]}>@@ -2515,6 +3040,7 @@ const ContentState = (props) => {setContentState={setContentState}contentStateRef={contentStateRef}lastDownloadInfo={contentState.lastDownloadInfo}+ lastRecordingBackend={contentState.lastRecordingBackend}/>)}</ContentStateContext.Provider>diff --git a/src/pages/Sandbox/layout/editor/AudioNav.js b/src/pages/Sandbox/layout/editor/AudioNav.jsindex 1dbd114..4aa85c3 100644--- a/src/pages/Sandbox/layout/editor/AudioNav.js+++ b/src/pages/Sandbox/layout/editor/AudioNav.js@@ -8,6 +8,7 @@ const AudioNav = () => {const [contentState, setContentState] = useContext(ContentStateContext);const handleCancel = () => {+ contentState.cancelEditOp();setContentState((prev) => ({...prev,mode: "player",@@ -19,6 +20,12 @@ const AudioNav = () => {};const handleRevert = () => {+ const prevSnap = {+ blob: contentState.blob,+ start: contentState.start,+ end: contentState.end,+ pendingAudio: contentState.pendingAudio,+ };setContentState((prev) => ({...prev,blob: contentState.originalBlob,@@ -26,6 +33,12 @@ const AudioNav = () => {end: 1,pendingAudio: null,}));+ contentState.openToast?.(+ chrome.i18n.getMessage("sandboxToastReverted"),+ () => {+ setContentState((p) => ({ ...p, ...prevSnap }));+ },+ );};const saveChanges = async () => {@@ -48,6 +61,10 @@ const AudioNav = () => {await contentState.waitForUpdatedBlob?.();contentState.clearBackup();+ contentState.openToast?.(+ chrome.i18n.getMessage("sandboxToastSaved"),+ () => contentState.undo?.(),+ );};return (@@ -71,7 +88,6 @@ const AudioNav = () => {<buttonclassName="button simpleButton blackButton"onClick={handleCancel}- disabled={contentState.isFfmpegRunning}>{chrome.i18n.getMessage("sandboxEditorCancelButton")}</button>diff --git a/src/pages/Sandbox/layout/editor/AudioUI.js b/src/pages/Sandbox/layout/editor/AudioUI.jsindex 3947039..93c4fe2 100644--- a/src/pages/Sandbox/layout/editor/AudioUI.js+++ b/src/pages/Sandbox/layout/editor/AudioUI.js@@ -1,21 +1,18 @@import React, { useState, useEffect, useContext, useRef } from "react";import styles from "../../styles/player/_RightPanel.module.scss";-// Componentsimport Dropdown from "../../components/editor/Dropdown";import * as Slider from "@radix-ui/react-slider";import Switch from "../../components/editor/Switch";-// Iconsconst URL = "/assets/";import { ReactSVG } from "react-svg";-// Context-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const AudioUI = (props) => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const [audio, setAudio] = useState(null);const prevBlob = useRef(null);const inputRef = useRef(null);@@ -33,15 +30,13 @@ const AudioUI = (props) => {const handleAudio = async (e) => {const file = e.target.files[0];- // Check if the file is an audio fileif (!file.type.includes("audio") || file.size === 0) {return;}- // Use rawBlob (webm from recovery) if blob (mp4) is not available yet+ // Fall back to rawBlob (webm from recovery) if mp4 blob isn't ready.const videoBlob =contentState.blob || contentState.rawBlob || contentState.webm;- //contentState.addAudio(videoBlob, file, contentState.volume);setAudio(file);setContentState((prev) => ({...prev,@@ -69,6 +64,29 @@ const AudioUI = (props) => {return (<div>+ {contentState.editErrorType === "audio-too-large" && (+ <div className={styles.alert}>+ <div className={styles.buttonLeft}>+ <ReactSVG src={URL + "editor/icons/alert.svg"} />+ </div>+ <div className={styles.buttonMiddle}>+ <div className={styles.buttonTitle}>+ {chrome.i18n.getMessage("editAudioTooLargeTitle")}+ </div>+ <div className={styles.buttonDescription}>+ {chrome.i18n.getMessage("editAudioTooLargeDescription")}+ </div>+ </div>+ <div+ className={styles.buttonRight}+ onClick={() =>+ setContentState((prev) => ({ ...prev, editErrorType: null }))+ }+ >+ {chrome.i18n.getMessage("permissionsModalDismiss")}+ </div>+ </div>+ )}<div className={styles.section}><div className={styles.sectionTitle}>Audio upload</div><input@@ -150,7 +168,6 @@ const AudioUI = (props) => {onValueChange={(newValue) => {setContentState((prevContentState) => ({...prevContentState,- // Round to the nearest integervolume: Math.round(newValue) / 100,}));}}@@ -163,13 +180,6 @@ const AudioUI = (props) => {</Slider.Root></div><Switch />- {/* <button- className={["button", "primaryButton", styles.updateButton].join(" ")}- onClick={updateAudio}- disabled={contentState.isFfmpegRunning || !audio}- >- {chrome.i18n.getMessage("sandboxAudioUpdateButton")}- </button> */}</div></div>);diff --git a/src/pages/Sandbox/layout/editor/CropNav.js b/src/pages/Sandbox/layout/editor/CropNav.jsindex a5c6fac..0abb021 100644--- a/src/pages/Sandbox/layout/editor/CropNav.js+++ b/src/pages/Sandbox/layout/editor/CropNav.js@@ -1,13 +1,14 @@import React, { useContext } from "react";import styles from "../../styles/edit/_EditorNav.module.scss";-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const URL = "/assets/";const CropNav = () => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const handleCancel = () => {+ contentState.cancelEditOp();setContentState((prevContentState) => ({...prevContentState,mode: "player",@@ -24,6 +25,16 @@ const CropNav = () => {};const handleRevert = () => {+ const prev = {+ blob: contentState.blob,+ start: contentState.start,+ end: contentState.end,+ width: contentState.width,+ height: contentState.height,+ left: contentState.left,+ top: contentState.top,+ fromCropper: contentState.fromCropper,+ };setContentState((prevContentState) => ({...prevContentState,blob: contentState.originalBlob,@@ -35,6 +46,12 @@ const CropNav = () => {top: 0,fromCropper: false,}));+ contentState.openToast?.(+ chrome.i18n.getMessage("sandboxToastReverted"),+ () => {+ setContentState((p) => ({ ...p, ...prev }));+ },+ );};const saveChanges = async () => {@@ -47,12 +64,15 @@ const CropNav = () => {setContentState((prev) => ({...prev,- // mode: "player",fromCropper: true,hasTempChanges: false,}));contentState.clearBackup();+ contentState.openToast?.(+ chrome.i18n.getMessage("sandboxToastSaved"),+ () => contentState.undo?.(),+ );};return (@@ -76,7 +96,6 @@ const CropNav = () => {<buttonclassName="button simpleButton blackButton"onClick={handleCancel}- disabled={contentState.isFfmpegRunning}>{chrome.i18n.getMessage("sandboxEditorCancelButton")}</button>diff --git a/src/pages/Sandbox/layout/editor/EditorNav.js b/src/pages/Sandbox/layout/editor/EditorNav.jsindex 93690a8..03d3ac6 100644--- a/src/pages/Sandbox/layout/editor/EditorNav.js+++ b/src/pages/Sandbox/layout/editor/EditorNav.js@@ -1,13 +1,14 @@import React, { useContext } from "react";import styles from "../../styles/edit/_EditorNav.module.scss";-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const URL = "/assets/";const EditorNav = () => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const handleCancel = () => {+ contentState.cancelEditOp();setContentState((prevContentState) => ({...prevContentState,mode: "player",@@ -19,12 +20,26 @@ const EditorNav = () => {};const handleRevert = () => {+ const prevBlob = contentState.blob;+ const prevStart = contentState.start;+ const prevEnd = contentState.end;setContentState((prevContentState) => ({...prevContentState,blob: contentState.originalBlob,start: 0,end: 1,}));+ contentState.openToast?.(+ chrome.i18n.getMessage("sandboxToastReverted"),+ () => {+ setContentState((prev) => ({+ ...prev,+ blob: prevBlob,+ start: prevStart,+ end: prevEnd,+ }));+ },+ );};const saveChanges = async () => {@@ -39,6 +54,10 @@ const EditorNav = () => {}));contentState.clearBackup();+ contentState.openToast?.(+ chrome.i18n.getMessage("sandboxToastSaved"),+ () => contentState.undo?.(),+ );};return (@@ -62,7 +81,6 @@ const EditorNav = () => {<buttonclassName="button simpleButton blackButton"onClick={handleCancel}- disabled={contentState.isFfmpegRunning}>{chrome.i18n.getMessage("sandboxEditorCancelButton")}</button>diff --git a/src/pages/Sandbox/layout/player/RightPanel.js b/src/pages/Sandbox/layout/player/RightPanel.jsindex 813ac24..f383c67 100644--- a/src/pages/Sandbox/layout/player/RightPanel.js+++ b/src/pages/Sandbox/layout/player/RightPanel.js@@ -8,15 +8,13 @@ import { ReactSVG } from "react-svg";const URL ="chrome-extension://" + chrome.i18n.getMessage("@@extension_id") + "/assets/";-// Componentsimport CropUI from "../editor/CropUI";import AudioUI from "../editor/AudioUI";-// Context-import { ContentStateContext } from "../../context/ContentState"; // Import the ContentState context+import { ContentStateContext } from "../../context/ContentState";const RightPanel = () => {- const [contentState, setContentState] = useContext(ContentStateContext); // Access the ContentState context+ const [contentState, setContentState] = useContext(ContentStateContext);const contentStateRef = useRef(contentState);const consoleErrorRef = useRef([]);@@ -30,7 +28,6 @@ const RightPanel = () => {contentStateRef.current = contentState;}, [contentState]);- // Returns a context-specific "not available" label for disabled buttonsconst getNotAvailableLabel = () => {if (contentState.fallback && contentState.noffmpeg && contentState.editLimit === 0) {return chrome.i18n.getMessage("notAvailableLongRecording");@@ -64,7 +61,7 @@ const RightPanel = () => {saveDrive: false,}));}- // On success, saveDrive is reset by the "saved-to-drive" message from background+ // On success, saveDrive is reset by the "saved-to-drive" message from background.};const handleDriveError = (err) => {@@ -76,7 +73,7 @@ const RightPanel = () => {};if (contentState.noffmpeg || !contentState.mp4ready || !contentState.blob) {- // Prefer the duration-fixed webm blob over rebuilding from raw chunks+ // Prefer duration-fixed webm over rebuilding from raw chunks.const fixedWebm = contentState.webm;if (fixedWebm && fixedWebm instanceof Blob && fixedWebm.size > 0) {const reader = new FileReader();@@ -113,7 +110,6 @@ const RightPanel = () => {.catch(handleDriveError);}} else {- // Blob to base64const reader = new FileReader();reader.onload = () => {const dataUrl = reader.result;@@ -170,13 +166,6 @@ const RightPanel = () => {mode: "edit",dragInteracted: false,}));-- if (!contentState.hasBeenEdited) {- setContentState((prevContentState) => ({- ...prevContentState,- hasBeenEdited: true,- }));- }};const handleCrop = () => {@@ -190,21 +179,22 @@ const RightPanel = () => {contentState.createBackup();- if (!contentState.frame && !contentState.isFfmpegRunning) {- contentState.getFrame();+ // If the frame isn't cached yet, request it and defer the mode switch+ // until "new-frame" arrives, otherwise the cropper mounts over a blank+ // stage and there's a black flash for the round-trip duration.+ if (!contentState.frame) {+ setContentState((prevContentState) => ({+ ...prevContentState,+ pendingCropEntry: true,+ }));+ if (!contentState.isFfmpegRunning) contentState.getFrame();+ return;}setContentState((prevContentState) => ({...prevContentState,mode: "crop",}));-- if (!contentState.hasBeenEdited) {- setContentState((prevContentState) => ({- ...prevContentState,- hasBeenEdited: true,- }));- }};const handleAddAudio = async () => {@@ -221,16 +211,9 @@ const RightPanel = () => {...prevContentState,mode: "audio",}));-- if (!contentState.hasBeenEdited) {- setContentState((prevContentState) => ({- ...prevContentState,- hasBeenEdited: true,- }));- }};- // Download best available blob: edited MP4 → fixed WebM → raw WebM.+ // Best available blob: edited MP4 → fixed WebM → raw WebM.const handleDownloadOriginal = () => {const s = contentStateRef.current;const source = s.blob || s.webm || s.rawBlob;@@ -274,10 +257,8 @@ const RightPanel = () => {const ext = blob.type.includes("mp4") ? "mp4" : "webm";const filename = `raw-recording.${ext}`;- // Base64-via-BG is the most reliable path from a sandboxed page —- // works in Brave, works when blob-URL downloads are restricted, and- // doesn't depend on chrome.downloads being accessible from here.- // This is the escape hatch, so prioritize reliability over speed.+ // base64-via-BG fallback: works in Brave and when blob-URL downloads+ // are restricted, doesn't depend on chrome.downloads from here.const fallbackViaBackground = async () => {const base64 = await new Promise((resolve, reject) => {const reader = new FileReader();@@ -310,9 +291,8 @@ const RightPanel = () => {reject(err);}});- // chrome.downloads.onChanged can tell us if the download was- // interrupted (not user-cancel). Same pattern as the main download- // flow in ContentState.jsx.+ // Detect interrupted (non-user-cancel) downloads; matches the+ // main download flow in ContentState.jsx.const interruptHandler = async (delta) => {if (delta.id !== downloadId || !delta.state) return;if (@@ -518,7 +498,6 @@ const RightPanel = () => {<divclassName={styles.buttonRight}onClick={() => {- //chrome.runtime.sendMessage({ type: "upgrade-info" });if (typeof contentState.openModal === "function") {contentState.openModal(chrome.i18n.getMessage("overLimitModalTitle"),@@ -850,10 +829,9 @@ const RightPanel = () => {</div>)}{(() => {- // WebCodecs / fast-recorder path produces a native MP4 blob.- // Downloading it is just a blob-URL anchor click — no ffmpeg,- // no re-encoding — so the editLimit and noffmpeg gates don't- // apply. Detect via blob MIME and unblock accordingly.+ // WebCodecs path produces a native MP4 blob; download is a+ // blob-URL anchor click, no ffmpeg/re-encode, so editLimit+ // and noffmpeg gates don't apply.const isNativeMp4 =contentState.blob?.type === "video/mp4";const mp4Disabled = isNativeMp4@@ -937,7 +915,15 @@ const RightPanel = () => {role="button"className={styles.button}onClick={() => {- if (!contentState.mp4ready) return;+ // disabled on a div is meaningless; gate click manually.+ if (+ contentState.isFfmpegRunning ||+ contentState.duration > 30 ||+ !contentState.mp4ready ||+ contentState.noffmpeg+ ) {+ return;+ }contentState.downloadGIF();}}disabled={@@ -976,7 +962,6 @@ const RightPanel = () => {</div></div><div className={styles.section}>- {/* Create an advanced section with a button to send logs and to download raw video file as a backup */}<div className={styles.sectionTitle}>{chrome.i18n.getMessage("sandboxAdvancedTitle")}</div>diff --git a/src/pages/Sandbox/recorderStorage/chooseReader.js b/src/pages/Sandbox/recorderStorage/chooseReader.jsnew file mode 100644index 0000000..a3d5515--- /dev/null+++ b/src/pages/Sandbox/recorderStorage/chooseReader.js@@ -0,0 +1,13 @@+import { IdbChunkReader } from "./idbChunkReader";+import { OpfsChunkReader } from "./opfsChunkReader";++export const chooseReader = (backendRef) => {+ const backend = backendRef?.backend || "idb";+ switch (backend) {+ case "opfs":+ return new OpfsChunkReader();+ case "idb":+ default:+ return new IdbChunkReader();+ }+};diff --git a/src/pages/Sandbox/recorderStorage/chunkReaderInterface.js b/src/pages/Sandbox/recorderStorage/chunkReaderInterface.jsnew file mode 100644index 0000000..dfb953c--- /dev/null+++ b/src/pages/Sandbox/recorderStorage/chunkReaderInterface.js@@ -0,0 +1,11 @@+// ChunkReader interface for the editor.+// IdbChunkReader iterates chunksStore. OpfsChunkReader returns the OPFS+// file as a Blob. SwRelayReader serves the legacy ffmpeg editor (null-+// origin) since it can't reach IDB/OPFS directly.+// chooseReader picks based on backendRef from the writer's close().+// ReadResult: { blob, byteSize, chunkCount }+export const ChunkReaderInterface = {+ async open(backendRef) {},+ async readBlob() {},+ async close() {},+};diff --git a/src/pages/Sandbox/recorderStorage/idbChunkReader.js b/src/pages/Sandbox/recorderStorage/idbChunkReader.jsnew file mode 100644index 0000000..f6a7d5c--- /dev/null+++ b/src/pages/Sandbox/recorderStorage/idbChunkReader.js@@ -0,0 +1,56 @@+// IDB ChunkReader. Iterates chunksStore, sorts by (timestamp, index).+import localforage from "localforage";++localforage.config({+ driver: localforage.INDEXEDDB,+ name: "screenity",+ version: 1,+});++const chunksStore = localforage.createInstance({+ name: "chunks",+});++export class IdbChunkReader {+ constructor() {+ this._opened = false;+ }++ async open(_backendRef) {+ await chunksStore.ready();+ this._opened = true;+ }++ async readBlob() {+ if (!this._opened) {+ throw new Error("idb-chunk-reader-not-opened");+ }+ const items = [];+ await chunksStore.iterate((value) => {+ items.push(value);+ return undefined;+ });+ // Tiebreak by index: WebCodecs-path chunks share timestamp; index+ // is the real byte order.+ items.sort((a, b) => {+ const dt = (a.timestamp ?? 0) - (b.timestamp ?? 0);+ if (dt !== 0) return dt;+ return (a.index ?? 0) - (b.index ?? 0);+ });+ const parts = items.map((c) =>+ c.chunk instanceof Blob ? c.chunk : new Blob([c.chunk]),+ );+ const byteSize = parts.reduce((s, p) => s + (p?.size || 0), 0);+ const inferredType = parts[0]?.type || "video/mp4";+ const blob = parts.length+ ? new Blob(parts, { type: inferredType })+ : new Blob([], { type: inferredType });+ return { blob, byteSize, chunkCount: parts.length };+ }++ async close() {+ this._opened = false;+ }+}++export { chunksStore as idbChunksStore };diff --git a/src/pages/Sandbox/recorderStorage/opfsChunkReader.js b/src/pages/Sandbox/recorderStorage/opfsChunkReader.jsnew file mode 100644index 0000000..33a70f9--- /dev/null+++ b/src/pages/Sandbox/recorderStorage/opfsChunkReader.js@@ -0,0 +1,96 @@+// 4 KB rejects empty/header-only files without blocking 2-3s legit clips+// (MP4 ftyp box alone is 28 bytes).+export const MIN_VALID_RECORDING_BYTES = 4096;++// editor can open before the writer's final flush lands (muxer trailer+// + moov can take hundreds of ms, or seconds on huge recordings). reading+// mid-flush produces a truncated blob, so wait for the writer to set+// lastRecordingFinalizedFileName, or for the backend ref to be replaced+// by a newer recording (which means our writer is gone).+const FINALIZE_POLL_INTERVAL_MS = 250;+const FINALIZE_HARD_TIMEOUT_MS = 60_000;+// don't flash the "finalizing" UI for the common <1s case+const SLOW_FINALIZE_NOTIFY_MS = 600;++const wait = (ms) => new Promise((r) => setTimeout(r, ms));++export class OpfsChunkReader {+ constructor() {+ this._fileName = null;+ this._opened = false;+ }++ async open(backendRef) {+ const name = backendRef?.fileName;+ if (!name) {+ throw new Error("opfs-chunk-reader-no-filename");+ }+ this._fileName = name;+ this._opened = true;+ }++ async _readRefState() {+ try {+ const { lastRecordingBackendRef, lastRecordingFinalizedFileName } =+ await chrome.storage.local.get([+ "lastRecordingBackendRef",+ "lastRecordingFinalizedFileName",+ ]);+ return {+ sameFile: lastRecordingBackendRef?.fileName === this._fileName,+ finalized: lastRecordingFinalizedFileName === this._fileName,+ };+ } catch {+ return { sameFile: false, finalized: false };+ }+ }++ async readBlob({ onSlowFinalize } = {}) {+ if (!this._opened) {+ throw new Error("opfs-chunk-reader-not-opened");+ }+ const dir = await navigator.storage.getDirectory();+ const handle = await dir.getFileHandle(this._fileName);++ let { sameFile, finalized } = await this._readRefState();++ // !sameFile means a newer recording replaced the ref (our writer is+ // gone, or we're opening an orphan file). sameFile && finalized means+ // the writer closed cleanly. otherwise wait for one of those.+ if (sameFile && !finalized) {+ const startedAt = Date.now();+ let notified = false;+ while (true) {+ if (Date.now() - startedAt > FINALIZE_HARD_TIMEOUT_MS) break;+ if (!notified && Date.now() - startedAt > SLOW_FINALIZE_NOTIFY_MS) {+ try {+ onSlowFinalize?.();+ } catch {}+ notified = true;+ }+ await wait(FINALIZE_POLL_INTERVAL_MS);+ ({ sameFile, finalized } = await this._readRefState());+ if (finalized || !sameFile) break;+ }+ }++ const file = await handle.getFile();+ if (file.size < MIN_VALID_RECORDING_BYTES) {+ const err = new Error(+ `opfs-file-too-small: ${file.size} bytes < ${MIN_VALID_RECORDING_BYTES}`,+ );+ err.code = "opfs-file-too-small";+ throw err;+ }+ const blob = new Blob([file], { type: "video/mp4" });+ return {+ blob,+ byteSize: blob.size,+ chunkCount: 1,+ };+ }++ async close() {+ this._opened = false;+ }+}diff --git a/src/pages/Sandbox/styles/global/_app.scss b/src/pages/Sandbox/styles/global/_app.scssindex bd58c1b..820360e 100644--- a/src/pages/Sandbox/styles/global/_app.scss+++ b/src/pages/Sandbox/styles/global/_app.scss@@ -582,3 +582,97 @@ button {min-width: 100px;}}++.ToastViewport {+ --viewport-padding: 25px;+ position: fixed;+ bottom: 0;+ right: 0;+ left: 0;+ margin: auto !important;+ display: flex;+ flex-direction: column;+ padding: var(--viewport-padding);+ gap: 14px;+ max-width: 100vw;+ width: fit-content;+ list-style: none;+ z-index: 2147483647;+ outline: none;+ pointer-events: none;+}++.ToastRoot {+ background-color: $color-text-primary;+ color: $color-text-contrast;+ border-radius: $container-border-radius;+ box-shadow: hsl(206 22% 7% / 35%) 0px 10px 38px -10px,+ hsl(206 22% 7% / 20%) 0px 10px 20px -15px;+ padding: 10px 14px;+ display: flex;+ flex-direction: row;+ gap: 8px;+ font-size: 15px;+ line-height: 1.5;+ max-width: min(480px, calc(100vw - 50px));+ overflow: hidden;+ justify-content: center;+ align-items: center;+ word-wrap: break-word;+ overflow-wrap: anywhere;+ pointer-events: all;+}++.ToastRoot[data-state="open"] {+ animation: screenitySandboxToastIn 150ms cubic-bezier(0.16, 1, 0.3, 1);+}+.ToastRoot[data-state="closed"] {+ animation: screenitySandboxToastOut 100ms ease-in;+}++.ToastTitle {+ color: $color-text-contrast;+ font-family: $font-medium;+}++@keyframes screenitySandboxToastIn {+ from {+ transform: translateY(calc(100% + var(--viewport-padding)));+ }+ to {+ transform: translateY(0);+ }+}+@keyframes screenitySandboxToastOut {+ from {+ opacity: 1;+ }+ to {+ opacity: 0;+ }+}++.ToastAction {+ color: $color-text-contrast;+ font-family: $font-medium;+ text-align: right;+}++.ToastEscButton {+ font-family: $font-medium;+ color: $color-text-contrast;+ background-color: #51515F;+ border: none;+ border-radius: $container-border-radius;+ padding: 0 12px;+ height: 24px;+ font-size: 13px;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ transition: background-color 120ms ease;+}+.ToastEscButton:hover {+ background-color: #6B6B79;+}diff --git a/src/pages/utils/buildDiagnosticZip.js b/src/pages/utils/buildDiagnosticZip.jsindex f139b26..9509e38 100644--- a/src/pages/utils/buildDiagnosticZip.js+++ b/src/pages/utils/buildDiagnosticZip.js@@ -5,6 +5,41 @@import JSZip from "jszip";import { getStartFlowTrace } from "./startFlowTrace";+// Last line of defense before the diag zip leaves the user's machine:+// strip user-home paths and URL query strings/fragments (recording IDs,+// signed-URL tokens, OAuth tokens).+const PII_REPLACEMENTS = [+ [/\/Users\/[^/\s"]+/g, "/Users/[redacted]"],+ [/\/home\/[^/\s"]+/g, "/home/[redacted]"],+ [/[A-Z]:\\Users\\[^\\\s"]+/g, "C:\\Users\\[redacted]"],+ [/(https?:\/\/[^\s?#"'<>]+)\?[^\s#"'<>]*/g, "$1?[query-redacted]"],+ [/(https?:\/\/[^\s#"'<>]+)#[^\s"'<>]*/g, "$1#[fragment-redacted]"],+ [/(chrome-extension:\/\/[^\s?#"'<>]+)\?[^\s#"'<>]*/g, "$1?[query-redacted]"],+ [/(chrome-extension:\/\/[^\s#"'<>]+)#[^\s"'<>]*/g, "$1#[fragment-redacted]"],+];++const redactString = (s) => {+ let out = s;+ for (const [pat, repl] of PII_REPLACEMENTS) {+ out = out.replace(pat, repl);+ }+ return out;+};++const redactPii = (value, depth = 0) => {+ if (depth > 12) return value;+ if (typeof value === "string") return redactString(value);+ if (Array.isArray(value)) return value.map((v) => redactPii(v, depth + 1));+ if (value && typeof value === "object") {+ const out = {};+ for (const [k, v] of Object.entries(value)) {+ out[k] = redactPii(v, depth + 1);+ }+ return out;+ }+ return value;+};+const FAST_RECORDER_KEYS = ["fastRecorderBeta","fastRecorderDecision",@@ -21,6 +56,12 @@ const FAST_RECORDER_KEYS = ["lastWebCodecsFailureAt","lastWebCodecsFailureCode","lastFailedValidation",+ "webcodecsConstructSnapshot",+ "recorderStartTimings",+ "countdownFinishedAt",+ "lastStartRecordingCaller",+ "lastCountdownFinishedDecision",+ "lastStartAfterCountdown",];export const buildDiagnosticZip = async ({@@ -29,14 +70,50 @@ export const buildDiagnosticZip = async ({} = {}) => {const userAgent = navigator.userAgent;- // Parallel fetches from background- const [platformInfo, diagData, fastRecorderData] = await Promise.all([- chrome.runtime.sendMessage({ type: "get-platform-info" }),- chrome.runtime.sendMessage({ type: "get-diagnostic-log" }),- new Promise((resolve) =>- chrome.storage.local.get(FAST_RECORDER_KEYS, resolve),- ),- ]);+ const [+ platformInfo,+ diagData,+ fastRecorderData,+ lifecycleData,+ perfTimeline,+ uploadTelemetry,+ ] = await Promise.all([+ chrome.runtime.sendMessage({ type: "get-platform-info" }),+ chrome.runtime.sendMessage({ type: "get-diagnostic-log" }),+ new Promise((resolve) =>+ chrome.storage.local.get(FAST_RECORDER_KEYS, resolve),+ ),+ new Promise((resolve) =>+ chrome.storage.local.get(["lifecycleLog"], (r) =>+ resolve(Array.isArray(r?.lifecycleLog) ? r.lifecycleLog : []),+ ),+ ),+ new Promise((resolve) =>+ // perfMarks writes per-context (perfTimeline.BG, etc) to avoid+ // write races; read all and merge by timestamp.+ chrome.storage.local.get(null, (all) => {+ const merged = [];+ for (const k of Object.keys(all || {})) {+ if (k === "perfTimeline" || k.startsWith("perfTimeline.")) {+ const arr = all[k];+ if (Array.isArray(arr)) merged.push(...arr);+ }+ }+ merged.sort((a, b) => (a.t ?? 0) - (b.t ?? 0));+ resolve(merged);+ }),+ ),+ new Promise((resolve) =>+ // CloudRecorder writes locally before posting; captures state when offline.+ chrome.storage.local.get(["cloudUploadTelemetryEvents"], (r) =>+ resolve(+ Array.isArray(r?.cloudUploadTelemetryEvents)+ ? r.cloudUploadTelemetryEvents+ : [],+ ),+ ),+ ),+ ]);const manifestVersion = chrome.runtime.getManifest().version;const now = new Date();@@ -44,7 +121,6 @@ export const buildDiagnosticZip = async ({const zip = new JSZip();- // manifest.json — export metadatazip.file("manifest.json",JSON.stringify({@@ -56,7 +132,6 @@ export const buildDiagnosticZip = async ({}),);- // environment.jsonzip.file("environment.json",JSON.stringify({@@ -71,7 +146,6 @@ export const buildDiagnosticZip = async ({}),);- // config.json — recording settings + caller-specific extraszip.file("config.json",JSON.stringify({@@ -80,9 +154,12 @@ export const buildDiagnosticZip = async ({}),);- // sessions.json — diagnostic session timeline with derived hintsif (diagData?.log) {- const annotated = JSON.parse(JSON.stringify(diagData.log));+ // structuredClone avoids the stringification round-trip on large logs.+ const annotated =+ typeof structuredClone === "function"+ ? structuredClone(diagData.log)+ : JSON.parse(JSON.stringify(diagData.log));if (annotated.sessions) {for (const session of annotated.sessions) {if (!session.events?.length) continue;@@ -99,27 +176,37 @@ export const buildDiagnosticZip = async ({if (hints.length > 0) session.hints = hints;}}- zip.file("sessions.json", JSON.stringify(annotated));+ zip.file("sessions.json", JSON.stringify(redactPii(annotated)));}- // errors.json — consolidated error-state keysif (diagData?.errors) {- zip.file("errors.json", JSON.stringify(diagData.errors));+ zip.file("errors.json", JSON.stringify(redactPii(diagData.errors)));}- // storage-flags.json — current boolean/numeric state flagsif (diagData?.flags) {- zip.file("storage-flags.json", JSON.stringify(diagData.flags));+ zip.file("storage-flags.json", JSON.stringify(redactPii(diagData.flags)));}- // start-flow-trace.jsontry {const trace = await getStartFlowTrace();if (trace) {zip.file("start-flow-trace.json", JSON.stringify(trace));}- } catch {- // best effort+ } catch {}++ if (Array.isArray(lifecycleData) && lifecycleData.length > 0) {+ zip.file("lifecycle-log.json", JSON.stringify(lifecycleData));+ }++ if (Array.isArray(perfTimeline) && perfTimeline.length > 0) {+ zip.file("perf-timeline.json", JSON.stringify(perfTimeline));+ }++ if (Array.isArray(uploadTelemetry) && uploadTelemetry.length > 0) {+ zip.file(+ "upload-telemetry.json",+ JSON.stringify(redactPii(uploadTelemetry)),+ );}const blob = await zip.generateAsync({ type: "blob" });diff --git a/src/pages/utils/buildSupportContext.js b/src/pages/utils/buildSupportContext.jsindex d98e6e2..1ca6f3f 100644--- a/src/pages/utils/buildSupportContext.js+++ b/src/pages/utils/buildSupportContext.js@@ -1,6 +1,6 @@/*** Builds a URL-safe support-context object for Tally form prefills.- * No URLs, tokens, page content, or blobs — only sanitized technical metadata.+ * No URLs, tokens, page content, or blobs, only sanitized technical metadata.*/const MAX_ERR_LEN = 120;@@ -14,6 +14,11 @@ const sanitizeError = (err) => {return str.replace(/https?:\/\/[^\s)]+/gi, "[url]").replace(/chrome-extension:\/\/[^\s)]+/gi, "[ext]")+ // strip user-home paths from stack traces so support payloads don't+ // leak the OS account name+ .replace(/\/Users\/[^/\s)]+/g, "/Users/[redacted]")+ .replace(/\/home\/[^/\s)]+/g, "/home/[redacted]")+ .replace(/[A-Z]:\\Users\\[^\\\s)]+/g, "C:\\Users\\[redacted]").slice(0, MAX_ERR_LEN);};@@ -30,19 +35,17 @@ const shortBrowser = () => {export const buildSupportContext = async (opts = {}) => {const ctx = {};- // ---- always included ----ctx.v = chrome.runtime.getManifest().version;ctx.lang = chrome.i18n.getMessage("@@ui_locale") || "unknown";ctx.br = shortBrowser();try {const info = await chrome.runtime.getPlatformInfo();- ctx.os = info.os; // "mac", "win", "linux", "cros", etc.+ ctx.os = info.os;} catch {ctx.os = "unknown";}- // Human-readable platform for Tally choice prefillconst platformMap = { mac: "macOS", win: "Windows", linux: "Linux", cros: "ChromeOS" };ctx.platform = platformMap[ctx.os] || "Other";@@ -53,7 +56,6 @@ export const buildSupportContext = async (opts = {}) => {ctx.src = opts.source;}- // ---- recording / error state (opt-in) ----if (opts.includeRecordingState) {try {const keys = [@@ -86,14 +88,12 @@ export const buildSupportContext = async (opts = {}) => {if (store.recordingAttemptId)ctx.attemptId = store.recordingAttemptId;- // Last diagnostic session outcome (compact — just the outcome string)if (store.diagnosticLog?.sessions?.length) {const last =store.diagnosticLog.sessions[store.diagnosticLog.sessions.length - 1];if (last?.outcome) ctx.lastOutcome = last.outcome;- // Detect incomplete editor handoff (editor opened but never loaded)if (last?.events?.length) {const hasEditorOpen = last.events.some((ev) => ev.e === "editor-open" && ev.d?.type === "editorwebcodecs",@@ -104,23 +104,18 @@ export const buildSupportContext = async (opts = {}) => {if (hasEditorOpen && !hasEditorReady) ctx.editorHandoff = "incomplete";}}- } catch {- // storage read failed — continue without recording state- }+ } catch {}}- // ---- explicit error overrides (from error modal "Get help" button) ----if (opts.errorCode) ctx.errCode = opts.errorCode;if (opts.errorWhy) ctx.lastErr = sanitizeError(opts.errorWhy);- // ---- support code (short human-readable reference) ----if (ctx.attemptId) {const hash = ctx.attemptId.replace(/[^a-z0-9]/gi, "").slice(-4).toUpperCase();const date = new Date().toISOString().slice(0, 10).replace(/-/g, "");ctx.supportCode = `SCR-${hash}-${date}`;}- // ---- user info (only when explicitly provided) ----if (opts.user) {if (opts.user.name) ctx.name = opts.user.name;if (opts.user.email) ctx.email = opts.user.email;diff --git a/src/pages/utils/buildSupportDebugInfo.js b/src/pages/utils/buildSupportDebugInfo.jsindex 546651d..e7283e8 100644--- a/src/pages/utils/buildSupportDebugInfo.js+++ b/src/pages/utils/buildSupportDebugInfo.js@@ -1,6 +1,6 @@/*** Clipboard-friendly debug summary for support.- * Same privacy rules as buildSupportContext — no URLs, tokens, or user content.+ * Same privacy rules as buildSupportContext, no URLs, tokens, or user content.*/import { makeSupportCode } from "./errorCodes";@@ -42,7 +42,6 @@ export const buildSupportDebugInfo = async (opts = {}) => {const os = await shortOS();const ts = new Date().toISOString();- // Pull relevant state from storagelet store = {};try {store = await chrome.storage.local.get([@@ -57,14 +56,11 @@ export const buildSupportDebugInfo = async (opts = {}) => {"streamLifecycleLog","diagnosticLog",]);- } catch {- // storage read failed — continue with defaults- }+ } catch {}const attemptId = store.recordingAttemptId || null;const supportCode = makeSupportCode(attemptId);- // Determine error code: prefer explicit, fall back to storedconst errorCode =opts.errorCode ||store.lastRecordingError?.errorCode ||@@ -74,13 +70,11 @@ export const buildSupportDebugInfo = async (opts = {}) => {opts.errorWhy || store.lastRecordingError?.why || "");- // Recording modeconst recType = store.recordingType || "unknown";const fastRec = store.fastRecorderInUse ? "active" : "off";const fastOff = store.fastRecorderDisabledReason || null;const sub = store.isSubscribed ? "pro" : "free";- // Last diagnostic session outcome + editor handoff checklet lastOutcome = null;let editorHandoffIncomplete = false;if (store.diagnosticLog?.sessions?.length) {@@ -98,7 +92,6 @@ export const buildSupportDebugInfo = async (opts = {}) => {}}- // Build the text blockconst lines = [`Screenity Debug Info`,`====================`,@@ -129,7 +122,6 @@ export const buildSupportDebugInfo = async (opts = {}) => {if (attemptId) lines.push(`Ref: ${attemptId}`);lines.push(`Time: ${ts}`);- // Start-flow trace timelinetry {const trace = await getStartFlowTrace();if (trace) {@@ -140,9 +132,7 @@ export const buildSupportDebugInfo = async (opts = {}) => {lines.push(timeline);}}- } catch {- // best effort- }+ } catch {}return lines.join("\n");};diff --git a/src/pages/utils/diagnosticLog.js b/src/pages/utils/diagnosticLog.jsindex 55294f9..61ba050 100644--- a/src/pages/utils/diagnosticLog.js+++ b/src/pages/utils/diagnosticLog.js@@ -5,10 +5,10 @@const MAX_SESSIONS = 5;const MAX_EVENTS = 100;-const FLUSH_EVERY_N = 10; // flush to storage every N events+const FLUSH_EVERY_N = 10;-let _log = null; // in-memory mirror of diagnosticLog-let _dirty = 0; // events written since last flush+let _log = null;+let _dirty = 0;const now = () => Date.now();@@ -26,15 +26,13 @@ const flush = async () => {_dirty = 0;try {await chrome.storage.local.set({ diagnosticLog: _log });- } catch {- // SW may be shutting down — best-effort- }+ } catch {}};const maybeFlush = () => {_dirty += 1;if (_dirty >= FLUSH_EVERY_N) {- flush(); // fire-and-forget+ flush();}};@@ -63,7 +61,6 @@ export const initDiagSession = async (config = {}) => {_log.sessions.push(session);- // Trim to MAX_SESSIONSwhile (_log.sessions.length > MAX_SESSIONS) {_log.sessions.shift();}@@ -75,7 +72,7 @@ export const initDiagSession = async (config = {}) => {/** Append an event to the current open session. */export const diagEvent = (eventType, data) => {const s = currentSession();- if (!s) return; // no open session+ if (!s) return;const entry = {t: now() - s.startedAt,@@ -87,7 +84,6 @@ export const diagEvent = (eventType, data) => {s.events.push(entry);- // Ring-buffer trimwhile (s.events.length > MAX_EVENTS) {s.events.shift();}@@ -190,6 +186,33 @@ export const getStorageFlags = async () => {"lowStorageAbortAt","lowStorageAbortChunks","editorLoadTimeoutAt",+ "lastRestartFlow",+ "restartFlowHistory",+ "lastFirstChunkWatchdog",+ // Cloud recorder lifecycle (Pro flow). Surfaces the recorder session+ // state machine + the message-flow flags needed to debug double-prompt+ // / silent-close scenarios.+ "recorderSession",+ "recorderPipelineState",+ "lastStartRecordingTabMessage",+ "lastRecordingBackendRef",+ "screenTrackLog",+ "cloudRestartPhase",+ "cloudRestartHistory",+ "tabPreferred",+ "tabStreamIdCache",+ "region",+ "customRegion",+ "multiMode",+ "multiProjectId",+ "multiSceneCount",+ "multiLastSceneId",+ "sceneId",+ "sceneIdStatus",+ "projectId",+ "isLoggedIn",+ "isSubscribed",+ "proSubscription",];try {return await chrome.storage.local.get(keys);diff --git a/src/pages/utils/errorCodes.js b/src/pages/utils/errorCodes.jsindex 998e31e..4a4dadc 100644--- a/src/pages/utils/errorCodes.js+++ b/src/pages/utils/errorCodes.js@@ -1,43 +1,31 @@-/**- * Error codes for recording flows.- *- * Codes are stored in `lastRecordingError.code` and flow through diagnostics- * and support context. They never contain URLs, page content, or user data.- */+// recording-flow error codes. land in lastRecordingError.code and the+// diagnostic / support payloads. never carry URLs or user data.-// -- Recording Start ---export const REC_START_PERM = "REC_START_PERM"; // permission denied-export const REC_START_STREAM = "REC_START_STREAM"; // getUserMedia / getDisplayMedia failed-export const REC_START_CODEC = "REC_START_CODEC"; // MediaRecorder or WebCodecs init failed-export const REC_START_REGION = "REC_START_REGION"; // region/crop target setup failed-export const REC_START_TAB = "REC_START_TAB"; // tab capture or message routing failed-export const REC_START_TIMEOUT = "REC_START_TIMEOUT"; // start flow timed out-export const REC_START_CANCEL = "REC_START_CANCEL"; // user cancelled the capture picker-export const REC_START_NOT_READY = "REC_START_NOT_READY"; // recorder tab not ready (likely discarded)-export const REC_START_NO_STREAM_MSG = "REC_START_NO_STREAM_MSG"; // start requested but streaming-data message never arrived from SW--// -- Recording Runtime ---export const REC_RUN_STREAM_END = "REC_RUN_STREAM_END"; // stream ended unexpectedly-export const REC_RUN_MEMORY = "REC_RUN_MEMORY"; // memory/quota pressure--// -- Recording Stop ---export const REC_STOP_CHUNKS = "REC_STOP_CHUNKS"; // chunk delivery failed-export const REC_STOP_EDITOR = "REC_STOP_EDITOR"; // editor tab open failed--// -- Drive ---export const DRV_AUTH = "DRV_AUTH"; // auth failed-export const DRV_FOLDER = "DRV_FOLDER"; // folder operation failed-export const DRV_UPLOAD = "DRV_UPLOAD"; // file upload failed--// -- Fallback ---export const UNKNOWN = "UNKNOWN";+export const REC_START_PERM = "REC_START_PERM";+export const REC_START_STREAM = "REC_START_STREAM";+export const REC_START_CODEC = "REC_START_CODEC";+export const REC_START_REGION = "REC_START_REGION";+export const REC_START_TAB = "REC_START_TAB";+export const REC_START_TIMEOUT = "REC_START_TIMEOUT";+export const REC_START_CANCEL = "REC_START_CANCEL";+export const REC_START_NOT_READY = "REC_START_NOT_READY";+export const REC_START_NO_STREAM_MSG = "REC_START_NO_STREAM_MSG";++export const REC_RUN_STREAM_END = "REC_RUN_STREAM_END";+export const REC_RUN_MEMORY = "REC_RUN_MEMORY";-// -- Classifier --+export const REC_STOP_CHUNKS = "REC_STOP_CHUNKS";+export const REC_STOP_EDITOR = "REC_STOP_EDITOR";-// Patterns that strongly indicate the user explicitly cancelled the picker.-// Note: "aborterror" is intentionally NOT here — Chrome throws AbortError for-// picker dismissal but also for unrelated abort scenarios. We only classify-// AbortError as cancel when the caller passes the "cancel-modal" hint.+export const DRV_AUTH = "DRV_AUTH";+export const DRV_FOLDER = "DRV_FOLDER";+export const DRV_UPLOAD = "DRV_UPLOAD";++export const UNKNOWN = "UNKNOWN";++// "aborterror" is intentionally NOT here: Chrome throws AbortError for+// picker dismissal AND unrelated abort scenarios. AbortError is only a+// cancel when the caller passes the "cancel-modal" hint.const CANCEL_PATTERNS = ["cancelled","canceled",@@ -113,17 +101,16 @@ const REGION_PATTERNS = [/*** Classify an error string into an error code.*- * @param {string} errorStr — raw error message- * @param {string} [errorType] — optional hint ("stream-error", "cancel-modal", etc.)+ * @param {string} errorStr , raw error message+ * @param {string} [errorType], optional hint ("stream-error", "cancel-modal", etc.)* @returns {string} one of the exported error code constants*/export const classifyError = (errorStr = "", errorType = "") => {const lower = String(errorStr).toLowerCase();const typeLower = String(errorType).toLowerCase();- // Explicit cancel — either the caller flagged it or the message clearly says so.- // AbortError only counts as cancel when the caller confirms via "cancel-modal",- // since Chrome reuses AbortError for non-cancel scenarios too.+ // AbortError only counts as cancel via the "cancel-modal" hint; Chrome+ // reuses AbortError for non-cancel scenarios.if (typeLower === "cancel-modal") {return REC_START_CANCEL;}@@ -131,7 +118,6 @@ export const classifyError = (errorStr = "", errorType = "") => {return REC_START_CANCEL;}- // Permission deniedif (PERM_PATTERNS.some((p) => lower.includes(p))) {return REC_START_PERM;}@@ -140,42 +126,35 @@ export const classifyError = (errorStr = "", errorType = "") => {return REC_START_NO_STREAM_MSG;}- // Recorder not ready (stream ref missing, likely tab discarded during countdown)+ // Recorder tab discarded during countdown.if (lower.includes("recording not ready") || lower.includes("screen stream is missing")) {return REC_START_NOT_READY;}- // Stream acquisitionif (STREAM_PATTERNS.some((p) => lower.includes(p))) {return REC_START_STREAM;}- // Codec / recorder initif (CODEC_PATTERNS.some((p) => lower.includes(p))) {return REC_START_CODEC;}- // Timeoutif (TIMEOUT_PATTERNS.some((p) => lower.includes(p))) {return REC_START_TIMEOUT;}- // Region / cropif (REGION_PATTERNS.some((p) => lower.includes(p))) {return REC_START_REGION;}- // Stream ended (runtime, not start)if (typeLower === "stream-ended" || lower.includes("stream ended")) {return REC_RUN_STREAM_END;}- // Tab routingif (TAB_PATTERNS.some((p) => lower.includes(p))) {return REC_START_TAB;}- // Memory / storageif (lower.includes("memory") ||lower.includes("quota") ||@@ -186,8 +165,8 @@ export const classifyError = (errorStr = "", errorType = "") => {return REC_RUN_MEMORY;}- // Bare AbortError without a cancel-modal hint — this is ambiguous, so treat- // it as a stream-level failure rather than assuming user intent.+ // Bare AbortError without cancel-modal hint is ambiguous; treat as+ // stream-level failure rather than assuming user intent.if (lower.includes("aborterror")) {return REC_START_STREAM;}@@ -195,9 +174,6 @@ export const classifyError = (errorStr = "", errorType = "") => {return UNKNOWN;};-// -- Helpers ----/** Short ID for a recording attempt (no crypto dependency). */export const makeRecordingAttemptId = () => {const ts = Date.now().toString(36);const rand = Math.random().toString(36).slice(2, 8);diff --git a/src/pages/utils/lifecycleLog.js b/src/pages/utils/lifecycleLog.jsnew file mode 100644index 0000000..88b4008--- /dev/null+++ b/src/pages/utils/lifecycleLog.js@@ -0,0 +1,69 @@+// cross-session ring buffer of lifecycle events for state-bleed bugs+// (recordingTab left set, region stuck, etc). per-session detail lives+// in diagnosticLog. ~500 entries in chrome.storage.local, dumped in the+// diag zip. writes serialized through a per-context promise chain.+// entry: { ts, src, ev, data? }++const STORAGE_KEY = "lifecycleLog";+const MAX_EVENTS = 500;++// Serialized so back-to-back lifecycle() calls don't race the read-modify-write.+let _writeChain = Promise.resolve();++const summarize = (data) => {+ if (data === null || data === undefined) return undefined;+ if (typeof data !== "object") return data;+ try {+ const json = JSON.stringify(data);+ if (json.length > 500) {+ return { _truncated: true, preview: json.slice(0, 480) };+ }+ return data;+ } catch {+ return { _serializeError: true };+ }+};++/** Append a lifecycle event. Returns a promise resolved after persist. */+export const lifecycleEvent = async (src, ev, data = null) => {+ const entry = {+ ts: Date.now(),+ src: String(src || "unknown"),+ ev: String(ev || "unknown"),+ };+ const summarized = summarize(data);+ if (summarized !== undefined) entry.data = summarized;++ _writeChain = _writeChain.then(async () => {+ try {+ const result = await chrome.storage.local.get([STORAGE_KEY]);+ const current = Array.isArray(result?.[STORAGE_KEY])+ ? result[STORAGE_KEY]+ : [];+ current.push(entry);+ while (current.length > MAX_EVENTS) current.shift();+ await chrome.storage.local.set({ [STORAGE_KEY]: current });+ } catch {}+ });+ return _writeChain;+};++/** Fire-and-forget convenience. */+export const lifecycle = (src, ev, data = null) => {+ lifecycleEvent(src, ev, data).catch(() => {});+};++/** For diag zip / inspection. Returns the current buffer. */+export const getLifecycleLog = async () => {+ try {+ const result = await chrome.storage.local.get([STORAGE_KEY]);+ return Array.isArray(result?.[STORAGE_KEY]) ? result[STORAGE_KEY] : [];+ } catch {+ return [];+ }+};++/** Wait for any pending writes to flush. */+export const flushLifecycleLog = async () => {+ await _writeChain;+};diff --git a/src/pages/utils/mediaDeviceFallback.js b/src/pages/utils/mediaDeviceFallback.jsindex 03ce4f8..b55b768 100644--- a/src/pages/utils/mediaDeviceFallback.js+++ b/src/pages/utils/mediaDeviceFallback.js@@ -2,8 +2,16 @@ const DEVICE_ID_ERRORS = new Set(["OverconstrainedError", "NotFoundError"]);const isDeviceIdError = (err) => err && DEVICE_ID_ERRORS.has(err.name);-const cloneConstraints = (constraints) =>- JSON.parse(JSON.stringify(constraints || {}));+// Constraints can contain nested objects (deviceId.exact) so a deep clone is required.+const cloneConstraints = (constraints) => {+ const src = constraints || {};+ if (typeof structuredClone === "function") {+ try {+ return structuredClone(src);+ } catch {}+ }+ return JSON.parse(JSON.stringify(src));+};const updateConstraintsDeviceId = (constraints, kind, deviceId) => {if (!constraints || !deviceId) return;diff --git a/src/pages/utils/perfMarks.js b/src/pages/utils/perfMarks.jsnew file mode 100644index 0000000..ba72fc8--- /dev/null+++ b/src/pages/utils/perfMarks.js@@ -0,0 +1,238 @@+// dev-only perf instrumentation; DCE'd to a no-op in prod via DefinePlugin.+// usage: perfMark("name", { ... }) or const end = perfSpan("name"); end({ ... })+// read via console "[perf]" lines, dumpPerf() in BG devtools, or perf-timeline.json.++const DEV = process.env.SCREENITY_DEV_MODE === "true";++const noop = () => {};+const noopSpan = () => () => {};+const noopAsyncArr = async () => [];++const buildDevImpl = () => {+ // Per-context storage keys avoid the read-modify-write race that loses+ // marks when contexts share a single key. dumpPerf merges at read time.+ const STORAGE_KEY_BASE = "perfTimeline";+ const MAX_EVENTS = 300;+ const FLUSH_DEBOUNCE_MS = 250;++ const detectContext = () => {+ try {+ if (typeof window === "undefined") return "BG";+ const path = (window.location && window.location.pathname) || "";+ if (path.endsWith("/region.html")) return "Region";+ if (path.endsWith("/recorder.html")) return "Recorder";+ if (path.endsWith("/cloudrecorder.html")) return "CloudRecorder";+ if (path.endsWith("/sandbox.html")) return "Sandbox";+ if (path.endsWith("/editor.html")) return "Editor";+ if (path.endsWith("/editorwebcodecs.html")) return "EditorWebCodecs";+ if (path.endsWith("/editorviewer.html")) return "EditorViewer";+ if (path.endsWith("/offscreenrecorder.html")) return "OffscreenRecorder";+ if (path.endsWith("/audiooffscreen.html")) return "AudioOffscreen";+ if (path.endsWith("/remuxoffscreen.html")) return "RemuxOffscreen";+ if (path.endsWith("/backup.html")) return "Backup";+ if (path.endsWith("/popup.html")) return "Popup";+ return "Content";+ } catch {+ return "unknown";+ }+ };++ const CTX = detectContext();+ const STORAGE_KEY = `${STORAGE_KEY_BASE}.${CTX}`;+ const localBuf = [];+ let lastMarkPerfNow = null;+ let pendingFlush = null;+ let writeChain = Promise.resolve();+ let cachedSessionId = null;++ const refreshSessionId = () => {+ try {+ chrome.storage.local+ .get(["recordingAttemptId"])+ .then((res) => {+ cachedSessionId = res?.recordingAttemptId || cachedSessionId;+ })+ .catch(() => {});+ } catch {}+ };++ const flushNow = () => {+ if (!localBuf.length) return;+ const batch = localBuf.splice(0, localBuf.length);+ writeChain = writeChain+ .then(async () => {+ try {+ const res = await chrome.storage.local.get([STORAGE_KEY]);+ const cur = Array.isArray(res?.[STORAGE_KEY]) ? res[STORAGE_KEY] : [];+ for (const e of batch) cur.push(e);+ while (cur.length > MAX_EVENTS) cur.shift();+ await chrome.storage.local.set({ [STORAGE_KEY]: cur });+ } catch {}+ })+ .catch(() => {});+ };++ const scheduleFlush = () => {+ if (pendingFlush) return;+ pendingFlush = setTimeout(() => {+ pendingFlush = null;+ flushNow();+ }, FLUSH_DEBOUNCE_MS);+ };++ const emit = (label, meta) => {+ if (!cachedSessionId) refreshSessionId();+ const now = Date.now();+ const perfNow =+ typeof performance !== "undefined" ? performance.now() : null;+ const delta =+ perfNow !== null && lastMarkPerfNow !== null+ ? Math.round(perfNow - lastMarkPerfNow)+ : null;+ lastMarkPerfNow = perfNow;+ const entry = {+ t: now,+ perfNow,+ ctx: CTX,+ label,+ sessionId: cachedSessionId || null,+ };+ if (meta && typeof meta === "object") {+ try {+ const json = JSON.stringify(meta);+ entry.meta = json.length > 400 ? { _truncated: true } : meta;+ } catch {+ entry.meta = { _serializeError: true };+ }+ }+ localBuf.push(entry);+ try {+ const tag = delta !== null ? `+${delta}ms` : "";+ if (meta) {+ console.debug("[perf]", CTX, label, tag, meta);+ } else {+ console.debug("[perf]", CTX, label, tag);+ }+ } catch {}+ scheduleFlush();+ };++ const perfMarkImpl = (label, meta = null) => {+ try {+ emit(label, meta);+ } catch {}+ };++ const perfSpanImpl = (label, startMeta = null) => {+ const startPerf =+ typeof performance !== "undefined" ? performance.now() : null;+ try {+ emit(`${label}.start`, startMeta);+ } catch {}+ return (endMeta = null) => {+ try {+ const dur =+ startPerf !== null && typeof performance !== "undefined"+ ? Math.round(performance.now() - startPerf)+ : null;+ emit(+ `${label}.end`,+ endMeta+ ? { ...endMeta, durMs: dur }+ : dur !== null+ ? { durMs: dur }+ : null,+ );+ } catch {}+ };+ };++ const perfResetImpl = (sessionId = null) => {+ try {+ cachedSessionId = sessionId;+ lastMarkPerfNow = null;+ chrome.storage.local.get(null).then((all) => {+ const cleared = {};+ for (const k of Object.keys(all || {})) {+ if (k === STORAGE_KEY_BASE || k.startsWith(`${STORAGE_KEY_BASE}.`)) {+ cleared[k] = [];+ }+ }+ if (Object.keys(cleared).length > 0) {+ chrome.storage.local.set(cleared).catch(() => {});+ }+ }).catch(() => {});+ } catch {}+ };++ const getPerfTimelineImpl = async () => {+ try {+ const all = await chrome.storage.local.get(null);+ const merged = [];+ for (const k of Object.keys(all || {})) {+ if (k === STORAGE_KEY_BASE || k.startsWith(`${STORAGE_KEY_BASE}.`)) {+ const arr = all[k];+ if (Array.isArray(arr)) merged.push(...arr);+ }+ }+ merged.sort((a, b) => (a.t ?? 0) - (b.t ?? 0));+ return merged;+ } catch {+ return [];+ }+ };++ const formatTimeline = (entries, sessionId = null) => {+ const filtered = sessionId+ ? entries.filter((e) => e.sessionId === sessionId)+ : entries;+ if (!filtered.length) return "[perf] no entries";+ const t0 = filtered[0].t;+ const lines = ["[perf] timeline (relative to first mark):"];+ let prevT = t0;+ for (const e of filtered) {+ const rel = e.t - t0;+ const delta = e.t - prevT;+ prevT = e.t;+ const meta = e.meta ? " " + JSON.stringify(e.meta) : "";+ lines.push(+ `+${String(rel).padStart(6)}ms (Δ${String(delta).padStart(5)}ms) ${e.ctx.padEnd(8)} ${e.label}${meta}`,+ );+ }+ return lines.join("\n");+ };++ try {+ const target =+ typeof globalThis !== "undefined"+ ? globalThis+ : typeof self !== "undefined"+ ? self+ : null;+ if (target) {+ target.dumpPerf = async (sessionId = null) => {+ const entries = await getPerfTimelineImpl();+ const out = formatTimeline(entries, sessionId);+ console.log(out);+ return entries;+ };+ target.resetPerf = perfResetImpl;+ }+ } catch {}++ refreshSessionId();++ return {+ perfMark: perfMarkImpl,+ perfSpan: perfSpanImpl,+ perfReset: perfResetImpl,+ getPerfTimeline: getPerfTimelineImpl,+ };+};++const impl = DEV ? buildDevImpl() : null;++export const perfMark = DEV ? impl.perfMark : noop;+export const perfSpan = DEV ? impl.perfSpan : noopSpan;+export const perfReset = DEV ? impl.perfReset : noop;+export const getPerfTimeline = DEV ? impl.getPerfTimeline : noopAsyncArr;diff --git a/webpack.config.js b/webpack.config.jsindex f156157..f7f9d8c 100755--- a/webpack.config.js+++ b/webpack.config.js@@ -8,6 +8,19 @@ const TerserPlugin = require("terser-webpack-plugin");const isDev = env.NODE_ENV === "development";+// SCREENITY_BS_BUILD=1: slim build for BrowserStack inline-CRX size limit.+// drops post-recording UI + WASM. recording + camera paths preserved.+const isBsBuild = process.env.SCREENITY_BS_BUILD === "1";+const BS_DROPPED_ENTRIES = new Set([+ "editorviewer",+ "cloudrecorder",+ "backup",+ "download",+ "waveform",+ "setup",+ "playground",+]);+const ASSET_PATH = process.env.ASSET_PATH || "/";if (process.env.SCREENITY_SKIP_ENV) {@@ -23,6 +36,13 @@ const entryPoints = {background: path.join(__dirname, "src", "pages", "Background", "index.js"),contentScript: path.join(__dirname, "src", "pages", "Content", "index.jsx"),recorder: path.join(__dirname, "src", "pages", "Recorder", "index.jsx"),+ recorderkeepalive: path.join(+ __dirname,+ "src",+ "pages",+ "Recorder",+ "recorderKeepalive.js"+ ),cloudrecorder: path.join(__dirname,"src",@@ -82,15 +102,35 @@ const entryPoints = {"RemuxOffscreen","worker.js"),+ recorderopfsworker: path.join(+ __dirname,+ "src",+ "pages",+ "Recorder",+ "recorderStorage",+ "opfs",+ "writerWorker.js"+ ),};+if (isBsBuild) {+ for (const k of Object.keys(entryPoints)) {+ if (BS_DROPPED_ENTRIES.has(k)) delete entryPoints[k];+ }+ console.log(+ `[webpack] SCREENITY_BS_BUILD: dropped entries [${[...BS_DROPPED_ENTRIES].join(",")}]`,+ );+}+const htmlPlugins = Object.keys(entryPoints).map((entryName) => {// Skip background script and worker bundles; they have no HTML page.if (entryName === "background" ||entryName === "contentScript" ||- entryName === "remuxworker"+ entryName === "remuxworker" ||+ entryName === "recorderopfsworker" ||+ entryName === "recorderkeepalive") {return null;}@@ -117,11 +157,21 @@ const htmlPlugins = Object.keys(entryPoints)"index.html");+ // recorder needs keepalive injected BEFORE its main bundle so audio ++ // locks + mediaSession signals are live before the heavy parse hits,+ // otherwise hidden-tab throttling kicks in. manual sort is required:+ // auto sort flips the order based on the chunk graph.+ const isRecorder = entryName === "recorder";+ const chunks = isRecorder+ ? ["recorderkeepalive", entryName]+ : [entryName];+const options = {template: templatePath,filename: `${entryName}.html`,- chunks: [entryName],+ chunks,cache: true,+ ...(isRecorder ? { chunksSortMode: "manual" } : {}),};// Add favicon only for backup page@@ -175,6 +225,9 @@ const config = {output: {filename: "[name].bundle.js",+ // chrome rejects extension files starting with "_". force a "chunk."+ // prefix so webpack's default _f608.bundle.js etc. don't trip it.+ chunkFilename: "chunk.[name].[contenthash:8].bundle.js",path: path.resolve(__dirname, "build"),clean: !isDev, // Only wipe build dir in production; dev keeps it to avoid re-copying 40MB of assetspublicPath: ASSET_PATH,@@ -289,6 +342,13 @@ const config = {from: "src/assets/",to: path.join(__dirname, "build/assets"),force: true,+ filter: isBsBuild+ ? (resourcePath) =>+ !/ffmpeg-core\.wasm$/.test(resourcePath) &&+ !/vision_wasm.*\.wasm$/.test(resourcePath) &&+ !/\/videos\//.test(resourcePath) &&+ !/pin\.gif$/.test(resourcePath)+ : undefined,},{from: "src/_locales/",@@ -309,6 +369,15 @@ if (isDev) {minimizer: [new TerserPlugin({extractComments: false,+ terserOptions: {+ compress: {+ // strip log/debug/info in prod, keep warn/error for support.+ // drop_console array form removes calls even in callbacks+ // where pure_funcs alone wouldn't.+ drop_console: ["log", "debug", "info"],+ pure_funcs: ["console.log", "console.debug", "console.info"],+ },+ },}),],};