codex-overleaf-link 1.8.6 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +45 -21
  2. package/bin/codex-overleaf-link.mjs +58 -0
  3. package/extension/assets/icons/codex-overleaf-dialog-icon.png +0 -0
  4. package/extension/assets/icons/codex-overleaf-icon.png +0 -0
  5. package/extension/assets/icons/icon128.png +0 -0
  6. package/extension/assets/icons/icon16.png +0 -0
  7. package/extension/assets/icons/icon32.png +0 -0
  8. package/extension/assets/icons/icon48.png +0 -0
  9. package/extension/bootstrap/background.js +404 -0
  10. package/extension/bootstrap/manifest.template.json +51 -0
  11. package/extension/bootstrap/popup.css +26 -0
  12. package/extension/bootstrap/popup.html +38 -0
  13. package/extension/bootstrap/popup.js +44 -0
  14. package/extension/bootstrap/runtimeContext.js +2 -0
  15. package/extension/runtime-manifest.json +60 -0
  16. package/extension/src/background.js +532 -0
  17. package/extension/src/content/applyResultFormatters.js +387 -0
  18. package/extension/src/content/composerAttachments.js +522 -0
  19. package/extension/src/content/composerPanel.js +254 -0
  20. package/extension/src/content/contentRuntime.js +8895 -0
  21. package/extension/src/content/contextTray.js +686 -0
  22. package/extension/src/content/diagnosticsController.js +659 -0
  23. package/extension/src/content/diagnosticsPanel.js +342 -0
  24. package/extension/src/content/diffReviewPanel.js +797 -0
  25. package/extension/src/content/localSkillsPanel.js +280 -0
  26. package/extension/src/content/markdownText.js +606 -0
  27. package/extension/src/content/mirrorHealth.js +92 -0
  28. package/extension/src/content/modelPicker.js +489 -0
  29. package/extension/src/content/nativeChannel.js +62 -0
  30. package/extension/src/content/otWarmMirror.js +964 -0
  31. package/extension/src/content/otWarmMirrorController.js +174 -0
  32. package/extension/src/content/panelMaintenance.js +367 -0
  33. package/extension/src/content/panelRenderer.js +253 -0
  34. package/extension/src/content/recentProjects.js +1063 -0
  35. package/extension/src/content/reviewHunks.js +247 -0
  36. package/extension/src/content/runController.js +242 -0
  37. package/extension/src/content/runTimelineView.js +1126 -0
  38. package/extension/src/content/sessionManager.js +487 -0
  39. package/extension/src/content/sessionPanel.js +263 -0
  40. package/extension/src/content/settingsPanel.js +527 -0
  41. package/extension/src/content/themeController.js +91 -0
  42. package/extension/src/content/updateIdle.js +67 -0
  43. package/extension/src/content/writebackController.js +300 -0
  44. package/extension/src/content/writebackOrchestrator.js +850 -0
  45. package/extension/src/contentScript.js +8 -0
  46. package/extension/src/page/compileBridge.js +460 -0
  47. package/extension/src/page/overleafCapabilities.js +100 -0
  48. package/extension/src/page/overleafEditor.js +282 -0
  49. package/extension/src/page/overleafProjectSnapshot.js +234 -0
  50. package/extension/src/page/overleafRealtimeObserver.js +491 -0
  51. package/extension/src/page/pageBridgeCapability.js +71 -0
  52. package/extension/src/page/snapshotRouter.js +948 -0
  53. package/extension/src/page/trackedChangesLifecycle.js +1506 -0
  54. package/extension/src/page/treeOperations.js +1584 -0
  55. package/extension/src/page/writeGuard.js +142 -0
  56. package/extension/src/page/writebackRouter.js +1934 -0
  57. package/extension/src/pageBridge.js +2224 -0
  58. package/extension/src/popup.js +247 -0
  59. package/extension/src/shared/compatibility.js +1 -1
  60. package/extension/styles/panel.css +4048 -0
  61. package/native-host/src/index.js +9 -2
  62. package/native-host/src/managedInstall.js +393 -0
  63. package/native-host/src/managedLauncherRuntime.js +71 -0
  64. package/native-host/src/nativeHostPlatform.js +16 -0
  65. package/native-host/src/runtimeInstaller.js +6 -1
  66. package/native-host/src/taskRunnerRuntime.js +8 -0
  67. package/native-host/src/updateArchive.js +253 -0
  68. package/native-host/src/updateManager.js +548 -0
  69. package/native-host/src/updateTrust.js +156 -0
  70. package/package.json +11 -2
  71. package/scripts/install-managed.mjs +64 -0
  72. package/scripts/uninstall-managed.mjs +48 -0
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <h1>Codex Overleaf Link</h1>
4
4
  <p><strong>Empower Overleaf with Codex.</strong></p>
5
5
  <p>
6
- <img src="https://img.shields.io/badge/version-1.8.6-blue" alt="version">
6
+ <img src="https://img.shields.io/badge/version-1.9.0-blue" alt="version">
7
7
  <img src="https://img.shields.io/badge/platform-macOS%20%2F%20Windows%20%2F%20Linux-lightgrey" alt="platform">
8
8
  <img src="https://img.shields.io/badge/chrome-MV3-green" alt="chrome manifest v3">
9
9
  <img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" alt="node version">
@@ -38,14 +38,14 @@ One command installs the native host **and** sets up the extension: the script r
38
38
  macOS / Linux:
39
39
 
40
40
  ```bash
41
- CODEX_OVERLEAF_REF=v1.8.6 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.8.6/install.sh)"
41
+ CODEX_OVERLEAF_REF=v1.9.0 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.9.0/install.sh)"
42
42
  ```
43
43
 
44
44
  Windows PowerShell:
45
45
 
46
46
  ```powershell
47
- iwr https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.8.6/install.ps1 -OutFile install.ps1
48
- $env:CODEX_OVERLEAF_REF='v1.8.6'
47
+ iwr https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.9.0/install.ps1 -OutFile install.ps1
48
+ $env:CODEX_OVERLEAF_REF='v1.9.0'
49
49
  powershell -ExecutionPolicy Bypass -File install.ps1
50
50
  ```
51
51
 
@@ -56,10 +56,10 @@ Then, in the `chrome://extensions` tab the script opened: enable **Developer mod
56
56
  `npm exec` installs and updates the **native host only** — it does not include the Chrome extension. Use it if you prefer a pinned npm package to a source checkout.
57
57
 
58
58
  ```bash
59
- npm exec --yes codex-overleaf-link@1.8.6 -- install-native
59
+ npm exec --yes codex-overleaf-link@1.9.0 -- install-managed
60
60
  ```
61
61
 
62
- Then add the extension yourself: download `codex-overleaf-link-extension-v1.8.6.zip` from the [v1.8.6 GitHub Release](https://github.com/Ghqqqq/codex-overleaf-link/releases/tag/v1.8.6), unzip it to a stable folder, and in `chrome://extensions` enable **Developer mode**, click **Load unpacked**, and select that folder.
62
+ Then add the extension yourself: download `codex-overleaf-link-extension-v1.9.0.zip` from the [v1.9.0 GitHub Release](https://github.com/Ghqqqq/codex-overleaf-link/releases/tag/v1.9.0), unzip it to a stable folder, and in `chrome://extensions` enable **Developer mode**, click **Load unpacked**, and select that folder.
63
63
 
64
64
  ### Open Overleaf
65
65
 
@@ -86,9 +86,9 @@ npm installs, updates, uninstalls, and diagnoses the native host only. npm does
86
86
 
87
87
  | Action | Command |
88
88
  |--------|---------|
89
- | Install / update | `npm exec --yes codex-overleaf-link@1.8.6 -- install-native` |
90
- | Diagnose | `npm exec --yes codex-overleaf-link@1.8.6 -- doctor` |
91
- | Uninstall | `npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native` |
89
+ | Install / update | `npm exec --yes codex-overleaf-link@1.9.0 -- install-managed` |
90
+ | Diagnose | `npm exec --yes codex-overleaf-link@1.9.0 -- doctor` |
91
+ | Uninstall | `npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed` |
92
92
 
93
93
  Use `--extension-id <chrome-extension-id>` only for a custom/dev unpacked extension id that differs from the official bundled id.
94
94
 
@@ -98,13 +98,13 @@ To update, re-run any of the [native host installers](#install) — they install
98
98
 
99
99
  ## GitHub Release Artifacts
100
100
 
101
- The v1.8.6 GitHub Release contains:
101
+ The v1.9.0 GitHub Release contains:
102
102
 
103
- - `codex-overleaf-link-extension-v1.8.6.zip`: loadable Chrome extension package for manual unpacked installation.
104
- - `codex-overleaf-native-host-v1.8.6.tar.gz`: native host runtime files used by the installer and release verification.
105
- - `codex-overleaf-link-1.8.6.tgz`: npm native host CLI package for pinned install, doctor, and uninstall flows.
106
- - `install.sh`: release-pinned macOS / Linux installer that defaults to `v1.8.6` when run directly from the release artifact.
107
- - `install.ps1`: release-pinned Windows PowerShell installer that defaults to `v1.8.6` when run directly from the release artifact.
103
+ - `codex-overleaf-link-extension-v1.9.0.zip`: loadable Chrome extension package for manual unpacked installation.
104
+ - `codex-overleaf-native-host-v1.9.0.tar.gz`: native host runtime files used by the installer and release verification.
105
+ - `codex-overleaf-link-1.9.0.tgz`: npm native host CLI package for pinned install, doctor, and uninstall flows.
106
+ - `install.sh`: release-pinned macOS / Linux installer that defaults to `v1.9.0` when run directly from the release artifact.
107
+ - `install.ps1`: release-pinned Windows PowerShell installer that defaults to `v1.9.0` when run directly from the release artifact.
108
108
  - `uninstall-native-host.mjs`: native host uninstaller that removes the Chrome Native Messaging manifest, bridge executable, and runtime copy.
109
109
  - `nativeHostPlatform.js`, `manifest.js`, `runtimeInstaller.js`: helper files required by the loose uninstaller asset.
110
110
  - `SHA256SUMS` and `release-manifest.json`: checksum and artifact metadata for release verification.
@@ -115,7 +115,7 @@ The v1.8.6 GitHub Release contains:
115
115
  Remove the native host (use `--browser chromium` on Linux Chromium):
116
116
 
117
117
  ```bash
118
- npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native
118
+ npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed
119
119
  ```
120
120
 
121
121
  The same command works on Windows PowerShell. If you installed from a manual checkout or source installer, you can also run `npm run uninstall:native` inside the repo, use `node ~/.codex-overleaf/source/scripts/uninstall-native-host.mjs` on macOS / Linux, or use `node $env:LOCALAPPDATA\CodexOverleaf\source\scripts\uninstall-native-host.mjs` on Windows PowerShell.
@@ -150,13 +150,13 @@ Then remove the extension from `chrome://extensions`. To delete local data: on m
150
150
  Linux Chromium install or update:
151
151
 
152
152
  ```bash
153
- CODEX_OVERLEAF_REF=v1.8.6 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.8.6/install.sh)" -- --browser chromium
153
+ CODEX_OVERLEAF_REF=v1.9.0 bash -c "$(curl -fsSL https://raw.githubusercontent.com/Ghqqqq/codex-overleaf-link/v1.9.0/install.sh)" -- --browser chromium
154
154
  ```
155
155
 
156
156
  Linux Chromium uninstall:
157
157
 
158
158
  ```bash
159
- npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native --browser chromium
159
+ npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed --browser chromium
160
160
  ```
161
161
 
162
162
  ## Features
@@ -291,7 +291,7 @@ Composer attachments are turn-scoped Codex context. Limits are 8 attachments per
291
291
  Re-run any [native host installer](#install), reload the extension in `chrome://extensions`, then refresh the Overleaf tab. This also fixes extension/native version mismatch and native protocol mismatch.
292
292
 
293
293
  ```bash
294
- npm exec --yes codex-overleaf-link@1.8.6 -- install-native
294
+ npm exec --yes codex-overleaf-link@1.9.0 -- install-managed
295
295
  ```
296
296
 
297
297
  **The Windows popup or panel shows a Bash recovery command**
@@ -340,8 +340,8 @@ Use this matrix for release-candidate signoff and compatibility reports. Record
340
340
  | Browser/channel/version | Google Chrome channel and version. | Google Chrome channel and version. | Google Chrome channel and version. | Chromium channel/package and version. |
341
341
  | Install mode | Manual unpacked extension from GitHub Release zip or checkout. | Manual unpacked extension from GitHub Release zip or checkout. | Manual unpacked extension from GitHub Release zip or checkout. | Manual unpacked extension from GitHub Release zip or checkout; native host installed with `--browser chromium`. |
342
342
  | Extension id | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. | Bundled id `illdpneeeopfffmiepaejglgmhpmdhdc`, or actual custom id passed with `--extension-id`. |
343
- | Installer/update command | `npm exec --yes codex-overleaf-link@1.8.6 -- install-native` | `npm exec --yes codex-overleaf-link@1.8.6 -- install-native` | `npm exec --yes codex-overleaf-link@1.8.6 -- install-native` | `npm exec --yes codex-overleaf-link@1.8.6 -- install-native --browser chromium` |
344
- | Uninstall command | `npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native` | `npm exec --yes codex-overleaf-link@1.8.6 -- uninstall-native --browser chromium` |
343
+ | Installer/update command | `npm exec --yes codex-overleaf-link@1.9.0 -- install-managed` | `npm exec --yes codex-overleaf-link@1.9.0 -- install-managed` | `npm exec --yes codex-overleaf-link@1.9.0 -- install-managed` | `npm exec --yes codex-overleaf-link@1.9.0 -- install-managed --browser chromium` |
344
+ | Uninstall command | `npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed` | `npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed` | `npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed` | `npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-managed --browser chromium` |
345
345
  | Manifest/registry path | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.codex.overleaf.json` | `HKCU\Software\Google\Chrome\NativeMessagingHosts\com.codex.overleaf` -> `%LOCALAPPDATA%\CodexOverleaf\native-host-runtime\com.codex.overleaf.json` | `~/.config/google-chrome/NativeMessagingHosts/com.codex.overleaf.json` | `~/.config/chromium/NativeMessagingHosts/com.codex.overleaf.json` |
346
346
  | Bridge/runtime/source path | Bridge `~/.codex-overleaf/codex-overleaf-bridge`; runtime `~/.codex-overleaf/native-host-runtime`; source `~/.codex-overleaf/source`. | Bridge `%LOCALAPPDATA%\CodexOverleaf\codex-overleaf-bridge.cmd`; runtime `%LOCALAPPDATA%\CodexOverleaf\native-host-runtime`; source `%LOCALAPPDATA%\CodexOverleaf\source`. | Bridge `~/.codex-overleaf/codex-overleaf-bridge`; runtime `~/.codex-overleaf/native-host-runtime`; source `~/.codex-overleaf/source`. | Bridge `~/.codex-overleaf/codex-overleaf-bridge`; runtime `~/.codex-overleaf/native-host-runtime`; source `~/.codex-overleaf/source`. |
347
347
  | Node/Git/Codex/TeX | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. | Node.js >= 20; Git; Codex CLI installed and logged in; TeX optional. |
@@ -371,3 +371,27 @@ Contributions are welcome. Please open an issue before submitting large changes
371
371
  ## License
372
372
 
373
373
  [MIT](LICENSE)
374
+
375
+ ## Managed Stable Updates (v1.9)
376
+
377
+ The recommended v1.9 installation owns one stable unpacked-extension directory and a versioned native-host directory:
378
+
379
+ ```bash
380
+ npm exec --yes codex-overleaf-link@1.9.0 -- install-managed
381
+ ```
382
+
383
+ Load the printed extension path once from `chrome://extensions`. Starting with the next signed stable release, Codex Overleaf Link checks GitHub Releases automatically, downloads and verifies the coordinated extension/native-host bundle, waits until every connected Overleaf tab is saved and idle, and then updates both components together. A failed health check restores the previous version automatically.
384
+
385
+ The stable updater ignores drafts and prereleases, performs no telemetry, and cannot add Chrome permissions silently. Releases that require a newer Bootstrap protocol display manual migration guidance.
386
+
387
+ The legacy native-only installer remains available for source or unmanaged extension directories:
388
+
389
+ ```bash
390
+ npm exec --yes codex-overleaf-link@1.9.0 -- install-native
391
+ ```
392
+
393
+ Legacy native-only installations can be removed with:
394
+
395
+ ```bash
396
+ npm exec --yes codex-overleaf-link@1.9.0 -- uninstall-native
397
+ ```
@@ -18,6 +18,8 @@ function printHelp() {
18
18
  console.log(`codex-overleaf-link ${packageJson.version}
19
19
 
20
20
  Commands:
21
+ install-managed Install the managed extension and native host
22
+ uninstall-managed Remove the managed extension and native host
21
23
  install-native Install the native host
22
24
  uninstall-native Uninstall the native host
23
25
  doctor Check local native host setup
@@ -29,6 +31,7 @@ const OPTION_DEFINITIONS = {
29
31
  '--extension-id': { key: 'extensionId', takesValue: true },
30
32
  '--browser': { key: 'browser', takesValue: true },
31
33
  '--runtime-root': { key: 'runtimeRoot', takesValue: true },
34
+ '--managed-root': { key: 'managedRoot', takesValue: true },
32
35
  '--force': { key: 'force', takesValue: false },
33
36
  '--keep-runtime': { key: 'keepRuntime', takesValue: false },
34
37
  '--reveal-paths': { key: 'revealPaths', takesValue: false },
@@ -56,6 +59,21 @@ const UNINSTALL_NATIVE_OPTIONS = new Set([
56
59
  '--help'
57
60
  ]);
58
61
 
62
+ const INSTALL_MANAGED_OPTIONS = new Set([
63
+ '--extension-id',
64
+ '--browser',
65
+ '--managed-root',
66
+ '--json',
67
+ '--help'
68
+ ]);
69
+
70
+ const UNINSTALL_MANAGED_OPTIONS = new Set([
71
+ '--browser',
72
+ '--managed-root',
73
+ '--json',
74
+ '--help'
75
+ ]);
76
+
59
77
  function parseNativeArgs(argv, allowedOptions) {
60
78
  const parsed = {};
61
79
 
@@ -139,6 +157,46 @@ switch (command) {
139
157
  console.log(packageJson.version);
140
158
  }
141
159
  break;
160
+ case 'install-managed': {
161
+ let installArgs;
162
+ try {
163
+ installArgs = parseNativeArgs(args, INSTALL_MANAGED_OPTIONS);
164
+ } catch (error) {
165
+ exitWithError(error);
166
+ }
167
+ if (installArgs.help) {
168
+ printHelp();
169
+ break;
170
+ }
171
+ try {
172
+ const { formatInstallManagedHuman, installManaged } = await import('../scripts/install-managed.mjs');
173
+ const result = installManaged({ ...installArgs, packageRoot });
174
+ process.stdout.write(installArgs.json ? JSON.stringify(result, null, 2) + '\n' : formatInstallManagedHuman(result));
175
+ } catch (error) {
176
+ exitWithError(error);
177
+ }
178
+ break;
179
+ }
180
+ case 'uninstall-managed': {
181
+ let uninstallArgs;
182
+ try {
183
+ uninstallArgs = parseNativeArgs(args, UNINSTALL_MANAGED_OPTIONS);
184
+ } catch (error) {
185
+ exitWithError(error);
186
+ }
187
+ if (uninstallArgs.help) {
188
+ printHelp();
189
+ break;
190
+ }
191
+ try {
192
+ const { uninstallManaged } = await import('../scripts/uninstall-managed.mjs');
193
+ const result = uninstallManaged(uninstallArgs);
194
+ process.stdout.write(uninstallArgs.json ? JSON.stringify(result, null, 2) + '\n' : 'Removed managed Codex Overleaf Link installation.\n');
195
+ } catch (error) {
196
+ exitWithError(error);
197
+ }
198
+ break;
199
+ }
142
200
  case 'install-native': {
143
201
  let installArgs;
144
202
  try {
@@ -0,0 +1,404 @@
1
+ 'use strict';
2
+
3
+ const CODEX_OVERLEAF_HOST = 'com.codex.overleaf';
4
+ const RUNTIME_SCRIPT_ID = 'codex-overleaf-managed-runtime';
5
+ const UPDATE_STATE_KEY = 'codex-overleaf-managed-update-state-v1';
6
+ const UPDATE_RELOAD_TABS_KEY = 'codex-overleaf-managed-update-tabs-v1';
7
+ const CHECK_ALARM = 'codex-overleaf-stable-update-check';
8
+ const IDLE_ALARM = 'codex-overleaf-staged-update-idle';
9
+ const OVERLEAF_MATCHES = [
10
+ 'https://www.overleaf.com/project/*',
11
+ 'https://overleaf.com/project/*'
12
+ ];
13
+ const APPLYING_STATES = new Set(['applying', 'awaiting_health', 'rolling_back']);
14
+
15
+ let runtimeLoadError = null;
16
+ try {
17
+ globalThis.__CODEX_OVERLEAF_RUNTIME_BASE__ = 'runtime';
18
+ importScripts(
19
+ chrome.runtime.getURL('runtime/src/shared/compatibility.js'),
20
+ chrome.runtime.getURL('runtime/src/background.js')
21
+ );
22
+ } catch (error) {
23
+ runtimeLoadError = error;
24
+ }
25
+
26
+ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
27
+ if (message?.type === 'codex-overleaf/update-get-state') {
28
+ getUpdateState().then(sendResponse);
29
+ return true;
30
+ }
31
+ if (message?.type === 'codex-overleaf/update-check-now') {
32
+ checkAndStage({ manual: true }).then(sendResponse).catch(error => sendResponse(failureBody(error)));
33
+ return true;
34
+ }
35
+ if (message?.type === 'codex-overleaf/update-postpone') {
36
+ postponeUpdate().then(sendResponse);
37
+ return true;
38
+ }
39
+ return undefined;
40
+ });
41
+
42
+ chrome.alarms.onAlarm.addListener(alarm => {
43
+ if (alarm.name === CHECK_ALARM) {
44
+ checkAndStage().catch(() => {});
45
+ }
46
+ if (alarm.name === IDLE_ALARM) {
47
+ tryApplyStagedUpdate().catch(() => {});
48
+ }
49
+ });
50
+
51
+ initializeBootstrap().catch(async error => {
52
+ await setUpdateState({ state: 'failed', code: safeCode(error), message: safeMessage(error) });
53
+ });
54
+
55
+ async function initializeBootstrap() {
56
+ try {
57
+ await registerManagedRuntime();
58
+ } catch (error) {
59
+ runtimeLoadError = runtimeLoadError || error;
60
+ }
61
+
62
+ if (runtimeLoadError) {
63
+ await rollbackBrokenRuntime(runtimeLoadError);
64
+ return;
65
+ }
66
+
67
+ const nativeStatus = await requestInternal({ method: 'update.status', params: {} }).catch(() => null);
68
+ const transaction = nativeStatus?.ok ? nativeStatus.result?.transaction : null;
69
+ if (transaction?.state === 'awaiting_health') {
70
+ await confirmPendingUpdate(transaction);
71
+ } else if (transaction?.state === 'rolled_back') {
72
+ await reloadPendingOverleafTabs();
73
+ }
74
+
75
+ chrome.alarms.create(CHECK_ALARM, { delayInMinutes: 0.5, periodInMinutes: 24 * 60 });
76
+ const state = await getUpdateState();
77
+ if (state.state === 'staged' || state.state === 'waiting_for_idle') {
78
+ chrome.alarms.create(IDLE_ALARM, { delayInMinutes: 0.1 });
79
+ }
80
+ }
81
+
82
+ async function registerManagedRuntime() {
83
+ const response = await fetch(chrome.runtime.getURL('runtime/runtime-manifest.json'), { cache: 'no-store' });
84
+ if (!response.ok) {
85
+ throw new Error('Managed runtime manifest could not be loaded.');
86
+ }
87
+ const manifest = await response.json();
88
+ validateRuntimeManifest(manifest);
89
+ const registered = await chrome.scripting.getRegisteredContentScripts({ ids: [RUNTIME_SCRIPT_ID] });
90
+ if (registered.length) {
91
+ await chrome.scripting.unregisterContentScripts({ ids: [RUNTIME_SCRIPT_ID] });
92
+ }
93
+ await chrome.scripting.registerContentScripts([{
94
+ id: RUNTIME_SCRIPT_ID,
95
+ matches: manifest.matches,
96
+ js: ['bootstrap/runtimeContext.js', ...manifest.js.map(value => 'runtime/' + value)],
97
+ css: manifest.css.map(value => 'runtime/' + value),
98
+ runAt: manifest.runAt || 'document_idle',
99
+ persistAcrossSessions: true
100
+ }]);
101
+ }
102
+
103
+ function validateRuntimeManifest(manifest) {
104
+ if (!manifest || manifest.schemaVersion !== 1 || !Array.isArray(manifest.matches) || !Array.isArray(manifest.js) || !Array.isArray(manifest.css)) {
105
+ throw new Error('Managed runtime manifest is invalid.');
106
+ }
107
+ if (!manifest.matches.length || manifest.matches.some(value => !OVERLEAF_MATCHES.includes(value))) {
108
+ throw new Error('Managed runtime match patterns are invalid.');
109
+ }
110
+ const paths = [...manifest.js, ...manifest.css];
111
+ if (!manifest.js.length || paths.some(value => typeof value !== 'string' || value.startsWith('/') || value.includes('..') || !/^[a-zA-Z0-9_./-]+$/.test(value))) {
112
+ throw new Error('Managed runtime file list is invalid.');
113
+ }
114
+ }
115
+
116
+ async function checkAndStage(options = {}) {
117
+ const current = await getUpdateState();
118
+ if (APPLYING_STATES.has(current.state)) {
119
+ return current;
120
+ }
121
+ if (!options.manual && Number(current.postponeUntil || 0) > Date.now()) {
122
+ return current;
123
+ }
124
+ await setUpdateState({ ...current, state: 'checking', code: '', message: '' });
125
+ const checked = await requestInternal({
126
+ method: 'update.check',
127
+ params: {
128
+ currentVersion: chrome.runtime.getManifest().version,
129
+ etag: current.etag || ''
130
+ }
131
+ });
132
+ if (!checked?.ok) {
133
+ const code = checked?.error?.code || 'update_check_failed';
134
+ if (code === 'update_not_managed') {
135
+ return setUpdateState({ state: 'idle', managed: false, code, message: checked.error.message });
136
+ }
137
+ throw nativeError(checked);
138
+ }
139
+ const checkResult = checked.result || {};
140
+ if (!checkResult.available) {
141
+ return setUpdateState({
142
+ state: 'idle',
143
+ managed: checkResult.managed !== false,
144
+ currentVersion: chrome.runtime.getManifest().version,
145
+ latestVersion: checkResult.latestVersion || chrome.runtime.getManifest().version,
146
+ etag: checkResult.etag || current.etag || '',
147
+ lastCheckedAt: Date.now(),
148
+ code: checkResult.reason || '',
149
+ message: ''
150
+ });
151
+ }
152
+
153
+ await setUpdateState({
154
+ ...current,
155
+ state: 'update_available',
156
+ managed: true,
157
+ currentVersion: chrome.runtime.getManifest().version,
158
+ latestVersion: checkResult.latestVersion,
159
+ etag: checkResult.etag || '',
160
+ lastCheckedAt: Date.now()
161
+ });
162
+ await setUpdateState({ state: 'downloading', managed: true, currentVersion: chrome.runtime.getManifest().version, latestVersion: checkResult.latestVersion });
163
+ const staged = await requestInternal({ method: 'update.stage', params: {} });
164
+ if (!staged?.ok) {
165
+ throw nativeError(staged);
166
+ }
167
+ await setUpdateState({
168
+ state: 'staged',
169
+ managed: true,
170
+ currentVersion: chrome.runtime.getManifest().version,
171
+ latestVersion: staged.result.targetVersion,
172
+ transactionId: staged.result.transactionId,
173
+ stagedAt: Date.now()
174
+ });
175
+ await broadcastUpdateState('staged');
176
+ chrome.alarms.create(IDLE_ALARM, { delayInMinutes: 0.1 });
177
+ return tryApplyStagedUpdate();
178
+ }
179
+
180
+ async function tryApplyStagedUpdate() {
181
+ const state = await getUpdateState();
182
+ if (!['staged', 'waiting_for_idle'].includes(state.state)) {
183
+ return state;
184
+ }
185
+ if (Number(state.postponeUntil || 0) > Date.now()) {
186
+ return state;
187
+ }
188
+ const tabs = await chrome.tabs.query({ url: OVERLEAF_MATCHES });
189
+ const probes = await Promise.all(tabs.map(tab => probeTabIdle(tab)));
190
+ const tabBlocker = probes.find(probe => probe.idle !== true);
191
+ const nativeGate = await requestInternal({ method: 'update.canApply', params: {} });
192
+ if (tabBlocker || !nativeGate?.ok || nativeGate.result?.idle !== true) {
193
+ const waiting = await setUpdateState({
194
+ ...state,
195
+ state: 'waiting_for_idle',
196
+ blocker: tabBlocker?.blockers?.[0] || nativeGate?.result?.blockers?.[0] || 'busy'
197
+ });
198
+ chrome.alarms.create(IDLE_ALARM, { delayInMinutes: 1 });
199
+ return waiting;
200
+ }
201
+
202
+ await chrome.storage.local.set({ [UPDATE_RELOAD_TABS_KEY]: tabs.map(tab => tab.id).filter(Number.isInteger) });
203
+ await setUpdateState({ ...state, state: 'applying', blocker: '' });
204
+ await broadcastUpdateState('applying');
205
+ const applied = await requestInternal({
206
+ method: 'update.apply',
207
+ params: { transactionId: state.transactionId }
208
+ });
209
+ if (!applied?.ok) {
210
+ throw nativeError(applied);
211
+ }
212
+ await setUpdateState({ ...state, state: 'awaiting_health', latestVersion: applied.result.targetVersion });
213
+ chrome.runtime.reload();
214
+ return { state: 'awaiting_health' };
215
+ }
216
+
217
+ async function probeTabIdle(tab) {
218
+ if (!Number.isInteger(tab?.id)) {
219
+ return { idle: false, blockers: ['tab_unavailable'] };
220
+ }
221
+ try {
222
+ return await withTimeout(
223
+ chrome.tabs.sendMessage(tab.id, { type: 'codex-overleaf/update-idle-probe' }),
224
+ 3500,
225
+ { idle: false, blockers: ['tab_probe_timeout'] }
226
+ );
227
+ } catch (_error) {
228
+ return { idle: false, blockers: ['tab_probe_unavailable'] };
229
+ }
230
+ }
231
+
232
+ async function confirmPendingUpdate(transaction) {
233
+ const targetVersion = transaction.targetVersion;
234
+ const runtimeHealthy = await verifyPendingRuntimeHealth(targetVersion);
235
+ if (!runtimeHealthy) {
236
+ await rollbackBrokenRuntime(new Error('Updated Overleaf content runtime did not report the target version.'));
237
+ return;
238
+ }
239
+ const ping = await requestInternal({ method: 'bridge.ping', params: {} }).catch(() => null);
240
+ if (!ping?.ok || ping.result?.version !== targetVersion) {
241
+ await rollbackBrokenRuntime(new Error('Updated native host did not report the target version.'));
242
+ return;
243
+ }
244
+ const confirmed = await requestInternal({
245
+ method: 'update.confirm',
246
+ params: {
247
+ transactionId: transaction.id,
248
+ extensionVersion: chrome.runtime.getManifest().version,
249
+ nativeVersion: ping.result.version
250
+ }
251
+ });
252
+ if (!confirmed?.ok) {
253
+ await rollbackBrokenRuntime(nativeError(confirmed));
254
+ return;
255
+ }
256
+ await setUpdateState({
257
+ state: 'committed',
258
+ managed: true,
259
+ currentVersion: targetVersion,
260
+ latestVersion: targetVersion,
261
+ lastCheckedAt: Date.now()
262
+ });
263
+ await chrome.storage.local.remove(UPDATE_RELOAD_TABS_KEY);
264
+ await broadcastUpdateState('committed');
265
+ }
266
+
267
+ async function verifyPendingRuntimeHealth(targetVersion) {
268
+ const tabIds = await getPendingOverleafTabIds();
269
+ if (!tabIds.length) return true;
270
+ await Promise.allSettled(tabIds.map(tabId => chrome.tabs.reload(tabId)));
271
+ const remaining = new Set(tabIds);
272
+ const deadline = Date.now() + 20000;
273
+ while (remaining.size && Date.now() < deadline) {
274
+ await Promise.all([...remaining].map(async tabId => {
275
+ try {
276
+ const response = await withTimeout(
277
+ chrome.tabs.sendMessage(tabId, { type: 'codex-overleaf/runtime-health-probe' }),
278
+ 2500,
279
+ null
280
+ );
281
+ if (response?.ok === true && response.version === targetVersion) {
282
+ remaining.delete(tabId);
283
+ }
284
+ } catch (_error) {
285
+ // The tab may still be reloading; retry until the bounded deadline.
286
+ }
287
+ }));
288
+ if (remaining.size) await new Promise(resolve => setTimeout(resolve, 250));
289
+ }
290
+ return remaining.size === 0;
291
+ }
292
+
293
+ async function rollbackBrokenRuntime(error) {
294
+ await setUpdateState({ state: 'rolling_back', code: safeCode(error), message: safeMessage(error) });
295
+ const rolledBack = await requestInternal({
296
+ method: 'update.rollback',
297
+ params: { reasonCode: safeCode(error) }
298
+ }).catch(() => null);
299
+ if (rolledBack?.ok) {
300
+ await setUpdateState({ state: 'rolled_back', code: safeCode(error), currentVersion: rolledBack.result.version });
301
+ chrome.runtime.reload();
302
+ return;
303
+ }
304
+ await setUpdateState({ state: 'failed', code: safeCode(error), message: safeMessage(error) });
305
+ }
306
+
307
+ async function reloadPendingOverleafTabs() {
308
+ const tabIds = await getPendingOverleafTabIds();
309
+ await chrome.storage.local.remove(UPDATE_RELOAD_TABS_KEY);
310
+ await Promise.allSettled(tabIds.map(tabId => chrome.tabs.reload(tabId)));
311
+ }
312
+
313
+ async function getPendingOverleafTabIds() {
314
+ const stored = await chrome.storage.local.get(UPDATE_RELOAD_TABS_KEY);
315
+ const tabIds = Array.isArray(stored[UPDATE_RELOAD_TABS_KEY]) ? stored[UPDATE_RELOAD_TABS_KEY] : [];
316
+ const openTabs = await chrome.tabs.query({ url: OVERLEAF_MATCHES });
317
+ const openIds = new Set(openTabs.map(tab => tab.id).filter(Number.isInteger));
318
+ return [...new Set(tabIds.filter(tabId => Number.isInteger(tabId) && openIds.has(tabId)))];
319
+ }
320
+
321
+ async function postponeUpdate() {
322
+ const state = await getUpdateState();
323
+ return setUpdateState({ ...state, postponeUntil: Date.now() + 24 * 60 * 60 * 1000 });
324
+ }
325
+
326
+ async function requestInternal(payload) {
327
+ if (globalThis.CodexOverleafNativeBridge?.requestInternal) {
328
+ return globalThis.CodexOverleafNativeBridge.requestInternal({
329
+ id: crypto.randomUUID(),
330
+ ...payload
331
+ });
332
+ }
333
+ return new Promise((resolve, reject) => {
334
+ chrome.runtime.sendNativeMessage(CODEX_OVERLEAF_HOST, {
335
+ id: crypto.randomUUID(),
336
+ ...payload
337
+ }, response => {
338
+ const error = chrome.runtime.lastError;
339
+ if (error) reject(new Error(error.message));
340
+ else resolve(response);
341
+ });
342
+ });
343
+ }
344
+
345
+ async function getUpdateState() {
346
+ const stored = await chrome.storage.local.get(UPDATE_STATE_KEY);
347
+ return stored[UPDATE_STATE_KEY] || {
348
+ state: 'idle',
349
+ managed: true,
350
+ currentVersion: chrome.runtime.getManifest().version,
351
+ latestVersion: chrome.runtime.getManifest().version
352
+ };
353
+ }
354
+
355
+ async function setUpdateState(next) {
356
+ const value = {
357
+ state: next.state || 'idle',
358
+ managed: next.managed !== false,
359
+ currentVersion: next.currentVersion || chrome.runtime.getManifest().version,
360
+ latestVersion: next.latestVersion || next.currentVersion || chrome.runtime.getManifest().version,
361
+ etag: next.etag || '',
362
+ lastCheckedAt: Number(next.lastCheckedAt || 0),
363
+ stagedAt: Number(next.stagedAt || 0),
364
+ postponeUntil: Number(next.postponeUntil || 0),
365
+ transactionId: next.transactionId || '',
366
+ blocker: next.blocker || '',
367
+ code: next.code || '',
368
+ message: String(next.message || '').slice(0, 300)
369
+ };
370
+ await chrome.storage.local.set({ [UPDATE_STATE_KEY]: value });
371
+ return value;
372
+ }
373
+
374
+ async function broadcastUpdateState(state) {
375
+ const tabs = await chrome.tabs.query({ url: OVERLEAF_MATCHES });
376
+ await Promise.allSettled(tabs.filter(tab => Number.isInteger(tab.id)).map(tab => (
377
+ chrome.tabs.sendMessage(tab.id, { type: 'codex-overleaf/update-state', state })
378
+ )));
379
+ }
380
+
381
+ function withTimeout(promise, timeoutMs, fallback) {
382
+ return Promise.race([
383
+ promise,
384
+ new Promise(resolve => setTimeout(() => resolve(fallback), timeoutMs))
385
+ ]);
386
+ }
387
+
388
+ function nativeError(response) {
389
+ const error = new Error(response?.error?.message || 'Managed update request failed.');
390
+ error.code = response?.error?.code || 'update_request_failed';
391
+ return error;
392
+ }
393
+
394
+ function safeCode(error) {
395
+ return /^[a-z0-9_]{1,80}$/.test(String(error?.code || '')) ? error.code : 'update_health_failed';
396
+ }
397
+
398
+ function safeMessage(error) {
399
+ return String(error?.message || 'Managed update failed.').replace(/(?:file:\/\/)?(?:[A-Za-z]:[\\/]|\/Users\/|\/home\/)[^\s]*/g, '[local path]').slice(0, 300);
400
+ }
401
+
402
+ function failureBody(error) {
403
+ return { ok: false, error: { code: safeCode(error), message: safeMessage(error) } };
404
+ }