Skip to content

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

Improve recording reliability, recovery, diagnostics, and support context

Alyssa Xee5fba556c1b
diff --git a/.babelrc b/.babelrc
index 08d007e..84b342e 100644
--- a/.babelrc
+++ b/.babelrc
@@ -1,6 +1,6 @@
{
"presets": [
- "@babel/preset-env",
+ ["@babel/preset-env", { "targets": { "chrome": "110" } }],
["@babel/preset-react", { "runtime": "automatic" }]
]
}
diff --git a/.gitignore b/.gitignore
index 4856463..c9833dc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,4 +12,5 @@ node_modules/
.env.production
.env.*.local
build/
-docs/
\ No newline at end of file
+docs/
+tools/
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index f39d6e5..c6a81e3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -66,7 +66,6 @@
"@types/react": "^18.3.21",
"@types/react-dom": "^18.3.7",
"babel-loader": "^9.1.3",
- "clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^7.0.0",
"cross-env": "^7.0.3",
"css-loader": "^6.7.2",
@@ -1748,53 +1747,6 @@
"node-pre-gyp": "bin/node-pre-gyp"
}
},
- "node_modules/@mapbox/node-pre-gyp/node_modules/chownr": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
- "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
- "license": "ISC",
- "optional": true,
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/@mapbox/node-pre-gyp/node_modules/minipass": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
- "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
- "license": "ISC",
- "optional": true,
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/@mapbox/node-pre-gyp/node_modules/minizlib": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
- "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "minipass": "^3.0.0",
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/@mapbox/node-pre-gyp/node_modules/minizlib/node_modules/minipass": {
- "version": "3.3.6",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
- "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "license": "ISC",
- "optional": true,
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/@mapbox/node-pre-gyp/node_modules/semver": {
"version": "7.7.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
@@ -1807,32 +1759,6 @@
"node": ">=10"
}
},
- "node_modules/@mapbox/node-pre-gyp/node_modules/tar": {
- "version": "6.2.1",
- "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
- "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
- "deprecated": "Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
- "license": "ISC",
- "optional": true,
- "dependencies": {
- "chownr": "^2.0.0",
- "fs-minipass": "^2.0.0",
- "minipass": "^5.0.0",
- "minizlib": "^2.1.1",
- "mkdirp": "^1.0.3",
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/@mapbox/node-pre-gyp/node_modules/yallist": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "license": "ISC",
- "optional": true
- },
"node_modules/@mediapipe/selfie_segmentation": {
"version": "0.1.1675465747",
"resolved": "https://registry.npmjs.org/@mediapipe/selfie_segmentation/-/selfie_segmentation-0.1.1675465747.tgz",
@@ -4053,16 +3979,6 @@
"@types/send": "*"
}
},
- "node_modules/@types/glob": {
- "version": "7.2.0",
- "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz",
- "integrity": "sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==",
- "dev": true,
- "dependencies": {
- "@types/minimatch": "*",
- "@types/node": "*"
- }
- },
"node_modules/@types/html-minifier-terser": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz",
@@ -4100,16 +4016,6 @@
"integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==",
"dev": true
},
- "node_modules/@types/minimatch": {
- "version": "6.0.0",
- "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-6.0.0.tgz",
- "integrity": "sha512-zmPitbQ8+6zNutpwgcQuLcsEpn/Cj54Kbn7L5pX0Os5kdWplB7xPgEh/g+SWOB/qmows2gpuCaPyduq8ZZRnxA==",
- "deprecated": "This is a stub types definition. minimatch provides its own type definitions, so you do not need this installed.",
- "dev": true,
- "dependencies": {
- "minimatch": "*"
- }
- },
"node_modules/@types/node": {
"version": "24.7.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.7.2.tgz",
@@ -4743,15 +4649,6 @@
"node": ">=8"
}
},
- "node_modules/array-uniq": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz",
- "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -5247,21 +5144,6 @@
"node": ">= 10.0"
}
},
- "node_modules/clean-webpack-plugin": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/clean-webpack-plugin/-/clean-webpack-plugin-4.0.0.tgz",
- "integrity": "sha512-WuWE1nyTNAyW5T7oNyys2EN0cfP2fdRxhxnIQWiAp0bMabPdHhoGxM8A6YL2GhqwgrPnnaemVE7nv5XJ2Fhh2w==",
- "dev": true,
- "dependencies": {
- "del": "^4.1.1"
- },
- "engines": {
- "node": ">=10.0.0"
- },
- "peerDependencies": {
- "webpack": ">=4.0.0 <6.0.0"
- }
- },
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
@@ -5547,10 +5429,11 @@
}
},
"node_modules/copy-webpack-plugin/node_modules/ajv": {
- "version": "6.12.6",
- "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
- "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
+ "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -5889,74 +5772,6 @@
"node": ">=8"
}
},
- "node_modules/del": {
- "version": "4.1.1",
- "resolved": "https://registry.npmjs.org/del/-/del-4.1.1.tgz",
- "integrity": "sha512-QwGuEUouP2kVwQenAsOof5Fv8K9t3D8Ca8NxcXKrIpEHjTXK5J2nXLdP+ALI1cgv8wj7KuwBhTwBkOZSJKM5XQ==",
- "dev": true,
- "dependencies": {
- "@types/glob": "^7.1.1",
- "globby": "^6.1.0",
- "is-path-cwd": "^2.0.0",
- "is-path-in-cwd": "^2.0.0",
- "p-map": "^2.0.0",
- "pify": "^4.0.1",
- "rimraf": "^2.6.3"
- },
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/del/node_modules/array-union": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz",
- "integrity": "sha512-Dxr6QJj/RdU/hCaBjOfxW+q6lyuVE6JFWIrAUpuOOhoJJoQ99cUn3igRaHVB5P9WrgFVN0FfArM3x0cueOU8ng==",
- "dev": true,
- "dependencies": {
- "array-uniq": "^1.0.1"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/del/node_modules/globby": {
- "version": "6.1.0",
- "resolved": "https://registry.npmjs.org/globby/-/globby-6.1.0.tgz",
- "integrity": "sha512-KVbFv2TQtbzCoxAnfD6JcHZTYCzyliEaaeM/gH8qQdkKr5s0OP9scEgvdcngyk7AVdY6YVW/TJHd+lQ/Df3Daw==",
- "dev": true,
- "dependencies": {
- "array-union": "^1.0.1",
- "glob": "^7.0.3",
- "object-assign": "^4.0.1",
- "pify": "^2.0.0",
- "pinkie-promise": "^2.0.0"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/del/node_modules/globby/node_modules/pify": {
- "version": "2.3.0",
- "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
- "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/del/node_modules/rimraf": {
- "version": "2.7.1",
- "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
- "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
- "deprecated": "Rimraf versions prior to v4 are no longer supported",
- "dev": true,
- "dependencies": {
- "glob": "^7.1.3"
- },
- "bin": {
- "rimraf": "bin.js"
- }
- },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -6746,39 +6561,6 @@
"node": ">=12"
}
},
- "node_modules/fs-minipass": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
- "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
- "license": "ISC",
- "optional": true,
- "dependencies": {
- "minipass": "^3.0.0"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/fs-minipass/node_modules/minipass": {
- "version": "3.3.6",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
- "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
- "license": "ISC",
- "optional": true,
- "dependencies": {
- "yallist": "^4.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/fs-minipass/node_modules/yallist": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
- "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
- "license": "ISC",
- "optional": true
- },
"node_modules/fs-monkey": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.1.0.tgz",
@@ -7358,10 +7140,11 @@
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="
},
"node_modules/immutable": {
- "version": "5.1.4",
- "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.4.tgz",
- "integrity": "sha512-p6u1bG3YSnINT5RQmx/yRZBpenIl30kVxkTLDyHLIMk0gict704Q9n+thfDI7lTRm9vXdDYutVzXhzcThxTnXA==",
- "dev": true
+ "version": "5.1.5",
+ "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.5.tgz",
+ "integrity": "sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==",
+ "dev": true,
+ "license": "MIT"
},
"node_modules/import-local": {
"version": "3.2.0",
@@ -7571,39 +7354,6 @@
"node": ">=0.12.0"
}
},
- "node_modules/is-path-cwd": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz",
- "integrity": "sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/is-path-in-cwd": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/is-path-in-cwd/-/is-path-in-cwd-2.1.0.tgz",
- "integrity": "sha512-rNocXHgipO+rvnP6dk3zI20RpOtrAM/kzbB258Uw5BWr3TpXi861yzjo16Dn4hUox07iw5AyeMLHWsujkjzvRQ==",
- "dev": true,
- "dependencies": {
- "is-path-inside": "^2.1.0"
- },
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/is-path-inside": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-2.1.0.tgz",
- "integrity": "sha512-wiyhTzfDWsvwAW53OBWF5zuvaOGlZ6PwYxAbPVDhpm+gM09xKQGjBq/8uYN12aDvMxnAnq3dxTyoSoRNmg5YFg==",
- "dev": true,
- "dependencies": {
- "path-is-inside": "^1.0.2"
- },
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/is-plain-obj": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-3.0.0.tgz",
@@ -8190,19 +7940,6 @@
"node": ">= 18"
}
},
- "node_modules/mkdirp": {
- "version": "1.0.4",
- "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
- "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
- "license": "MIT",
- "optional": true,
- "bin": {
- "mkdirp": "bin/cmd.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -8548,15 +8285,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/p-map": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz",
- "integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/p-retry": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
@@ -8683,12 +8411,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/path-is-inside": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz",
- "integrity": "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w==",
- "dev": true
- },
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
@@ -8734,36 +8456,6 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
- "node_modules/pify": {
- "version": "4.0.1",
- "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",
- "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==",
- "dev": true,
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/pinkie": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz",
- "integrity": "sha512-MnUuEycAemtSaeFSjXKW/aroV7akBbY+Sv+RkyqFjgAe73F+MR0TBWKBRDkmfWq/HiFmdavfZ1G7h4SPZXaCSg==",
- "dev": true,
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/pinkie-promise": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz",
- "integrity": "sha512-0Gni6D4UcLTbv9c57DfxDGdr41XfgUjqWZu492f0cIGr16zDU06BWP/RAEvOuo7CQ0CNjHaLlM59YJJFm3NWlw==",
- "dev": true,
- "dependencies": {
- "pinkie": "^2.0.0"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
"node_modules/pkg-dir": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-7.0.0.tgz",
@@ -9063,6 +8755,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
"integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
+ "dev": true,
"dependencies": {
"safe-buffer": "^5.1.0"
}
@@ -9161,9 +8854,10 @@
}
},
"node_modules/raw-loader/node_modules/ajv": {
- "version": "6.12.6",
- "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
- "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
+ "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==",
+ "license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -10412,15 +10106,14 @@
}
},
"node_modules/terser-webpack-plugin": {
- "version": "5.3.16",
- "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.16.tgz",
- "integrity": "sha512-h9oBFCWrq78NyWWVcSwZarJkZ01c2AyGrzs1crmHZO3QUg9D61Wu4NPjBy69n7JqylFF5y+CsUZYmYEIZ3mR+Q==",
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.4.0.tgz",
+ "integrity": "sha512-Bn5vxm48flOIfkdl5CaD2+1CiUVbonWQ3KQPyP7/EuIl9Gbzq/gQFOzaMFUEgVjB1396tcK0SG8XcNJ/2kDH8g==",
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.25",
"jest-worker": "^27.4.5",
"schema-utils": "^4.3.0",
- "serialize-javascript": "^6.0.2",
"terser": "^5.31.1"
},
"engines": {
@@ -10445,14 +10138,6 @@
}
}
},
- "node_modules/terser-webpack-plugin/node_modules/serialize-javascript": {
- "version": "6.0.2",
- "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
- "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
- "dependencies": {
- "randombytes": "^2.1.0"
- }
- },
"node_modules/terser/node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
diff --git a/package.json b/package.json
index ee68676..cdf6600 100755
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "screenity",
- "version": "4.0.0",
+ "version": "4.3.0",
"description": "The free and privacy-friendly screen recorder with no sign in needed.",
"scripts": {
"build": "cross-env NODE_ENV=production node utils/build.js",
@@ -72,7 +72,6 @@
"@types/react": "^18.3.21",
"@types/react-dom": "^18.3.7",
"babel-loader": "^9.1.3",
- "clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^7.0.0",
"cross-env": "^7.0.3",
"css-loader": "^6.7.2",
diff --git a/src/_locales/ca/messages.json b/src/_locales/ca/messages.json
index e6bb218..c798f81 100644
--- a/src/_locales/ca/messages.json
+++ b/src/_locales/ca/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Reinicia l'onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/de/messages.json b/src/_locales/de/messages.json
index 65ec1b4..15f8a49 100644
--- a/src/_locales/de/messages.json
+++ b/src/_locales/de/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Onboarding zurücksetzen",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/en/messages.json b/src/_locales/en/messages.json
index f7549c4..44f6e00 100644
--- a/src/_locales/en/messages.json
+++ b/src/_locales/en/messages.json
@@ -872,11 +872,11 @@
"description": "Raw recording modal button"
},
"troubleshootModalTitle": {
- "message": "Download system information and video data and send for troubleshooting",
+ "message": "Download diagnostic report for troubleshooting",
"description": "Troubleshoot modal title"
},
"troubleshootModalDescription": {
- "message": "After downloading, send the file to [email protected] with any relevant information. We will use this data to help you troubleshoot any issues you are having with the extension, and recover your video if possible.",
+ "message": "This will download a diagnostic report with system info and recent recording session data. Send it to [email protected] to help us troubleshoot your issue. No video or audio data is included.",
"description": "Troubleshoot modal description"
},
"troubleshootModalButton": {
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Reset onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
}
diff --git a/src/_locales/es/messages.json b/src/_locales/es/messages.json
index ed837d1..eb1f8c8 100644
--- a/src/_locales/es/messages.json
+++ b/src/_locales/es/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Reiniciar onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/fr/messages.json b/src/_locales/fr/messages.json
index 371bcf4..e52676e 100644
--- a/src/_locales/fr/messages.json
+++ b/src/_locales/fr/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Réinitialiser l'onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/hi/messages.json b/src/_locales/hi/messages.json
index 34ec510..75a2c90 100644
--- a/src/_locales/hi/messages.json
+++ b/src/_locales/hi/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "ऑनबोर्डिंग रीसेट करें",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/id/messages.json b/src/_locales/id/messages.json
index 6c1798b..841f9c2 100644
--- a/src/_locales/id/messages.json
+++ b/src/_locales/id/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Reset onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/it/messages.json b/src/_locales/it/messages.json
index 2555bf4..7b72f87 100644
--- a/src/_locales/it/messages.json
+++ b/src/_locales/it/messages.json
@@ -1432,5 +1432,29 @@
"resetOnboardingOption": {
"message": "Reimposta onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/ko/messages.json b/src/_locales/ko/messages.json
index 5a60523..c35e5ac 100644
--- a/src/_locales/ko/messages.json
+++ b/src/_locales/ko/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "온보딩 다시 시작",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/pl/messages.json b/src/_locales/pl/messages.json
index c36b068..068c5e0 100644
--- a/src/_locales/pl/messages.json
+++ b/src/_locales/pl/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Zresetuj onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/pt_BR/messages.json b/src/_locales/pt_BR/messages.json
index d1d048f..2b450e0 100644
--- a/src/_locales/pt_BR/messages.json
+++ b/src/_locales/pt_BR/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Redefinir onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/pt_PT/messages.json b/src/_locales/pt_PT/messages.json
index b848d4b..d7f8a6a 100644
--- a/src/_locales/pt_PT/messages.json
+++ b/src/_locales/pt_PT/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Repor onboarding",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/ru/messages.json b/src/_locales/ru/messages.json
index f15be0a..7a23593 100644
--- a/src/_locales/ru/messages.json
+++ b/src/_locales/ru/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Сбросить онбординг",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/ta/messages.json b/src/_locales/ta/messages.json
index bb7ae61..924a8db 100644
--- a/src/_locales/ta/messages.json
+++ b/src/_locales/ta/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Onboarding-ஐ மீட்டமை",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/tr/messages.json b/src/_locales/tr/messages.json
index 15c1c9b..6ce89a4 100644
--- a/src/_locales/tr/messages.json
+++ b/src/_locales/tr/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "Onboarding'i sıfırla",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/uk/messages.json b/src/_locales/uk/messages.json
index 5041680..c14f2b0 100644
--- a/src/_locales/uk/messages.json
+++ b/src/_locales/uk/messages.json
@@ -1440,5 +1440,29 @@
"resetOnboardingOption": {
"message": "Скинути онбординг",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json
index 6f0b6cf..abbd40f 100644
--- a/src/_locales/zh_CN/messages.json
+++ b/src/_locales/zh_CN/messages.json
@@ -1444,5 +1444,29 @@
"resetOnboardingOption": {
"message": "重置引导",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json
index 356777f..811aed8 100644
--- a/src/_locales/zh_TW/messages.json
+++ b/src/_locales/zh_TW/messages.json
@@ -1448,5 +1448,29 @@
"resetOnboardingOption": {
"message": "重設導覽",
"description": "Reset pro onboarding option label in popup settings menu"
+ },
+ "recoverLastRecordingOption": {
+ "message": "Recover last recording",
+ "description": "Settings menu item to manually trigger cloud recording recovery"
+ },
+ "toastRecoveredSession": {
+ "message": "Recovered unsaved recording from the previous session.",
+ "description": "Toast shown when a crashed recording session is auto-recovered on startup"
+ },
+ "toastStorageCritical": {
+ "message": "Low disk space detected. Recording is stopping to avoid corruption.",
+ "description": "Toast shown when available storage drops below the critical threshold during recording"
+ },
+ "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"
+ },
+ "toastAudioCaptureDegraded": {
+ "message": "Transcription capture paused due to memory pressure. Video upload continues.",
+ "description": "Toast shown when the audio recorder is stopped early because the audio buffer limit was reached"
+ },
+ "toastNetworkOffline": {
+ "message": "Network offline. Upload paused. Screen chunks are saved locally.",
+ "description": "Toast shown when the browser goes offline during a cloud recording upload"
}
-}
+}
\ No newline at end of file
diff --git a/src/manifest.json b/src/manifest.json
index c624f07..224e8af 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.2.9",
+ "version": "4.3.0",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/pages/Background/alarms/handleAlarm.js b/src/pages/Background/alarms/handleAlarm.js
index 020a4d2..f59ef93 100644
--- a/src/pages/Background/alarms/handleAlarm.js
+++ b/src/pages/Background/alarms/handleAlarm.js
@@ -1,8 +1,19 @@
import { stopRecording } from "../recording/stopRecording.js";
import { sendMessageTab } from "../tabManagement";
import { sendMessageRecord } from "../recording/sendMessageRecord.js";
+import { diagEvent } from "../../utils/diagnosticLog";
+import { chunksStore } from "../recording/chunkHandler";
+import {
+ CLOUD_LOCAL_PLAYBACK_KEY,
+ CLOUD_LOCAL_PLAYBACK_EVENT_KEY,
+ CLOUD_LOCAL_PLAYBACK_ALARM,
+} from "../recording/cloudLocalPlaybackConstants";
-// Utility to handle tab messaging logic
+// 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.
const handleTabMessaging = async (tab) => {
const { activeTab } = await chrome.storage.local.get(["activeTab"]);
@@ -11,7 +22,8 @@ const handleTabMessaging = async (tab) => {
if (targetTab) {
sendMessageTab(activeTab, { type: "stop-recording-tab" });
- } else {
+ } 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 });
}
@@ -25,11 +37,73 @@ export const handleAlarm = async (alarm) => {
const { recording } = await chrome.storage.local.get(["recording"]);
if (recording) {
+ diagEvent("alarm-fired");
stopRecording();
sendMessageRecord({ type: "stop-recording-tab" });
- await handleTabMessaging(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);
}
await chrome.alarms.clear("recording-alarm");
+ return;
+ }
+
+ if (alarm.name === CLOUD_LOCAL_PLAYBACK_ALARM) {
+ const {
+ [CLOUD_LOCAL_PLAYBACK_KEY]: localPlaybackOffer,
+ recording,
+ pendingRecording,
+ restarting,
+ } = await chrome.storage.local.get([
+ CLOUD_LOCAL_PLAYBACK_KEY,
+ "recording",
+ "pendingRecording",
+ "restarting",
+ ]);
+
+ if (!localPlaybackOffer?.offerId) {
+ await chrome.alarms.clear(CLOUD_LOCAL_PLAYBACK_ALARM);
+ return;
+ }
+
+ const hasActiveRecording = Boolean(recording || pendingRecording || restarting);
+ if (hasActiveRecording) {
+ // Never clear local chunks while a new recording is active; retry soon.
+ const retryAt = Date.now() + 5 * 60 * 1000;
+ await chrome.alarms
+ .create(CLOUD_LOCAL_PLAYBACK_ALARM, { when: retryAt })
+ .catch(() => {});
+ return;
+ }
+
+ const expired = Number(localPlaybackOffer.expiresAt || 0) <= Date.now();
+ if (!expired) {
+ await chrome.alarms
+ .create(CLOUD_LOCAL_PLAYBACK_ALARM, {
+ when: Number(localPlaybackOffer.expiresAt),
+ })
+ .catch(() => {});
+ return;
+ }
+
+ await chunksStore.clear().catch((err) => {
+ console.warn(
+ "[Screenity][BG] Failed to clear chunksStore for local playback expiry",
+ err,
+ );
+ });
+ await chrome.storage.local.remove([CLOUD_LOCAL_PLAYBACK_KEY]);
+ await chrome.storage.local.set({
+ [CLOUD_LOCAL_PLAYBACK_EVENT_KEY]: {
+ event: "offer-expired",
+ at: Date.now(),
+ offerId: localPlaybackOffer.offerId,
+ projectId: localPlaybackOffer.projectId || null,
+ sceneId: localPlaybackOffer.sceneId || null,
+ },
+ });
+ await chrome.alarms.clear(CLOUD_LOCAL_PLAYBACK_ALARM);
}
};
diff --git a/src/pages/Background/index.js b/src/pages/Background/index.js
index 0e5ec71..562a49b 100644
--- a/src/pages/Background/index.js
+++ b/src/pages/Background/index.js
@@ -4,12 +4,60 @@ import {
messageRouter,
messageDispatcher,
} from "../../messaging/messageRouter";
+import { hydrateDiagnosticLog, diagEvent } from "../utils/diagnosticLog";
-// Initialize message router
-messageRouter();
+// 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.
+const clearStaleLocks = async () => {
+ try {
+ const { sendingChunks, postStopEditorOpening, postStopEditorOpened } =
+ await chrome.storage.local.get([
+ "sendingChunks",
+ "postStopEditorOpening",
+ "postStopEditorOpened",
+ ]);
-// Start all listeners
-initializeListeners();
+ const stale = {};
+ if (sendingChunks) {
+ stale.sendingChunks = false;
+ 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");
+ }
+ if (postStopEditorOpened) {
+ stale.postStopEditorOpened = false;
+ console.warn("[Screenity][BG] Stale lock found on startup: postStopEditorOpened — clearing");
+ }
-// Set up message handlers
+ if (Object.keys(stale).length > 0) {
+ await chrome.storage.local.set(stale);
+ console.info(
+ "[Screenity][BG] Startup stale locks cleared:",
+ Object.keys(stale).join(", "),
+ );
+ }
+ } 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.
+messageRouter();
+initializeListeners();
setupHandlers();
+
+// 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.
+clearStaleLocks();
+
+// Hydrate the diagnostic log from storage and record that the SW (re)started.
+hydrateDiagnosticLog().then(() => {
+ diagEvent("sw-init", { ts: Date.now() });
+});
diff --git a/src/pages/Background/listeners/onActionButtonClickedListener.js b/src/pages/Background/listeners/onActionButtonClickedListener.js
index fb650cd..fda6c13 100644
--- a/src/pages/Background/listeners/onActionButtonClickedListener.js
+++ b/src/pages/Background/listeners/onActionButtonClickedListener.js
@@ -1,4 +1,9 @@
-import { sendMessageTab, getCurrentTab } from "../tabManagement";
+import {
+ sendMessageTab,
+ getCurrentTab,
+ setEditorTabReference,
+ clearEditorTabReference,
+} from "../tabManagement";
import { sendMessageRecord } from "../recording/sendMessageRecord.js";
import { stopRecording } from "../recording/stopRecording.js";
import { loginWithWebsite } from "../auth/loginWithWebsite.js";
@@ -33,18 +38,22 @@ const handleTabMessaging = async (tab) => {
// Utility to open Playground or inject popup
const openPlaygroundOrPopup = async (tab) => {
const editorUrlPattern =
- /https?:\/\/(app\.screenity\.io|localhost:3000)\/editor\/([^\/]+)(\/edit)?\/?/;
+ /https:\/\/app\.screenity\.io\/editor\/([^\/]+)(\/edit)?\/?/;
if (tab.url && editorUrlPattern.test(tab.url)) {
- await chrome.storage.local.set({ editorTab: tab.id });
+ const match = tab.url.match(editorUrlPattern);
+ const projectIdFromUrl = match?.[2] || null;
+ await setEditorTabReference({
+ tabId: tab.id,
+ tabUrl: tab.url,
+ source: "action-click-editor",
+ expectedProjectId: projectIdFromUrl,
+ });
if (CLOUD_FEATURES_ENABLED) {
const result = await loginWithWebsite();
if (result?.authenticated) {
- const match = tab.url.match(editorUrlPattern);
- const projectIdFromUrl = match[2];
-
await chrome.storage.local.set({
projectId: projectIdFromUrl,
recordingToScene: true,
@@ -69,6 +78,10 @@ const openPlaygroundOrPopup = async (tab) => {
});
}
} else {
+ await clearEditorTabReference("action-click-non-editor-tab", {
+ tabId: tab.id,
+ tabUrl: tab.url,
+ });
await chrome.storage.local.set({
projectId: null,
recordingToScene: false,
@@ -127,7 +140,34 @@ export const onActionButtonClickedListener = () => {
);
if (isRecordingActive) {
- await handleTabMessaging(tab);
+ // Check whether an actual recorder still exists before treating this as
+ // an active recording. If no recorder is present, the flags are stale
+ // (e.g. countdown was cancelled while a race left recording:true in
+ // storage). Reset and open the popup instead of silently swallowing the
+ // click.
+ const { recordingTab, offscreen } = await chrome.storage.local.get([
+ "recordingTab",
+ "offscreen",
+ ]);
+ const hasActiveRecorder = recordingTab || offscreen || sessionRecording;
+
+ if (!hasActiveRecorder) {
+ console.warn(
+ "[Screenity] Stale recording flags detected (no recorder). Resetting.",
+ { recording, pendingRecording, restarting, sessionRecording },
+ );
+ await chrome.storage.local.set({
+ recording: false,
+ pendingRecording: false,
+ restarting: false,
+ recordingToScene: false,
+ projectId: null,
+ activeSceneId: null,
+ });
+ await openPlaygroundOrPopup(tab);
+ } else {
+ await handleTabMessaging(tab);
+ }
} else {
// Reset storage keys before opening the popup
await chrome.storage.local.set({
diff --git a/src/pages/Background/listeners/onInstalledListener.js b/src/pages/Background/listeners/onInstalledListener.js
index 12326fd..d9d3396 100644
--- a/src/pages/Background/listeners/onInstalledListener.js
+++ b/src/pages/Background/listeners/onInstalledListener.js
@@ -1,5 +1,6 @@
import { removeTab } from "../tabManagement";
import { executeScripts } from "../utils/executeScripts";
+import { supportContextQuery } from "../../utils/buildSupportContext";
const cloudFeaturesEnabled =
process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";
@@ -14,10 +15,12 @@ export const onInstalledListener = () => {
chrome.storage.local.clear();
// Set uninstall URL based on locale
+ const installQs = await supportContextQuery({ source: "uninstall" });
+ const installUrl = `https://tally.so/r/w8Zro5?${installQs}`;
chrome.runtime.setUninstallURL(
locale.includes("en")
- ? `https://tally.so/r/w8Zro5?version=${version}`
- : `http://translate.google.com/translate?js=n&sl=auto&tl=${locale}&u=https://tally.so/r/w8Zro5?version=${version}`
+ ? installUrl
+ : `http://translate.google.com/translate?js=n&sl=auto&tl=${locale}&u=${encodeURIComponent(installUrl)}`
);
chrome.storage.local.set({
@@ -50,10 +53,12 @@ export const onInstalledListener = () => {
}
}
+ const updateQs = await supportContextQuery({ source: "uninstall" });
+ const updateUrl = `https://tally.so/r/3Ex6kX?${updateQs}`;
chrome.runtime.setUninstallURL(
locale.includes("en")
- ? `https://tally.so/r/3Ex6kX?version=${version}`
- : `http://translate.google.com/translate?js=n&sl=auto&tl=${locale}&u=https://tally.so/r/3Ex6kX?version=${version}`
+ ? updateUrl
+ : `http://translate.google.com/translate?js=n&sl=auto&tl=${locale}&u=${encodeURIComponent(updateUrl)}`
);
}
diff --git a/src/pages/Background/listeners/onMessageExternalListener.js b/src/pages/Background/listeners/onMessageExternalListener.js
index f02a19d..882b9ff 100644
--- a/src/pages/Background/listeners/onMessageExternalListener.js
+++ b/src/pages/Background/listeners/onMessageExternalListener.js
@@ -1,4 +1,10 @@
-import { getCurrentTab, sendMessageTab, removeTab } from "../tabManagement";
+import {
+ getCurrentTab,
+ sendMessageTab,
+ parseEditorTargetUrl,
+ setEditorTabReference,
+ clearEditorTabReference,
+} from "../tabManagement";
import { loginWithWebsite } from "../auth/loginWithWebsite";
const CLOUD_FEATURES_ENABLED =
@@ -90,9 +96,24 @@ export const onMessageExternalListener = () => {
instantMode: false,
projectId: message.projectId,
activeSceneId: message.activeSceneId,
- editorTab: tab.id, // Set editorTab in storage
});
+ const parsedTarget = parseEditorTargetUrl(tab.url);
+ if (parsedTarget?.projectId === message.projectId) {
+ await setEditorTabReference({
+ tabId: tab.id,
+ tabUrl: tab.url,
+ source: "webapp-open-popup-project",
+ expectedProjectId: message.projectId,
+ });
+ } else {
+ await clearEditorTabReference("webapp-open-popup-project-not-editor", {
+ tabId: tab.id,
+ tabUrl: tab.url,
+ expectedProjectId: message.projectId,
+ });
+ }
+
const result = await loginWithWebsite();
if (!result?.authenticated) {
diff --git a/src/pages/Background/listeners/onTabRemovedListener.js b/src/pages/Background/listeners/onTabRemovedListener.js
index 0fc9e02..6890b1e 100644
--- a/src/pages/Background/listeners/onTabRemovedListener.js
+++ b/src/pages/Background/listeners/onTabRemovedListener.js
@@ -1,5 +1,6 @@
-import { sendMessageTab } from "../tabManagement";
+import { sendMessageTab, clearEditorTabReference } from "../tabManagement";
import { sendMessageRecord } from "../recording/sendMessageRecord";
+import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";
/**
* Listener for when a tab is removed.
@@ -17,6 +18,7 @@ export const onTabRemovedListener = () => {
recordingUiTabId,
activeTab,
recorderSession,
+ editorTab,
} = await chrome.storage.local.get([
"recording",
"pendingRecording",
@@ -26,8 +28,13 @@ export const onTabRemovedListener = () => {
"recordingUiTabId",
"activeTab",
"recorderSession",
+ "editorTab",
]);
+ if (tabId === editorTab) {
+ await clearEditorTabReference("editor-tab-closed", { tabId });
+ }
+
const recordedTabId = tabRecordedID || recordingTab;
// Check both recording flag AND recorderSession
@@ -46,6 +53,7 @@ export const onTabRemovedListener = () => {
.catch(() => {});
if (recorderSession && recorderSession.status === "recording") {
+ diagEvent("crash", { reason: "recorder-owner-tab-removed", tabId });
await chrome.storage.local.set({
recorderSession: {
...recorderSession,
@@ -54,11 +62,13 @@ export const onTabRemovedListener = () => {
},
recording: false,
});
+ endDiagSession("crashed");
}
}
// 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 tab
chrome.storage.local.set({ recordingTab: null, tabRecordedID: null });
@@ -89,6 +99,8 @@ export const onTabRemovedListener = () => {
tabId === recordingTab &&
recordingTab !== recordedTabId
) {
+ diagEvent("crash", { reason: "cloud-recorder-tab-closed", tabId });
+ endDiagSession("crashed");
console.error("CloudRecorder tab was closed during recording!");
chrome.storage.local.set({
recording: false,
diff --git a/src/pages/Background/listeners/onTabUpdatedListener.js b/src/pages/Background/listeners/onTabUpdatedListener.js
index 66c8d0d..64efe39 100644
--- a/src/pages/Background/listeners/onTabUpdatedListener.js
+++ b/src/pages/Background/listeners/onTabUpdatedListener.js
@@ -1,4 +1,5 @@
import { sendMessageTab } from "../tabManagement";
+import { diagEvent } from "../../utils/diagnosticLog";
export const handleTabUpdate = async (tabId, changeInfo, tab) => {
try {
@@ -36,6 +37,7 @@ export const handleTabUpdate = async (tabId, changeInfo, tab) => {
sendMessageTab(tabId, { type: "recording-ended" });
} else if (isActivelyRecording) {
if (tabRecordedID && tabRecordedID === tabId) {
+ diagEvent("recorded-tab-navigated");
sendMessageTab(tabId, {
type: "recording-check",
force: true,
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index 059370a..53855e9 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -25,6 +25,8 @@ import {
restartActiveTab,
getCurrentTab,
sendMessageTab,
+ parseEditorTargetUrl,
+ resolveEditorTabForTarget,
} from "../tabManagement";
import {
handleRestart,
@@ -38,6 +40,15 @@ import {
} from "../utils/browserHelpers";
import { requestDownload, downloadIndexedDB } from "../utils/downloadHelpers";
import { restoreRecording, checkRestore } from "../recording/restoreRecording";
+import {
+ checkCloudRestore,
+ restoreCloudRecording,
+} from "../recording/restoreCloudRecording";
+import {
+ CLOUD_LOCAL_PLAYBACK_KEY,
+ CLOUD_LOCAL_PLAYBACK_EVENT_KEY,
+ CLOUD_LOCAL_PLAYBACK_ALARM,
+} from "../recording/cloudLocalPlaybackConstants";
import { desktopCapture } from "../recording/desktopCapture";
import {
writeFile,
@@ -53,16 +64,166 @@ import { newChunk, clearAllRecordings } from "../recording/chunkHandler";
import { setMicActiveTab } from "../tabManagement/tabHelpers";
import { handleSignOutDrive } from "../drive/handleSignOutDrive";
import { loginWithWebsite } from "../auth/loginWithWebsite";
+import {
+ getDiagnosticLog,
+ getErrorSnapshot,
+ getStorageFlags,
+ diagEvent,
+} from "../../utils/diagnosticLog";
+import { supportContextQuery } from "../../utils/buildSupportContext";
const API_BASE = process.env.SCREENITY_API_BASE_URL;
+const APP_BASE = process.env.SCREENITY_APP_BASE;
const CLOUD_FEATURES_ENABLED =
process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true";
// Debug toggle for post-stop/chunk flow
const DEBUG_POSTSTOP = true;
const STOP_RECORDING_TAB_DEBOUNCE_MS = 1200;
+const CLOUD_LOCAL_PLAYBACK_MAX_BYTES = 250 * 1024 * 1024;
+const CLOUD_LOCAL_PLAYBACK_MAX_CHUNKS = 4000;
+const CLOUD_LOCAL_PLAYBACK_MIN_TTL_MS = 60 * 1000;
+const CLOUD_LOCAL_PLAYBACK_MAX_TTL_MS = 24 * 60 * 60 * 1000;
let stopRecordingTabInFlight = false;
let stopRecordingTabLastAt = 0;
+const getEditorTargetUrl = ({ projectId, instantMode = false } = {}) => {
+ if (!projectId) return null;
+ if (instantMode) {
+ return `${APP_BASE}/view/${projectId}?load=true`;
+ }
+ return `${APP_BASE}/editor/${projectId}/edit?load=true`;
+};
+
+const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
+
+const normalizeLocalPlaybackOffer = (offer = {}) => {
+ const now = Date.now();
+ const expiresAtRaw = Number(offer.expiresAt) || 0;
+ const ttl =
+ expiresAtRaw > now
+ ? clamp(
+ expiresAtRaw - now,
+ CLOUD_LOCAL_PLAYBACK_MIN_TTL_MS,
+ CLOUD_LOCAL_PLAYBACK_MAX_TTL_MS,
+ )
+ : CLOUD_LOCAL_PLAYBACK_MIN_TTL_MS;
+ const expiresAt = now + ttl;
+ const chunkCount = Math.max(
+ 0,
+ Math.min(CLOUD_LOCAL_PLAYBACK_MAX_CHUNKS, Number(offer.chunkCount) || 0),
+ );
+ const estimatedBytes = Math.max(0, Number(offer.estimatedBytes) || 0);
+ const createdAt = Number(offer.createdAt) || now;
+
+ return {
+ offerId: offer.offerId || crypto.randomUUID(),
+ projectId: offer.projectId || null,
+ sceneId: offer.sceneId || null,
+ recordingSessionId: offer.recordingSessionId || null,
+ trackType: "screen",
+ source: offer.source || "indexeddb-screen-chunks",
+ status: offer.status || "available",
+ chunkCount,
+ estimatedBytes,
+ mediaId: offer.mediaId || null,
+ bunnyVideoId: offer.bunnyVideoId || null,
+ createdAt,
+ expiresAt,
+ updatedAt: now,
+ };
+};
+
+const isLocalPlaybackOfferExpired = (offer) =>
+ !offer || Number(offer.expiresAt || 0) <= Date.now();
+
+const scheduleLocalPlaybackAlarm = async (offer) => {
+ if (!offer?.expiresAt || !chrome.alarms?.create) return;
+ try {
+ await chrome.alarms.clear(CLOUD_LOCAL_PLAYBACK_ALARM);
+ await chrome.alarms.create(CLOUD_LOCAL_PLAYBACK_ALARM, {
+ when: Number(offer.expiresAt),
+ });
+ } catch (err) {
+ console.warn("[Screenity][BG] Failed to schedule local playback alarm", err);
+ }
+};
+
+const getStoredLocalPlaybackOffer = async () => {
+ const result = await chrome.storage.local.get([CLOUD_LOCAL_PLAYBACK_KEY]);
+ return result?.[CLOUD_LOCAL_PLAYBACK_KEY] || null;
+};
+
+const clearStoredLocalPlaybackOffer = async ({
+ reason = "unknown",
+ clearChunks = true,
+ onlyIfOfferId = null,
+} = {}) => {
+ const existing = await getStoredLocalPlaybackOffer();
+ if (onlyIfOfferId && existing?.offerId && existing.offerId !== onlyIfOfferId) {
+ return { ok: true, skipped: true, reason: "offer-id-mismatch" };
+ }
+
+ await chrome.storage.local.remove([CLOUD_LOCAL_PLAYBACK_KEY]);
+ if (chrome.alarms?.clear) {
+ await chrome.alarms.clear(CLOUD_LOCAL_PLAYBACK_ALARM).catch(() => {});
+ }
+
+ if (clearChunks) {
+ await chunksStore.clear().catch((err) => {
+ console.warn(
+ "[Screenity][BG] Failed to clear chunksStore while clearing local playback offer",
+ err,
+ );
+ });
+ }
+
+ await chrome.storage.local.set({
+ [CLOUD_LOCAL_PLAYBACK_EVENT_KEY]: {
+ event: "offer-cleared",
+ reason,
+ clearedAt: Date.now(),
+ clearedOfferId: existing?.offerId || null,
+ clearChunks: Boolean(clearChunks),
+ },
+ });
+
+ if (existing?.offerId) {
+ console.info("[Screenity][BG] Cleared local screen playback offer", {
+ reason,
+ offerId: existing.offerId,
+ clearChunks: Boolean(clearChunks),
+ });
+ }
+
+ return { ok: true, clearedOfferId: existing?.offerId || null };
+};
+
+const getValidLocalPlaybackOffer = async ({
+ offerId = null,
+ projectId = null,
+ sceneId = null,
+} = {}) => {
+ const offer = await getStoredLocalPlaybackOffer();
+ if (!offer) return null;
+
+ if (isLocalPlaybackOfferExpired(offer)) {
+ await clearStoredLocalPlaybackOffer({
+ reason: "offer-expired",
+ clearChunks: true,
+ onlyIfOfferId: offer.offerId || null,
+ });
+ return null;
+ }
+
+ if (offerId && offer.offerId !== offerId) return null;
+ if (projectId && offer.projectId !== projectId) return null;
+ if (sceneId && offer.sceneId && offer.sceneId !== sceneId) return null;
+ if (offer.trackType !== "screen") return null;
+ if (!offer.chunkCount || !offer.estimatedBytes) return null;
+
+ return offer;
+};
+
const ensureAudioOffscreen = async () => {
if (!chrome.offscreen) return false;
try {
@@ -290,26 +451,43 @@ const handleFinishMultiRecording = async () => {
}
});
} else {
- // Multi recording on existing project
- const { editorTab } = await chrome.storage.local.get(["editorTab"]);
- // check if editor tab is valid, if so focus to it, otherwise use active tab
- if (editorTab) {
- focusTab(editorTab);
- sendMessageTab(editorTab, {
+ // Multi recording on existing project: only reuse editorTab if it still
+ // matches this project and expected editor/view URL.
+ const { projectId, instantMode } = await chrome.storage.local.get([
+ "projectId",
+ "instantMode",
+ ]);
+ const targetUrl = getEditorTargetUrl({
+ projectId,
+ instantMode: Boolean(instantMode),
+ });
+ const expectedKind = instantMode ? "view" : "editor";
+ const resolved = await resolveEditorTabForTarget({
+ targetUrl,
+ expectedProjectId: projectId || null,
+ expectedKind,
+ reason: "finish-multi-recording",
+ });
+ const messageTab = resolved.tabId || (await getCurrentTab())?.id || null;
+
+ if (messageTab) {
+ await focusTab(messageTab, { reason: "finish-multi-recording:notify" });
+ await sendMessageTab(messageTab, {
type: "update-project-ready",
share: false,
newProject: false,
- });
+ projectId: projectId || null,
+ }).catch((err) =>
+ console.warn(
+ "[Screenity][BG] Failed to send update-project-ready (finish-multi-recording)",
+ err,
+ ),
+ );
} else {
- const activeTab = (await getCurrentTab())?.id || null;
- if (activeTab) {
- focusTab(activeTab);
- sendMessageTab(activeTab, {
- type: "update-project-ready",
- share: false,
- newProject: false,
- });
- }
+ console.warn(
+ "[Screenity][BG] No tab available for update-project-ready (finish-multi-recording)",
+ { projectId, instantMode: Boolean(instantMode) },
+ );
}
chrome.storage.local.set({
@@ -320,6 +498,7 @@ const handleFinishMultiRecording = async () => {
multiMode: false,
multiProjectId: null,
editorTab: null,
+ editorTabMeta: null,
});
const tab = await getCurrentTab();
@@ -554,6 +733,7 @@ export const setupHandlers = () => {
// runs. During restart, `recording` may still be true briefly from the
// previous session, so only block when recording is active AND not restarting.
if (recording && !restarting) {
+ diagEvent("countdown-finished", { skipped: true, reason: "already-recording" });
const decisionAt = Date.now();
await chrome.storage.local.set({
lastCountdownFinishedDecision: {
@@ -570,6 +750,7 @@ export const setupHandlers = () => {
});
return { ok: true, skipped: true };
}
+ diagEvent("countdown-finished", { skipped: false });
const decisionAt = Date.now();
await chrome.storage.local.set({
countdownFinishedAt: message?.endedAt || decisionAt,
@@ -739,13 +920,19 @@ export const setupHandlers = () => {
registerMessage("dismiss-recording-tab", (message) =>
handleDismissRecordingTab(message),
);
- registerMessage("pause-recording-tab", () =>
- sendMessageRecord({ type: "pause-recording-tab" }),
- );
- registerMessage("resume-recording-tab", () =>
- sendMessageRecord({ type: "resume-recording-tab" }),
- );
+ registerMessage("pause-recording-tab", () => {
+ diagEvent("pause");
+ return sendMessageRecord({ type: "pause-recording-tab" });
+ });
+ registerMessage("resume-recording-tab", () => {
+ diagEvent("resume");
+ return sendMessageRecord({ type: "resume-recording-tab" });
+ });
registerMessage("set-mic-active-tab", (message) => setMicActiveTab(message));
+
+ // Diagnostic events routed from content scripts
+ registerMessage("diag-countdown-started", () => diagEvent("countdown-started"));
+ registerMessage("diag-countdown-cancelled", () => diagEvent("countdown-cancelled"));
registerMessage("recording-error", async (message) => {
await handleRecordingError(message);
await clearRecordingSessionSafe("recording-error", {
@@ -854,14 +1041,13 @@ export const setupHandlers = () => {
registerMessage("open-home", () =>
createTab("https://screenity.io/", false, true),
);
- registerMessage("report-bug", () =>
- createTab(
- "https://tally.so/r/3ElpXq?version=" +
- chrome.runtime.getManifest().version,
- false,
- true,
- ),
- );
+ registerMessage("report-bug", async () => {
+ const qs = await supportContextQuery({
+ includeRecordingState: true,
+ source: "settings",
+ });
+ createTab(`https://tally.so/r/3ElpXq?${qs}`, false, true);
+ });
registerMessage("clear-recordings", () => clearAllRecordings());
registerMessage("force-processing", (message) => forceProcessing(message));
registerMessage("focus-this-tab", (message, sender) =>
@@ -874,12 +1060,31 @@ export const setupHandlers = () => {
downloadIndexedDB(message),
);
registerMessage("get-platform-info", async () => await getPlatformInfo());
+ registerMessage(
+ "get-diagnostic-log",
+ async (_message, _sender, sendResponse) => {
+ const log = await getDiagnosticLog();
+ const errors = await getErrorSnapshot();
+ const flags = await getStorageFlags();
+ sendResponse({ log, errors, flags });
+ return true;
+ },
+ );
registerMessage("restore-recording", (message) => restoreRecording(message));
registerMessage("check-restore", async (message, sender, sendResponse) => {
const response = await checkRestore();
sendResponse(response);
return true;
});
+ registerMessage(
+ "check-cloud-restore",
+ async (_message, _sender, sendResponse) => {
+ const response = await checkCloudRestore();
+ sendResponse(response);
+ return true;
+ },
+ );
+ registerMessage("restore-cloud-recording", () => restoreCloudRecording());
registerMessage(
"check-capture-permissions",
async (message, sender, sendResponse) => {
@@ -1201,8 +1406,40 @@ export const setupHandlers = () => {
console.warn("Cloud features disabled");
return;
}
- const createdTab = await createTab(message.url, true, true);
- chrome.storage.local.set({ editorTab: createdTab?.id || null });
+ const targetUrl = message.url || null;
+ const parsedTarget = parseEditorTargetUrl(targetUrl);
+ const expectedProjectId = message.projectId || parsedTarget?.projectId || null;
+
+ await chrome.storage.local.set({
+ pendingEditorOpen: {
+ url: targetUrl,
+ publicUrl: message.publicUrl || null,
+ projectId: expectedProjectId,
+ instantMode: Boolean(message.instantMode),
+ ts: Date.now(),
+ },
+ });
+
+ console.info("[Screenity][BG] prepare-open-editor", {
+ projectId: expectedProjectId,
+ targetUrl,
+ instantMode: Boolean(message.instantMode),
+ hasPublicUrl: Boolean(message.publicUrl),
+ });
+
+ const expectedKind = message.instantMode ? "view" : "editor";
+ const resolved = await resolveEditorTabForTarget({
+ targetUrl,
+ expectedProjectId: expectedProjectId,
+ expectedKind,
+ reason: "prepare-open-editor",
+ });
+ console.info("[Screenity][BG] prepare-open-editor resolved", {
+ tabId: resolved.tabId || null,
+ reused: Boolean(resolved.reused),
+ opened: Boolean(resolved.opened),
+ projectId: expectedProjectId,
+ });
});
registerMessage("prepare-editor-existing", async (message) => {
if (!CLOUD_FEATURES_ENABLED) {
@@ -1214,15 +1451,36 @@ export const setupHandlers = () => {
if (message.multiMode) {
messageTab = (await getCurrentTab())?.id || null;
} else {
- const { editorTab } = await chrome.storage.local.get(["editorTab"]);
- messageTab = editorTab;
- focusTab(editorTab);
+ const { projectId, instantMode } = await chrome.storage.local.get([
+ "projectId",
+ "instantMode",
+ ]);
+ const targetUrl = getEditorTargetUrl({
+ projectId,
+ instantMode: Boolean(instantMode),
+ });
+ const resolved = await resolveEditorTabForTarget({
+ targetUrl,
+ expectedProjectId: projectId || null,
+ expectedKind: instantMode ? "view" : "editor",
+ reason: "prepare-editor-existing",
+ });
+ messageTab = resolved.tabId;
}
- sendMessageTab(messageTab, {
- type: "update-project-loading",
- multiMode: message.multiMode,
- });
+ if (messageTab) {
+ await sendMessageTab(messageTab, {
+ type: "update-project-loading",
+ multiMode: message.multiMode,
+ }).catch((err) =>
+ console.warn(
+ "[Screenity][BG] Failed to send update-project-loading",
+ err,
+ ),
+ );
+ } else {
+ console.warn("❗ No valid messageTab found in prepare-editor-existing");
+ }
});
registerMessage("preparing-recording", async () => {
const tab = await getCurrentTab();
@@ -1239,60 +1497,303 @@ export const setupHandlers = () => {
console.warn("Cloud features disabled");
return;
}
+ const { pendingEditorOpen } = await chrome.storage.local.get([
+ "pendingEditorOpen",
+ ]);
+
let messageTab = null;
+ const projectId = message.projectId || pendingEditorOpen?.projectId || null;
+ const instantMode = Boolean(
+ message.instantMode ?? pendingEditorOpen?.instantMode,
+ );
+ const targetUrl = getEditorTargetUrl({
+ projectId,
+ instantMode,
+ });
+ const editorUrl = message.editorUrl || pendingEditorOpen?.url || targetUrl;
+ const expectedKind = instantMode ? "view" : "editor";
+ const publicUrl = message.publicUrl || pendingEditorOpen?.publicUrl || null;
const sceneId = message.sceneId || null;
+ const localPlaybackOffer =
+ (await getValidLocalPlaybackOffer({
+ offerId: message?.localPlayback?.offerId || null,
+ projectId: projectId || null,
+ sceneId: sceneId || null,
+ })) ||
+ null;
+
+ console.info("[Screenity][BG] editor-ready received", {
+ newProject: Boolean(message.newProject),
+ multiMode: Boolean(message.multiMode),
+ projectId,
+ hasSceneId: Boolean(sceneId),
+ editorUrl,
+ hasPendingOpen: Boolean(pendingEditorOpen),
+ localPlaybackAvailable: Boolean(localPlaybackOffer?.offerId),
+ localPlaybackOfferId: localPlaybackOffer?.offerId || null,
+ });
if (message.newProject) {
- const { editorTab } = await chrome.storage.local.get(["editorTab"]);
- messageTab = editorTab;
+ const resolved = await resolveEditorTabForTarget({
+ targetUrl: editorUrl,
+ expectedProjectId: projectId,
+ expectedKind,
+ reason: "editor-ready:new-project",
+ });
+ messageTab = resolved.tabId;
chrome.runtime.sendMessage({ type: "turn-off-pip" });
- // FLAG: this should go here right?
- const res = await fetch(
- `${API_BASE}/videos/${message.projectId}/auto-publish`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${await chrome.storage.local
- .get("screenityToken")
- .then((r) => r.screenityToken)}`,
- },
- },
- );
+ // 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.
+ if (publicUrl) {
+ copyToClipboard(publicUrl);
+ }
- if (editorTab) {
- focusTab(editorTab);
+ 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 {
- const { editorTab } = await chrome.storage.local.get(["editorTab"]);
- messageTab = editorTab;
+ const resolved = await resolveEditorTabForTarget({
+ targetUrl: editorUrl,
+ expectedProjectId: projectId,
+ expectedKind,
+ reason: "editor-ready:existing-project",
+ });
+ messageTab = resolved.tabId;
chrome.runtime.sendMessage({ type: "turn-off-pip" });
-
- if (editorTab) {
- focusTab(editorTab);
- }
}
- // Only copy once if there's a publicUrl
- if (message.publicUrl) {
- copyToClipboard(message.publicUrl);
+ // 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).
+ if (publicUrl && !message.newProject) {
+ copyToClipboard(publicUrl);
}
if (messageTab) {
- sendMessageTab(messageTab, {
+ await sendMessageTab(messageTab, {
type: "update-project-ready",
- share: Boolean(message.publicUrl),
+ share: Boolean(publicUrl),
newProject: Boolean(message.newProject),
sceneId: sceneId,
- });
+ projectId,
+ localPlayback: localPlaybackOffer
+ ? {
+ available: true,
+ offerId: localPlaybackOffer.offerId,
+ trackType: "screen",
+ chunkCount: localPlaybackOffer.chunkCount,
+ estimatedBytes: localPlaybackOffer.estimatedBytes,
+ expiresAt: localPlaybackOffer.expiresAt,
+ source: localPlaybackOffer.source || "indexeddb-screen-chunks",
+ mediaId: localPlaybackOffer.mediaId || null,
+ bunnyVideoId: localPlaybackOffer.bunnyVideoId || null,
+ }
+ : {
+ available: false,
+ trackType: "screen",
+ },
+ }).catch((err) =>
+ console.warn("[Screenity][BG] Failed to send update-project-ready", err),
+ );
} else {
console.warn("❗ No valid messageTab found in editor-ready");
}
+
+ if (pendingEditorOpen) {
+ await chrome.storage.local.remove(["pendingEditorOpen"]);
+ }
+ });
+ registerMessage("cloud-local-playback-register", async (message) => {
+ const normalizedOffer = normalizeLocalPlaybackOffer(message?.offer || {});
+ if (!normalizedOffer.projectId || !normalizedOffer.sceneId) {
+ return { ok: false, error: "missing-project-or-scene" };
+ }
+ if (!normalizedOffer.chunkCount || !normalizedOffer.estimatedBytes) {
+ return { ok: false, error: "missing-local-screen-bytes" };
+ }
+ if (normalizedOffer.estimatedBytes > CLOUD_LOCAL_PLAYBACK_MAX_BYTES) {
+ return {
+ ok: false,
+ error: "offer-too-large",
+ maxBytes: CLOUD_LOCAL_PLAYBACK_MAX_BYTES,
+ };
+ }
+
+ await chrome.storage.local.set({
+ [CLOUD_LOCAL_PLAYBACK_KEY]: normalizedOffer,
+ [CLOUD_LOCAL_PLAYBACK_EVENT_KEY]: {
+ event: "offer-registered",
+ at: Date.now(),
+ offerId: normalizedOffer.offerId,
+ projectId: normalizedOffer.projectId,
+ sceneId: normalizedOffer.sceneId,
+ chunkCount: normalizedOffer.chunkCount,
+ estimatedBytes: normalizedOffer.estimatedBytes,
+ expiresAt: normalizedOffer.expiresAt,
+ },
+ });
+ await scheduleLocalPlaybackAlarm(normalizedOffer);
+
+ console.info("[Screenity][BG] Registered local screen playback offer", {
+ offerId: normalizedOffer.offerId,
+ projectId: normalizedOffer.projectId,
+ sceneId: normalizedOffer.sceneId,
+ chunkCount: normalizedOffer.chunkCount,
+ estimatedBytes: normalizedOffer.estimatedBytes,
+ expiresAt: normalizedOffer.expiresAt,
+ });
+
+ return { ok: true, offer: normalizedOffer };
+ });
+ registerMessage("cloud-local-playback-clear", async (message) => {
+ const result = await clearStoredLocalPlaybackOffer({
+ reason: message?.reason || "explicit-clear",
+ clearChunks: message?.clearChunks !== false,
+ onlyIfOfferId: message?.offerId || null,
+ });
+ return result;
+ });
+ registerMessage("cloud-local-playback-get-offer", async (message) => {
+ const offer = await getValidLocalPlaybackOffer({
+ offerId: message?.offerId || null,
+ projectId: message?.projectId || null,
+ sceneId: message?.sceneId || null,
+ });
+ if (!offer) {
+ return { ok: false, error: "offer-unavailable" };
+ }
+ return { ok: true, offer };
+ });
+ registerMessage("cloud-local-playback-read-chunk", async (message) => {
+ const offer = await getValidLocalPlaybackOffer({
+ offerId: message?.offerId || null,
+ projectId: message?.projectId || null,
+ sceneId: message?.sceneId || null,
+ });
+ if (!offer) {
+ return { ok: false, error: "offer-unavailable" };
+ }
+
+ const index = Number(message?.index);
+ if (!Number.isInteger(index) || index < 0 || index >= offer.chunkCount) {
+ return { ok: false, error: "chunk-index-out-of-range", index };
+ }
+
+ const item = await chunksStore.getItem(`chunk_${index}`).catch(() => null);
+ if (!item?.chunk) {
+ return { ok: false, error: "chunk-missing", index };
+ }
+
+ const blob =
+ item.chunk instanceof Blob
+ ? item.chunk
+ : new Blob([item.chunk], { type: "video/webm" });
+ const arrayBuffer = await blob.arrayBuffer();
+ const base64 = btoa(
+ new Uint8Array(arrayBuffer).reduce(
+ (data, byte) => data + String.fromCharCode(byte),
+ "",
+ ),
+ );
+
+ return {
+ ok: true,
+ chunk: {
+ index,
+ size: blob.size,
+ mimeType: blob.type || "video/webm",
+ base64,
+ },
+ offer: {
+ offerId: offer.offerId,
+ expiresAt: offer.expiresAt,
+ },
+ };
+ });
+ registerMessage("cloud-local-playback-mark-used", async (message) => {
+ const offer = await getValidLocalPlaybackOffer({
+ offerId: message?.offerId || null,
+ projectId: message?.projectId || null,
+ sceneId: message?.sceneId || null,
+ });
+ if (!offer) {
+ return { ok: false, error: "offer-unavailable" };
+ }
+ const updated = {
+ ...offer,
+ status: "used",
+ usedAt: Date.now(),
+ usedBy: message?.usedBy || "editor",
+ updatedAt: Date.now(),
+ };
+ await chrome.storage.local.set({
+ [CLOUD_LOCAL_PLAYBACK_KEY]: updated,
+ [CLOUD_LOCAL_PLAYBACK_EVENT_KEY]: {
+ event: "offer-used",
+ at: Date.now(),
+ offerId: updated.offerId,
+ projectId: updated.projectId,
+ sceneId: updated.sceneId,
+ },
+ });
+ console.info("[Screenity][BG] Local screen playback offer marked used", {
+ offerId: updated.offerId,
+ projectId: updated.projectId,
+ sceneId: updated.sceneId,
+ });
+ return { ok: true, offer: updated };
+ });
+ registerMessage("cloud-local-playback-mark-fallback", async (message) => {
+ const offer = await getValidLocalPlaybackOffer({
+ offerId: message?.offerId || null,
+ projectId: message?.projectId || null,
+ sceneId: message?.sceneId || null,
+ });
+ if (!offer) {
+ return { ok: false, error: "offer-unavailable" };
+ }
+ const updated = {
+ ...offer,
+ status: "fallback",
+ fallbackReason: message?.reason || "unknown",
+ fallbackAt: Date.now(),
+ updatedAt: Date.now(),
+ };
+ await chrome.storage.local.set({
+ [CLOUD_LOCAL_PLAYBACK_KEY]: updated,
+ [CLOUD_LOCAL_PLAYBACK_EVENT_KEY]: {
+ event: "offer-fallback",
+ at: Date.now(),
+ offerId: updated.offerId,
+ reason: updated.fallbackReason,
+ },
+ });
+ console.info("[Screenity][BG] Local screen playback offer fallback", {
+ offerId: updated.offerId,
+ reason: updated.fallbackReason,
+ });
+ return { ok: true, offer: updated };
});
registerMessage("finish-multi-recording", async () => {
if (!CLOUD_FEATURES_ENABLED) {
@@ -1349,13 +1850,12 @@ export const setupHandlers = () => {
}
const { name, email } = user;
- const query = new URLSearchParams({
- extension: "true",
- name,
- email,
+ const qs = await supportContextQuery({
+ includeRecordingState: true,
+ source: "settings",
+ user: { name, email },
});
-
- const url = `https://tally.so/r/310MNg?${query.toString()}`;
+ const url = `https://tally.so/r/310MNg?extension=true&${qs}`;
createTab(url, true, true);
});
registerMessage("check-banner-support", async (message, sendResponse) => {
diff --git a/src/pages/Background/offscreen/offscreenDocument.js b/src/pages/Background/offscreen/offscreenDocument.js
index 4e94117..c171bf8 100644
--- a/src/pages/Background/offscreen/offscreenDocument.js
+++ b/src/pages/Background/offscreen/offscreenDocument.js
@@ -54,10 +54,16 @@ const openRecorderTab = async (
chrome.tabs.onUpdated.addListener(function _(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status === "complete") {
chrome.tabs.onUpdated.removeListener(_);
+ // Include tabPreferred in the message so CloudRecorder can use it
+ // synchronously without racing against its own storage read.
+ const isPlayground = activeTab.url.includes(
+ chrome.runtime.getURL("playground.html")
+ );
sendMessageRecord({
type: "loaded",
request: request,
backup: backup,
+ tabPreferred: isPlayground,
...(isRegion
? {
isTab: true,
diff --git a/src/pages/Background/recording/chunkHandler.js b/src/pages/Background/recording/chunkHandler.js
index ee6fae0..fc1971a 100644
--- a/src/pages/Background/recording/chunkHandler.js
+++ b/src/pages/Background/recording/chunkHandler.js
@@ -12,7 +12,7 @@ export const chunksStore = localforage.createInstance({ name: "chunks" });
export const localDirectoryStore = localforage.createInstance({
name: "localDirectory",
});
-const DEBUG_POSTSTOP = true;
+const DEBUG_POSTSTOP = false;
export const clearAllRecordings = async () => {
try {
diff --git a/src/pages/Background/recording/cloudLocalPlaybackConstants.js b/src/pages/Background/recording/cloudLocalPlaybackConstants.js
new file mode 100644
index 0000000..c21b31e
--- /dev/null
+++ b/src/pages/Background/recording/cloudLocalPlaybackConstants.js
@@ -0,0 +1,3 @@
+export const CLOUD_LOCAL_PLAYBACK_KEY = "cloudLocalScreenPlaybackOffer";
+export const CLOUD_LOCAL_PLAYBACK_EVENT_KEY = "lastCloudLocalPlaybackEvent";
+export const CLOUD_LOCAL_PLAYBACK_ALARM = "cloud-local-playback-expiry";
diff --git a/src/pages/Background/recording/discardRecording.js b/src/pages/Background/recording/discardRecording.js
index 40a4361..a7e7833 100644
--- a/src/pages/Background/recording/discardRecording.js
+++ b/src/pages/Background/recording/discardRecording.js
@@ -12,6 +12,8 @@ export const discardRecording = async () => {
recordingTab: null,
sandboxTab: null,
recording: false,
+ restarting: false,
+ pendingRecording: false,
});
chrome.storage.local.set({ pipForceClose: Date.now() });
chrome.storage.local.set({ recordingUiTabId: null });
diff --git a/src/pages/Background/recording/recordingHelpers.js b/src/pages/Background/recording/recordingHelpers.js
index ac77cb6..1e7498e 100644
--- a/src/pages/Background/recording/recordingHelpers.js
+++ b/src/pages/Background/recording/recordingHelpers.js
@@ -9,6 +9,7 @@ import { stopRecording } from "./stopRecording";
import { addAlarmListener } from "../alarms/addAlarmListener";
import { getStreamingData } from "./getStreamingData";
import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocuments";
+import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";
export const checkCapturePermissions = async ({ isLoggedIn, isSubscribed }) => {
const permissions = ["desktopCapture", "alarms", "offscreen"];
@@ -102,9 +103,15 @@ export const handleRecordingError = async (request) => {
pendingRecording: false,
});
+ const isWarningOnly = request.error === "stream-ended";
+ diagEvent(isWarningOnly ? "warning" : "error", {
+ error: request?.error || null,
+ why: request?.why || null,
+ });
+
// For stream-ended, we just notify the user but DON'T stop the recording
// The user can decide whether to continue or stop
- if (request.error === "stream-ended") {
+ if (isWarningOnly) {
sendMessageTab(activeTab, {
type: "stream-ended-warning",
message: request.why || "Screen sharing stopped unexpectedly.",
@@ -112,6 +119,8 @@ export const handleRecordingError = async (request) => {
return; // Don't continue with the normal error handling
}
+ endDiagSession("error");
+
await chrome.storage.local.set({
recording: false,
recordingUiTabId: null,
diff --git a/src/pages/Background/recording/restartRecording.js b/src/pages/Background/recording/restartRecording.js
index 0a7a54d..70a66ab 100644
--- a/src/pages/Background/recording/restartRecording.js
+++ b/src/pages/Background/recording/restartRecording.js
@@ -1,5 +1,6 @@
import { sendMessageRecord } from "./sendMessageRecord";
import { resetActiveTabRestart } from "../tabManagement/resetActiveTab";
+import { diagEvent } from "../../utils/diagnosticLog";
const RESTART_ACK_TIMEOUT_MS = 7000;
@@ -33,6 +34,7 @@ export const handleRestart = async (message = {}, sender = null) => {
: {}),
});
await persistRestartFlow("requested", { sourceTabId });
+ diagEvent("restart-requested");
try {
const response = await withTimeout(
@@ -53,11 +55,13 @@ export const handleRestart = async (message = {}, sender = null) => {
});
await resetActiveTabRestart({ sourceTabId });
await persistRestartFlow("countdown-dispatched", { sourceTabId });
+ diagEvent("restart-completed");
return { ok: true, restarted: true };
} catch (error) {
const reason = error?.message || String(error);
await chrome.storage.local.set({ restarting: false });
await persistRestartFlow("failed", { sourceTabId, reason });
+ diagEvent("restart-failed", { reason });
return { ok: false, error: reason };
}
};
diff --git a/src/pages/Background/recording/restoreCloudRecording.js b/src/pages/Background/recording/restoreCloudRecording.js
new file mode 100644
index 0000000..a0c8299
--- /dev/null
+++ b/src/pages/Background/recording/restoreCloudRecording.js
@@ -0,0 +1,60 @@
+import localforage from "localforage";
+import { createTab, sendMessageTab } from "../tabManagement";
+
+const RECOVERABLE_CLOUD_STATUSES = new Set([
+ "recording",
+ "hidden",
+ "unload",
+ "stopping",
+ "finalize-failed",
+ "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" });
+
+export const checkCloudRestore = async () => {
+ try {
+ const { recorderSession } = await chrome.storage.local.get([
+ "recorderSession",
+ ]);
+ if (
+ !recorderSession ||
+ !RECOVERABLE_CLOUD_STATUSES.has(recorderSession.status)
+ ) {
+ return { cloudRestore: false };
+ }
+
+ const [screenCount, cameraCount, audioCount] = await Promise.all([
+ cloudScreenStore.length().catch(() => 0),
+ cloudCameraStore.length().catch(() => 0),
+ cloudAudioStore.length().catch(() => 0),
+ ]);
+
+ return {
+ cloudRestore: screenCount > 0 || cameraCount > 0 || audioCount > 0,
+ };
+ } catch (err) {
+ console.warn("[CloudRestore] checkCloudRestore failed:", err);
+ return { cloudRestore: false };
+ }
+};
+
+export const restoreCloudRecording = async () => {
+ const { cloudRestore } = await checkCloudRestore();
+ if (!cloudRestore) return;
+
+ const tab = await createTab("download.html", true, true);
+ if (!tab?.id) return;
+
+ chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
+ if (info.status === "complete" && tabId === tab.id) {
+ chrome.tabs.onUpdated.removeListener(listener);
+ sendMessageTab(tab.id, { type: "recover-cloud-indexed-db" });
+ }
+ });
+};
diff --git a/src/pages/Background/recording/sendChunks.js b/src/pages/Background/recording/sendChunks.js
index 639a893..29ee090 100644
--- a/src/pages/Background/recording/sendChunks.js
+++ b/src/pages/Background/recording/sendChunks.js
@@ -1,5 +1,6 @@
import { chunksStore } from "./chunkHandler";
import { handleChunks } from "./chunkHandler";
+import { diagEvent } from "../../utils/diagnosticLog";
export const sendChunks = async (override = false, target = null) => {
try {
@@ -34,6 +35,7 @@ export const sendChunks = async (override = false, target = null) => {
},
});
} catch {}
+ diagEvent("chunks-fail", { why: "no-chunks-after-wait" });
return { status: "empty", chunkCount: 0 };
}
@@ -46,6 +48,7 @@ export const sendChunks = async (override = false, target = null) => {
});
// Await handleChunks to ensure messaging completes before returning
await handleChunks(chunks, override, target);
+ diagEvent("chunks-sent", { count: chunks.length });
return { status: "ok", chunkCount: chunks.length };
} catch (error) {
console.error("Failed to send chunks. Reloading extension.", error);
diff --git a/src/pages/Background/recording/startRecording.js b/src/pages/Background/recording/startRecording.js
index 83dec35..cfed4c2 100644
--- a/src/pages/Background/recording/startRecording.js
+++ b/src/pages/Background/recording/startRecording.js
@@ -1,4 +1,5 @@
import { sendMessageRecord } from "./sendMessageRecord";
+import { initDiagSession, diagEvent } from "../../utils/diagnosticLog";
export const startRecording = async () => {
chrome.storage.local.set({
@@ -55,6 +56,34 @@ export const startRecording = async () => {
chrome.storage.local.remove(["recordingMeta"]);
}
+ // Initialize diagnostic session for this recording
+ const { quality, systemAudio, audioInput, backup, offscreen, alarm, alarmTime, countdown } =
+ await chrome.storage.local.get([
+ "quality",
+ "systemAudio",
+ "audioInput",
+ "backup",
+ "offscreen",
+ "alarm",
+ "alarmTime",
+ "countdown",
+ ]);
+ await initDiagSession({
+ recordingType: recordingType || "screen",
+ quality: quality || null,
+ region: Boolean(customRegion),
+ systemAudio: Boolean(systemAudio),
+ audioInput: Boolean(audioInput),
+ backup: Boolean(backup),
+ offscreen: Boolean(offscreen),
+ alarm: Boolean(alarm),
+ 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) });
+
if (customRegion) {
sendMessageRecord({ type: "start-recording-tab", region: true })
.then(() => {
@@ -75,6 +104,7 @@ export const startRecording = async () => {
error: String(err),
},
});
+ diagEvent("start-fail", { region: true, error: String(err) });
});
} else {
sendMessageRecord({ type: "start-recording-tab" })
@@ -96,12 +126,11 @@ export const startRecording = async () => {
error: String(err),
},
});
+ diagEvent("start-fail", { region: false, error: String(err) });
});
}
chrome.action.setIcon({ path: "assets/recording-logo.png" });
// Set up alarm if set in storage
- const { alarm } = await chrome.storage.local.get(["alarm"]);
- const { alarmTime } = await chrome.storage.local.get(["alarmTime"]);
if (alarm) {
const seconds = parseFloat(alarmTime);
chrome.alarms.create("recording-alarm", { delayInMinutes: seconds / 60 });
diff --git a/src/pages/Background/recording/stopRecording.js b/src/pages/Background/recording/stopRecording.js
index a4d1c53..529c3f0 100644
--- a/src/pages/Background/recording/stopRecording.js
+++ b/src/pages/Background/recording/stopRecording.js
@@ -3,6 +3,7 @@ import { discardOffscreenDocuments } from "../offscreen/discardOffscreenDocument
import { sendMessageRecord } from "./sendMessageRecord";
import { sendChunks } from "./sendChunks";
import { waitForContentScript } from "../utils/waitForContentScript";
+import { diagEvent, endDiagSession } from "../../utils/diagnosticLog";
const acquirePostStopEditorLock = async (recordingId = null) => {
const { postStopEditorOpening } = await chrome.storage.local.get([
@@ -28,13 +29,14 @@ const releasePostStopEditorLock = async (overrides = {}) => {
export const stopRecording = async () => {
chrome.action.setIcon({ path: "assets/icon-34.png" });
chrome.storage.local.set({ restarting: false });
- const { recordingStartTime, isSubscribed, paused, pausedAt, totalPausedMs } =
+ const { recordingStartTime, isSubscribed, paused, pausedAt, totalPausedMs, recordingDuration: storedDuration } =
await chrome.storage.local.get([
"recordingStartTime",
"isSubscribed",
"paused",
"pausedAt",
"totalPausedMs",
+ "recordingDuration",
]);
const startTime = Number(recordingStartTime);
@@ -50,8 +52,17 @@ export const stopRecording = async () => {
Number.isFinite(startTime) && startTime > 0
? 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.
+ if (duration === 0 && Number(storedDuration) > 0) {
+ duration = Number(storedDuration);
+ }
const maxDuration = 7 * 60 * 1000;
+ diagEvent("stop", { duration, isSubscribed: Boolean(isSubscribed) });
+
chrome.storage.local.set({
recording: false,
recordingDuration: duration,
@@ -104,6 +115,7 @@ export const stopRecording = async () => {
// Editor already opened by stop-recording-tab flow; avoid opening a second tab.
// That flow will trigger processing when the tab finishes loading.
} else if (hasWebCodecs) {
+ diagEvent("editor-open", { type: "editorwebcodecs" });
// Use Mediabunny (editorwebcodecs.html) when WebCodecs is supported
const query = postStopRecordingId
? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`
@@ -134,6 +146,7 @@ export const stopRecording = async () => {
chrome.runtime.sendMessage({ type: "turn-off-pip" });
} else if (duration > maxDuration) {
+ diagEvent("editor-open", { type: "editorviewer", duration });
// Fallback for large recordings without WebCodecs - use viewer mode
const query = postStopRecordingId
@@ -165,6 +178,7 @@ export const stopRecording = async () => {
chrome.runtime.sendMessage({ type: "turn-off-pip" });
} else {
+ diagEvent("editor-open", { type: "editor-ffmpeg" });
// Use FFmpeg (editor.html) for browsers without WebCodecs
const query = postStopRecordingId
? `?mode=postStop&recordingId=${encodeURIComponent(postStopRecordingId)}`
@@ -193,6 +207,11 @@ export const stopRecording = async () => {
chrome.runtime.sendMessage({ type: "turn-off-pip" });
}
+ // 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.
+ endDiagSession("ok");
+
const { wasRegion } = await chrome.storage.local.get(["wasRegion"]);
if (wasRegion) {
chrome.storage.local.set({ wasRegion: false, region: true });
@@ -205,6 +224,7 @@ export const stopRecording = async () => {
export const handleStopRecordingTab = async (request) => {
chrome.action.setIcon({ path: "assets/icon-34.png" });
if (request.memoryError) {
+ diagEvent("error", { type: "memory-error" });
chrome.storage.local.set({
recording: false,
restarting: false,
@@ -228,6 +248,20 @@ export const handleStopRecordingTab = async (request) => {
"totalPausedMs",
"fastRecorderInUse",
]);
+ const stopTabNow = Date.now();
+ const stopTabStartTime = Number(recordingStartTime);
+ const stopTabBasePaused = Number(totalPausedMs) || 0;
+ const stopTabPausedAtMs = Number(pausedAt);
+ const stopTabExtraPaused =
+ paused && Number.isFinite(stopTabPausedAtMs) && stopTabPausedAtMs > 0
+ ? Math.max(0, stopTabNow - stopTabPausedAtMs)
+ : 0;
+ const stopTabDuration =
+ Number.isFinite(stopTabStartTime) && stopTabStartTime > 0
+ ? Math.max(0, stopTabNow - stopTabStartTime - stopTabBasePaused - stopTabExtraPaused)
+ : 0;
+ diagEvent("stop-tab", { duration: stopTabDuration, reason: request.reason || null, memoryError: Boolean(request.memoryError), fastRecorderInUse: Boolean(fastRecorderInUse) });
+
if (!isSubscribed) {
const { fastRecorderActiveRecordingId } = await chrome.storage.local.get([
"fastRecorderActiveRecordingId",
@@ -258,6 +292,7 @@ export const handleStopRecordingTab = async (request) => {
}
if (fastRecorderInUse) {
+ diagEvent("editor-open", { type: "editorwebcodecs", via: "stop-tab" });
const editorUrl = "editorwebcodecs.html";
// Open editor immediately in postStop mode (WebCodecs only)
chrome.tabs.create(
@@ -300,6 +335,7 @@ export const handleStopRecordingTab = async (request) => {
} else {
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)
chrome.tabs.create({ url: editorUrl, active: true }, (tab) => {
if (chrome.runtime.lastError || !tab?.id) {
diff --git a/src/pages/Background/tabManagement/editorTab.js b/src/pages/Background/tabManagement/editorTab.js
new file mode 100644
index 0000000..6f4f511
--- /dev/null
+++ b/src/pages/Background/tabManagement/editorTab.js
@@ -0,0 +1,304 @@
+import { createTab } from "./createTab";
+import { focusTab } from "./focusTab";
+
+const APP_BASE_URL = process.env.SCREENITY_APP_BASE;
+const EDITOR_TAB_META_KEY = "editorTabMeta";
+
+const toUrl = (value) => {
+ if (!value || typeof value !== "string") return null;
+ try {
+ return new URL(value);
+ } catch {
+ return null;
+ }
+};
+
+const getAppOrigin = () => {
+ const appUrl = toUrl(APP_BASE_URL);
+ return appUrl?.origin || null;
+};
+
+export const parseEditorTargetUrl = (rawUrl) => {
+ const url = toUrl(rawUrl);
+ if (!url) return null;
+
+ const appOrigin = getAppOrigin();
+ if (!appOrigin || url.origin !== appOrigin) return null;
+
+ const editorMatch = url.pathname.match(/^\/editor\/([^/]+)\/edit\/?$/);
+ if (editorMatch?.[1]) {
+ return {
+ kind: "editor",
+ projectId: editorMatch[1],
+ origin: url.origin,
+ href: url.href,
+ };
+ }
+
+ const viewMatch = url.pathname.match(/^\/view\/([^/]+)\/?$/);
+ if (viewMatch?.[1]) {
+ return {
+ kind: "view",
+ projectId: viewMatch[1],
+ origin: url.origin,
+ href: url.href,
+ };
+ }
+
+ return null;
+};
+
+const getTabUrl = (tab) => tab?.pendingUrl || tab?.url || null;
+
+const getTabById = async (tabId) => {
+ if (!Number.isInteger(tabId)) return null;
+ try {
+ return await chrome.tabs.get(tabId);
+ } catch {
+ return null;
+ }
+};
+
+export const clearEditorTabReference = async (reason = "unknown", extra = {}) => {
+ await chrome.storage.local.set({
+ editorTab: null,
+ [EDITOR_TAB_META_KEY]: null,
+ });
+ console.info("[Screenity][BG] Cleared editorTab reference", {
+ reason,
+ ...extra,
+ });
+};
+
+export const setEditorTabReference = async ({
+ tabId,
+ tabUrl,
+ source = "unknown",
+ expectedProjectId = null,
+}) => {
+ if (!Number.isInteger(tabId)) {
+ await clearEditorTabReference("set-editor-tab-invalid-id", {
+ source,
+ tabId,
+ });
+ return null;
+ }
+
+ const parsed = parseEditorTargetUrl(tabUrl);
+ if (!parsed) {
+ await clearEditorTabReference("set-editor-tab-invalid-url", {
+ source,
+ tabId,
+ tabUrl,
+ });
+ return null;
+ }
+
+ if (expectedProjectId && expectedProjectId !== parsed.projectId) {
+ await clearEditorTabReference("set-editor-tab-project-mismatch", {
+ source,
+ tabId,
+ expectedProjectId,
+ parsedProjectId: parsed.projectId,
+ tabUrl,
+ });
+ return null;
+ }
+
+ const meta = {
+ source,
+ setAt: Date.now(),
+ projectId: parsed.projectId,
+ kind: parsed.kind,
+ origin: parsed.origin,
+ url: parsed.href,
+ };
+
+ await chrome.storage.local.set({
+ editorTab: tabId,
+ [EDITOR_TAB_META_KEY]: meta,
+ });
+
+ console.info("[Screenity][BG] Stored editorTab reference", {
+ tabId,
+ ...meta,
+ });
+
+ return { tabId, meta };
+};
+
+export const getValidatedEditorTab = async ({
+ expectedProjectId = null,
+ expectedKind = null,
+ reason = "unknown",
+}) => {
+ const { editorTab, editorTabMeta } = await chrome.storage.local.get([
+ "editorTab",
+ EDITOR_TAB_META_KEY,
+ ]);
+
+ if (!Number.isInteger(editorTab)) {
+ return { ok: false, reason: "missing-tab-id" };
+ }
+
+ const tab = await getTabById(editorTab);
+ if (!tab?.id) {
+ await clearEditorTabReference("validate-editor-tab-missing-tab", {
+ reason,
+ editorTab,
+ });
+ return { ok: false, reason: "tab-not-found" };
+ }
+
+ const tabUrl = getTabUrl(tab);
+ const parsedUrl = parseEditorTargetUrl(tabUrl);
+ if (!parsedUrl) {
+ await clearEditorTabReference("validate-editor-tab-not-editor-url", {
+ reason,
+ editorTab,
+ tabUrl,
+ });
+ return { ok: false, reason: "tab-not-editor-url" };
+ }
+
+ if (expectedProjectId && parsedUrl.projectId !== expectedProjectId) {
+ await clearEditorTabReference("validate-editor-tab-project-mismatch", {
+ reason,
+ editorTab,
+ expectedProjectId,
+ parsedProjectId: parsedUrl.projectId,
+ tabUrl,
+ });
+ return { ok: false, reason: "project-mismatch" };
+ }
+
+ if (expectedKind && parsedUrl.kind !== expectedKind) {
+ await clearEditorTabReference("validate-editor-tab-kind-mismatch", {
+ reason,
+ editorTab,
+ expectedKind,
+ parsedKind: parsedUrl.kind,
+ tabUrl,
+ });
+ return { ok: false, reason: "kind-mismatch" };
+ }
+
+ if (editorTabMeta?.projectId && editorTabMeta.projectId !== parsedUrl.projectId) {
+ await clearEditorTabReference("validate-editor-tab-meta-project-mismatch", {
+ reason,
+ editorTab,
+ metaProjectId: editorTabMeta.projectId,
+ parsedProjectId: parsedUrl.projectId,
+ tabUrl,
+ });
+ return { ok: false, reason: "meta-project-mismatch" };
+ }
+
+ if (editorTabMeta?.kind && editorTabMeta.kind !== parsedUrl.kind) {
+ await clearEditorTabReference("validate-editor-tab-meta-kind-mismatch", {
+ reason,
+ editorTab,
+ metaKind: editorTabMeta.kind,
+ parsedKind: parsedUrl.kind,
+ tabUrl,
+ });
+ return { ok: false, reason: "meta-kind-mismatch" };
+ }
+
+ return {
+ ok: true,
+ tab,
+ tabUrl,
+ parsedUrl,
+ meta: editorTabMeta || null,
+ };
+};
+
+export const resolveEditorTabForTarget = async ({
+ targetUrl,
+ expectedProjectId = null,
+ expectedKind = null,
+ reason = "unknown",
+}) => {
+ const parsedTarget = parseEditorTargetUrl(targetUrl);
+ const projectId = expectedProjectId || parsedTarget?.projectId || null;
+ const kind = expectedKind || parsedTarget?.kind || null;
+
+ const existing = await getValidatedEditorTab({
+ expectedProjectId: projectId,
+ expectedKind: kind,
+ reason,
+ });
+
+ if (existing.ok && existing.tab?.id) {
+ const focused = await focusTab(existing.tab.id, {
+ reason: `${reason}:reuse`,
+ projectId,
+ kind,
+ });
+ if (focused) {
+ console.info("[Screenity][BG] Reusing validated editor tab", {
+ reason,
+ tabId: existing.tab.id,
+ projectId,
+ kind,
+ });
+ return { tabId: existing.tab.id, reused: true, opened: false };
+ }
+ console.warn("[Screenity][BG] Failed to focus validated editor tab", {
+ reason,
+ tabId: existing.tab.id,
+ projectId,
+ kind,
+ });
+ } else {
+ console.info("[Screenity][BG] Stored editor tab not reusable", {
+ reason,
+ projectId,
+ kind,
+ validationReason: existing.reason,
+ });
+ }
+
+ if (!targetUrl) {
+ console.warn("[Screenity][BG] Cannot open fallback editor tab: missing URL", {
+ reason,
+ projectId,
+ kind,
+ });
+ return { tabId: null, reused: false, opened: false };
+ }
+
+ const createdTab = await createTab(targetUrl, true, true);
+ if (!createdTab?.id) {
+ console.warn("[Screenity][BG] Failed to open fallback editor tab", {
+ reason,
+ targetUrl,
+ projectId,
+ kind,
+ });
+ return { tabId: null, reused: false, opened: false };
+ }
+
+ await setEditorTabReference({
+ tabId: createdTab.id,
+ tabUrl: getTabUrl(createdTab) || targetUrl,
+ source: `fallback-open:${reason}`,
+ expectedProjectId: projectId,
+ });
+ await focusTab(createdTab.id, {
+ reason: `${reason}:opened`,
+ projectId,
+ kind,
+ });
+
+ console.info("[Screenity][BG] Opened fallback editor tab", {
+ reason,
+ tabId: createdTab.id,
+ targetUrl,
+ projectId,
+ kind,
+ });
+
+ return { tabId: createdTab.id, reused: false, opened: true };
+};
diff --git a/src/pages/Background/tabManagement/focusTab.js b/src/pages/Background/tabManagement/focusTab.js
index 9852750..3db1c12 100644
--- a/src/pages/Background/tabManagement/focusTab.js
+++ b/src/pages/Background/tabManagement/focusTab.js
@@ -1,19 +1,31 @@
-export const focusTab = async (tabId) => {
- if (tabId === null) return;
-
- try {
- const tab = await new Promise((resolve) => {
- chrome.tabs.get(tabId, (tab) => {
- resolve(tab);
- });
+export const focusTab = async (tabId, context = {}) => {
+ if (!Number.isInteger(tabId)) {
+ console.warn("[Screenity][BG] focusTab skipped: invalid tabId", {
+ tabId,
+ context,
});
+ return false;
+ }
- if (tab && tab.id) {
- chrome.windows.update(tab.windowId, { focused: true }).then(() => {
- chrome.tabs.update(tab.id, { active: true });
+ try {
+ const tab = await chrome.tabs.get(tabId);
+ if (!tab?.id || typeof tab.windowId !== "number") {
+ console.warn("[Screenity][BG] focusTab skipped: tab unavailable", {
+ tabId,
+ context,
});
+ return false;
}
+
+ await chrome.windows.update(tab.windowId, { focused: true });
+ await chrome.tabs.update(tab.id, { active: true });
+ return true;
} catch (error) {
- // Tab doesn't exist or can't be accessed
+ console.warn("[Screenity][BG] focusTab failed", {
+ tabId,
+ context,
+ error: error?.message || String(error),
+ });
+ return false;
}
};
diff --git a/src/pages/Background/tabManagement/index.js b/src/pages/Background/tabManagement/index.js
index c183001..ac2685c 100644
--- a/src/pages/Background/tabManagement/index.js
+++ b/src/pages/Background/tabManagement/index.js
@@ -9,6 +9,13 @@ import {
restartActiveTab,
} from "./resetActiveTab";
import { setSurface } from "./setSurface";
+import {
+ parseEditorTargetUrl,
+ setEditorTabReference,
+ clearEditorTabReference,
+ getValidatedEditorTab,
+ resolveEditorTabForTarget,
+} from "./editorTab";
export {
createTab,
@@ -20,4 +27,9 @@ export {
resetActiveTabRestart,
restartActiveTab,
setSurface,
+ parseEditorTargetUrl,
+ setEditorTabReference,
+ clearEditorTabReference,
+ getValidatedEditorTab,
+ resolveEditorTabForTarget,
};
diff --git a/src/pages/CloudRecorder/CloudRecorder.jsx b/src/pages/CloudRecorder/CloudRecorder.jsx
index 47ead0c..9def0d7 100644
--- a/src/pages/CloudRecorder/CloudRecorder.jsx
+++ b/src/pages/CloudRecorder/CloudRecorder.jsx
@@ -19,8 +19,31 @@ localforage.config({
const API_BASE = process.env.SCREENITY_API_BASE_URL;
const DEBUG_START_FLOW =
typeof window !== "undefined" ? !!window.SCREENITY_DEBUG_RECORDER : false;
+const SCREEN_CHUNK_MEMORY_WINDOW = 8;
+const CAMERA_CHUNK_MEMORY_WINDOW = 8;
+const AUDIO_CHUNK_MEMORY_WINDOW = 8;
+const STORAGE_CHECK_INTERVAL_MS = 5000;
+const STORAGE_LOW_HEADROOM_BYTES = 250 * 1024 * 1024;
+const STORAGE_CRITICAL_HEADROOM_BYTES = 120 * 1024 * 1024;
+const AUDIO_MAX_BUFFER_BYTES = 150 * 1024 * 1024;
+const LOCAL_SCREEN_PLAYBACK_TTL_MS = 20 * 60 * 1000;
+const LOCAL_SCREEN_PLAYBACK_MAX_BYTES = 250 * 1024 * 1024;
+const MAX_UPLOAD_TELEMETRY_EVENTS = 300;
+const UPLOAD_TELEMETRY_KEY = "cloudUploadTelemetryEvents";
+const UPLOAD_TELEMETRY_ENDPOINT = `${API_BASE}/log/upload-event`;
+const SESSION_STATE_INDEX_KEY = "cloudRecorderSessionStateIndex";
+const RECOVERABLE_SESSION_STATUSES = new Set([
+ "recording",
+ "hidden",
+ "unload",
+ "stopping",
+ "finalize-failed",
+ "upload-stalled",
+]);
const chunksStore = localforage.createInstance({ name: "chunks" });
+const audioChunksStore = localforage.createInstance({ name: "audioChunks" });
+const cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });
const urlParams = new URLSearchParams(window.location.search);
const IS_INJECTED_IFRAME = urlParams.has("injected");
@@ -71,6 +94,7 @@ const CloudRecorder = () => {
const screenUploader = useRef(null);
const cameraUploader = useRef(null);
const uploadMetaRef = useRef(null);
+ const localScreenPlaybackOfferRef = useRef(null);
const emptyCleanupRef = useRef(false);
const backupRef = useRef(false);
@@ -108,6 +132,27 @@ const CloudRecorder = () => {
const firstChunkLoggedRef = useRef(false);
const recorderSession = useRef(null);
+ const recordingSessionId = useRef(null);
+ const unloadGuardRef = useRef({
+ pagehideSeen: false,
+ beforeUnloadSeen: false,
+ abandonedSent: false,
+ stopTriggeredFromUnload: false,
+ });
+ const telemetryRuntimeRef = useRef({
+ extensionVersion: null,
+ browserVersion: null,
+ platform: null,
+ arch: null,
+ os: null,
+ });
+ const uploadTelemetryTokenRef = useRef(null);
+ const uploadTelemetryNetworkDisabledRef = useRef(false);
+ const audioChunkStoreReadyRef = useRef(false);
+ const audioChunkIndexRef = useRef(0);
+ const cameraChunkStoreReadyRef = useRef(false);
+ const cameraChunkIndexRef = useRef(0);
+ const sessionStateIndexedRef = useRef(false);
const sessionHeartbeat = useRef(null);
const chunkStallTimer = useRef(null);
const uploadHeartbeatTimer = useRef(null);
@@ -115,14 +160,69 @@ const CloudRecorder = () => {
screen: 0,
camera: 0,
ts: 0,
+ lastPersistAt: 0,
});
const stallNotified = useRef(false);
const fatalErrorRef = useRef(false);
const idbReadyRef = useRef(false);
const recoveryAttempted = useRef(false);
+ const recoveryExportedRef = useRef(false);
const screenTrackLostRef = useRef(false);
const screenTrackMonitor = useRef(null);
const pausedStateRef = useRef(false);
+ const audioCaptureDegradedRef = useRef(false);
+ const storagePressureRef = useRef({
+ lastEstimateAt: 0,
+ quota: null,
+ usage: null,
+ headroom: null,
+ lowSpace: false,
+ critical: false,
+ warned: false,
+ stopSent: false,
+ });
+ const networkStateRef = useRef({
+ online: navigator.onLine,
+ offlineSince: null,
+ });
+ const sessionTrackState = useRef({
+ screen: {
+ chunkCount: 0,
+ bytesRecorded: 0,
+ lastChunkAt: null,
+ inMemoryChunkCount: 0,
+ droppedInMemoryChunks: 0,
+ durableChunkCount: 0,
+ lastPersistedChunkIndex: null,
+ lastPersistedAt: null,
+ lastUploadOffset: 0,
+ uploaderUpdatedAt: null,
+ },
+ camera: {
+ chunkCount: 0,
+ bytesRecorded: 0,
+ lastChunkAt: null,
+ inMemoryChunkCount: 0,
+ droppedInMemoryChunks: 0,
+ durableChunkCount: 0,
+ lastPersistedChunkIndex: null,
+ lastPersistedAt: null,
+ lastUploadOffset: 0,
+ uploaderUpdatedAt: null,
+ },
+ audio: {
+ chunkCount: 0,
+ bytesRecorded: 0,
+ lastChunkAt: null,
+ inMemoryChunkCount: 0,
+ droppedInMemoryChunks: 0,
+ durableChunkCount: 0,
+ lastPersistedChunkIndex: null,
+ lastPersistedAt: null,
+ lastUploadOffset: 0,
+ uploaderUpdatedAt: null,
+ },
+ });
// This checks if the recording was previously initialized
const isInit = useRef(false);
@@ -239,6 +339,369 @@ const CloudRecorder = () => {
}
};
+ const ensureRecordingSessionId = () => {
+ if (!recordingSessionId.current) {
+ recordingSessionId.current = crypto.randomUUID();
+ }
+ return recordingSessionId.current;
+ };
+
+ const getBrowserVersion = () => {
+ const ua = navigator.userAgent || "";
+ const chromeMatch = ua.match(/Chrome\/([0-9.]+)/);
+ return chromeMatch?.[1] || null;
+ };
+
+ const getBrowserName = () => {
+ const ua = navigator.userAgent || "";
+ if (ua.includes("Edg/")) return "Edge";
+ if (ua.includes("Chrome/")) return "Chrome";
+ if (ua.includes("Firefox/")) return "Firefox";
+ if (ua.includes("Safari/") && !ua.includes("Chrome/")) return "Safari";
+ return "Other";
+ };
+
+ const getOsName = () => {
+ const p = navigator.platform || "";
+ if (p.includes("Mac")) return "macOS";
+ if (p.includes("Win")) return "Windows";
+ if (p.includes("Linux")) return "Linux";
+ return "Other";
+ };
+
+ const ensureTelemetryRuntimeContext = async () => {
+ if (telemetryRuntimeRef.current.extensionVersion) {
+ return telemetryRuntimeRef.current;
+ }
+ const manifestVersion =
+ chrome?.runtime?.getManifest?.()?.version || null;
+ let platformInfo = null;
+ try {
+ platformInfo = await chrome.runtime.sendMessage({
+ type: "get-platform-info",
+ });
+ } catch {
+ platformInfo = null;
+ }
+ telemetryRuntimeRef.current = {
+ extensionVersion: manifestVersion,
+ browserVersion: getBrowserVersion(),
+ platform: platformInfo?.os || navigator.platform || null,
+ arch: platformInfo?.arch || null,
+ os: platformInfo?.os || null,
+ };
+ return telemetryRuntimeRef.current;
+ };
+
+ const appendUploadTelemetryEvent = async (eventPayload) => {
+ try {
+ const existing = await chrome.storage.local.get([UPLOAD_TELEMETRY_KEY]);
+ const current = Array.isArray(existing?.[UPLOAD_TELEMETRY_KEY])
+ ? existing[UPLOAD_TELEMETRY_KEY]
+ : [];
+ const next = [...current, eventPayload].slice(-MAX_UPLOAD_TELEMETRY_EVENTS);
+ await chrome.storage.local.set({
+ [UPLOAD_TELEMETRY_KEY]: next,
+ lastUploadTelemetryEvent: eventPayload,
+ });
+ } catch (err) {
+ console.warn("Failed to persist upload telemetry event:", err);
+ }
+ };
+
+ const resolveUploadTelemetryToken = async () => {
+ if (uploadTelemetryTokenRef.current) {
+ return uploadTelemetryTokenRef.current;
+ }
+ try {
+ const { screenityToken } = await chrome.storage.local.get([
+ "screenityToken",
+ ]);
+ if (screenityToken) {
+ uploadTelemetryTokenRef.current = screenityToken;
+ return screenityToken;
+ }
+ } catch {
+ // ignore
+ }
+
+ try {
+ const res = await fetch(`${API_BASE}/auth/get-extension-token`, {
+ method: "GET",
+ credentials: "include",
+ });
+ if (res.ok) {
+ const data = await res.json().catch(() => null);
+ const token = data?.token || data?.extensionToken || null;
+ if (token) {
+ uploadTelemetryTokenRef.current = token;
+ return token;
+ }
+ }
+ } catch {
+ // ignore
+ }
+ return null;
+ };
+
+ const toUploadTelemetryRequest = async (eventPayload) => {
+ const mediaId =
+ eventPayload.mediaId ||
+ screenUploader.current?.getMeta?.()?.mediaId ||
+ cameraUploader.current?.getMeta?.()?.mediaId ||
+ null;
+ if (!mediaId) {
+ return null;
+ }
+
+ const browserVersion = eventPayload.browserVersion || null;
+ const browserMajor =
+ browserVersion && Number.isFinite(parseInt(browserVersion, 10))
+ ? parseInt(browserVersion, 10)
+ : null;
+
+ return {
+ recordingId: mediaId,
+ recordingSessionId: eventPayload.recordingSessionId || null,
+ projectId: eventPayload.projectId || null,
+ sceneId: eventPayload.sceneId || null,
+ mediaId: eventPayload.mediaId || null,
+ bunnyVideoId: eventPayload.bunnyVideoId || null,
+ source: "extension",
+ extVersion: eventPayload.extensionVersion || null,
+ env: {
+ os: getOsName(),
+ browser: getBrowserName(),
+ browserMajor,
+ appVersion: null,
+ },
+ event: {
+ type: eventPayload.event,
+ t: eventPayload.ts || Date.now(),
+ trackType: eventPayload.trackType || null,
+ offsetBytes:
+ typeof eventPayload.offset === "number"
+ ? eventPayload.offset
+ : null,
+ fileSize:
+ typeof eventPayload.totalBytes === "number"
+ ? eventPayload.totalBytes
+ : typeof eventPayload.finalizedBytes === "number"
+ ? eventPayload.finalizedBytes
+ : null,
+ online: typeof navigator !== "undefined" ? navigator.onLine : null,
+ visibilityState:
+ typeof document !== "undefined" ? document.visibilityState : null,
+ errCode: eventPayload.errorCode || null,
+ errMsg: eventPayload.message || eventPayload.error || null,
+ reason: eventPayload.reason || null,
+ mediaId: eventPayload.mediaId || null,
+ bunnyVideoId: eventPayload.bunnyVideoId || null,
+ projectId: eventPayload.projectId || null,
+ sceneId: eventPayload.sceneId || null,
+ recordingSessionId: eventPayload.recordingSessionId || null,
+ },
+ };
+ };
+
+ const sendUploadTelemetryNetwork = async (eventPayload) => {
+ if (uploadTelemetryNetworkDisabledRef.current) return;
+ try {
+ const requestBody = await toUploadTelemetryRequest(eventPayload);
+ if (!requestBody) {
+ return;
+ }
+ const body = JSON.stringify(requestBody);
+ const token = await resolveUploadTelemetryToken();
+ const headers = {
+ "Content-Type": "application/json",
+ "x-screenity-source": "extension",
+ };
+ if (eventPayload.extensionVersion) {
+ headers["x-screenity-ext-version"] = String(
+ eventPayload.extensionVersion,
+ );
+ }
+ if (token) {
+ headers.Authorization = `Bearer ${token}`;
+ }
+ if (
+ (eventPayload.event === "upload_pagehide" ||
+ eventPayload.event === "upload_abandoned_on_unload") &&
+ navigator.sendBeacon
+ ) {
+ const sent = navigator.sendBeacon(
+ UPLOAD_TELEMETRY_ENDPOINT,
+ new Blob([body], { type: "application/json" }),
+ );
+ if (sent) return;
+ }
+ const res = await fetch(UPLOAD_TELEMETRY_ENDPOINT, {
+ method: "POST",
+ headers,
+ credentials: "include",
+ keepalive: true,
+ body,
+ });
+ if (res.status === 404 || res.status === 405) {
+ uploadTelemetryNetworkDisabledRef.current = true;
+ }
+ } catch {
+ // best effort
+ }
+ };
+
+ const emitUploadTelemetry = async (event, payload = {}) => {
+ const runtime = await ensureTelemetryRuntimeContext();
+ const screenSceneId = screenUploader.current?.getMeta?.()?.sceneId || null;
+ const cameraSceneId = cameraUploader.current?.getMeta?.()?.sceneId || null;
+ const eventPayload = {
+ event,
+ ts: Date.now(),
+ recordingSessionId:
+ payload.recordingSessionId ||
+ recorderSession.current?.id ||
+ recordingSessionId.current ||
+ null,
+ projectId:
+ payload.projectId || recorderSession.current?.projectId || null,
+ sceneId: payload.sceneId || screenSceneId || cameraSceneId || null,
+ mediaId: payload.mediaId || null,
+ bunnyVideoId: payload.bunnyVideoId || null,
+ trackType: payload.trackType || null,
+ uploaderType: payload.uploaderType || "cloud_recorder",
+ extensionVersion: runtime.extensionVersion,
+ browserVersion: runtime.browserVersion,
+ platform: runtime.platform,
+ arch: runtime.arch,
+ os: runtime.os,
+ ...payload,
+ };
+
+ await appendUploadTelemetryEvent(eventPayload);
+ if (event !== "upload_progress") {
+ void sendUploadTelemetryNetwork(eventPayload);
+ }
+ };
+
+ const resetUnloadGuard = () => {
+ unloadGuardRef.current = {
+ pagehideSeen: false,
+ beforeUnloadSeen: false,
+ abandonedSent: false,
+ stopTriggeredFromUnload: false,
+ };
+ };
+
+ const emitAbandonedOnUnloadOnce = (reason, extra = {}) => {
+ if (unloadGuardRef.current.abandonedSent) return;
+ unloadGuardRef.current.abandonedSent = true;
+ void emitUploadTelemetry("upload_abandoned_on_unload", {
+ reason,
+ ...extra,
+ });
+ };
+
+ const resetSessionTrackState = () => {
+ sessionTrackState.current = {
+ screen: {
+ chunkCount: 0,
+ bytesRecorded: 0,
+ lastChunkAt: null,
+ inMemoryChunkCount: 0,
+ droppedInMemoryChunks: 0,
+ durableChunkCount: 0,
+ lastPersistedChunkIndex: null,
+ lastPersistedAt: null,
+ lastUploadOffset: 0,
+ uploaderUpdatedAt: null,
+ },
+ camera: {
+ chunkCount: 0,
+ bytesRecorded: 0,
+ lastChunkAt: null,
+ inMemoryChunkCount: 0,
+ droppedInMemoryChunks: 0,
+ durableChunkCount: 0,
+ lastPersistedChunkIndex: null,
+ lastPersistedAt: null,
+ lastUploadOffset: 0,
+ uploaderUpdatedAt: null,
+ },
+ audio: {
+ chunkCount: 0,
+ bytesRecorded: 0,
+ lastChunkAt: null,
+ inMemoryChunkCount: 0,
+ droppedInMemoryChunks: 0,
+ durableChunkCount: 0,
+ lastPersistedChunkIndex: null,
+ lastPersistedAt: null,
+ lastUploadOffset: 0,
+ uploaderUpdatedAt: null,
+ },
+ };
+ };
+
+ const trimChunkBuffer = (ref, maxChunks) => {
+ if (!ref?.current || ref.current.length <= maxChunks) return 0;
+ const removed = ref.current.length - maxChunks;
+ ref.current.splice(0, removed);
+ return removed;
+ };
+
+ const noteTrackChunk = (track, blob, extra = {}) => {
+ if (!blob || !track || !sessionTrackState.current[track]) return;
+ const current = sessionTrackState.current[track];
+ sessionTrackState.current[track] = {
+ ...current,
+ chunkCount: (current.chunkCount || 0) + 1,
+ bytesRecorded: (current.bytesRecorded || 0) + (blob.size || 0),
+ lastChunkAt: Date.now(),
+ ...extra,
+ };
+ };
+
+ const patchTrackState = (track, extra = {}) => {
+ if (!track || !sessionTrackState.current[track]) return;
+ sessionTrackState.current[track] = {
+ ...sessionTrackState.current[track],
+ ...extra,
+ };
+ };
+
+ const getUploaderResumeMeta = (uploaderRef) => {
+ if (!uploaderRef?.current) return null;
+ if (typeof uploaderRef.current.getResumeState === "function") {
+ return uploaderRef.current.getResumeState();
+ }
+ if (typeof uploaderRef.current.getMeta === "function") {
+ return uploaderRef.current.getMeta();
+ }
+ return null;
+ };
+
+ const buildTrackSnapshot = () => ({
+ screen: {
+ ...sessionTrackState.current.screen,
+ inMemoryChunkCount: screenChunks.current.length,
+ hasDurableLocalChunks: true,
+ uploader: getUploaderResumeMeta(screenUploader),
+ },
+ camera: {
+ ...sessionTrackState.current.camera,
+ inMemoryChunkCount: cameraChunks.current.length,
+ hasDurableLocalChunks: cameraChunkStoreReadyRef.current,
+ uploader: getUploaderResumeMeta(cameraUploader),
+ },
+ audio: {
+ ...sessionTrackState.current.audio,
+ inMemoryChunkCount: audioChunks.current.length,
+ hasDurableLocalChunks: audioChunkStoreReadyRef.current,
+ uploader: null,
+ },
+ });
+
const setPipelineState = async (step, extra = {}) => {
const state = {
step,
@@ -585,9 +1048,16 @@ const CloudRecorder = () => {
await chunksStore.setItem("__probe", { ts: Date.now() });
await chunksStore.removeItem("__probe");
idbReadyRef.current = true;
+ void emitUploadTelemetry("upload_local_backup_enabled", {
+ backupType: "screen",
+ });
return true;
} catch (err) {
fatalErrorRef.current = true;
+ void emitUploadTelemetry("upload_local_backup_unavailable", {
+ backupType: "screen",
+ error: err?.message || String(err),
+ });
sendRecordingError(
"Local storage is blocked (IndexedDB unavailable). Recording cannot start.",
);
@@ -595,22 +1065,299 @@ const CloudRecorder = () => {
}
};
+ const ensureAudioChunkStoreReady = async () => {
+ if (audioChunkStoreReadyRef.current) return true;
+ try {
+ await audioChunksStore.setItem("__probe", { ts: Date.now() });
+ await audioChunksStore.removeItem("__probe");
+ audioChunkStoreReadyRef.current = true;
+ void emitUploadTelemetry("upload_local_backup_enabled", {
+ backupType: "audio",
+ });
+ return true;
+ } catch (err) {
+ audioChunkStoreReadyRef.current = false;
+ void emitUploadTelemetry("upload_local_backup_degraded", {
+ backupType: "audio",
+ error: err?.message || String(err),
+ });
+ return false;
+ }
+ };
+
+ 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.
+ try {
+ await audioChunksStore.clear();
+ console.info("[CloudRecorder] clearAudioChunkStore:", reason);
+ } catch (err) {
+ console.warn("Failed to clear audio chunk store:", err);
+ }
+ };
+
+ const ensureCameraChunkStoreReady = async () => {
+ if (cameraChunkStoreReadyRef.current) return true;
+ try {
+ await cameraChunksStore.setItem("__probe", { ts: Date.now() });
+ await cameraChunksStore.removeItem("__probe");
+ cameraChunkStoreReadyRef.current = true;
+ void emitUploadTelemetry("upload_local_backup_enabled", {
+ backupType: "camera",
+ });
+ return true;
+ } catch (err) {
+ cameraChunkStoreReadyRef.current = false;
+ void emitUploadTelemetry("upload_local_backup_degraded", {
+ backupType: "camera",
+ error: err?.message || String(err),
+ });
+ return false;
+ }
+ };
+
+ const clearCameraChunkStore = async (reason = "unknown") => {
+ cameraChunkIndexRef.current = 0;
+ // Always attempt clear regardless of cameraChunkStoreReadyRef 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.
+ try {
+ await cameraChunksStore.clear();
+ console.info("[CloudRecorder] clearCameraChunkStore:", reason);
+ } catch (err) {
+ console.warn("Failed to clear camera chunk store:", err);
+ }
+ };
+
+ const clearLocalScreenPlaybackOffer = async (reason = "unknown") => {
+ const existingOffer = localScreenPlaybackOfferRef.current;
+ localScreenPlaybackOfferRef.current = null;
+ try {
+ const result = await chrome.runtime.sendMessage({
+ type: "cloud-local-playback-clear",
+ offerId: existingOffer?.offerId || null,
+ reason,
+ });
+ if (result?.ok) {
+ console.info(
+ "[CloudRecorder] Cleared local screen playback offer",
+ {
+ reason,
+ offerId: existingOffer?.offerId || null,
+ },
+ );
+ }
+ } catch (err) {
+ console.warn(
+ "[CloudRecorder] Failed to clear local screen playback offer",
+ {
+ reason,
+ error: err?.message || err,
+ },
+ );
+ }
+ };
+
+ const registerLocalScreenPlaybackOffer = async ({
+ projectId,
+ sceneId,
+ uploadMeta,
+ }) => {
+ if (!projectId || !sceneId) {
+ return null;
+ }
+
+ let chunkCount = 0;
+ try {
+ chunkCount = await chunksStore.length();
+ } catch {
+ chunkCount = 0;
+ }
+ if (!chunkCount) {
+ console.info(
+ "[CloudRecorder] Local-first screen offer unavailable: no local chunks",
+ {
+ projectId,
+ sceneId,
+ },
+ );
+ return null;
+ }
+
+ const estimatedBytes =
+ screenUploader.current?.offset ||
+ sessionTrackState.current?.screen?.bytesRecorded ||
+ 0;
+ if (!estimatedBytes || estimatedBytes <= 0) {
+ console.info(
+ "[CloudRecorder] Local-first screen offer unavailable: no byte estimate",
+ {
+ projectId,
+ sceneId,
+ chunkCount,
+ },
+ );
+ return null;
+ }
+
+ if (estimatedBytes > LOCAL_SCREEN_PLAYBACK_MAX_BYTES) {
+ console.info(
+ "[CloudRecorder] Local-first screen offer skipped: source too large",
+ {
+ projectId,
+ sceneId,
+ chunkCount,
+ estimatedBytes,
+ maxBytes: LOCAL_SCREEN_PLAYBACK_MAX_BYTES,
+ },
+ );
+ return null;
+ }
+
+ const now = Date.now();
+ const nextOffer = {
+ offerId: crypto.randomUUID(),
+ projectId,
+ sceneId,
+ recordingSessionId:
+ recorderSession.current?.id || recordingSessionId.current || null,
+ trackType: "screen",
+ chunkCount,
+ estimatedBytes,
+ mediaId: uploadMeta?.screen?.mediaId || null,
+ bunnyVideoId: uploadMeta?.screen?.videoId || null,
+ createdAt: now,
+ expiresAt: now + LOCAL_SCREEN_PLAYBACK_TTL_MS,
+ status: "available",
+ source: "indexeddb-screen-chunks",
+ };
+
+ try {
+ const result = await chrome.runtime.sendMessage({
+ type: "cloud-local-playback-register",
+ offer: nextOffer,
+ });
+ if (result?.ok && result.offer) {
+ localScreenPlaybackOfferRef.current = result.offer;
+ console.info(
+ "[CloudRecorder] Local-first screen offer registered",
+ {
+ projectId,
+ sceneId,
+ offerId: result.offer.offerId,
+ chunkCount: result.offer.chunkCount,
+ estimatedBytes: result.offer.estimatedBytes,
+ expiresAt: result.offer.expiresAt,
+ },
+ );
+ return result.offer;
+ }
+ } catch (err) {
+ console.warn(
+ "[CloudRecorder] Failed to register local-first screen offer",
+ {
+ projectId,
+ sceneId,
+ error: err?.message || err,
+ },
+ );
+ }
+
+ return null;
+ };
+
+ 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 {
+ const recovered = [];
+ await audioChunksStore.iterate((value) => {
+ if (value?.chunk) {
+ recovered.push(value);
+ }
+ });
+ recovered.sort((a, b) => (a.index || 0) - (b.index || 0));
+ if (recovered.length > 0) {
+ console.info("[CloudRecorder] buildAudioBlobFromDurableStore: using IDB", {
+ chunks: recovered.length,
+ storeWasReady: audioChunkStoreReadyRef.current,
+ });
+ return createBlobFromChunks(
+ recovered.map((entry) => entry.chunk),
+ "audio/webm",
+ );
+ }
+ console.info("[CloudRecorder] buildAudioBlobFromDurableStore: IDB empty, using memory", {
+ memoryChunks: audioChunks.current.length,
+ storeWasReady: audioChunkStoreReadyRef.current,
+ });
+ } catch (err) {
+ console.warn("[CloudRecorder] buildAudioBlobFromDurableStore: IDB read failed, falling back to memory", {
+ error: err?.message || String(err),
+ memoryChunks: audioChunks.current.length,
+ storeWasReady: audioChunkStoreReadyRef.current,
+ });
+ void emitUploadTelemetry("upload_local_backup_degraded", {
+ backupType: "audio",
+ reason: "audio-idb-read-failed-at-finalize",
+ error: err?.message || String(err),
+ });
+ }
+ return createBlobFromChunks(audioChunks.current, "audio/webm");
+ };
+
+ const getSessionStateKey = (sessionId) =>
+ sessionId ? `cloudRecorderSession:${sessionId}` : null;
+
const persistSessionState = async (overrides = {}) => {
if (!recorderSession.current) return;
+ const tracks = buildTrackSnapshot();
+ const sessionStateKey = getSessionStateKey(recorderSession.current.id);
const nextState = {
...recorderSession.current,
+ recordingSessionId: recorderSession.current.id,
lastChunkIndex: index.current - 1,
lastChunkTime: lastTimecode.current || null,
lastUploadOffset: {
screen: screenUploader.current?.offset || 0,
camera: cameraUploader.current?.offset || 0,
},
+ tracks,
+ network: {
+ online: networkStateRef.current.online,
+ offlineSince: networkStateRef.current.offlineSince,
+ },
+ storagePressure: {
+ quota: storagePressureRef.current.quota,
+ usage: storagePressureRef.current.usage,
+ headroom: storagePressureRef.current.headroom,
+ lowSpace: storagePressureRef.current.lowSpace,
+ critical: storagePressureRef.current.critical,
+ },
updatedAt: Date.now(),
...overrides,
};
recorderSession.current = nextState;
try {
- await chrome.storage.local.set({ recorderSession: nextState });
+ const payload = {
+ recorderSession: nextState,
+ [sessionStateKey]: nextState,
+ };
+ if (!sessionStateIndexedRef.current) {
+ const existing = await chrome.storage.local.get([SESSION_STATE_INDEX_KEY]);
+ const index = Array.isArray(existing?.[SESSION_STATE_INDEX_KEY])
+ ? existing[SESSION_STATE_INDEX_KEY]
+ : [];
+ payload[SESSION_STATE_INDEX_KEY] = index.includes(recorderSession.current.id)
+ ? index
+ : [...index, recorderSession.current.id].slice(-30);
+ sessionStateIndexedRef.current = true;
+ }
+ await chrome.storage.local.set(payload);
} catch (err) {
console.warn("Failed to persist recorder session state:", err);
}
@@ -623,8 +1370,10 @@ const CloudRecorder = () => {
recorderOwnerTabId = tabRes?.tabId || null;
} catch {}
+ const sessionId = meta.sessionId || ensureRecordingSessionId();
const session = {
- id: crypto.randomUUID(),
+ id: sessionId,
+ recordingSessionId: sessionId,
startedAt: Date.now(),
recorderTabId: recorderOwnerTabId,
capturedTabId: recordingTabId.current || null,
@@ -633,10 +1382,28 @@ const CloudRecorder = () => {
isTab: isTab.current,
region: Boolean(regionRef.current),
status: "recording",
+ tracks: buildTrackSnapshot(),
+ network: {
+ online: networkStateRef.current.online,
+ offlineSince: networkStateRef.current.offlineSince,
+ },
...meta,
};
recorderSession.current = session;
- await chrome.storage.local.set({ recorderSession: session });
+ const sessionStateKey = getSessionStateKey(sessionId);
+ const existing = await chrome.storage.local.get([SESSION_STATE_INDEX_KEY]);
+ const index = Array.isArray(existing?.[SESSION_STATE_INDEX_KEY])
+ ? existing[SESSION_STATE_INDEX_KEY]
+ : [];
+ const nextIndex = index.includes(sessionId)
+ ? index
+ : [...index, sessionId].slice(-30);
+ await chrome.storage.local.set({
+ recorderSession: session,
+ [sessionStateKey]: session,
+ [SESSION_STATE_INDEX_KEY]: nextIndex,
+ });
+ sessionStateIndexedRef.current = true;
logDebugEvent("recorder-session-started", {
sessionId: session.id,
projectId: meta.projectId || null,
@@ -649,7 +1416,10 @@ const CloudRecorder = () => {
if (result?.ok === false) {
fatalErrorRef.current = true;
recorderSession.current = null;
- chrome.storage.local.remove("recorderSession");
+ recordingSessionId.current = null;
+ sessionStateIndexedRef.current = false;
+ const sessionStateKey = getSessionStateKey(sessionId);
+ chrome.storage.local.remove(["recorderSession", sessionStateKey]);
sendRecordingError(
result?.error ||
"Another Screenity recorder is already running. Please close it and try again.",
@@ -667,17 +1437,21 @@ const CloudRecorder = () => {
const finalizeRecorderSession = async (status = "completed") => {
if (!recorderSession.current) return;
+ const sessionId = recorderSession.current.id;
+ const sessionStateKey = getSessionStateKey(sessionId);
logDebugEvent("recorder-session-finalize-start", {
status,
- sessionId: recorderSession.current.id,
+ sessionId,
});
try {
+ const finalizedState = {
+ ...recorderSession.current,
+ status,
+ finishedAt: Date.now(),
+ };
await chrome.storage.local.set({
- recorderSession: {
- ...recorderSession.current,
- status,
- finishedAt: Date.now(),
- },
+ recorderSession: finalizedState,
+ [sessionStateKey]: finalizedState,
});
await chrome.runtime.sendMessage({
type: "clear-recording-session",
@@ -695,10 +1469,23 @@ const CloudRecorder = () => {
throw err;
} finally {
recorderSession.current = null;
+ recordingSessionId.current = null;
+ sessionStateIndexedRef.current = false;
+ resetSessionTrackState();
logDebugEvent("recorder-session-finalized", { status });
}
};
+ const startSessionHeartbeat = () => {
+ if (sessionHeartbeat.current) clearInterval(sessionHeartbeat.current);
+ sessionHeartbeat.current = setInterval(() => {
+ if (!recorderSession.current) return;
+ persistSessionState({
+ heartbeatAt: Date.now(),
+ });
+ }, 5000);
+ };
+
const startChunkWatchdog = () => {
if (chunkStallTimer.current) clearInterval(chunkStallTimer.current);
chunkStallTimer.current = setInterval(() => {
@@ -732,8 +1519,10 @@ const CloudRecorder = () => {
screen: screenOffset,
camera: cameraOffset,
ts: now,
+ lastPersistAt: lastUploadProgress.current.lastPersistAt || 0,
};
stallNotified.current = false;
+ recoveryExportedRef.current = false;
persistSessionState();
return;
}
@@ -755,7 +1544,10 @@ const CloudRecorder = () => {
ts &&
now - ts > 45000
) {
- exportLocalRecovery("upload-stalled");
+ if (!recoveryExportedRef.current) {
+ recoveryExportedRef.current = true;
+ exportLocalRecovery("upload-stalled");
+ }
}
}, 5000);
};
@@ -868,20 +1660,23 @@ const CloudRecorder = () => {
};
const exportLocalRecovery = async (reason = "upload failed") => {
try {
- let blob =
- createBlobFromChunks(screenChunks.current, "video/webm") ||
- createBlobFromChunks(cameraChunks.current, "video/webm");
- if (!blob) {
- const recovered = [];
- await chunksStore.iterate((value) => {
- recovered.push(value);
- });
- recovered.sort((a, b) => a.index - b.index);
+ let blob = null;
+ const recovered = [];
+ await chunksStore.iterate((value) => {
+ recovered.push(value);
+ });
+ recovered.sort((a, b) => a.index - b.index);
+ if (recovered.length > 0) {
blob = createBlobFromChunks(
recovered.map((c) => c.chunk),
"video/webm",
);
}
+ if (!blob) {
+ blob =
+ createBlobFromChunks(screenChunks.current, "video/webm") ||
+ createBlobFromChunks(cameraChunks.current, "video/webm");
+ }
if (!blob) return;
const objectUrl = URL.createObjectURL(blob);
try {
@@ -902,6 +1697,89 @@ 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.
+ const clearStaleUploadJournals = async (storedSession) => {
+ const keysToRemove = [];
+ const tracks = storedSession?.tracks || {};
+
+ for (const trackData of Object.values(tracks)) {
+ const upl = trackData?.uploader;
+ if (!upl) continue;
+
+ if (upl.journalKey) keysToRemove.push(upl.journalKey);
+ if (upl.journalLookupKey) keysToRemove.push(upl.journalLookupKey);
+
+ // Also clear the Bunny video-map fallback entry
+ const pid = upl.projectId || storedSession?.projectId || null;
+ const sid = upl.sceneId || null;
+ const t = upl.type || upl.trackType || null;
+ if (pid && t) {
+ keysToRemove.push(
+ `bunnyVideoMap-${pid}-${sid || "none"}-${t || "none"}`,
+ );
+ }
+ }
+
+ // Force a fresh sceneId on the next recording so getOrCreateSceneId doesn't
+ // reuse the stale scene that is tied to the now-cleared journals.
+ keysToRemove.push("sceneId", "sceneIdStatus");
+
+ const uniqKeys = [...new Set(keysToRemove)];
+
+ const screenUpl = tracks.screen?.uploader || null;
+ const cameraUpl = tracks.camera?.uploader || null;
+
+ console.info(
+ "[CloudRecorder] clearStaleUploadJournals: removing stale journal + sceneId keys",
+ {
+ sessionId: storedSession?.id || null,
+ keyCount: uniqKeys.length,
+ screen: {
+ journalKey: screenUpl?.journalKey || null,
+ mediaId: screenUpl?.mediaId || null,
+ journalOffset: screenUpl?.offset || 0,
+ journalTotalBytes: screenUpl?.totalBytes || 0,
+ journalStatus: screenUpl?.status || null,
+ },
+ camera: {
+ journalKey: cameraUpl?.journalKey || null,
+ mediaId: cameraUpl?.mediaId || null,
+ journalOffset: cameraUpl?.offset || 0,
+ },
+ },
+ );
+
+ void emitUploadTelemetry("upload_recovery_journals_cleared", {
+ reason: "post-crash-recovery",
+ sessionId: storedSession?.id || null,
+ projectId: storedSession?.projectId || null,
+ clearedKeyCount: uniqKeys.length,
+ screenJournalKey: screenUpl?.journalKey || null,
+ screenMediaId: screenUpl?.mediaId || null,
+ screenJournalOffset: screenUpl?.offset || 0,
+ screenJournalTotalBytes: screenUpl?.totalBytes || 0,
+ screenJournalStatus: screenUpl?.status || null,
+ cameraJournalKey: cameraUpl?.journalKey || null,
+ cameraMediaId: cameraUpl?.mediaId || null,
+ cameraJournalOffset: cameraUpl?.offset || 0,
+ });
+
+ if (!uniqKeys.length) return;
+ try {
+ await chrome.storage.local.remove(uniqKeys);
+ } catch (err) {
+ console.warn(
+ "[CloudRecorder] clearStaleUploadJournals: failed to remove keys",
+ { keys: uniqKeys, error: err?.message || String(err) },
+ );
+ }
+ };
+
const tryRecoverPreviousSession = useCallback(async () => {
if (recoveryAttempted.current) return;
recoveryAttempted.current = true;
@@ -910,40 +1788,116 @@ const CloudRecorder = () => {
["recorderSession"],
);
- const chunkCount = await chunksStore.length().catch(() => 0);
- if (
- storedSession &&
- storedSession.status === "recording" &&
- chunkCount > 0
- ) {
- const recovered = [];
- await chunksStore.iterate((value) => {
- recovered.push(value);
+ const [chunkCount, cameraChunkCount, audioChunkCount] = await Promise.all([
+ chunksStore.length().catch(() => 0),
+ cameraChunksStore.length().catch(() => 0),
+ audioChunksStore.length().catch(() => 0),
+ ]);
+ const isRecoverable = RECOVERABLE_SESSION_STATUSES.has(
+ storedSession?.status,
+ );
+ const hasDurableChunks =
+ chunkCount > 0 || cameraChunkCount > 0 || audioChunkCount > 0;
+ if (storedSession && isRecoverable && hasDurableChunks) {
+ void emitUploadTelemetry("upload_recovery_available", {
+ reason: "durable-chunks",
+ recoveredChunkCount: chunkCount,
+ recoveredCameraChunkCount: cameraChunkCount,
+ recoveredAudioChunkCount: audioChunkCount,
+ recordingSessionId: storedSession?.id || null,
+ projectId: storedSession?.projectId || null,
});
- recovered.sort((a, b) => a.index - b.index);
- const blob = createBlobFromChunks(
- recovered.map((c) => c.chunk),
- "video/webm",
- );
- if (blob) {
- const objectUrl = URL.createObjectURL(blob);
- try {
- await chrome.downloads.download({
- url: objectUrl,
- filename: `Screenity-Recovered-${new Date().toISOString()}.webm`,
- saveAs: false,
- });
- chrome.runtime.sendMessage({
- type: "show-toast",
- message: "Recovered unsaved recording from the previous session.",
- });
- } finally {
- URL.revokeObjectURL(objectUrl);
+ const ts = new Date().toISOString();
+
+ if (chunkCount > 0) {
+ const recovered = [];
+ await chunksStore.iterate((value) => {
+ recovered.push(value);
+ });
+ recovered.sort((a, b) => a.index - b.index);
+ const blob = createBlobFromChunks(
+ recovered.map((c) => c.chunk),
+ "video/webm",
+ );
+ if (blob) {
+ const objectUrl = URL.createObjectURL(blob);
+ try {
+ await chrome.downloads.download({
+ url: objectUrl,
+ filename: `Screenity-Recovered-${ts}.webm`,
+ saveAs: false,
+ });
+ } finally {
+ URL.revokeObjectURL(objectUrl);
+ }
+ }
+ }
+
+ if (cameraChunkCount > 0) {
+ const cameraRecovered = [];
+ await cameraChunksStore.iterate((value) => {
+ cameraRecovered.push(value);
+ });
+ cameraRecovered.sort((a, b) => (a.index || 0) - (b.index || 0));
+ const cameraBlob = createBlobFromChunks(
+ cameraRecovered.map((c) => c.chunk),
+ "video/webm",
+ );
+ if (cameraBlob) {
+ const cameraObjectUrl = URL.createObjectURL(cameraBlob);
+ try {
+ await chrome.downloads.download({
+ url: cameraObjectUrl,
+ filename: `Screenity-Recovered-Camera-${ts}.webm`,
+ saveAs: false,
+ });
+ } finally {
+ URL.revokeObjectURL(cameraObjectUrl);
+ }
}
}
+
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ 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 clearStaleUploadJournals(storedSession);
await chrome.storage.local.set({
- recorderSession: { ...storedSession, status: "recovered" },
+ recorderSession: {
+ ...storedSession,
+ status: "recovered",
+ recoveredAt: Date.now(),
+ recoveredChunkCount: chunkCount,
+ recoveredCameraChunkCount: cameraChunkCount,
+ },
+ });
+ } else if (storedSession && isRecoverable) {
+ void emitUploadTelemetry("upload_recovery_available", {
+ reason: "metadata-only",
+ recoveredChunkCount: 0,
+ recordingSessionId: storedSession?.id || null,
+ projectId: storedSession?.projectId || null,
+ });
+ // Even 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.
+ await clearStaleUploadJournals(storedSession);
+ await chrome.storage.local.set({
+ recorderSession: {
+ ...storedSession,
+ status: "recovery-metadata-only",
+ recoveredAt: Date.now(),
+ recoveredChunkCount: 0,
+ },
+ });
+ } else {
+ void emitUploadTelemetry("upload_recovery_unavailable", {
+ reason: "no-recoverable-session",
});
}
} catch (err) {
@@ -1030,13 +1984,99 @@ const CloudRecorder = () => {
};
const checkMaxMemory = () => {
- navigator.storage.estimate().then((data) => {
- const minMemory = 26214400;
- if (data.quota < minMemory) {
- chrome.storage.local.set({ memoryError: true });
- sendStopRecording("low-storage-quota");
+ const now = Date.now();
+ if (now - storagePressureRef.current.lastEstimateAt < STORAGE_CHECK_INTERVAL_MS) {
+ return;
+ }
+ storagePressureRef.current.lastEstimateAt = now;
+
+ navigator.storage
+ .estimate()
+ .then((data) => {
+ const minQuota = 25 * 1024 * 1024;
+ const quota = data?.quota || 0;
+ const usage = data?.usage || 0;
+ const headroom = Math.max(0, quota - usage);
+ const lowSpace = headroom > 0 && headroom < STORAGE_LOW_HEADROOM_BYTES;
+ const critical =
+ headroom > 0 && headroom < STORAGE_CRITICAL_HEADROOM_BYTES;
+
+ storagePressureRef.current = {
+ ...storagePressureRef.current,
+ quota,
+ usage,
+ headroom,
+ lowSpace,
+ critical,
+ };
+
+ if (quota < minQuota) {
+ void emitUploadTelemetry("upload_storage_pressure", {
+ severity: "quota-too-low",
+ quota,
+ usage,
+ headroom,
+ });
+ chrome.storage.local.set({
+ memoryError: true,
+ cloudRecorderDegradedMode: {
+ reason: "low-storage-quota",
+ quota,
+ usage,
+ headroom,
+ at: Date.now(),
+ },
+ });
+ if (!storagePressureRef.current.stopSent) {
+ storagePressureRef.current.stopSent = true;
+ sendStopRecording("low-storage-quota");
+ }
+ return;
}
- });
+
+ if (critical) {
+ void emitUploadTelemetry("upload_storage_pressure", {
+ severity: "critical",
+ quota,
+ usage,
+ headroom,
+ });
+ chrome.storage.local.set({
+ cloudRecorderDegradedMode: {
+ reason: "critical-storage-headroom",
+ quota,
+ usage,
+ headroom,
+ at: Date.now(),
+ },
+ });
+ if (!storagePressureRef.current.stopSent) {
+ storagePressureRef.current.stopSent = true;
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("toastStorageCritical"),
+ });
+ sendStopRecording("critical-storage-headroom");
+ }
+ } else if (lowSpace && !storagePressureRef.current.warned) {
+ storagePressureRef.current.warned = true;
+ void emitUploadTelemetry("upload_storage_pressure", {
+ severity: "warning",
+ quota,
+ usage,
+ headroom,
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("toastStorageLow"),
+ });
+ } else if (!lowSpace) {
+ storagePressureRef.current.warned = false;
+ }
+ })
+ .catch((err) => {
+ console.warn("Failed to estimate storage usage:", err);
+ });
};
const setMic = async (result) => {
@@ -1202,6 +2242,11 @@ const CloudRecorder = () => {
totalPausedMs: 0,
});
pausedStateRef.current = false;
+ await clearAudioChunkStore(restarting ? "dismiss-restart" : "dismiss-recording");
+ await clearCameraChunkStore(restarting ? "dismiss-restart" : "dismiss-recording");
+ await clearLocalScreenPlaybackOffer(
+ restarting ? "dismiss-restart" : "dismiss-recording",
+ );
const { projectId, multiMode, multiSceneCount, recordingToScene } =
await chrome.storage.local.get([
@@ -1227,6 +2272,11 @@ const CloudRecorder = () => {
console.warn("❌ Failed to delete media:", err);
}
}
+ try {
+ await finalizeRecorderSession("restarting");
+ } catch {
+ // best effort
+ }
uploadMetaRef.current = null;
sentLast.current = false;
screenUploader.current = null;
@@ -1332,6 +2382,11 @@ const CloudRecorder = () => {
screenChunks.current = [];
cameraChunks.current = [];
audioChunks.current = [];
+ await clearAudioChunkStore("restart");
+ await clearCameraChunkStore("restart");
+ resetSessionTrackState();
+ recoveryExportedRef.current = false;
+ audioCaptureDegradedRef.current = false;
index.current = 0;
lastTimecode.current = 0;
@@ -1365,6 +2420,7 @@ const CloudRecorder = () => {
try {
emptyCleanupRef.current = false;
const { projectId } = await chrome.storage.local.get(["projectId"]);
+ const sessionId = ensureRecordingSessionId();
const sceneId = await getOrCreateSceneId({
forceNew: forceNewSceneId,
@@ -1383,8 +2439,51 @@ const CloudRecorder = () => {
throw new Error("Missing projectId");
}
- const onStall = (payload) => {
+ const onUploaderTelemetry =
+ (trackType) => (eventName, payload = {}) => {
+ void emitUploadTelemetry(eventName, {
+ projectId,
+ sceneId,
+ trackType,
+ ...payload,
+ });
+ };
+
+ const onUploaderStateChange = (trackType) => (state = {}) => {
+ patchTrackState(trackType, {
+ lastUploadOffset: state?.offset || 0,
+ uploaderUpdatedAt: Date.now(),
+ });
+ persistSessionState();
+ if (state?.status === "error" && state?.error) {
+ persistSessionState({
+ uploadHealth: "error",
+ uploadError: state.error,
+ uploadErrorTrack: trackType,
+ });
+ }
+ };
+
+ const onStall = (trackType) => (payload) => {
stallNotified.current = true;
+ persistSessionState({
+ uploadHealth: "stalled",
+ stalledAt: Date.now(),
+ stalledMediaId: payload?.mediaId || null,
+ stalledOffset: payload?.offset || 0,
+ stalledTrack: trackType,
+ });
+ void emitUploadTelemetry("upload_stalled", {
+ projectId,
+ sceneId,
+ trackType,
+ mediaId: payload?.mediaId || null,
+ bunnyVideoId: payload?.videoId || null,
+ offset: payload?.offset || 0,
+ stallMs: payload?.diff || null,
+ reason: payload?.reason || "heartbeat",
+ uploaderType: "bunny_tus",
+ });
chrome.runtime.sendMessage({
type: "upload-stalled",
offset: {
@@ -1396,15 +2495,27 @@ const CloudRecorder = () => {
if (screenStream.current) {
screenUploader.current = new BunnyTusUploader({
+ sessionId,
+ trackType: "screen",
onProgress: ({ offset }) => {
+ const now = Date.now();
lastUploadProgress.current = {
...lastUploadProgress.current,
screen: offset,
- ts: Date.now(),
+ ts: now,
};
- persistSessionState();
+ patchTrackState("screen", {
+ lastUploadOffset: offset,
+ uploaderUpdatedAt: now,
+ });
+ if (now - (lastUploadProgress.current.lastPersistAt || 0) > 2000) {
+ lastUploadProgress.current.lastPersistAt = now;
+ persistSessionState();
+ }
},
- onStall,
+ onStall: onStall("screen"),
+ onTelemetry: onUploaderTelemetry("screen"),
+ onStateChange: onUploaderStateChange("screen"),
});
const track = screenStream.current.getVideoTracks()[0];
let width, height;
@@ -1422,6 +2533,7 @@ const CloudRecorder = () => {
width,
height,
sceneId,
+ sessionId,
});
logDebugEvent("uploader-ready", {
type: "screen",
@@ -1434,15 +2546,27 @@ const CloudRecorder = () => {
if (cameraStream.current) {
cameraUploader.current = new BunnyTusUploader({
+ sessionId,
+ trackType: "camera",
onProgress: ({ offset }) => {
+ const now = Date.now();
lastUploadProgress.current = {
...lastUploadProgress.current,
camera: offset,
- ts: Date.now(),
+ ts: now,
};
- persistSessionState();
+ patchTrackState("camera", {
+ lastUploadOffset: offset,
+ uploaderUpdatedAt: now,
+ });
+ if (now - (lastUploadProgress.current.lastPersistAt || 0) > 2000) {
+ lastUploadProgress.current.lastPersistAt = now;
+ persistSessionState();
+ }
},
- onStall,
+ onStall: onStall("camera"),
+ onTelemetry: onUploaderTelemetry("camera"),
+ onStateChange: onUploaderStateChange("camera"),
});
const track = cameraStream.current.getVideoTracks()[0];
if (track?.readyState === "ended") {
@@ -1456,6 +2580,7 @@ const CloudRecorder = () => {
width,
height,
sceneId,
+ sessionId,
});
logDebugEvent("uploader-ready", {
type: "camera",
@@ -1474,6 +2599,11 @@ const CloudRecorder = () => {
return true;
} catch (err) {
console.error("❌ Failed to initialize uploaders:", err);
+ void emitUploadTelemetry("upload_error", {
+ reason: "uploaders-init-failed",
+ message: err?.message || String(err),
+ uploaderType: "cloud_recorder",
+ });
sendRecordingError("Failed to initialize uploaders: " + err.message);
await setPipelineState("uploaders-error", {
status: "error",
@@ -1490,7 +2620,16 @@ const CloudRecorder = () => {
recorder.ondataavailable = (event) => {
if (event.data && event.data.size > 0) {
- onDataAvailable(event.data);
+ try {
+ const maybePromise = onDataAvailable(event.data);
+ if (maybePromise && typeof maybePromise.catch === "function") {
+ maybePromise.catch((err) => {
+ console.warn("onDataAvailable failed:", err);
+ });
+ }
+ } catch (err) {
+ console.warn("onDataAvailable failed:", err);
+ }
}
};
@@ -1508,11 +2647,14 @@ const CloudRecorder = () => {
const startRecording = async () => {
setInitProject(false);
+ await clearLocalScreenPlaybackOffer("start-recording");
// Start silent audio to prevent Chrome from freezing this background tab
startTabKeepAlive();
const storageReady = await ensureChunkStoreReady();
if (!storageReady) return;
+ await ensureAudioChunkStoreReady();
+ await ensureCameraChunkStoreReady();
const pinned = await chrome.runtime
.sendMessage({ type: "is-pinned" })
@@ -1561,10 +2703,18 @@ const CloudRecorder = () => {
}
if (!recorderSession.current) {
- const registered = await startRecorderSession({ projectId });
+ const registered = await startRecorderSession({
+ projectId,
+ sessionId: ensureRecordingSessionId(),
+ });
if (!registered) return;
}
+ await Promise.allSettled([
+ screenUploader.current?.setSessionId?.(recorderSession.current?.id || null),
+ cameraUploader.current?.setSessionId?.(recorderSession.current?.id || null),
+ ]);
+
if (!screenUploader.current && !cameraUploader.current) {
sendRecordingError("Uploaders not ready. Please restart recording.");
logStartFlow("recording_error", { reason: "uploaders-not-ready" });
@@ -1573,6 +2723,8 @@ const CloudRecorder = () => {
try {
await chunksStore.clear();
+ await clearAudioChunkStore("start-recording");
+ await clearCameraChunkStore("start-recording");
} catch (err) {
fatalErrorRef.current = true;
sendRecordingError(
@@ -1584,6 +2736,16 @@ const CloudRecorder = () => {
hasChunks.current = false;
index.current = 0;
firstChunkLoggedRef.current = false;
+ resetUnloadGuard();
+ recoveryExportedRef.current = false;
+ storagePressureRef.current.stopSent = false;
+ storagePressureRef.current.warned = false;
+ networkStateRef.current = {
+ online: navigator.onLine,
+ offlineSince: navigator.onLine ? null : Date.now(),
+ };
+ audioCaptureDegradedRef.current = false;
+ resetSessionTrackState();
// Clear blob storage arrays
screenChunks.current = [];
@@ -1650,6 +2812,16 @@ const CloudRecorder = () => {
// Store for final blob creation
screenChunks.current.push(blob);
+ const screenDropped = trimChunkBuffer(
+ screenChunks,
+ SCREEN_CHUNK_MEMORY_WINDOW,
+ );
+ noteTrackChunk("screen", blob, {
+ inMemoryChunkCount: screenChunks.current.length,
+ droppedInMemoryChunks:
+ (sessionTrackState.current.screen?.droppedInMemoryChunks || 0) +
+ screenDropped,
+ });
const timestamp = Date.now();
@@ -1683,6 +2855,12 @@ const CloudRecorder = () => {
throw err;
});
+ patchTrackState("screen", {
+ durableChunkCount: index.current + 1,
+ lastPersistedChunkIndex: index.current,
+ lastPersistedAt: timestamp,
+ });
+
persistSessionState({ lastChunkIndex: index.current });
if (uploadersInitialized.current && screenUploader.current) {
@@ -1737,9 +2915,72 @@ const CloudRecorder = () => {
audioRecorder.current = createMediaRecorder(
rawMicStream.current,
audioOptions,
- (blob) => {
- // Store chunks for final blob creation
+ async (blob) => {
+ const timestamp = Date.now();
+ // Keep a small in-memory window for UI/quick fallback only.
audioChunks.current.push(blob);
+ const droppedAudio = trimChunkBuffer(
+ audioChunks,
+ AUDIO_CHUNK_MEMORY_WINDOW,
+ );
+ noteTrackChunk("audio", blob, {
+ inMemoryChunkCount: audioChunks.current.length,
+ droppedInMemoryChunks:
+ (sessionTrackState.current.audio?.droppedInMemoryChunks || 0) +
+ droppedAudio,
+ });
+ if (audioChunkStoreReadyRef.current) {
+ const audioChunkIndex = audioChunkIndexRef.current;
+ audioChunkIndexRef.current += 1;
+ try {
+ await audioChunksStore.setItem(`audio_chunk_${audioChunkIndex}`, {
+ index: audioChunkIndex,
+ chunk: blob,
+ timestamp,
+ });
+ patchTrackState("audio", {
+ durableChunkCount: audioChunkIndex + 1,
+ lastPersistedChunkIndex: audioChunkIndex,
+ lastPersistedAt: timestamp,
+ });
+ } catch (err) {
+ audioChunkStoreReadyRef.current = false;
+ void emitUploadTelemetry("upload_local_backup_degraded", {
+ backupType: "audio",
+ reason: "audio-idb-write-failed",
+ error: err?.message || String(err),
+ });
+ }
+ }
+ if (
+ !audioCaptureDegradedRef.current &&
+ (sessionTrackState.current.audio?.bytesRecorded || 0) >
+ AUDIO_MAX_BUFFER_BYTES
+ ) {
+ audioCaptureDegradedRef.current = true;
+ void emitUploadTelemetry("upload_local_backup_degraded", {
+ backupType: "audio",
+ reason: "audio-buffer-limit",
+ bytesRecorded:
+ sessionTrackState.current.audio?.bytesRecorded || 0,
+ });
+ persistSessionState({
+ degradedReason: "audio-buffer-limit",
+ audioCaptureDegradedAt: Date.now(),
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("toastAudioCaptureDegraded"),
+ });
+ try {
+ if (audioRecorder.current?.state === "recording") {
+ audioRecorder.current.stop();
+ }
+ } catch (err) {
+ console.warn("Failed to stop audio recorder after degradation:", err);
+ }
+ return;
+ }
if (!firstChunkLoggedRef.current) {
firstChunkLoggedRef.current = true;
logStartFlow("first_chunk", { type: "audio" });
@@ -1788,12 +3029,50 @@ const CloudRecorder = () => {
// Store for final blob creation
cameraChunks.current.push(blob);
+ const cameraDropped = trimChunkBuffer(
+ cameraChunks,
+ CAMERA_CHUNK_MEMORY_WINDOW,
+ );
+ noteTrackChunk("camera", blob, {
+ inMemoryChunkCount: cameraChunks.current.length,
+ droppedInMemoryChunks:
+ (sessionTrackState.current.camera?.droppedInMemoryChunks || 0) +
+ cameraDropped,
+ });
if (!firstChunkLoggedRef.current) {
firstChunkLoggedRef.current = true;
logStartFlow("first_chunk", { type: "camera" });
assertCountdownBeforeFirstChunk(Date.now());
}
+ if (cameraChunkStoreReadyRef.current) {
+ const cameraChunkIndex = cameraChunkIndexRef.current;
+ cameraChunkIndexRef.current += 1;
+ try {
+ await cameraChunksStore.setItem(
+ `camera_chunk_${cameraChunkIndex}`,
+ {
+ index: cameraChunkIndex,
+ chunk: blob,
+ timestamp: Date.now(),
+ },
+ );
+ patchTrackState("camera", {
+ durableChunkCount: cameraChunkIndex + 1,
+ lastPersistedChunkIndex: cameraChunkIndex,
+ lastPersistedAt: Date.now(),
+ });
+ } catch (err) {
+ cameraChunkStoreReadyRef.current = false;
+ console.warn("Failed to persist camera chunk to IDB:", err);
+ void emitUploadTelemetry("upload_local_backup_degraded", {
+ backupType: "camera",
+ reason: "camera-idb-write-failed",
+ error: err?.message || String(err),
+ });
+ }
+ }
+
if (uploadersInitialized.current && cameraUploader.current) {
try {
if (cameraUploader.current?.isPaused) return;
@@ -1870,6 +3149,7 @@ const CloudRecorder = () => {
});
pausedStateRef.current = false;
persistSessionState({ status: "recording" });
+ startSessionHeartbeat();
setStarted(true);
await setPipelineState("recording", {
projectId,
@@ -1905,6 +3185,7 @@ const CloudRecorder = () => {
screen: screenUploader.current?.offset || 0,
camera: cameraUploader.current?.offset || 0,
ts: Date.now(),
+ lastPersistAt: Date.now(),
};
startChunkWatchdog();
startUploadHeartbeat();
@@ -2091,7 +3372,23 @@ const CloudRecorder = () => {
cameraRecorder.current?.state === "recording" ||
audioRecorder.current?.state === "recording";
- if (hasActiveRecorder && !sentLast.current && isActualUnload) {
+ if (!unloadGuardRef.current.pagehideSeen) {
+ unloadGuardRef.current.pagehideSeen = true;
+ void emitUploadTelemetry("upload_pagehide", {
+ persisted: Boolean(event.persisted),
+ hasActiveRecorder,
+ });
+ }
+
+ if (
+ hasActiveRecorder &&
+ !sentLast.current &&
+ !isFinishing.current &&
+ isActualUnload &&
+ !unloadGuardRef.current.stopTriggeredFromUnload
+ ) {
+ unloadGuardRef.current.stopTriggeredFromUnload = true;
+ emitAbandonedOnUnloadOnce("pagehide");
console.warn("⚠️ Recorder page unloading — finalizing");
// Use sendBeacon or sync storage write for reliability
navigator.sendBeacon?.(
@@ -2109,22 +3406,95 @@ const CloudRecorder = () => {
useEffect(() => {
const onVisibilityChange = () => {
if (document.visibilityState === "hidden") {
- persistSessionState({ status: "hidden" });
+ persistSessionState({
+ visibilityState: "hidden",
+ visibilityChangedAt: Date.now(),
+ });
}
};
- const onBeforeUnload = () => {
- if (hasChunks.current) {
- persistSessionState({ status: "unload" });
+ const onBeforeUnload = () => {
+ if (hasChunks.current) {
+ if (!unloadGuardRef.current.beforeUnloadSeen) {
+ unloadGuardRef.current.beforeUnloadSeen = true;
+ emitAbandonedOnUnloadOnce("beforeunload");
+ }
+ persistSessionState({
+ unloadAt: Date.now(),
+ unloadReason: "beforeunload",
+ });
+ }
+ };
+
+ document.addEventListener("visibilitychange", onVisibilityChange);
+ window.addEventListener("beforeunload", onBeforeUnload);
+
+ return () => {
+ document.removeEventListener("visibilitychange", onVisibilityChange);
+ window.removeEventListener("beforeunload", onBeforeUnload);
+ };
+ }, []);
+
+ useEffect(() => {
+ const onOffline = () => {
+ networkStateRef.current = {
+ online: false,
+ offlineSince: Date.now(),
+ };
+ screenUploader.current?.pause?.();
+ cameraUploader.current?.pause?.();
+ void emitUploadTelemetry("upload_stalled", {
+ reason: "network-offline",
+ uploaderType: "cloud_recorder",
+ });
+ persistSessionState({
+ networkOfflineAt: networkStateRef.current.offlineSince,
+ degradedReason: "network-offline",
+ });
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("toastNetworkOffline"),
+ });
+ };
+
+ const RESUMABLE_UPLOADER_STATUSES = new Set([
+ "uploading",
+ "paused",
+ "error",
+ "ready",
+ ]);
+
+ const onOnline = () => {
+ networkStateRef.current = {
+ online: true,
+ offlineSince: null,
+ };
+ if (
+ screenUploader.current &&
+ RESUMABLE_UPLOADER_STATUSES.has(screenUploader.current.status)
+ ) {
+ screenUploader.current.resume();
+ }
+ if (
+ cameraUploader.current &&
+ RESUMABLE_UPLOADER_STATUSES.has(cameraUploader.current.status)
+ ) {
+ cameraUploader.current.resume();
}
+ void emitUploadTelemetry("upload_resumed", {
+ reason: "network-online",
+ uploaderType: "cloud_recorder",
+ });
+ persistSessionState({
+ networkOnlineAt: Date.now(),
+ });
};
- document.addEventListener("visibilitychange", onVisibilityChange);
- window.addEventListener("beforeunload", onBeforeUnload);
-
+ window.addEventListener("offline", onOffline);
+ window.addEventListener("online", onOnline);
return () => {
- document.removeEventListener("visibilitychange", onVisibilityChange);
- window.removeEventListener("beforeunload", onBeforeUnload);
+ window.removeEventListener("offline", onOffline);
+ window.removeEventListener("online", onOnline);
};
}, []);
@@ -2132,6 +3502,10 @@ const CloudRecorder = () => {
tryRecoverPreviousSession();
}, [tryRecoverPreviousSession]);
+ useEffect(() => {
+ void ensureTelemetryRuntimeContext();
+ }, []);
+
useEffect(() => {
recoverPendingScenes();
}, [recoverPendingScenes]);
@@ -2149,6 +3523,74 @@ const CloudRecorder = () => {
};
}, []);
+ const sendEditorReady = ({
+ projectId,
+ sceneId,
+ recordingToScene,
+ multiMode,
+ }) => {
+ const localPlayback = localScreenPlaybackOfferRef.current;
+ const localPlaybackAvailable =
+ Boolean(localPlayback?.offerId) &&
+ localPlayback?.trackType === "screen" &&
+ Number(localPlayback?.expiresAt || 0) > Date.now();
+
+ const shouldNotifyEditor = !multiMode || recordingToScene;
+ if (!shouldNotifyEditor || !projectId || !sceneId) {
+ console.warn("[Screenity][CloudRecorder] Skipping editor-ready", {
+ shouldNotifyEditor,
+ hasProjectId: Boolean(projectId),
+ hasSceneId: Boolean(sceneId),
+ recordingToScene: Boolean(recordingToScene),
+ multiMode: Boolean(multiMode),
+ });
+ return;
+ }
+
+ console.info("[Screenity][CloudRecorder] Sending editor-ready", {
+ projectId,
+ sceneId,
+ recordingToScene: Boolean(recordingToScene),
+ multiMode: Boolean(multiMode),
+ instantMode: Boolean(instantMode.current),
+ localPlaybackAvailable,
+ localPlaybackOfferId: localPlayback?.offerId || null,
+ });
+ chrome.runtime.sendMessage({
+ type: "editor-ready",
+ publicUrl: !recordingToScene
+ ? `${process.env.SCREENITY_APP_BASE}/view/${projectId}/`
+ : undefined,
+ newProject: !recordingToScene && !multiMode,
+ multiMode: Boolean(multiMode),
+ instantMode: instantMode.current,
+ sceneId,
+ projectId,
+ editorUrl:
+ !recordingToScene && !multiMode
+ ? instantMode.current
+ ? `${process.env.SCREENITY_APP_BASE}/view/${projectId}?load=true`
+ : `${process.env.SCREENITY_APP_BASE}/editor/${projectId}/edit?load=true`
+ : undefined,
+ localPlayback: localPlaybackAvailable
+ ? {
+ available: true,
+ offerId: localPlayback.offerId,
+ trackType: "screen",
+ chunkCount: localPlayback.chunkCount || 0,
+ estimatedBytes: localPlayback.estimatedBytes || 0,
+ expiresAt: localPlayback.expiresAt || null,
+ mediaId: localPlayback.mediaId || null,
+ bunnyVideoId: localPlayback.bunnyVideoId || null,
+ source: localPlayback.source || "indexeddb-screen-chunks",
+ }
+ : {
+ available: false,
+ trackType: "screen",
+ },
+ });
+ };
+
const createSceneOrHandleMultiMode = async (
uploadMeta,
durations,
@@ -2199,180 +3641,179 @@ const CloudRecorder = () => {
);
}
- const existingStatus = await getSceneCreateStatus(uploadMeta.sceneId);
+ const sceneId = uploadMeta.sceneId;
+ const existingStatus = await getSceneCreateStatus(sceneId);
+ let sceneOutcome = null;
+ let shouldIncrementMultiSceneCount = false;
+
if (existingStatus?.status === "created") {
logDebugEvent("scene-create-skip", {
projectId,
- sceneId: uploadMeta.sceneId,
+ sceneId,
});
await ensureMediaLinked({
projectId,
- sceneId: uploadMeta.sceneId,
+ sceneId,
mediaIds: [
uploadMeta.screen?.mediaId,
uploadMeta.camera?.mediaId,
uploadMeta.audio?.mediaId,
],
});
- return { reused: true };
- }
-
- await setSceneCreateStatus(uploadMeta.sceneId, "creating", {
- projectId,
- });
- await setPipelineState("scene-creating", {
- projectId,
- sceneId: uploadMeta.sceneId,
- });
- logDebugEvent("scene-create-start", {
- projectId,
- sceneId: uploadMeta.sceneId,
- });
-
- const payload = {
- sceneId: uploadMeta.sceneId,
- screenMediaId: uploadMeta.screen?.mediaId || null,
- cameraMediaId: uploadMeta.camera?.mediaId || null,
- screenVideoId: uploadMeta.screen?.videoId || null,
- cameraVideoId: uploadMeta.camera?.videoId || null,
- audioMediaId: uploadMeta.audio?.mediaId || null,
- recordingSessionId: recorderSession.current?.id || null,
- durations,
- captionSource: uploadMeta.screen ? "screen" : "camera",
- transcriptionSourceMediaId: !isSilent
- ? uploadMeta.audio?.mediaId || null
- : null,
- thumbnail: uploadMeta.screen?.thumbnail || null,
- dimensions: {
- screen: {
- width: uploadMeta.screen?.width || 1920,
- height: uploadMeta.screen?.height || 1080,
- },
- camera: uploadMeta.camera
- ? {
- width: uploadMeta.camera?.width || 1920,
- height: uploadMeta.camera?.height || 1080,
- flip: cameraFlipped,
- }
- : null,
- },
- clickEvents,
- surface,
- instantMode: instantMode.current,
- newProject: !recordingToScene && (!multiMode || multiSceneCount === 0),
- insertAfterSceneId,
- isTab: isTab.current && !regionRef.current,
- 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),
- });
-
- if (!res.ok) {
- const errorText = await res.text();
- const recoverResult = await recoverScene({
+ await removePendingScene(sceneId);
+ await markSceneComplete(sceneId);
+ await setPipelineState("scene-reused", {
projectId,
- sceneId: uploadMeta.sceneId,
+ sceneId,
+ });
+ sceneOutcome = "reused";
+ } else {
+ await setSceneCreateStatus(sceneId, "creating", {
+ projectId,
+ });
+ await setPipelineState("scene-creating", {
+ projectId,
+ sceneId,
+ });
+ logDebugEvent("scene-create-start", {
+ projectId,
+ sceneId,
+ });
+
+ const payload = {
+ sceneId,
screenMediaId: uploadMeta.screen?.mediaId || null,
cameraMediaId: uploadMeta.camera?.mediaId || null,
+ screenVideoId: uploadMeta.screen?.videoId || null,
+ cameraVideoId: uploadMeta.camera?.videoId || null,
audioMediaId: uploadMeta.audio?.mediaId || null,
+ recordingSessionId: recorderSession.current?.id || null,
+ durations,
+ captionSource: uploadMeta.screen ? "screen" : "camera",
+ transcriptionSourceMediaId: !isSilent
+ ? uploadMeta.audio?.mediaId || null
+ : null,
+ thumbnail: uploadMeta.screen?.thumbnail || null,
+ dimensions: {
+ screen: {
+ width: uploadMeta.screen?.width || 1920,
+ height: uploadMeta.screen?.height || 1080,
+ },
+ camera: uploadMeta.camera
+ ? {
+ width: uploadMeta.camera?.width || 1920,
+ height: uploadMeta.camera?.height || 1080,
+ flip: cameraFlipped,
+ }
+ : null,
+ },
+ clickEvents,
+ surface,
+ instantMode: instantMode.current,
+ newProject: !recordingToScene && (!multiMode || multiSceneCount === 0),
+ insertAfterSceneId,
+ isTab: isTab.current && !regionRef.current,
+ 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),
});
- if (recoverResult.ok) {
- await setSceneCreateStatus(uploadMeta.sceneId, "created", {
- recovered: true,
+ if (!res.ok) {
+ const errorText = await res.text();
+ const recoverResult = await recoverScene({
+ projectId,
+ sceneId,
+ screenMediaId: uploadMeta.screen?.mediaId || null,
+ cameraMediaId: uploadMeta.camera?.mediaId || null,
+ audioMediaId: uploadMeta.audio?.mediaId || null,
});
+
+ if (recoverResult.ok) {
+ await setSceneCreateStatus(sceneId, "created", {
+ recovered: true,
+ });
+ await ensureMediaLinked({
+ projectId,
+ sceneId,
+ mediaIds: [
+ uploadMeta.screen?.mediaId,
+ uploadMeta.camera?.mediaId,
+ uploadMeta.audio?.mediaId,
+ ],
+ });
+ await removePendingScene(sceneId);
+ await markSceneComplete(sceneId);
+ await setPipelineState("scene-recovered", {
+ projectId,
+ sceneId,
+ });
+ logDebugEvent("scene-recovered", {
+ projectId,
+ sceneId,
+ });
+ sceneOutcome = "recovered";
+ shouldIncrementMultiSceneCount = true;
+ } else {
+ logDebugEvent("scene-create-failed", {
+ projectId,
+ sceneId,
+ error: errorText,
+ });
+ await setSceneCreateStatus(sceneId, "failed", {
+ error: errorText,
+ });
+ throw new Error(`Failed to create scene: ${errorText}`);
+ }
+ } else {
+ await setSceneCreateStatus(sceneId, "created");
await ensureMediaLinked({
projectId,
- sceneId: uploadMeta.sceneId,
+ sceneId,
mediaIds: [
uploadMeta.screen?.mediaId,
uploadMeta.camera?.mediaId,
uploadMeta.audio?.mediaId,
],
});
- await removePendingScene(uploadMeta.sceneId);
- await markSceneComplete(uploadMeta.sceneId);
- await setPipelineState("scene-recovered", {
+ await removePendingScene(sceneId);
+ await markSceneComplete(sceneId);
+ await setPipelineState("scene-created", {
projectId,
- sceneId: uploadMeta.sceneId,
+ sceneId,
});
- logDebugEvent("scene-recovered", {
+ logDebugEvent("scene-create-complete", {
projectId,
- sceneId: uploadMeta.sceneId,
+ sceneId,
});
- return { recovered: true };
+ sceneOutcome = "created";
+ shouldIncrementMultiSceneCount = true;
}
+ }
- logDebugEvent("scene-create-failed", {
- projectId,
- sceneId: uploadMeta.sceneId,
- error: errorText,
- });
- await setSceneCreateStatus(uploadMeta.sceneId, "failed", {
- error: errorText,
- });
- throw new Error(`Failed to create scene: ${errorText}`);
- } else {
- await setSceneCreateStatus(uploadMeta.sceneId, "created");
- await ensureMediaLinked({
- projectId,
- sceneId: uploadMeta.sceneId,
- mediaIds: [
- uploadMeta.screen?.mediaId,
- uploadMeta.camera?.mediaId,
- uploadMeta.audio?.mediaId,
- ],
- });
- await removePendingScene(uploadMeta.sceneId);
- await markSceneComplete(uploadMeta.sceneId);
- await setPipelineState("scene-created", {
- projectId,
- sceneId: uploadMeta.sceneId,
+ if (multiMode && shouldIncrementMultiSceneCount) {
+ await chrome.storage.local.set({
+ multiSceneCount: multiSceneCount + 1,
+ multiLastSceneId: sceneId,
});
- logDebugEvent("scene-create-complete", {
- projectId,
- sceneId: uploadMeta.sceneId,
+ chrome.runtime.sendMessage({
+ type: "reopen-popup-multi",
});
- if (multiMode) {
- await chrome.storage.local.set({
- multiSceneCount: multiSceneCount + 1,
- multiLastSceneId: payload.sceneId,
- });
- chrome.runtime.sendMessage({
- type: "reopen-popup-multi",
- });
-
- if (recordingToScene) {
- chrome.runtime.sendMessage({
- type: "editor-ready",
- publicUrl: undefined,
- newProject: false,
- multiMode: true,
- sceneId: payload.sceneId,
- });
- }
- } else {
- // Fetch the scene in the editor page
- chrome.runtime.sendMessage({
- type: "editor-ready",
- publicUrl: !recordingToScene
- ? `${process.env.SCREENITY_APP_BASE}/view/${projectId}/`
- : undefined,
- newProject: !recordingToScene,
- multiMode: false,
- instantMode: instantMode.current,
- sceneId: payload.sceneId,
- projectId,
- });
- }
}
- chrome.storage.local.remove("clickEvents");
+ sendEditorReady({
+ projectId,
+ sceneId,
+ recordingToScene,
+ multiMode,
+ });
+
+ await chrome.storage.local.remove("clickEvents");
+ return { [sceneOutcome || "created"]: true };
};
// Check if audio is silent to skip transcription
@@ -2394,6 +3835,8 @@ const CloudRecorder = () => {
const stopRecording = async (shouldFinalize = true, reason = "unknown") => {
if (isFinishing.current || sentLast.current) return;
+ // Lock immediately to prevent duplicate stop/finalize races under unload pressure.
+ isFinishing.current = true;
clearPendingStart();
if (DEBUG_START_FLOW) {
@@ -2405,7 +3848,9 @@ const CloudRecorder = () => {
audioState: audioRecorder.current?.state,
screenOffset: screenUploader.current?.offset || 0,
cameraOffset: cameraUploader.current?.offset || 0,
- chunkCount: screenChunks.current.length + cameraChunks.current.length,
+ chunkCount:
+ (sessionTrackState.current.screen?.chunkCount || 0) +
+ (sessionTrackState.current.camera?.chunkCount || 0),
});
}
logStartFlow("recording_stop", { reason, shouldFinalize });
@@ -2414,7 +3859,9 @@ const CloudRecorder = () => {
reason,
screenOffset: screenUploader.current?.offset || 0,
cameraOffset: cameraUploader.current?.offset || 0,
- chunkCount: screenChunks.current.length + cameraChunks.current.length,
+ chunkCount:
+ (sessionTrackState.current.screen?.chunkCount || 0) +
+ (sessionTrackState.current.camera?.chunkCount || 0),
ts: Date.now(),
},
});
@@ -2437,7 +3884,9 @@ const CloudRecorder = () => {
await persistSessionState({ status: "stopping" });
- if (shouldFinalize) {
+ 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.
if (recordingToScene) {
chrome.runtime.sendMessage({
type: "prepare-editor-existing",
@@ -2446,6 +3895,7 @@ const CloudRecorder = () => {
} else if (!multiMode && !recordingToScene) {
chrome.runtime.sendMessage({
type: "prepare-open-editor",
+ projectId,
url: instantMode.current
? `${process.env.SCREENITY_APP_BASE}/view/${projectId}?load=true`
: `${process.env.SCREENITY_APP_BASE}/editor/${projectId}/edit?load=true`,
@@ -2454,7 +3904,6 @@ const CloudRecorder = () => {
});
}
}
- isFinishing.current = true;
await setRecordingTimingState({
recording: false,
paused: false,
@@ -2467,6 +3916,46 @@ const CloudRecorder = () => {
await stopAllRecorders();
+ const { sceneId } = await chrome.storage.local.get(["sceneId"]);
+ 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
+ sceneId:
+ screenUploader.current?.getMeta()?.sceneId ||
+ cameraUploader.current?.getMeta()?.sceneId ||
+ sceneId,
+ };
+ uploadMetaRef.current = uploadMeta;
+ cleanupTimers();
+
+ if (!shouldFinalize) {
+ console.info("[CloudRecorder] stopRecording: skipping uploader finalize", {
+ reason,
+ shouldFinalize,
+ screenStatus: uploadMeta.screen?.status || "none",
+ cameraStatus: uploadMeta.camera?.status || "none",
+ });
+ void emitUploadTelemetry("upload_cancelled", {
+ reason: reason || "stop-without-finalize",
+ uploaderType: "cloud_recorder",
+ });
+ try {
+ await chrome.storage.local.set({ sceneIdStatus: "cancelled" });
+ } catch {
+ // ignore
+ }
+ await finalizeRecorderSession("cancelled");
+ await chunksStore.clear().catch((e) =>
+ console.warn("[CloudRecorder] chunksStore.clear failed (cancelled-stop):", e),
+ );
+ await clearAudioChunkStore("cancelled-stop");
+ await clearCameraChunkStore("cancelled-stop");
+ await clearLocalScreenPlaybackOffer("cancelled-stop");
+ return;
+ }
+
const durations = calculateDurations();
await flushPendingChunks();
@@ -2547,37 +4036,19 @@ const CloudRecorder = () => {
});
}
- const { sceneId } = await chrome.storage.local.get(["sceneId"]);
-
- const uploadMeta = {
- screen: screenUploader.current?.getMeta() || null,
- camera: cameraUploader.current?.getMeta() || null,
- audio: null,
- //sceneId,
- // use sceneId as per the metadata in screenUploader or cameraUploader, whichever exists
- sceneId:
- screenUploader.current?.getMeta()?.sceneId ||
- cameraUploader.current?.getMeta()?.sceneId ||
- sceneId,
- };
-
- uploadMetaRef.current = uploadMeta;
-
- cleanupTimers();
-
- if (!shouldFinalize) {
- try {
- await chrome.storage.local.set({ sceneIdStatus: "cancelled" });
- } catch {
- // ignore
- }
- await finalizeRecorderSession("cancelled");
- return;
- }
-
if (finalizeError) {
+ void emitUploadTelemetry("upload_error", {
+ reason: "uploader-finalize-incomplete",
+ uploaderType: "cloud_recorder",
+ });
await exportLocalRecovery("finalize-error");
+ await chunksStore.clear().catch((e) =>
+ console.warn("[CloudRecorder] chunksStore.clear failed (finalize-error):", e),
+ );
await finalizeRecorderSession("failed");
+ await clearAudioChunkStore("finalize-error");
+ await clearCameraChunkStore("finalize-error");
+ await clearLocalScreenPlaybackOffer("finalize-error");
sendRecordingError(
"Upload failed to finalize. A recovery copy was downloaded.",
);
@@ -2641,7 +4112,13 @@ const CloudRecorder = () => {
} else {
await cleanupIfEmptyUploads("no-upload");
await exportLocalRecovery("no-upload");
+ await chunksStore.clear().catch((e) =>
+ console.warn("[CloudRecorder] chunksStore.clear failed (no-upload):", e),
+ );
await finalizeRecorderSession("failed");
+ await clearAudioChunkStore("no-upload");
+ await clearCameraChunkStore("no-upload");
+ await clearLocalScreenPlaybackOffer("no-upload");
sendRecordingError(
`No media was successfully uploaded. Screen: ${screenStatus} (${screenOffset} bytes, error: ${screenError}), Camera: ${cameraStatus} (${cameraOffset} bytes, error: ${cameraError})`,
);
@@ -2649,8 +4126,8 @@ const CloudRecorder = () => {
}
}
- // Create final audio blob from chunks
- const audioBlob = createBlobFromChunks(audioChunks.current, "audio/webm");
+ // Create final audio blob from durable store when available.
+ const audioBlob = await buildAudioBlobFromDurableStore();
const silent = audioBlob ? await isAudioSilent(audioBlob) : true;
await upsertPendingScene(uploadMeta.sceneId, {
@@ -2669,6 +4146,14 @@ const CloudRecorder = () => {
sceneId: uploadMeta.sceneId,
});
+ localScreenPlaybackOfferRef.current = await registerLocalScreenPlaybackOffer(
+ {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ uploadMeta,
+ },
+ );
+
chrome.storage.local.set({ uploadMeta });
isInit.current = false;
@@ -2699,12 +4184,32 @@ const CloudRecorder = () => {
}
chrome.runtime.sendMessage({ type: "video-ready", uploadMeta });
- await chunksStore.clear().catch(() => {});
+ if (localScreenPlaybackOfferRef.current?.offerId) {
+ console.info(
+ "[CloudRecorder] Retaining local screen chunks for editor local-first playback",
+ {
+ offerId: localScreenPlaybackOfferRef.current.offerId,
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ chunkCount: localScreenPlaybackOfferRef.current.chunkCount || 0,
+ },
+ );
+ } else {
+ await chunksStore.clear().catch(() => {});
+ }
+ await clearAudioChunkStore("success");
+ await clearCameraChunkStore("success");
await setPipelineState("completed", {
projectId,
sceneId: uploadMeta.sceneId,
});
await finalizeRecorderSession("completed");
+ void emitUploadTelemetry("upload_complete_client", {
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ uploaderType: "cloud_recorder",
+ mediaId: uploadMeta.screen?.mediaId || uploadMeta.camera?.mediaId || null,
+ });
if (!IS_IFRAME_CONTEXT) {
try {
@@ -2731,6 +4236,13 @@ const CloudRecorder = () => {
userMessage += err.message;
}
+ void emitUploadTelemetry("upload_error", {
+ reason: "scene-create-failed",
+ message: err?.message || String(err),
+ uploaderType: "cloud_recorder",
+ projectId,
+ sceneId: uploadMeta.sceneId,
+ });
sendRecordingError(userMessage);
chrome.storage.local.set({
@@ -2759,12 +4271,18 @@ const CloudRecorder = () => {
}
}, 3000);
await exportLocalRecovery("scene-error");
+ await chunksStore.clear().catch((e) =>
+ console.warn("[CloudRecorder] chunksStore.clear failed (scene-error):", e),
+ );
try {
await chrome.storage.local.set({ sceneIdStatus: "failed" });
} catch {
// ignore
}
await finalizeRecorderSession("failed");
+ await clearAudioChunkStore("scene-error");
+ await clearCameraChunkStore("scene-error");
+ await clearLocalScreenPlaybackOffer("scene-error");
}
}
};
@@ -3274,7 +4792,11 @@ const CloudRecorder = () => {
name: "microphone",
});
- if (isTab.current && data.recordingType !== "region") {
+ 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.
let attempts = 0;
while (!tabID.current && attempts < 20) {
// wait for tab stream id to resolve
@@ -3290,7 +4812,12 @@ const CloudRecorder = () => {
if (data.recordingType === "camera") {
startStream(data, null, permissions, permissions2);
- } else if (!isTab.current && data.recordingType != "region") {
+ } 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.
chrome.desktopCapture.chooseDesktopMedia(
["screen", "window", "tab", "audio"],
null,
@@ -3382,6 +4909,18 @@ const CloudRecorder = () => {
chrome.runtime.sendMessage({ type: "get-streaming-data" });
}
} else if (!request.region) {
+ // 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.
+ if (typeof request.tabPreferred === "boolean") {
+ tabPreferred.current = request.tabPreferred;
+ console.info(
+ "[CloudRecorder] tabPreferred from loaded message:",
+ request.tabPreferred,
+ );
+ }
if (!tabPreferred.current) {
isTab.current = request.isTab;
recordingTabId.current = request.tabID || null;
@@ -3498,6 +5037,10 @@ const CloudRecorder = () => {
paused: true,
pausedAt: now,
});
+ void persistSessionState({
+ paused: true,
+ pausedAt: now,
+ });
} else if (request.type === "resume-recording-tab") {
if (!isInit.current) return;
if (!pausedStateRef.current) return;
@@ -3535,6 +5078,10 @@ const CloudRecorder = () => {
pausedAt: null,
totalPausedMs: (totalPausedMs || 0) + additional,
});
+ await persistSessionState({
+ paused: false,
+ resumedAt: now,
+ });
} catch (err) {
console.warn("Failed to update resume timing state:", err);
}
diff --git a/src/pages/CloudRecorder/bunnyTusUploader.js b/src/pages/CloudRecorder/bunnyTusUploader.js
index 1184dbe..fe99191 100644
--- a/src/pages/CloudRecorder/bunnyTusUploader.js
+++ b/src/pages/CloudRecorder/bunnyTusUploader.js
@@ -66,6 +66,9 @@ export default class BunnyTusUploader {
this.MAX_QUEUE_SIZE = options.maxQueueSize || 100;
this.onProgress = options.onProgress || null;
this.onStall = options.onStall || null;
+ this.onTelemetry = options.onTelemetry || null;
+ this.onStateChange = options.onStateChange || null;
+ this.trackType = options.trackType || null;
this.totalBytes = 0;
this.uploadUrl = null;
@@ -92,6 +95,31 @@ export default class BunnyTusUploader {
this.queueProcessingPromise = null;
this.queuedBytes = 0;
this._hasExtractedMeta = true; // Skip in-flight thumbnail extraction to avoid timeouts/noise
+ this.sessionId = options.sessionId || null;
+ this.journalKey = null;
+ this.journalLookupKey = null;
+ this.fingerprint = null;
+ this.metaWidth = null;
+ this.metaHeight = null;
+ this.lastJournalPersistAt = 0;
+ this.journalPersistTimer = null;
+ this.JOURNAL_WRITE_INTERVAL_MS = options.journalWriteIntervalMs || 4000;
+ this.PROGRESS_EVENT_INTERVAL_MS =
+ options.progressEventIntervalMs || 5000;
+ this.createdAt = null;
+ this.readyAt = null;
+ this.firstByteAt = null;
+ this.lastChunkQueuedAt = null;
+ this.lastErrorAt = null;
+ this.lastErrorCode = null;
+ this.finalizeStartedAt = null;
+ this.finalizedAt = null;
+ this.resumeCount = 0;
+ this.lastServerOffset = 0;
+ this.hasEmittedClientStarted = false;
+ this.hasEmittedFirstByte = false;
+ this.lastProgressEventAt = 0;
+ this.initializedFromResume = false;
}
debugLog(message, payload = null) {
@@ -103,6 +131,118 @@ export default class BunnyTusUploader {
console.info(`[BunnyTusUploader] ${message}`);
}
+ getUploaderType() {
+ return this.trackType || this.metadata?.type || null;
+ }
+
+ emitTelemetry(event, payload = {}) {
+ if (typeof this.onTelemetry !== "function") return;
+ try {
+ this.onTelemetry(event, {
+ projectId: this.projectId || null,
+ sceneId: this.sceneId || null,
+ recordingSessionId: this.sessionId || null,
+ mediaId: this.mediaId || null,
+ bunnyVideoId: this.videoId || null,
+ trackType: this.getUploaderType(),
+ uploaderType: "bunny_tus",
+ status: this.status,
+ offset: this.offset || 0,
+ totalBytes: this.totalBytes || 0,
+ queuedBytes: this.queuedBytes || 0,
+ ...payload,
+ });
+ } catch (err) {
+ console.warn("Upload telemetry callback failed:", err);
+ }
+ }
+
+ notifyStateChange(reason = null, extra = {}) {
+ if (typeof this.onStateChange !== "function") return;
+ try {
+ this.onStateChange({
+ reason: reason || null,
+ ...this.getResumeState(),
+ ...extra,
+ });
+ } catch (err) {
+ console.warn("Upload state callback failed:", err);
+ }
+ }
+
+ setUploaderError(errorCode, err = null) {
+ this.status = "error";
+ this.error = errorCode || err?.message || "upload-error";
+ this.lastErrorAt = Date.now();
+ this.lastErrorCode = errorCode || null;
+ this.emitTelemetry("upload_error", {
+ errorCode: errorCode || null,
+ message: err?.message || this.error || "upload-error",
+ });
+ this.scheduleJournalPersist({ force: true });
+ }
+
+ async setSessionId(sessionId) {
+ this.sessionId = sessionId || null;
+ await this.persistUploadJournal({ force: true });
+ this.notifyStateChange("session-updated");
+ }
+
+ getResumeState() {
+ return {
+ projectId: this.projectId || null,
+ sceneId: this.sceneId || null,
+ type: this.metadata?.type || null,
+ trackType: this.getUploaderType(),
+ sessionId: this.sessionId || null,
+ videoId: this.videoId || null,
+ mediaId: this.mediaId || null,
+ uploadUrl: this.uploadUrl || null,
+ offset: this.offset || 0,
+ totalBytes: this.totalBytes || 0,
+ status: this.status,
+ error: this.error || null,
+ stalled: this.stalled,
+ queueLength: this.chunkQueue.length,
+ queuedBytes: this.queuedBytes,
+ lastProgressAt: this.lastProgressAt || null,
+ journalKey: this.journalKey || null,
+ journalLookupKey: this.journalLookupKey || null,
+ resumeCount: this.resumeCount || 0,
+ firstByteAt: this.firstByteAt || null,
+ readyAt: this.readyAt || null,
+ createdAt: this.createdAt || null,
+ finalizedAt: this.finalizedAt || null,
+ lastErrorAt: this.lastErrorAt || null,
+ lastErrorCode: this.lastErrorCode || null,
+ updatedAt: Date.now(),
+ };
+ }
+
+ scheduleJournalPersist({ force = false } = {}) {
+ if (force) {
+ if (this.journalPersistTimer) {
+ clearTimeout(this.journalPersistTimer);
+ this.journalPersistTimer = null;
+ }
+ void this.persistUploadJournal({ force: true });
+ return;
+ }
+
+ const sinceLastPersist = Date.now() - this.lastJournalPersistAt;
+ if (sinceLastPersist >= this.JOURNAL_WRITE_INTERVAL_MS) {
+ void this.persistUploadJournal({ force: false });
+ return;
+ }
+
+ if (this.journalPersistTimer) return;
+ const waitMs = this.JOURNAL_WRITE_INTERVAL_MS - sinceLastPersist;
+ this.journalPersistTimer = setTimeout(() => {
+ this.journalPersistTimer = null;
+ void this.persistUploadJournal({ force: false });
+ }, Math.max(250, waitMs));
+ }
+
getJournalKey(mediaId) {
return mediaId ? `uploadJournal-${mediaId}` : null;
}
@@ -140,6 +280,7 @@ export default class BunnyTusUploader {
projectId,
sceneId: sceneId || null,
type: type || null,
+ trackType: this.getUploaderType(),
videoId,
mediaId,
sessionId: sessionId || null,
@@ -171,6 +312,10 @@ export default class BunnyTusUploader {
this.debugLog("Cleared upload journal", {
keys: keysToRemove,
});
+ if (!journal || !journal.key || journal.key === this.journalKey) {
+ this.journalKey = null;
+ }
+ this.notifyStateChange("journal-cleared");
} catch (err) {
this.debugLog("Failed to clear upload journal", {
error: err?.message || err,
@@ -179,20 +324,47 @@ export default class BunnyTusUploader {
}
}
- async persistUploadJournal() {
+ async persistUploadJournal({ force = false } = {}) {
if (
typeof chrome === "undefined" ||
!chrome.storage?.local ||
!this.mediaId
)
return;
- const journalKey = this.getJournalKey(this.mediaId);
- const lookupKey = this.journalLookupKey;
+ if (this.journalPersistTimer && force) {
+ clearTimeout(this.journalPersistTimer);
+ this.journalPersistTimer = null;
+ }
+
+ if (
+ !force &&
+ Date.now() - this.lastJournalPersistAt < this.JOURNAL_WRITE_INTERVAL_MS
+ ) {
+ return;
+ }
+
+ const journalKey = this.journalKey || this.getJournalKey(this.mediaId);
+ this.journalKey = journalKey;
+
+ const inferredLookupKey =
+ this.projectId && this.metadata?.type
+ ? this.getJournalLookupKey(
+ this.projectId,
+ this.sceneId,
+ this.metadata.type,
+ )
+ : null;
+ const lookupKey = this.journalLookupKey || inferredLookupKey;
+ this.journalLookupKey = lookupKey;
+
+ const updatedAt = Date.now();
const payload = {
+ journalVersion: 2,
key: journalKey,
projectId: this.projectId || null,
sceneId: this.sceneId || null,
type: this.metadata.type || null,
+ trackType: this.getUploaderType(),
width: this.metaWidth || null,
height: this.metaHeight || null,
fingerprint: this.fingerprint || null,
@@ -203,11 +375,25 @@ export default class BunnyTusUploader {
libraryId: this.libraryId || null,
offset: this.offset,
totalBytes: this.totalBytes,
- updatedAt: Date.now(),
+ updatedAt,
videoId: this.videoId,
mediaId: this.mediaId,
stalled: this.stalled,
status: this.status,
+ error: this.error || null,
+ queueLength: this.chunkQueue.length,
+ queuedBytes: this.queuedBytes,
+ lastProgressAt: this.lastProgressAt || null,
+ createdAt: this.createdAt || null,
+ readyAt: this.readyAt || null,
+ firstByteAt: this.firstByteAt || null,
+ lastChunkQueuedAt: this.lastChunkQueuedAt || null,
+ finalizeStartedAt: this.finalizeStartedAt || null,
+ finalizedAt: this.finalizedAt || null,
+ lastErrorAt: this.lastErrorAt || null,
+ lastErrorCode: this.lastErrorCode || null,
+ lastServerOffset: this.lastServerOffset || 0,
+ resumeCount: this.resumeCount || 0,
};
const toStore = {
@@ -220,7 +406,16 @@ export default class BunnyTusUploader {
updatedAt: payload.updatedAt,
};
}
- await chrome.storage.local.set(toStore);
+ try {
+ await chrome.storage.local.set(toStore);
+ this.lastJournalPersistAt = updatedAt;
+ this.notifyStateChange("journal-persisted");
+ } catch (err) {
+ this.debugLog("Failed to persist upload journal", {
+ error: err?.message || err,
+ mediaId: this.mediaId,
+ });
+ }
}
isResumeJournalStale(updatedAt) {
@@ -392,6 +587,7 @@ export default class BunnyTusUploader {
linkedMediaId = null,
reuse = null,
sceneId = null,
+ sessionId = null,
},
) {
if (this.status !== "idle" && this.status !== "error") {
@@ -401,14 +597,21 @@ export default class BunnyTusUploader {
try {
this.projectId = projectId;
this.metadata = { title, type, linkedMediaId, sceneId };
+ this.trackType = this.trackType || type || null;
this.sceneId = sceneId;
this.metaWidth = width;
this.metaHeight = height;
+ this.sessionId = sessionId || this.sessionId || null;
+ this.journalLookupKey = this.getJournalLookupKey(projectId, sceneId, type);
+ this.createdAt = this.createdAt || Date.now();
this.status = "initializing";
this.error = null;
this.offset = 0;
this.totalBytes = 0;
+ this.lastErrorAt = null;
+ this.lastErrorCode = null;
+ this.initializedFromResume = false;
// Build fingerprint for resume journal matching
const fingerprint = this.buildFingerprint({
@@ -439,12 +642,19 @@ export default class BunnyTusUploader {
this.videoId = reuse.videoId;
this.mediaId = reuse.mediaId;
} else if (resumeJournal?.videoId && resumeJournal?.mediaId) {
+ this.initializedFromResume = true;
this.videoId = resumeJournal.videoId;
this.mediaId = resumeJournal.mediaId;
this.uploadUrl = resumeJournal.uploadUrl || null;
this.offset = resumeJournal.offset || 0;
this.totalBytes = resumeJournal.totalBytes || 0;
- this.journalKey = resumeJournal.key || this.getJournalKey(this.mediaId);
+ this.journalKey =
+ resumeJournal.key || this.journalKey || this.getJournalKey(this.mediaId);
+ this.journalLookupKey = resumeJournal.lookupKey || this.journalLookupKey;
+ if (!this.sessionId && resumeJournal.sessionId) {
+ this.sessionId = resumeJournal.sessionId;
+ }
+ this.resumeCount = (resumeJournal.resumeCount || 0) + 1;
this.debugLog("Resuming upload from journal candidate", {
projectId,
sceneId,
@@ -465,6 +675,7 @@ export default class BunnyTusUploader {
if (existingMap?.videoId && existingMap?.mediaId) {
this.videoId = existingMap.videoId;
this.mediaId = existingMap.mediaId;
+ this.journalKey = this.getJournalKey(this.mediaId);
this.debugLog("Reusing Bunny video from map", {
projectId,
sceneId,
@@ -530,14 +741,45 @@ export default class BunnyTusUploader {
});
}
+ this.journalKey = this.journalKey || this.getJournalKey(this.mediaId);
await this.refreshTusAuth();
- await this.initTusUpload();
+
+ if (this.uploadUrl) {
+ const serverOffset = await this.getServerOffset();
+ if (Number.isFinite(serverOffset) && serverOffset >= 0) {
+ this.lastServerOffset = serverOffset;
+ this.offset = serverOffset;
+ this.totalBytes = Math.max(this.totalBytes || 0, serverOffset);
+ if (this.initializedFromResume || serverOffset > 0) {
+ this.emitTelemetry("upload_resumed", {
+ resumedOffset: serverOffset,
+ resumeCount: this.resumeCount || 1,
+ });
+ }
+ } else {
+ this.setUploaderError("resume-offset-unverified");
+ throw new Error("Could not verify server offset during resume.");
+ }
+ } else {
+ await this.initTusUpload();
+ }
+
+ await this.persistUploadJournal({ force: true });
this.startHeartbeat();
this.status = "ready";
+ this.readyAt = Date.now();
+ this.emitTelemetry("upload_started", {
+ resumed: this.initializedFromResume,
+ resumeCount: this.resumeCount || 0,
+ });
+ this.scheduleJournalPersist({ force: true });
return { videoId: this.videoId, mediaId: this.mediaId };
} catch (err) {
- this.status = "error";
- this.error = err.message;
+ if (this.status !== "error") {
+ this.setUploaderError("initialize-failed", err);
+ } else {
+ this.scheduleJournalPersist({ force: true });
+ }
throw err;
}
}
@@ -551,6 +793,7 @@ export default class BunnyTusUploader {
this.signature = signature;
this.expires = expires;
this.libraryId = libraryId;
+ this.scheduleJournalPersist();
}
async initTusUpload() {
@@ -601,6 +844,7 @@ export default class BunnyTusUploader {
expires: this.expires,
});
}
+ await this.persistUploadJournal({ force: true });
}
async write(chunk) {
@@ -615,6 +859,10 @@ export default class BunnyTusUploader {
await this.checkAuthExpiration();
this.status = "uploading";
+ if (!this.hasEmittedClientStarted) {
+ this.hasEmittedClientStarted = true;
+ this.emitTelemetry("upload_client_started");
+ }
for (let i = 0; i < chunk.size; i += this.CHUNK_SIZE) {
const subChunk = chunk.slice(i, i + this.CHUNK_SIZE);
@@ -622,6 +870,8 @@ export default class BunnyTusUploader {
this.queuedBytes += subChunk.size;
this.totalBytes += subChunk.size;
}
+ this.lastChunkQueuedAt = Date.now();
+ this.scheduleJournalPersist();
// Always ensure queue is processing
if (!this.isProcessingQueue) {
@@ -688,6 +938,7 @@ export default class BunnyTusUploader {
// Fallback if Bunny doesn't return it for some reason
this.offset = currentOffset + data.length;
}
+ this.lastServerOffset = this.offset;
this.recordProgress(data.length);
return;
@@ -699,6 +950,13 @@ export default class BunnyTusUploader {
this.status = "error";
this.error = "tus-session-missing";
this.stalled = true;
+ this.lastErrorAt = Date.now();
+ this.lastErrorCode = "tus-session-missing";
+ this.emitTelemetry("upload_error", {
+ errorCode: "tus-session-missing",
+ httpStatus: 404,
+ });
+ this.scheduleJournalPersist({ force: true });
if (typeof this.onStall === "function") {
this.onStall({
mediaId: this.mediaId,
@@ -722,23 +980,16 @@ export default class BunnyTusUploader {
// Query server for current offset using HEAD request
try {
- const headRes = await fetch(this.uploadUrl, {
- method: "HEAD",
- headers: {
- "Tus-Resumable": "1.0.0",
- AuthorizationSignature: this.signature,
- AuthorizationExpire: String(this.expires),
- LibraryId: String(this.libraryId),
- VideoId: this.videoId,
- },
- });
-
- if (headRes.ok) {
- const serverOffset = parseInt(
- headRes.headers.get("Upload-Offset") || "0",
- );
-
+ const serverOffset = await this.getServerOffset();
+ if (Number.isFinite(serverOffset) && serverOffset >= 0) {
+ this.lastServerOffset = serverOffset;
this.offset = serverOffset;
+ this.totalBytes = Math.max(this.totalBytes || 0, serverOffset);
+ this.emitTelemetry("upload_resumed", {
+ resumedOffset: serverOffset,
+ reason: "offset-conflict",
+ });
+ this.scheduleJournalPersist({ force: true });
// Retry with corrected offset
continue;
@@ -759,6 +1010,7 @@ export default class BunnyTusUploader {
`❌ Failed to upload chunk after ${this.MAX_RETRIES} retries:`,
err,
);
+ this.setUploaderError("chunk-upload-retries-exhausted", err);
throw err;
}
console.warn(
@@ -795,8 +1047,7 @@ export default class BunnyTusUploader {
this.queuedBytes += chunk.size;
// Set error state
- this.status = "error";
- this.error = `Upload failed: ${err.message}`;
+ this.setUploaderError("queue-upload-failed", err);
// Stop processing queue on error
break;
@@ -848,16 +1099,97 @@ export default class BunnyTusUploader {
async finalize() {
if (this.isFinalizing) throw new Error("Already finalizing");
this.isFinalizing = true;
- await this.waitForPendingUploads();
- await this.checkAuthExpiration();
-
- // Re-validate offset with server to avoid partial finalization
- let serverOffset = null;
+ this.status = "finalizing";
+ this.finalizeStartedAt = Date.now();
+ this.emitTelemetry("upload_finalize_started");
+ this.scheduleJournalPersist({ force: true });
try {
- const headRes = await fetch(this.uploadUrl, {
- method: "HEAD",
+ await this.waitForPendingUploads();
+ await this.checkAuthExpiration();
+
+ // Re-validate offset with server to avoid partial finalization
+ let serverOffset = null;
+ try {
+ const headRes = await fetch(this.uploadUrl, {
+ method: "HEAD",
+ headers: {
+ "Tus-Resumable": "1.0.0",
+ AuthorizationSignature: this.signature,
+ AuthorizationExpire: String(this.expires),
+ LibraryId: String(this.libraryId),
+ VideoId: this.videoId,
+ },
+ });
+
+ if (headRes.ok) {
+ serverOffset = parseInt(
+ headRes.headers.get("Upload-Offset") || "0",
+ 10,
+ );
+ this.offset = serverOffset;
+ }
+ } catch (err) {
+ console.warn("⚠️ Failed HEAD before finalize:", err);
+ }
+
+ // If server didn't receive everything, don't "finalize" into a ghost upload.
+ if (serverOffset === null) {
+ this.setUploaderError("finalize-offset-unverified");
+ throw new Error("Finalize failed: could not verify server offset.");
+ }
+
+ if (serverOffset === 0) {
+ this.status = "error";
+ this.error = "server-offset-0";
+ this.lastErrorAt = Date.now();
+ this.lastErrorCode = "server-offset-0";
+ this.emitTelemetry("upload_error", {
+ errorCode: "server-offset-0",
+ });
+ this.scheduleJournalPersist({ force: true });
+ throw new Error("Finalize failed: server has 0 bytes.");
+ }
+
+ if (serverOffset < this.totalBytes) {
+ this.status = "error";
+ this.error = `incomplete-upload server=${serverOffset} expected=${this.totalBytes}`;
+ this.lastErrorAt = Date.now();
+ this.lastErrorCode = "finalize-incomplete-upload";
+ this.emitTelemetry("upload_error", {
+ errorCode: "finalize-incomplete-upload",
+ serverOffset,
+ expectedBytes: this.totalBytes,
+ });
+ this.scheduleJournalPersist({ force: true });
+ throw new Error(
+ `Finalize blocked: upload incomplete (server ${serverOffset} / expected ${this.totalBytes}).`,
+ );
+ }
+
+ if (serverOffset > this.totalBytes) {
+ this.status = "error";
+ this.error = `invalid-length server=${serverOffset} expected=${this.totalBytes}`;
+ this.lastErrorAt = Date.now();
+ this.lastErrorCode = "finalize-invalid-length";
+ this.emitTelemetry("upload_error", {
+ errorCode: "finalize-invalid-length",
+ serverOffset,
+ expectedBytes: this.totalBytes,
+ });
+ this.scheduleJournalPersist({ force: true });
+ throw new Error(
+ `Finalize blocked: serverOffset (${serverOffset}) exceeds expected totalBytes (${this.totalBytes}).`,
+ );
+ }
+
+ // Now we can safely complete the tus upload by declaring the final length
+ const res = await fetch(this.uploadUrl, {
+ method: "PATCH",
headers: {
"Tus-Resumable": "1.0.0",
+ "Content-Type": "application/offset+octet-stream",
+ "Upload-Offset": String(serverOffset),
+ "Upload-Length": String(this.totalBytes),
AuthorizationSignature: this.signature,
AuthorizationExpire: String(this.expires),
LibraryId: String(this.libraryId),
@@ -865,62 +1197,34 @@ export default class BunnyTusUploader {
},
});
- if (headRes.ok) {
- serverOffset = parseInt(
- headRes.headers.get("Upload-Offset") || "0",
- 10,
- );
- this.offset = serverOffset;
+ if (!res.ok && res.status !== 204) {
+ this.setUploaderError("finalize-patch-failed");
+ throw new Error("Finalization failed");
}
+ this.status = "completed";
+ this.finalizedAt = Date.now();
+ this.emitTelemetry("upload_finalize_completed", {
+ finalizedBytes: this.totalBytes,
+ });
+ this.emitTelemetry("upload_complete_client", {
+ finalizedBytes: this.totalBytes,
+ });
+ this.stopHeartbeat();
+ await this.clearUploadJournal();
+ this.notifyStateChange("finalize-completed");
} catch (err) {
- console.warn("⚠️ Failed HEAD before finalize:", err);
- }
-
- // If server didn't receive everything, don't "finalize" into a ghost upload.
- if (serverOffset === null) {
- throw new Error("Finalize failed: could not verify server offset.");
- }
-
- if (serverOffset === 0) {
- this.status = "error";
- this.error = "server-offset-0";
- throw new Error("Finalize failed: server has 0 bytes.");
- }
-
- if (serverOffset < this.totalBytes) {
- this.status = "error";
- this.error = `incomplete-upload server=${serverOffset} expected=${this.totalBytes}`;
- throw new Error(
- `Finalize blocked: upload incomplete (server ${serverOffset} / expected ${this.totalBytes}).`,
- );
- }
-
- if (serverOffset > this.totalBytes) {
- this.status = "error";
- this.error = `invalid-length server=${serverOffset} expected=${this.totalBytes}`;
- throw new Error(
- `Finalize blocked: serverOffset (${serverOffset}) exceeds expected totalBytes (${this.totalBytes}).`,
- );
+ // 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".
+ this.isFinalizing = false;
+ console.warn("[BunnyTusUploader] finalize failed — isFinalizing reset for retry", {
+ trackType: this.trackType,
+ error: err?.message || String(err),
+ offset: this.offset,
+ totalBytes: this.totalBytes,
+ });
+ throw err;
}
-
- // Now we can safely complete the tus upload by declaring the final length
- const res = await fetch(this.uploadUrl, {
- method: "PATCH",
- headers: {
- "Tus-Resumable": "1.0.0",
- "Content-Type": "application/offset+octet-stream",
- "Upload-Offset": String(serverOffset),
- "Upload-Length": String(this.totalBytes),
- AuthorizationSignature: this.signature,
- AuthorizationExpire: String(this.expires),
- LibraryId: String(this.libraryId),
- VideoId: this.videoId,
- },
- });
-
- if (!res.ok && res.status !== 204) throw new Error("Finalization failed");
- this.status = "completed";
- this.stopHeartbeat();
}
getMeta() {
@@ -947,14 +1251,29 @@ export default class BunnyTusUploader {
pause() {
this.isPaused = true;
+ if (this.status !== "completed" && this.status !== "error") {
+ this.status = "paused";
+ }
+ this.scheduleJournalPersist();
}
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();
}
}
@@ -967,6 +1286,13 @@ export default class BunnyTusUploader {
this.totalBytes = 0;
this.pendingUploads = [];
this.stopHeartbeat();
+ this.emitTelemetry("upload_cancelled");
+ if (this.journalPersistTimer) {
+ clearTimeout(this.journalPersistTimer);
+ this.journalPersistTimer = null;
+ }
+ await this.clearUploadJournal();
+ this.notifyStateChange("aborted");
}
startHeartbeat() {
@@ -978,6 +1304,10 @@ export default class BunnyTusUploader {
const diff = now - this.lastProgressAt;
if (diff > this.HEARTBEAT_LAG_MS) {
this.stalled = true;
+ this.emitTelemetry("upload_stalled", {
+ stallMs: diff,
+ });
+ this.scheduleJournalPersist({ force: true });
if (typeof this.onStall === "function") {
this.onStall({
mediaId: this.mediaId,
@@ -998,6 +1328,9 @@ export default class BunnyTusUploader {
recordProgress(bytes) {
this.lastProgressAt = Date.now();
this.stalled = false;
+ if (!this.firstByteAt) {
+ this.firstByteAt = this.lastProgressAt;
+ }
if (typeof this.onProgress === "function") {
try {
this.onProgress({
@@ -1011,20 +1344,23 @@ export default class BunnyTusUploader {
console.warn("Progress callback failed:", err);
}
}
-
- // Journal offsets locally to aid recovery
- if (typeof chrome !== "undefined" && chrome.storage?.local) {
- const key = `uploadJournal-${this.mediaId}`;
- chrome.storage.local.set({
- [key]: {
- offset: this.offset,
- updatedAt: this.lastProgressAt,
- videoId: this.videoId,
- mediaId: this.mediaId,
- stalled: this.stalled,
- },
+ if (!this.hasEmittedFirstByte) {
+ this.hasEmittedFirstByte = true;
+ this.emitTelemetry("upload_first_byte", {
+ bytes,
+ });
+ }
+ if (
+ this.lastProgressEventAt === 0 ||
+ this.lastProgressAt - this.lastProgressEventAt >=
+ this.PROGRESS_EVENT_INTERVAL_MS
+ ) {
+ this.lastProgressEventAt = this.lastProgressAt;
+ this.emitTelemetry("upload_progress", {
+ bytes,
});
}
+ this.scheduleJournalPersist();
}
}
diff --git a/src/pages/Content/context/ContentState.jsx b/src/pages/Content/context/ContentState.jsx
index 5501bbf..aaf5d65 100644
--- a/src/pages/Content/context/ContentState.jsx
+++ b/src/pages/Content/context/ContentState.jsx
@@ -276,14 +276,20 @@ const ContentState = (props) => {
element.classList.remove("screenity-blur");
});
setTimer(0);
- chrome.runtime.sendMessage({ type: "stop-recording-tab" }, (res) => {
+ chrome.runtime.sendMessage(
+ { type: "stop-recording-tab", reason: "content-toolbar-stop" },
+ (res) => {
if (!res || res.ok !== true) {
console.warn("Stop command not acknowledged, retrying…");
setTimeout(() => {
- chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ chrome.runtime.sendMessage({
+ type: "stop-recording-tab",
+ reason: "content-toolbar-stop-retry",
+ });
}, 200);
}
- });
+ },
+ );
});
const pauseRecording = useCallback((dismiss) => {
@@ -636,7 +642,7 @@ const ContentState = (props) => {
pipEnded: false,
}));
}
- }, [contentState, contentStateRef]);
+ }, [contentStateRef]);
const tryRestartRecording = useCallback(() => {
if (!contentStateRef.current.paused) {
@@ -676,7 +682,7 @@ const ContentState = (props) => {
} else {
contentStateRef.current.dismissRecording();
}
- }, [contentState, contentStateRef.current]);
+ }, [contentStateRef]);
const handleDevicePermissions = (data) => {
if (data && data != undefined && data.success) {
@@ -965,6 +971,15 @@ const ContentState = (props) => {
}
},
cancelCountdown: () => {
+ // 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.
+ chrome.storage.local.set({
+ pendingRecording: false,
+ recording: false,
+ restarting: false,
+ });
+ chrome.runtime.sendMessage({ type: "diag-countdown-cancelled" }).catch(() => {});
setContentState((prev) => ({
...prev,
countdownActive: false,
diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.js
index 7007567..edf715c 100644
--- a/src/pages/Content/context/messaging/handlers.js
+++ b/src/pages/Content/context/messaging/handlers.js
@@ -19,6 +19,348 @@ export const setupHandlers = () => {
window.__screenitySetupHandlersRan = true;
let lastToggleDrawingAt = 0;
const TOGGLE_DRAWING_COOLDOWN_MS = 400;
+ let projectReadySeq = 0;
+ const LOCAL_PLAYBACK_MAX_BYTES = 250 * 1024 * 1024;
+ let latestLocalPlaybackOffer = null;
+ let latestLocalPlaybackProjectId = null;
+ let latestLocalPlaybackSceneId = null;
+ let localPlaybackBuildPromise = null;
+ let localPlaybackBuildOfferId = null;
+ let activeLocalPlaybackSource = null;
+ const TRUSTED_APP_ORIGIN = (() => {
+ try {
+ const appBase = process.env.SCREENITY_APP_BASE;
+ return appBase ? new URL(appBase).origin : null;
+ } catch {
+ return null;
+ }
+ })();
+
+ const getProjectMessageTargetOrigin = () => {
+ if (!TRUSTED_APP_ORIGIN) return null;
+ return window.location.origin === TRUSTED_APP_ORIGIN
+ ? TRUSTED_APP_ORIGIN
+ : null;
+ };
+
+ const postProjectHandoff = (payload) => {
+ const targetOrigin = getProjectMessageTargetOrigin();
+ if (!targetOrigin) {
+ console.warn(
+ "[Screenity][Content] Ignoring project handoff on untrusted origin",
+ {
+ source: payload?.source || "unknown",
+ pageOrigin: window.location.origin,
+ trustedOrigin: TRUSTED_APP_ORIGIN,
+ projectId: payload?.projectId || null,
+ },
+ );
+ return false;
+ }
+
+ window.postMessage(payload, targetOrigin);
+ // Replay once shortly after first post to reduce race conditions with late listeners.
+ setTimeout(() => {
+ window.postMessage(
+ {
+ ...payload,
+ replay: true,
+ replayAt: Date.now(),
+ },
+ targetOrigin,
+ );
+ }, 250);
+ return true;
+ };
+
+ const revokeActiveLocalPlaybackSource = (reason = "unknown") => {
+ if (activeLocalPlaybackSource?.url) {
+ URL.revokeObjectURL(activeLocalPlaybackSource.url);
+ console.info("[Screenity][Content] Revoked local screen playback URL", {
+ reason,
+ offerId: activeLocalPlaybackSource.offerId || null,
+ });
+ }
+ activeLocalPlaybackSource = null;
+ };
+
+ const markLocalPlaybackFallback = async ({
+ offerId,
+ projectId,
+ sceneId,
+ reason,
+ }) => {
+ if (!offerId) return;
+ try {
+ await chrome.runtime.sendMessage({
+ type: "cloud-local-playback-mark-fallback",
+ offerId,
+ projectId: projectId || null,
+ sceneId: sceneId || null,
+ reason: reason || "unknown",
+ });
+ } catch {
+ // best effort
+ }
+ };
+
+ const fetchLocalPlaybackSourceFromExtension = async ({
+ offerId,
+ projectId,
+ sceneId,
+ }) => {
+ const offerRes = await chrome.runtime.sendMessage({
+ type: "cloud-local-playback-get-offer",
+ offerId,
+ projectId,
+ sceneId,
+ });
+ if (!offerRes?.ok || !offerRes.offer) {
+ throw new Error("local-playback-offer-unavailable");
+ }
+ const offer = offerRes.offer;
+ if (
+ !offer.chunkCount ||
+ !offer.estimatedBytes ||
+ offer.estimatedBytes > LOCAL_PLAYBACK_MAX_BYTES
+ ) {
+ throw new Error("local-playback-offer-too-large-or-empty");
+ }
+
+ const parts = [];
+ for (let i = 0; i < offer.chunkCount; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const chunkRes = await chrome.runtime.sendMessage({
+ type: "cloud-local-playback-read-chunk",
+ offerId: offer.offerId,
+ projectId: offer.projectId,
+ sceneId: offer.sceneId,
+ index: i,
+ });
+ if (!chunkRes?.ok || !chunkRes.chunk?.base64) {
+ throw new Error(`local-playback-chunk-read-failed:${i}`);
+ }
+ const binary = atob(chunkRes.chunk.base64);
+ const bytes = new Uint8Array(binary.length);
+ for (let j = 0; j < binary.length; j += 1) {
+ bytes[j] = binary.charCodeAt(j);
+ }
+ const mimeType = chunkRes.chunk.mimeType || "video/webm";
+ parts.push(new Blob([bytes], { type: mimeType }));
+ }
+
+ const blob = new Blob(parts, {
+ type: parts[0]?.type || "video/webm",
+ });
+ const url = URL.createObjectURL(blob);
+ return {
+ offer,
+ url,
+ size: blob.size || 0,
+ mimeType: blob.type || "video/webm",
+ chunkCount: parts.length,
+ };
+ };
+
+ const ensureLocalPlaybackReady = async ({ projectId, sceneId, offer }) => {
+ if (!offer?.offerId) {
+ throw new Error("local-playback-offer-missing");
+ }
+
+ if (
+ activeLocalPlaybackSource?.offerId === offer.offerId &&
+ activeLocalPlaybackSource?.url
+ ) {
+ return activeLocalPlaybackSource;
+ }
+
+ if (
+ localPlaybackBuildPromise &&
+ localPlaybackBuildOfferId === offer.offerId
+ ) {
+ return localPlaybackBuildPromise;
+ }
+
+ localPlaybackBuildOfferId = offer.offerId;
+ localPlaybackBuildPromise = (async () => {
+ const source = await fetchLocalPlaybackSourceFromExtension({
+ offerId: offer.offerId,
+ projectId,
+ sceneId,
+ });
+
+ revokeActiveLocalPlaybackSource("new-offer");
+ activeLocalPlaybackSource = {
+ offerId: source.offer.offerId,
+ projectId: source.offer.projectId || projectId || null,
+ sceneId: source.offer.sceneId || sceneId || null,
+ url: source.url,
+ mimeType: source.mimeType,
+ size: source.size,
+ chunkCount: source.chunkCount,
+ expiresAt: source.offer.expiresAt || null,
+ };
+
+ try {
+ await chrome.runtime.sendMessage({
+ type: "cloud-local-playback-mark-used",
+ offerId: source.offer.offerId,
+ projectId: source.offer.projectId || null,
+ sceneId: source.offer.sceneId || null,
+ usedBy: "app-editor",
+ });
+ } catch {
+ // best effort
+ }
+
+ return activeLocalPlaybackSource;
+ })();
+
+ try {
+ const ready = await localPlaybackBuildPromise;
+ return ready;
+ } finally {
+ localPlaybackBuildPromise = null;
+ localPlaybackBuildOfferId = null;
+ }
+ };
+
+ const postLocalPlaybackHandoff = ({
+ projectId,
+ sceneId,
+ offer,
+ readySource = null,
+ fallbackReason = null,
+ forceRefresh = true,
+ }) =>
+ postProjectHandoff({
+ source: "update-project-ready-local-playback",
+ projectId: projectId || null,
+ sceneId: sceneId || null,
+ forceRefresh,
+ handoffAt: Date.now(),
+ localPlayback: {
+ available: Boolean(offer?.offerId),
+ trackType: "screen",
+ offerId: offer?.offerId || null,
+ chunkCount: offer?.chunkCount || 0,
+ estimatedBytes: offer?.estimatedBytes || 0,
+ expiresAt: offer?.expiresAt || null,
+ source: offer?.source || "indexeddb-screen-chunks",
+ ready: Boolean(readySource?.url),
+ url: readySource?.url || null,
+ mimeType: readySource?.mimeType || null,
+ localBytes: readySource?.size || null,
+ fallbackReason: fallbackReason || null,
+ },
+ });
+
+ const onWindowProjectMessage = (event) => {
+ if (event.source !== window) return;
+ if (event.origin !== TRUSTED_APP_ORIGIN) return;
+ const data = event?.data || {};
+ if (data?.type !== "screenity-local-playback-request") return;
+
+ const requestedProjectId = data?.projectId || null;
+ const requestedSceneId = data?.sceneId || null;
+ const requestId = data?.requestId || null;
+ const offer = latestLocalPlaybackOffer;
+
+ if (
+ !offer?.offerId ||
+ !offer.available ||
+ !requestedProjectId ||
+ requestedProjectId !== latestLocalPlaybackProjectId ||
+ (requestedSceneId &&
+ latestLocalPlaybackSceneId &&
+ requestedSceneId !== latestLocalPlaybackSceneId)
+ ) {
+ postProjectHandoff({
+ source: "screenity-local-playback-response",
+ requestId,
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId,
+ localPlayback: {
+ available: false,
+ trackType: "screen",
+ fallbackReason: "offer-unavailable",
+ },
+ });
+ return;
+ }
+
+ void ensureLocalPlaybackReady({
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId || latestLocalPlaybackSceneId,
+ offer,
+ })
+ .then((readySource) => {
+ console.info("[Screenity][Content] Local screen playback used", {
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId || latestLocalPlaybackSceneId || null,
+ offerId: offer.offerId,
+ bytes: readySource?.size || 0,
+ });
+ postProjectHandoff({
+ source: "screenity-local-playback-response",
+ requestId,
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId || latestLocalPlaybackSceneId || null,
+ forceRefresh: true,
+ localPlayback: {
+ available: true,
+ ready: true,
+ trackType: "screen",
+ offerId: offer.offerId,
+ url: readySource?.url || null,
+ mimeType: readySource?.mimeType || null,
+ localBytes: readySource?.size || null,
+ chunkCount: offer.chunkCount || 0,
+ estimatedBytes: offer.estimatedBytes || 0,
+ expiresAt: offer.expiresAt || null,
+ source: offer.source || "indexeddb-screen-chunks",
+ },
+ });
+ })
+ .catch((err) => {
+ const reason = err?.message || "local-playback-build-failed";
+ console.warn(
+ "[Screenity][Content] Local screen playback fallback",
+ {
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId || latestLocalPlaybackSceneId || null,
+ offerId: offer.offerId,
+ reason,
+ },
+ );
+ void markLocalPlaybackFallback({
+ offerId: offer.offerId,
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId || latestLocalPlaybackSceneId || null,
+ reason,
+ });
+ postProjectHandoff({
+ source: "screenity-local-playback-response",
+ requestId,
+ projectId: requestedProjectId,
+ sceneId: requestedSceneId || latestLocalPlaybackSceneId || null,
+ forceRefresh: true,
+ localPlayback: {
+ available: true,
+ ready: false,
+ trackType: "screen",
+ offerId: offer.offerId,
+ fallbackReason: reason,
+ },
+ });
+ });
+ };
+
+ window.addEventListener("message", onWindowProjectMessage);
+ window.addEventListener("beforeunload", () => {
+ revokeActiveLocalPlaybackSource("content-beforeunload");
+ });
+
// Initialize message router
if (!window.__screenityHandlersInitialized) {
messageRouter();
@@ -60,6 +402,7 @@ export const setupHandlers = () => {
isCountdownVisible: true,
countdownCancelled: false,
}));
+ chrome.runtime.sendMessage({ type: "diag-countdown-started" }).catch(() => {});
} else {
// Start recording immediately if countdown is disabled
if (!state.countdownCancelled) {
@@ -553,7 +896,25 @@ export const setupHandlers = () => {
});
registerMessage("get-project-info", (message) => {
- window.postMessage({ source: "get-project-info" }, "*");
+ const payload = {
+ source: "get-project-info",
+ requestedAt: Date.now(),
+ };
+ if (activeLocalPlaybackSource?.url && latestLocalPlaybackOffer?.offerId) {
+ payload.localPlayback = {
+ available: true,
+ ready: true,
+ trackType: "screen",
+ offerId: latestLocalPlaybackOffer.offerId,
+ url: activeLocalPlaybackSource.url,
+ mimeType: activeLocalPlaybackSource.mimeType || "video/webm",
+ localBytes: activeLocalPlaybackSource.size || null,
+ chunkCount: latestLocalPlaybackOffer.chunkCount || 0,
+ estimatedBytes: latestLocalPlaybackOffer.estimatedBytes || 0,
+ expiresAt: latestLocalPlaybackOffer.expiresAt || null,
+ };
+ }
+ postProjectHandoff(payload);
});
registerMessage("check-auth", async (message) => {
if (!CLOUD_FEATURES_ENABLED) {
@@ -621,16 +982,126 @@ export const setupHandlers = () => {
updateFromStorage(true, sender.id);
});
- registerMessage("update-project-ready", (message) => {
- window.postMessage(
- {
- source: "update-project-ready",
- share: message.share,
- newProject: message.newProject,
- sceneId: message.sceneId,
- },
- "*",
- );
+ registerMessage("update-project-ready", (message, sender) => {
+ const projectId = message?.projectId || null;
+ if (!projectId) {
+ console.warn(
+ "[Screenity][Content] Ignoring update-project-ready without projectId",
+ );
+ return;
+ }
+
+ projectReadySeq += 1;
+ const handoffAt = Date.now();
+ const handoffId = `${projectId}:${handoffAt}:${projectReadySeq}`;
+ const localPlayback = message?.localPlayback || null;
+ latestLocalPlaybackOffer =
+ localPlayback?.available && localPlayback?.trackType === "screen"
+ ? localPlayback
+ : null;
+ latestLocalPlaybackProjectId = latestLocalPlaybackOffer ? projectId : null;
+ latestLocalPlaybackSceneId = latestLocalPlaybackOffer
+ ? message.sceneId || null
+ : null;
+
+ const posted = postProjectHandoff({
+ source: "update-project-ready",
+ share: message.share,
+ newProject: message.newProject,
+ sceneId: message.sceneId,
+ projectId,
+ localPlayback:
+ localPlayback?.available && localPlayback?.trackType === "screen"
+ ? {
+ ...localPlayback,
+ ready:
+ activeLocalPlaybackSource?.offerId === localPlayback.offerId &&
+ Boolean(activeLocalPlaybackSource?.url),
+ url:
+ activeLocalPlaybackSource?.offerId === localPlayback.offerId
+ ? activeLocalPlaybackSource.url
+ : null,
+ mimeType:
+ activeLocalPlaybackSource?.offerId === localPlayback.offerId
+ ? activeLocalPlaybackSource.mimeType || "video/webm"
+ : null,
+ localBytes:
+ activeLocalPlaybackSource?.offerId === localPlayback.offerId
+ ? activeLocalPlaybackSource.size || null
+ : null,
+ }
+ : {
+ available: false,
+ trackType: "screen",
+ },
+ handoffAt,
+ handoffId,
+ handoffSeq: projectReadySeq,
+ forceRefresh: true,
+ });
+
+ if (posted) {
+ window.__screenityLastProjectReady = {
+ projectId,
+ sceneId: message.sceneId || null,
+ handoffAt,
+ handoffId,
+ localPlaybackOfferId: localPlayback?.offerId || null,
+ };
+ updateFromStorage(false, sender?.id);
+ }
+
+ const capturedOffer = latestLocalPlaybackOffer;
+ if (posted && capturedOffer?.offerId) {
+ const capturedSceneId = message.sceneId || null;
+ console.info("[Screenity][Content] Local screen playback offered", {
+ projectId,
+ sceneId: capturedSceneId,
+ offerId: capturedOffer.offerId,
+ chunkCount: capturedOffer.chunkCount || 0,
+ estimatedBytes: capturedOffer.estimatedBytes || 0,
+ });
+ void ensureLocalPlaybackReady({
+ projectId,
+ sceneId: capturedSceneId,
+ offer: capturedOffer,
+ })
+ .then((readySource) => {
+ console.info("[Screenity][Content] Local screen playback ready", {
+ projectId,
+ sceneId: capturedSceneId,
+ offerId: capturedOffer.offerId,
+ bytes: readySource?.size || 0,
+ });
+ postLocalPlaybackHandoff({
+ projectId,
+ sceneId: capturedSceneId,
+ offer: capturedOffer,
+ readySource,
+ });
+ })
+ .catch((err) => {
+ const reason = err?.message || "local-playback-build-failed";
+ console.warn("[Screenity][Content] Local screen playback fallback", {
+ projectId,
+ sceneId: capturedSceneId,
+ offerId: capturedOffer.offerId,
+ reason,
+ });
+ void markLocalPlaybackFallback({
+ offerId: capturedOffer.offerId,
+ projectId,
+ sceneId: capturedSceneId,
+ reason,
+ });
+ postLocalPlaybackHandoff({
+ projectId,
+ sceneId: capturedSceneId,
+ offer: capturedOffer,
+ fallbackReason: reason,
+ });
+ });
+ }
});
registerMessage("clear-project-recording", (message) => {
updateFromStorage(false, message.senderId);
diff --git a/src/pages/Content/popup/PopupContainer.jsx b/src/pages/Content/popup/PopupContainer.jsx
index 4e02b52..6f71aaf 100644
--- a/src/pages/Content/popup/PopupContainer.jsx
+++ b/src/pages/Content/popup/PopupContainer.jsx
@@ -40,6 +40,7 @@ import {
// Context
import { contentStateContext } from "../context/ContentState";
+import { supportContextQuery } from "../../utils/buildSupportContext";
const PopupContainer = (props) => {
const [contentState, setContentState] = useContext(contentStateContext);
@@ -90,32 +91,35 @@ const PopupContainer = (props) => {
]);
useEffect(() => {
- const locale = chrome.i18n.getMessage("@@ui_locale");
-
- // Default URL
- let baseURL = "https://help.screenity.io/";
-
- // If logged in, switch to Tally with prefilled params
- if (contentState?.isLoggedIn && contentState?.screenityUser) {
- const { name, email } = contentState.screenityUser;
- const query = new URLSearchParams({
- extension: "true",
- name,
- email,
- });
- baseURL = `https://tally.so/r/310MNg?${query.toString()}`;
- }
+ const buildURL = async () => {
+ const locale = chrome.i18n.getMessage("@@ui_locale");
+
+ // Default URL
+ let baseURL = "https://help.screenity.io/";
+
+ // If logged in, switch to Tally with prefilled params
+ if (contentState?.isLoggedIn && contentState?.screenityUser) {
+ const { name, email } = contentState.screenityUser;
+ const qs = await supportContextQuery({
+ includeRecordingState: true,
+ source: "popup",
+ user: { name, email },
+ });
+ baseURL = `https://tally.so/r/310MNg?extension=true&${qs}`;
+ }
- // If non-English locale, wrap with Google Translate
- if (!locale.includes("en")) {
- setURL(
- `https://translate.google.com/translate?sl=en&tl=${locale}&u=${encodeURIComponent(
- baseURL
- )}`
- );
- } else {
- setURL(baseURL);
- }
+ // If non-English locale, wrap with Google Translate
+ if (!locale.includes("en")) {
+ setURL(
+ `https://translate.google.com/translate?sl=en&tl=${locale}&u=${encodeURIComponent(
+ baseURL
+ )}`
+ );
+ } else {
+ setURL(baseURL);
+ }
+ };
+ buildURL();
}, [contentState]);
const onValueChange = (tab) => {
diff --git a/src/pages/Content/popup/layout/SettingsMenu.jsx b/src/pages/Content/popup/layout/SettingsMenu.jsx
index 9354e29..89c61d7 100644
--- a/src/pages/Content/popup/layout/SettingsMenu.jsx
+++ b/src/pages/Content/popup/layout/SettingsMenu.jsx
@@ -9,7 +9,7 @@ import TooltipWrap from "../components/TooltipWrap";
import { CheckWhiteIcon, DropdownGroup } from "../../images/popup/images";
-import JSZip from "jszip";
+import { buildDiagnosticZip } from "../../../utils/buildDiagnosticZip";
// Context
import { contentStateContext } from "../../context/ContentState";
@@ -27,6 +27,7 @@ const CLOUD_FEATURES_ENABLED =
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);
@@ -61,82 +62,49 @@ const SettingsMenu = (props) => {
chrome.i18n.getMessage("troubleshootModalDescription"),
chrome.i18n.getMessage("troubleshootModalButton"),
chrome.i18n.getMessage("sandboxEditorCancelButton"),
- () => {
- const userAgent = navigator.userAgent;
- let platformInfo = {};
- chrome.runtime
- .sendMessage({ type: "get-platform-info" })
- .then((response) => {
- platformInfo = response;
- const manifestInfo = chrome.runtime.getManifest().version;
- chrome.storage.local.get(
- [
- "fastRecorderBeta",
- "fastRecorderDecision",
- "fastRecorderDisabledForDevice",
- "fastRecorderDisabledReason",
- "fastRecorderDisabledDetails",
- "fastRecorderDisabledAt",
- "fastRecorderProbe",
- "fastRecorderValidation",
- "fastRecorderValidationFailed",
- "fastRecorderInUse",
- ],
- (fastRecorderData) => {
- const data = {
- userAgent: userAgent,
- platformInfo: platformInfo,
- manifestInfo: manifestInfo,
- defaultAudioInput: contentState.defaultAudioInput,
- defaultAudioOutput: contentState.defaultAudioOutput,
- defaultVideoInput: contentState.defaultVideoInput,
- quality: contentState.quality,
- systemAudio: contentState.systemAudio,
- audioInput: contentState.audioInput,
- audioOutput: contentState.audioOutput,
- backgroundEffectsActive: contentState.backgroundEffectsActive,
- recording: contentState.recording,
- recordingType: contentState.recordingType,
- askForPermissions: contentState.askForPermissions,
- cameraPermission: contentState.cameraPermission,
- microphonePermission: contentState.microphonePermission,
- askMicrophone: contentState.askMicrophone,
- cursorMode: contentState.cursorMode,
- zoomEnabled: contentState.zoomEnabled,
- offscreenRecording: contentState.offscreenRecording,
- updateChrome: contentState.updateChrome,
- permissionsChecked: contentState.permissionsChecked,
- permissionsLoaded: contentState.permissionsLoaded,
- hideUI: contentState.hideUI,
- alarm: contentState.alarm,
- alarmTime: contentState.alarmTime,
- surface: contentState.surface,
- blurMode: contentState.blurMode,
- fastRecorder: fastRecorderData,
- //contentState: contentStateData,
- };
- // Create a zip file with the original recording and the data
- const zip = new JSZip();
- zip.file("troubleshooting.json", JSON.stringify(data));
- zip.generateAsync({ type: "blob" }).then(function (blob) {
- const url = window.URL.createObjectURL(blob);
-
- // Download file
- const a = document.createElement("a");
- a.href = url;
- a.download = "screenity-troubleshooting.zip";
- a.click();
- window.URL.revokeObjectURL(url);
-
- chrome.runtime.sendMessage({
- type: "indexed-db-download",
- });
- });
- }
- );
+ async () => {
+ try {
+ const { blob, filename } = await buildDiagnosticZip({
+ source: "popup-settings",
+ extraConfig: {
+ defaultAudioInput: contentState.defaultAudioInput,
+ defaultAudioOutput: contentState.defaultAudioOutput,
+ defaultVideoInput: contentState.defaultVideoInput,
+ quality: contentState.quality,
+ systemAudio: contentState.systemAudio,
+ audioInput: contentState.audioInput,
+ audioOutput: contentState.audioOutput,
+ backgroundEffectsActive: contentState.backgroundEffectsActive,
+ recording: contentState.recording,
+ recordingType: contentState.recordingType,
+ askForPermissions: contentState.askForPermissions,
+ cameraPermission: contentState.cameraPermission,
+ microphonePermission: contentState.microphonePermission,
+ askMicrophone: contentState.askMicrophone,
+ cursorMode: contentState.cursorMode,
+ zoomEnabled: contentState.zoomEnabled,
+ offscreenRecording: contentState.offscreenRecording,
+ updateChrome: contentState.updateChrome,
+ permissionsChecked: contentState.permissionsChecked,
+ permissionsLoaded: contentState.permissionsLoaded,
+ hideUI: contentState.hideUI,
+ alarm: contentState.alarm,
+ alarmTime: contentState.alarmTime,
+ surface: contentState.surface,
+ blurMode: contentState.blurMode,
+ },
});
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ a.click();
+ window.URL.revokeObjectURL(url);
+ } catch (err) {
+ console.error("[Screenity] Troubleshooting export failed:", err);
+ }
},
- () => {}
+ () => {},
);
}
};
@@ -314,6 +282,15 @@ const SettingsMenu = (props) => {
setRestore(response.restore);
});
+ if (CLOUD_FEATURES_ENABLED && contentState.isSubscribed) {
+ chrome.runtime
+ .sendMessage({ type: "check-cloud-restore" })
+ .then((response) => {
+ setCloudRestore(response?.cloudRestore ?? false);
+ })
+ .catch(() => setCloudRestore(false));
+ }
+
chrome.storage.local.get(["fastRecorderStatus"], (result) => {
const status = result.fastRecorderStatus || null;
setFastRecorderInfo((prev) => ({
@@ -882,6 +859,20 @@ const SettingsMenu = (props) => {
"Reset onboarding"}
</DropdownMenu.Item>
)}
+ {contentState.isLoggedIn && contentState.isSubscribed && (
+ <DropdownMenu.Item
+ className="DropdownMenuItem"
+ onSelect={(e) => {
+ e.preventDefault();
+ chrome.runtime.sendMessage({
+ type: "restore-cloud-recording",
+ });
+ }}
+ disabled={!cloudRestore}
+ >
+ {chrome.i18n.getMessage("recoverLastRecordingOption")}
+ </DropdownMenu.Item>
+ )}
</>
)}
{CLOUD_FEATURES_ENABLED && (
diff --git a/src/pages/Download/Download.jsx b/src/pages/Download/Download.jsx
index 7da9cc6..04692ee 100644
--- a/src/pages/Download/Download.jsx
+++ b/src/pages/Download/Download.jsx
@@ -9,9 +9,9 @@ localforage.config({
});
// Get chunks store
-const chunksStore = localforage.createInstance({
- name: "chunks",
-});
+const chunksStore = localforage.createInstance({ name: "chunks" });
+const cameraChunksStore = localforage.createInstance({ name: "cameraChunks" });
+const audioChunksStore = localforage.createInstance({ name: "audioChunks" });
const Download = () => {
const base64ToUint8Array = (base64) => {
@@ -77,6 +77,83 @@ const Download = () => {
window.close();
});
});
+ } else if (message.type === "recover-cloud-indexed-db") {
+ (async () => {
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
+ let downloaded = 0;
+
+ const downloadTrack = async (store, label, mimeType) => {
+ const entries = [];
+ await store.iterate((value) => {
+ if (value?.chunk) entries.push(value);
+ });
+ entries.sort((a, b) => (a.index || 0) - (b.index || 0));
+ if (!entries.length) return;
+ const blob = new Blob(entries.map((e) => e.chunk), { type: mimeType });
+ const url = URL.createObjectURL(blob);
+ await chrome.downloads.download({
+ url,
+ filename: `Screenity-Recovery-${label}-${ts}.webm`,
+ saveAs: false,
+ });
+ URL.revokeObjectURL(url);
+ downloaded++;
+ };
+
+ await downloadTrack(chunksStore, "Screen", "video/webm");
+ await downloadTrack(cameraChunksStore, "Camera", "video/webm");
+ await downloadTrack(audioChunksStore, "Audio", "audio/webm");
+
+ // Clear all three stores after download is initiated
+ await Promise.allSettled([
+ chunksStore.clear(),
+ cameraChunksStore.clear(),
+ audioChunksStore.clear(),
+ ]);
+
+ const { recorderSession } = await chrome.storage.local.get([
+ "recorderSession",
+ ]);
+
+ // Remove stale TUS journal + scene keys so the next recording cannot
+ // accidentally resume the crashed upload or reuse the old scene.
+ // Mirrors clearStaleUploadJournals() in CloudRecorder.jsx.
+ const journalKeysToRemove = ["sceneId", "sceneIdStatus"];
+ const tracks = recorderSession?.tracks || {};
+ for (const trackData of Object.values(tracks)) {
+ const upl = trackData?.uploader;
+ if (!upl) continue;
+ if (upl.journalKey) journalKeysToRemove.push(upl.journalKey);
+ if (upl.journalLookupKey)
+ journalKeysToRemove.push(upl.journalLookupKey);
+ const pid = upl.projectId || recorderSession?.projectId || null;
+ const sid = upl.sceneId || null;
+ const t = upl.type || upl.trackType || null;
+ if (pid && t) {
+ journalKeysToRemove.push(
+ `bunnyVideoMap-${pid}-${sid || "none"}-${t || "none"}`,
+ );
+ }
+ }
+ try {
+ await chrome.storage.local.remove([...new Set(journalKeysToRemove)]);
+ } catch (err) {
+ console.warn("[CloudRestore] failed to remove stale journal keys", err);
+ }
+
+ // Mark session as recovered so the popup button disables on next open
+ if (recorderSession) {
+ await chrome.storage.local.set({
+ recorderSession: {
+ ...recorderSession,
+ status: "recovered",
+ recoveredAt: Date.now(),
+ },
+ });
+ }
+
+ if (downloaded > 0) window.close();
+ })();
} else if (message.type === "recover-indexed-db-mp4") {
const chunkArray = [];
chunksStore
diff --git a/src/pages/Sandbox/layout/player/RightPanel.js b/src/pages/Sandbox/layout/player/RightPanel.js
index a9e4a4a..5aa2be5 100644
--- a/src/pages/Sandbox/layout/player/RightPanel.js
+++ b/src/pages/Sandbox/layout/player/RightPanel.js
@@ -1,7 +1,7 @@
import React, { useContext, useEffect, useState, useRef } from "react";
import styles from "../../styles/player/_RightPanel.module.scss";
-import JSZip from "jszip";
+import { buildDiagnosticZip } from "../../../utils/buildDiagnosticZip";
import { ReactSVG } from "react-svg";
@@ -214,41 +214,39 @@ const RightPanel = () => {
chrome.i18n.getMessage("troubleshootModalDescription"),
chrome.i18n.getMessage("troubleshootModalButton"),
chrome.i18n.getMessage("sandboxEditorCancelButton"),
- () => {
- // Need to create a file with the original data, any console logs, and system info
- const userAgent = navigator.userAgent;
- let platformInfo = {};
- chrome.runtime.getPlatformInfo(function (info) {
- platformInfo = info;
- const manifestInfo = chrome.runtime.getManifest().version;
- const blob = contentStateRef.current.rawBlob;
-
- // Now we need to create a file with all of this data
- const data = {
- userAgent: userAgent,
- platformInfo: platformInfo,
- manifestInfo: manifestInfo,
- contentState: contentStateRef.current,
- };
- // Create a zip file with the original recording and the data
- const zip = new JSZip();
- zip.file("recording.webm", blob);
- zip.file("troubleshooting.json", JSON.stringify(data));
- zip.generateAsync({ type: "blob" }).then(function (blob) {
- const url = window.URL.createObjectURL(blob);
- chrome.downloads.download(
- {
- url: url,
- filename: "troubleshooting.zip",
- },
- () => {
- window.URL.revokeObjectURL(url);
- }
- );
+ async () => {
+ try {
+ const cs = contentStateRef.current;
+ const { blob, filename } = await buildDiagnosticZip({
+ source: "sandbox-editor",
+ extraConfig: {
+ editorMode: cs.mode || null,
+ duration: cs.duration || null,
+ width: cs.width || null,
+ height: cs.height || null,
+ hasBlobReady: Boolean(cs.blob || cs.rawBlob),
+ mp4ready: Boolean(cs.mp4ready),
+ ffmpegLoaded: Boolean(cs.ffmpegLoaded),
+ fallback: Boolean(cs.fallback),
+ offline: Boolean(cs.offline),
+ noffmpeg: Boolean(cs.noffmpeg),
+ updateChrome: Boolean(cs.updateChrome),
+ hasBeenEdited: Boolean(cs.hasBeenEdited),
+ editLimit: cs.editLimit || null,
+ },
});
- });
+ const url = window.URL.createObjectURL(blob);
+ chrome.downloads.download(
+ { url, filename },
+ () => {
+ window.URL.revokeObjectURL(url);
+ },
+ );
+ } catch (err) {
+ console.error("[Screenity] Troubleshooting export failed:", err);
+ }
},
- () => {}
+ () => {},
);
}
};
diff --git a/src/pages/utils/buildDiagnosticZip.js b/src/pages/utils/buildDiagnosticZip.js
new file mode 100644
index 0000000..eed9a8f
--- /dev/null
+++ b/src/pages/utils/buildDiagnosticZip.js
@@ -0,0 +1,104 @@
+/**
+ * Shared helper that builds the diagnostic ZIP blob used by both:
+ * - popup Settings Menu ("Download data for troubleshooting")
+ * - Sandbox/Editor RightPanel ("Get help with your recording")
+ *
+ * Returns { blob, filename } so the caller can decide how to trigger the download
+ * (content script uses <a>.click(), sandbox uses chrome.downloads.download).
+ *
+ * @param {Object} [options]
+ * @param {Object} [options.extraConfig] — caller-specific config fields merged into config.json
+ * @param {string} [options.source] — label for which entry point triggered the export
+ */
+import JSZip from "jszip";
+
+const FAST_RECORDER_KEYS = [
+ "fastRecorderBeta",
+ "fastRecorderDecision",
+ "fastRecorderDisabledForDevice",
+ "fastRecorderDisabledReason",
+ "fastRecorderDisabledDetails",
+ "fastRecorderDisabledAt",
+ "fastRecorderProbe",
+ "fastRecorderValidation",
+ "fastRecorderValidationFailed",
+ "fastRecorderInUse",
+];
+
+export const buildDiagnosticZip = async ({
+ extraConfig = {},
+ source = "unknown",
+} = {}) => {
+ 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 manifestVersion = chrome.runtime.getManifest().version;
+ const now = new Date();
+ const ts = now.toISOString().replace(/[:.]/g, "-").slice(0, 19);
+
+ const zip = new JSZip();
+
+ // manifest.json — export metadata
+ zip.file(
+ "manifest.json",
+ JSON.stringify({
+ extensionVersion: manifestVersion,
+ schemaVersion: 1,
+ exportedAt: now.toISOString(),
+ chromeVersion: /Chrome\/([\d.]+)/.exec(userAgent)?.[1] || null,
+ source,
+ }),
+ );
+
+ // environment.json
+ zip.file(
+ "environment.json",
+ JSON.stringify({
+ userAgent,
+ platformInfo,
+ screen: {
+ width: window.screen.availWidth,
+ height: window.screen.availHeight,
+ devicePixelRatio: window.devicePixelRatio,
+ },
+ deviceMemory: navigator.deviceMemory || null,
+ }),
+ );
+
+ // config.json — recording settings + caller-specific extras
+ zip.file(
+ "config.json",
+ JSON.stringify({
+ fastRecorder: fastRecorderData,
+ ...extraConfig,
+ }),
+ );
+
+ // sessions.json — diagnostic session timeline
+ if (diagData?.log) {
+ zip.file("sessions.json", JSON.stringify(diagData.log));
+ }
+
+ // errors.json — consolidated error-state keys
+ if (diagData?.errors) {
+ zip.file("errors.json", JSON.stringify(diagData.errors));
+ }
+
+ // storage-flags.json — current boolean/numeric state flags
+ if (diagData?.flags) {
+ zip.file("storage-flags.json", JSON.stringify(diagData.flags));
+ }
+
+ const blob = await zip.generateAsync({ type: "blob" });
+ const filename = `screenity-diagnostics-${ts}.zip`;
+
+ return { blob, filename };
+};
diff --git a/src/pages/utils/buildSupportContext.js b/src/pages/utils/buildSupportContext.js
new file mode 100644
index 0000000..76d93fb
--- /dev/null
+++ b/src/pages/utils/buildSupportContext.js
@@ -0,0 +1,124 @@
+/**
+ * Builds a flat, URL-safe support-context object for Tally form prefills.
+ *
+ * Privacy rules:
+ * - No full URLs, user IDs, auth tokens, or page content
+ * - Error messages are stripped of URL-like substrings and truncated
+ * - No raw diagnostic logs, video blobs, or storage dumps
+ * - User name/email only included when caller explicitly passes them
+ *
+ * All values are short strings safe for URLSearchParams.
+ */
+
+const MAX_ERR_LEN = 120;
+
+/** Strip anything that looks like a URL from an error string. */
+const sanitizeError = (err) => {
+ if (!err) return "";
+ const str = typeof err === "string" ? err : String(err);
+ return str
+ .replace(/https?:\/\/[^\s)]+/gi, "[url]")
+ .replace(/chrome-extension:\/\/[^\s)]+/gi, "[ext]")
+ .slice(0, MAX_ERR_LEN);
+};
+
+/** Extract "Chrome/124" or "Edg/124" from the user-agent string. */
+const shortBrowser = () => {
+ const ua = navigator.userAgent || "";
+ const edg = ua.match(/Edg\/(\d+)/);
+ if (edg) return `Edge/${edg[1]}`;
+ const ch = ua.match(/Chrome\/(\d+)/);
+ if (ch) return `Chrome/${ch[1]}`;
+ return "Unknown";
+};
+
+/**
+ * Build support context.
+ *
+ * @param {Object} [opts]
+ * @param {boolean} [opts.includeRecordingState] — pull last-recording fields from storage
+ * @param {string} [opts.source] — where the form was opened (e.g. "popup", "settings", "editor")
+ * @param {{name:string, email:string}} [opts.user] — only pass when the user is already authenticated
+ * @returns {Promise<Record<string, string>>} flat key-value pairs for URLSearchParams
+ */
+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.
+ } catch {
+ ctx.os = "unknown";
+ }
+
+ ctx.cloud =
+ process.env.SCREENITY_ENABLE_CLOUD_FEATURES === "true" ? "1" : "0";
+
+ if (opts.source) {
+ ctx.src = opts.source;
+ }
+
+ // ---- recording / error state (opt-in) ----
+ if (opts.includeRecordingState) {
+ try {
+ const keys = [
+ "lastRecordingError",
+ "recordingType",
+ "fastRecorderInUse",
+ "fastRecorderDisabledReason",
+ "isSubscribed",
+ "diagnosticLog",
+ ];
+ const store = await chrome.storage.local.get(keys);
+
+ if (store.recordingType) ctx.recType = store.recordingType;
+ if (store.fastRecorderInUse != null)
+ ctx.fast = store.fastRecorderInUse ? "1" : "0";
+ if (store.fastRecorderDisabledReason)
+ ctx.fastOff = String(store.fastRecorderDisabledReason).slice(0, 60);
+ if (store.isSubscribed != null)
+ ctx.sub = store.isSubscribed ? "1" : "0";
+ if (store.lastRecordingError)
+ ctx.lastErr = sanitizeError(store.lastRecordingError);
+
+ // 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;
+ }
+ } catch {
+ // storage read failed — continue without recording state
+ }
+ }
+
+ // ---- 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;
+ }
+
+ return ctx;
+};
+
+/**
+ * Convenience: build context and return it as a query string.
+ * Drops any key whose value is empty/undefined.
+ */
+export const supportContextQuery = async (opts = {}) => {
+ const ctx = await buildSupportContext(opts);
+ const params = new URLSearchParams();
+ for (const [k, val] of Object.entries(ctx)) {
+ if (val !== undefined && val !== null && val !== "") {
+ params.set(k, val);
+ }
+ }
+ return params.toString();
+};
diff --git a/src/pages/utils/diagnosticLog.js b/src/pages/utils/diagnosticLog.js
new file mode 100644
index 0000000..d11b856
--- /dev/null
+++ b/src/pages/utils/diagnosticLog.js
@@ -0,0 +1,227 @@
+/**
+ * Always-on diagnostic log for free/local recording sessions.
+ *
+ * Stores a compact ring buffer of session events in chrome.storage.local
+ * under the key "diagnosticLog". Max 5 sessions, 100 events each (~100 KB).
+ *
+ * Usage (background service worker):
+ * import { initDiagSession, diagEvent, endDiagSession } from '../utils/diagnosticLog';
+ * await initDiagSession({ recordingType: 'screen', quality: '1080p', ... });
+ * diagEvent('chunk', { idx: 10, bytes: 45000 });
+ * await endDiagSession('ok');
+ */
+
+const MAX_SESSIONS = 5;
+const MAX_EVENTS = 100;
+const FLUSH_EVERY_N = 10; // flush to storage every N events
+
+let _log = null; // in-memory mirror of diagnosticLog
+let _dirty = 0; // events written since last flush
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+const now = () => Date.now();
+
+const makeId = () =>
+ `diag-${now()}-${Math.random().toString(16).slice(2, 7)}`;
+
+const currentSession = () => {
+ if (!_log || !_log.sessions || _log.sessions.length === 0) return null;
+ const last = _log.sessions[_log.sessions.length - 1];
+ return last.endedAt == null ? last : null;
+};
+
+const flush = async () => {
+ if (!_log) return;
+ _dirty = 0;
+ try {
+ await chrome.storage.local.set({ diagnosticLog: _log });
+ } catch {
+ // SW may be shutting down — best-effort
+ }
+};
+
+const maybeFlush = () => {
+ _dirty += 1;
+ if (_dirty >= FLUSH_EVERY_N) {
+ flush(); // fire-and-forget
+ }
+};
+
+// ---------------------------------------------------------------------------
+// Public API
+// ---------------------------------------------------------------------------
+
+/**
+ * Hydrate the in-memory log from storage. Call once on service-worker init.
+ */
+export const hydrateDiagnosticLog = async () => {
+ try {
+ const res = await chrome.storage.local.get("diagnosticLog");
+ _log = res?.diagnosticLog || { schemaVersion: 1, sessions: [] };
+ } catch {
+ _log = { schemaVersion: 1, sessions: [] };
+ }
+};
+
+/**
+ * Begin a new diagnostic session. Call from startRecording().
+ * @param {Object} config — snapshot of recording settings
+ */
+export const initDiagSession = async (config = {}) => {
+ if (!_log) await hydrateDiagnosticLog();
+
+ const session = {
+ id: makeId(),
+ startedAt: now(),
+ endedAt: null,
+ outcome: "in-progress",
+ config,
+ events: [],
+ };
+
+ _log.sessions.push(session);
+
+ // Trim to MAX_SESSIONS
+ while (_log.sessions.length > MAX_SESSIONS) {
+ _log.sessions.shift();
+ }
+
+ await flush();
+ return session.id;
+};
+
+/**
+ * Append an event to the current (open) session.
+ * @param {string} eventType — short event name, e.g. "stop", "error"
+ * @param {Object} [data] — small payload (keep lightweight)
+ */
+export const diagEvent = (eventType, data) => {
+ const s = currentSession();
+ if (!s) return; // no open session
+
+ const entry = {
+ t: now() - s.startedAt,
+ e: eventType,
+ };
+ if (data !== undefined && data !== null) {
+ entry.d = data;
+ }
+
+ s.events.push(entry);
+
+ // Ring-buffer trim
+ while (s.events.length > MAX_EVENTS) {
+ s.events.shift();
+ }
+
+ // Immediate flush for errors, crashes, and all session lifecycle events.
+ // A normal recording only produces ~6-8 events, which is well under the
+ // FLUSH_EVERY_N threshold of 10. If the SW is killed before reaching
+ // that threshold, all buffered events are lost. Force-flushing on every
+ // lifecycle event prevents this at negligible cost.
+ const ALWAYS_FLUSH = [
+ "error",
+ "crash",
+ "start-fail",
+ "warning",
+ "session-start",
+ "stop",
+ "stop-tab",
+ "editor-open",
+ "chunks-sent",
+ "chunks-fail",
+ "sw-init",
+ "countdown-started",
+ "countdown-cancelled",
+ "countdown-finished",
+ "pause",
+ "resume",
+ "restart-requested",
+ "restart-completed",
+ "restart-failed",
+ "alarm-fired",
+ "recorded-tab-closed",
+ "recorded-tab-navigated",
+ ];
+ if (ALWAYS_FLUSH.includes(eventType)) {
+ flush();
+ } else {
+ maybeFlush();
+ }
+};
+
+/**
+ * Close the current session with a final outcome.
+ * @param {"ok"|"error"|"crashed"|"cancelled"} outcome
+ */
+export const endDiagSession = async (outcome = "ok") => {
+ const s = currentSession();
+ if (!s) return;
+ s.endedAt = now();
+ s.outcome = outcome;
+ await flush();
+};
+
+/**
+ * Return the full diagnostic log (for export).
+ */
+export const getDiagnosticLog = async () => {
+ if (!_log) await hydrateDiagnosticLog();
+ return _log;
+};
+
+/**
+ * Read all scattered error-state keys and return a consolidated object.
+ */
+export const getErrorSnapshot = async () => {
+ const keys = [
+ "lastRecordingError",
+ "lastChunkSendFailure",
+ "lastStartRecordingDispatch",
+ "recorderSession",
+ "freeRecorderSession",
+ "fastRecorderValidation",
+ "fastRecorderProbe",
+ "fastRecorderDecision",
+ "fastRecorderDisabledReason",
+ "fastRecorderDisabledDetails",
+ "fastRecorderDisabledAt",
+ "memoryError",
+ ];
+ try {
+ return await chrome.storage.local.get(keys);
+ } catch {
+ return {};
+ }
+};
+
+/**
+ * Read current boolean/numeric state flags for export.
+ */
+export const getStorageFlags = async () => {
+ const keys = [
+ "recording",
+ "pendingRecording",
+ "restarting",
+ "paused",
+ "offscreen",
+ "sendingChunks",
+ "postStopEditorOpening",
+ "postStopEditorOpened",
+ "recordingStartTime",
+ "totalPausedMs",
+ "recordingDuration",
+ "recordingTab",
+ "sandboxTab",
+ "recordingUiTabId",
+ "fastRecorderInUse",
+ ];
+ try {
+ return await chrome.storage.local.get(keys);
+ } catch {
+ return {};
+ }
+};
diff --git a/webpack.config.js b/webpack.config.js
index d787e7b..742fe1f 100755
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -5,7 +5,8 @@ const env = require("./utils/env");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
-const { CleanWebpackPlugin } = require("clean-webpack-plugin");
+
+const isDev = env.NODE_ENV === "development";
const ASSET_PATH = process.env.ASSET_PATH || "/";
@@ -95,7 +96,7 @@ const htmlPlugins = Object.keys(entryPoints)
template: templatePath,
filename: `${entryName}.html`,
chunks: [entryName],
- cache: false,
+ cache: true,
};
// Add favicon only for backup page
@@ -139,10 +140,18 @@ const config = {
performance: { hints: false },
entry: entryPoints,
+ // Persistent filesystem cache for fast rebuilds
+ cache: {
+ type: "filesystem",
+ buildDependencies: {
+ config: [__filename],
+ },
+ },
+
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "build"),
- clean: true,
+ clean: !isDev, // Only wipe build dir in production; dev keeps it to avoid re-copying 40MB of assets
publicPath: ASSET_PATH,
},
module: {
@@ -172,10 +181,15 @@ const config = {
test: /\.(ts|tsx)$/,
loader: "ts-loader",
exclude: /node_modules/,
+ options: {
+ transpileOnly: isDev,
+ },
},
{
test: /\.(js|jsx)$/,
- use: [{ loader: "source-map-loader" }, { loader: "babel-loader" }],
+ use: isDev
+ ? [{ loader: "babel-loader" }]
+ : [{ loader: "source-map-loader" }, { loader: "babel-loader" }],
exclude: /node_modules/,
},
],
@@ -186,12 +200,10 @@ const config = {
"react-dom": path.resolve("./node_modules/react-dom"),
"react/jsx-runtime": path.resolve("./node_modules/react/jsx-runtime"),
},
- extensions: fileExtensions
- .map((extension) => `.${extension}`)
- .concat([".js", ".jsx", ".ts", ".tsx", ".css"]),
+ // Code extensions first — image/font extensions are only needed for explicit imports with extensions
+ extensions: [".js", ".jsx", ".ts", ".tsx", ".css"],
},
plugins: [
- new CleanWebpackPlugin({ verbose: false }),
new webpack.ProgressPlugin(),
new webpack.DefinePlugin({
"process.env.SCREENITY_APP_BASE": JSON.stringify(
@@ -252,7 +264,7 @@ const config = {
],
};
-if (env.NODE_ENV === "development") {
+if (isDev) {
config.devtool = "cheap-module-source-map";
} else {
config.optimization = {