synabun 2.4.3 → 2.4.5

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 (177) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +66 -36
  4. package/docs/whatsapp.md +3 -3
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +12 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -17
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +19 -4
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +85 -17
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  34. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-observe.js +113 -27
  36. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  38. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  39. package/mcp-server/dist/tools/browser-readers.js +17 -0
  40. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  41. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  42. package/mcp-server/dist/tools/remember.js +6 -2
  43. package/mcp-server/dist/tools/remember.js.map +1 -1
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  45. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  47. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  49. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  50. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  51. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  53. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  54. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  55. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  56. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  57. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  58. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  59. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  60. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  61. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  62. package/mcp-server/package-lock.json +2 -2
  63. package/mcp-server/package.json +1 -1
  64. package/mcp-server/src/http.ts +8 -1
  65. package/mcp-server/src/services/identity.ts +5 -0
  66. package/mcp-server/src/services/memory-client.ts +32 -12
  67. package/mcp-server/src/services/memory-writer.ts +5 -2
  68. package/mcp-server/src/services/neural-interface.ts +67 -19
  69. package/mcp-server/src/services/typesafe-config.ts +268 -7
  70. package/mcp-server/src/tools/agents.ts +79 -17
  71. package/mcp-server/src/tools/browser-observe.ts +117 -28
  72. package/mcp-server/src/tools/browser-readers.ts +19 -0
  73. package/mcp-server/src/tools/remember.ts +6 -1
  74. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  75. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  76. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  77. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  78. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  79. package/neural-interface/i18n/en.json +487 -8
  80. package/neural-interface/i18n/pt-BR.json +487 -8
  81. package/neural-interface/lib/agents-studio-api.js +7 -2
  82. package/neural-interface/lib/antigravity/home.js +43 -8
  83. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  84. package/neural-interface/lib/assistant-api.js +90 -0
  85. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-dispatch.js +276 -42
  88. package/neural-interface/lib/assistant-memory.js +3 -1
  89. package/neural-interface/lib/assistant-persona.js +14 -3
  90. package/neural-interface/lib/assistant-route-gate.js +11 -2
  91. package/neural-interface/lib/assistant-router.js +18 -8
  92. package/neural-interface/lib/assistant-runtime.js +103 -6
  93. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-default.js +22 -2
  97. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  98. package/neural-interface/lib/browser-extension-bridge.js +89 -9
  99. package/neural-interface/lib/browser-extension-folder.js +50 -11
  100. package/neural-interface/lib/browser-extension-package.js +6 -5
  101. package/neural-interface/lib/browser-extension-pin.json +15 -13
  102. package/neural-interface/lib/browser-extension-protocol.js +141 -14
  103. package/neural-interface/lib/browser-extension-setup.js +210 -40
  104. package/neural-interface/lib/browser-extension-update.js +104 -0
  105. package/neural-interface/lib/browser-extraction.js +38 -14
  106. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  107. package/neural-interface/lib/claude-history.js +12 -1
  108. package/neural-interface/lib/confined-fs.js +25 -0
  109. package/neural-interface/lib/coordination/operations.js +2 -0
  110. package/neural-interface/lib/db.js +39 -16
  111. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  112. package/neural-interface/lib/git-bash/manager.js +28 -3
  113. package/neural-interface/lib/git-status-runner.js +31 -3
  114. package/neural-interface/lib/loop-inventory.js +162 -0
  115. package/neural-interface/lib/loop-stall.js +74 -4
  116. package/neural-interface/lib/memory-session-capture.js +157 -66
  117. package/neural-interface/lib/native-loop-providers.js +73 -13
  118. package/neural-interface/lib/native-loop-runtime.js +3 -0
  119. package/neural-interface/lib/opencode-protocol.js +4 -2
  120. package/neural-interface/lib/peer-identity.js +62 -16
  121. package/neural-interface/lib/remote-policy.js +24 -7
  122. package/neural-interface/lib/session-cache-builder.js +66 -18
  123. package/neural-interface/lib/session-capture-gate.js +42 -0
  124. package/neural-interface/lib/session-indexer.js +28 -20
  125. package/neural-interface/lib/teams/README.md +22 -1
  126. package/neural-interface/lib/teams/api.js +79 -6
  127. package/neural-interface/lib/teams/index.js +2 -0
  128. package/neural-interface/lib/teams/recovery.js +68 -0
  129. package/neural-interface/lib/teams/scheduler.js +352 -31
  130. package/neural-interface/lib/teams/worktrees.js +123 -30
  131. package/neural-interface/lib/ui-blob-api.js +14 -5
  132. package/neural-interface/lib/ui-blob-store.js +302 -39
  133. package/neural-interface/package-lock.json +2 -2
  134. package/neural-interface/package.json +1 -1
  135. package/neural-interface/public/extension-setup.html +7 -2
  136. package/neural-interface/public/shared/agents/studio/ax-api.js +16 -0
  137. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +318 -13
  138. package/neural-interface/public/shared/agents/studio/ax-teams.js +141 -9
  139. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  140. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  141. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  142. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  143. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  144. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  145. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  146. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  147. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  148. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  149. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  150. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  151. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  152. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  153. package/neural-interface/public/shared/browser-extension-updates.js +90 -0
  154. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  155. package/neural-interface/public/shared/extension-setup/es-page.js +41 -15
  156. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  157. package/neural-interface/public/shared/extension-update-view.js +34 -0
  158. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  159. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  160. package/neural-interface/public/shared/settings/settings-browser-extension.js +581 -197
  161. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  162. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  163. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  164. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  165. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  166. package/neural-interface/public/shared/styles.css +200 -13
  167. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  168. package/neural-interface/public/shared/ui-notifications.js +23 -4
  169. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  170. package/neural-interface/public/shared/ui-settings.js +48 -11
  171. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  172. package/neural-interface/public/shared/worker-end.js +18 -0
  173. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  174. package/neural-interface/scripts/rebuild-pty.js +10 -0
  175. package/neural-interface/server.js +503 -281
  176. package/npm-shrinkwrap.json +2 -2
  177. package/package.json +1 -1
@@ -1,42 +1,84 @@
1
- // The one-button setup of the everyday-browser extension (Settings → Browser → "Connect your browser";
2
- // docs/browser-extension-bridge.md → One-button setup). The owner presses the button; SynaBun finds the default
3
- // browser, prepares the extension folder, opens its own "Connect your browser" page (SETUP_PAGE_PATH) in that browser and
4
- // shows the folder in Finder, Explorer or the file manager. The owner does the three steps no app may do for them
5
- // (the extensions page, Developer mode, Load unpacked); the extension then pairs by itself with a one-time token.
1
+ // The setup of the everyday-browser extension (Settings → Browser → "Connect your browser";
2
+ // docs/browser-extension-bridge.md → One-button setup). SynaBun finds the browsers, prepares the extension folder and
3
+ // keeps a pairing session open; the owner does the steps no app may do for them (the extensions page, Developer mode,
4
+ // Load unpacked, Allow user scripts); the extension then pairs by itself with a one-time token on SynaBun's own
5
+ // loopback page (SETUP_PAGE_PATH), which its content script recognises.
6
+ //
7
+ // Two ways in. The Settings guide (start with `present: 'none'`) shows the steps in Settings itself: the start prepares
8
+ // the folder and opens the pairing session but opens and shows nothing; the guide then asks, one click each, for the
9
+ // browser's extensions page (openExtensions: the companion page first, once, so the extension finds it when it loads),
10
+ // the browser brought forward for a paste (focus: that same companion page once, then a page that never pairs), the
11
+ // pairing page again (reopen: Pair in <Browser>) and the folder (reveal). The status says `guided`, and the companion page then
12
+ // draws only its pairing status. The older way (start without `present`: the extension popup, older pages) opens the
13
+ // page with its own four steps in the browser. Neither shows the folder by itself: only the owner's click (reveal).
6
14
  //
7
15
  // The folder's files are the one package this release pins, downloaded from synabun.ai and verified
8
16
  // (lib/browser-extension-package.js). A folder that is already there is used as it is, in the same request as before.
9
17
  // One that is not there yet, or is older than the pin, is fetched first: the setup is then `downloading` (with the
10
- // bytes so far), and the browser and the folder are opened only once the verified files are in place. A download that
18
+ // bytes so far), and the older way opens its page only once the verified files are in place. A download that
11
19
  // fails ends the setup with its code (offline, unavailable, verification failed) and Start again tries once more;
12
20
  // nothing is ever installed that did not verify.
13
21
  //
14
22
  // Every route that reaches this is the owner's (server.js mounts them behind the same guard as pairing and the mode:
15
- // ownerRouteGuard, this boot's page secret, no automation caller). Nothing here starts a program by itself: `exec` is
16
- // injected (server.js: execFile, no shell, detached) and gets a plan from lib/browser-default.js.
23
+ // ownerRouteGuard, this boot's page secret, no automation caller; the guide's open-extensions, focus and capabilities
24
+ // check also need Settings' own same-origin request with X-SynaBun-UI). Nothing here starts a program by itself: `exec`
25
+ // is injected (server.js: spawn with an argument array, no shell, detached) and gets a plan from lib/browser-default.js.
26
+ // A request names a browser by its id only; the program comes from the detected install, the address from the catalog.
17
27
  //
18
28
  // The token: made by ticket(), only while a setup is active and still waiting for the extension, at most
19
29
  // MAX_TICKETS times per setup (each one replaces the last), each valid TICKET_MS (and never past the setup's end). The
20
30
  // bridge accepts it once, in its pairing handshake, and forgets it (lib/browser-extension-bridge.js
21
31
  // beginSetupPairing). It is never logged, never in a status and never in a URL.
22
- import { launchPlan, revealPlan, SUPPORTED_BROWSER_IDS } from './browser-default.js';
32
+ import { BROWSERS, extensionsPagePlan, launchPlan, revealPlan, SUPPORTED_BROWSER_IDS } from './browser-default.js';
23
33
  import { compareVersions, SETUP_PAGE_PATH } from './browser-extension-folder.js';
24
34
  import { randomBytes } from 'node:crypto';
25
35
 
26
36
  export const SETUP_STATES = Object.freeze(['idle', 'downloading', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
27
37
  /** The codes a download of the extension package can end a setup with (lib/browser-extension-package.js). */
28
38
  export const DOWNLOAD_ERRORS = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED']);
39
+ /** What a start may be told to show: nothing (the Settings guide). Without it, the older way opens its page. */
40
+ export const PRESENT_MODES = Object.freeze(['none']);
29
41
  export const SETUP_WINDOW_MS = 15 * 60 * 1000;
30
42
  export const TICKET_MS = 2 * 60 * 1000;
31
43
  export const MAX_TICKETS = 5;
44
+ /** How long a look at the installed browsers is reused: the guide polls, and each look starts plutil or reg. */
45
+ export const DETECT_CACHE_MS = 30 * 1000;
46
+ /**
47
+ * The wait between the companion page and the extensions page when both are opened by one click. Each launch only
48
+ * starts a program that hands the address to the browser and returns at once, so two started together may arrive in
49
+ * either order; the extensions page should be the tab the owner sees.
50
+ */
51
+ export const COMPANION_GAP_MS = 800;
52
+ /** How long the capabilities check waits for the extension (lib/browser-extension-bridge.js probe). */
53
+ export const PROBE_TIMEOUT_MS = 4000;
54
+ /** The query of the setup page opened only to bring a browser forward (focus): that page never pairs. */
55
+ export const FOCUS_QUERY = 'focus=1';
32
56
  const fail = (code, message = code) => { throw Object.assign(new Error(message), { code }); };
57
+ const PLATFORM_NAMES = Object.freeze({ darwin: 'mac', win32: 'windows' });
58
+ const UNKNOWN_BROWSER = Object.freeze({ id: 'unknown', name: 'Unknown browser', supported: false });
59
+ /**
60
+ * The browser a request names: a body of exactly `{ browser: <supported id> }`. Any other key, a value that is not
61
+ * one of SUPPORTED_BROWSER_IDS (an address, a path, a program, an argument) is INVALID_MESSAGE: nothing of the request
62
+ * ever becomes a program, an argument or an address; those come from the detected install and the catalog.
63
+ */
64
+ function requestedBrowser(body) {
65
+ if (!body || typeof body !== 'object' || Array.isArray(body)) fail('INVALID_MESSAGE');
66
+ const keys = Object.keys(body);
67
+ if (keys.length !== 1 || keys[0] !== 'browser' || typeof body.browser !== 'string' || !SUPPORTED_BROWSER_IDS.includes(body.browser)) fail('INVALID_MESSAGE');
68
+ return body.browser;
69
+ }
70
+ /** A browser by its id, named from the catalog only (never a raw bundle id, ProgId or desktop file). */
71
+ const named = browser => {
72
+ const known = browser && typeof browser.id === 'string' && Object.hasOwn(BROWSERS, browser.id) ? BROWSERS[browser.id] : null;
73
+ return known ? { id: known.id, name: known.name } : { id: UNKNOWN_BROWSER.id, name: UNKNOWN_BROWSER.name };
74
+ };
33
75
 
34
76
  /**
35
77
  * Whether the browser should be told to reload the extension: it is connected, the folder holds what this release
36
78
  * wants (the pinned version, or a newer one a later release left there) and the browser runs something else. While
37
79
  * the folder itself is older than the pin a Reload changes nothing: that is `updateNeeded`, which SynaBun settles by
38
80
  * downloading the pinned package. `reloadPending`: the folder's marker asks for a Reload until the setup page saw the
39
- * extension running again; `reloadReason` says why. 'port': the setup port changed while the version stayed, and the
81
+ * extension running again; `reloadReason` says why. 'version': a verified upgrade awaits the new peer. 'port': the setup port changed while the version stayed, and the
40
82
  * browser still runs the old manifest (asked only while the extension is connected). 'repair': files that were not
41
83
  * the pinned extension were replaced, and the browser may still run them at the same version, connected or not (the
42
84
  * changed code may not connect at all): asked until the owner confirms the Reload in Settings, and said in its own
@@ -45,7 +87,7 @@ const fail = (code, message = code) => { throw Object.assign(new Error(message),
45
87
  export function extensionVersions({ connected, extensionVersion, folderVersion, pinnedVersion, reloadPending = false, reloadReason = null }) {
46
88
  const current = !!folderVersion && (!pinnedVersion || compareVersions(folderVersion, pinnedVersion) >= 0);
47
89
  const repaired = current && reloadPending === true && reloadReason === 'repair';
48
- const reloadNeeded = repaired || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
90
+ const reloadNeeded = repaired || (current && reloadPending === true && reloadReason === 'version') || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
49
91
  return {
50
92
  reloadNeeded,
51
93
  updateNeeded: !!(folderVersion && pinnedVersion && compareVersions(folderVersion, pinnedVersion) < 0),
@@ -61,15 +103,53 @@ export function extensionVersions({ connected, extensionVersion, folderVersion,
61
103
  * `folderVersion()` the version the folder holds, `packageStatus()` → { pinnedVersion, needs, phase, received, total,
62
104
  * code, reloadPending } (browser-extension-package.js status; `needs` says that `prepare` will download),
63
105
  * `confirmReload()` the setup page saw the extension's content script on this port (browser-extension-package.js; it
64
- * never clears a repair's Reload).
106
+ * never clears a repair's Reload). `detectMs`: how long a look at the browsers is reused (DETECT_CACHE_MS);
107
+ * `pause(ms)` waits between two launches of one click (tests pass one that does not wait).
65
108
  */
66
109
  export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin, platform = process.platform, now = Date.now,
67
- windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false } = {}) {
110
+ windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false, updateStatus,
111
+ detectMs = DETECT_CACHE_MS, companionGapMs = COMPANION_GAP_MS, probeTimeoutMs = PROBE_TIMEOUT_MS, pause = ms => new Promise(resolve => setTimeout(resolve, ms)) } = {}) {
68
112
  let setup = null;
69
113
  // The latest start, from its first step: a cancel or a later start ends it before it prepares or opens anything.
70
114
  let attempt = null;
115
+ // The last look at the browsers ({ at, value }) and the one under way. The Settings guide asks for the list while it
116
+ // is open; a look starts plutil or reg, so one is reused for `detectMs` (a start, and ?refresh=1, always look again).
117
+ let detection = null, detecting = null;
118
+ // The browser whose setup made the bridge's current pairing ({ browser: { id, name }, pairedAt }), remembered when
119
+ // state() first sees that pairing and reported while the bridge still holds it. In memory only: after a restart a
120
+ // pairing has no setup to name, and the guide then asks the owner rather than calling an earlier browser ready.
121
+ let pairedThrough = null;
71
122
  const pageUrl = () => `${appOrigin()}${SETUP_PAGE_PATH}`;
123
+ // The same page opened only to bring the browser forward (focus): it never asks for a token (es-page.js FOCUS_ONLY).
124
+ const focusUrl = () => `${pageUrl()}?${FOCUS_QUERY}`;
72
125
  const describe = browser => browser ? { id: browser.id, name: browser.name, supported: browser.supported === true, extensionsUrl: browser.extensionsUrl || null } : null;
126
+ // The supported browsers a look found, once each; the default as it was found (it may be unsupported or unknown).
127
+ const normalize = found => {
128
+ const installed = [];
129
+ for (const browser of Array.isArray(found?.installedBrowsers) ? found.installedBrowsers : []) {
130
+ if (browser?.supported && SUPPORTED_BROWSER_IDS.includes(browser.id) && !installed.some(b => b.id === browser.id)) installed.push(browser);
131
+ }
132
+ return { browser: found?.browser && typeof found.browser === 'object' ? found.browser : null, installedBrowsers: installed };
133
+ };
134
+ // A look that fails is no browser and none installed, never an error: the guide then says what it could not find.
135
+ function look() {
136
+ const run = Promise.resolve().then(() => detect()).then(normalize, () => normalize(null));
137
+ detecting = run;
138
+ void run.then(value => { if (detecting === run) { detecting = null; detection = { at: now(), value }; } });
139
+ return run;
140
+ }
141
+ function browsers({ refresh = false } = {}) {
142
+ const at = now();
143
+ if (!refresh && detection && at >= detection.at && at - detection.at < detectMs) return Promise.resolve(detection.value);
144
+ if (!refresh && detecting) return detecting;
145
+ return look();
146
+ }
147
+ // An installed supported browser by its id, with its `launch` (never shown): only what a look found is started.
148
+ async function installedBrowser(id) {
149
+ const browser = (await browsers()).installedBrowsers.find(b => b.id === id);
150
+ if (!browser) fail('BROWSER_NOT_INSTALLED');
151
+ return browser;
152
+ }
73
153
  function state() {
74
154
  if (!setup) return 'idle';
75
155
  if (setup.error) return 'error';
@@ -77,34 +157,58 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
77
157
  const bridgeStatus = bridge.status();
78
158
  // Paired by this setup: a pairing made after it began (its token, or the typed code as a fallback). Connected once
79
159
  // the extension's first inventory arrived; "Pairing…" from the token's handshake until then.
80
- if (bridgeStatus.paired && bridgeStatus.pairedAt !== setup.pairedBefore) return bridgeStatus.connected ? 'connected' : 'pairing';
160
+ if (bridgeStatus.paired && bridgeStatus.pairedAt !== setup.pairedBefore) {
161
+ if (pairedThrough?.pairedAt !== bridgeStatus.pairedAt) pairedThrough = setup.browser?.supported ? { browser: named(setup.browser), pairedAt: bridgeStatus.pairedAt } : null;
162
+ return bridgeStatus.connected ? 'connected' : 'pairing';
163
+ }
81
164
  if (bridge.setupPairing().attempted) return 'pairing';
82
165
  if (now() >= setup.until) { expire(); return 'error'; }
83
166
  if (!setup.browser?.supported) return 'unsupported';
84
167
  return 'waiting-for-extension';
85
168
  }
169
+ // The browser that made the bridge's current pairing through a setup, or null once that pairing is gone or replaced.
170
+ function pairedNow(bridgeStatus) {
171
+ if (pairedThrough && (!bridgeStatus.paired || bridgeStatus.pairedAt !== pairedThrough.pairedAt)) pairedThrough = null;
172
+ return pairedThrough ? { ...pairedThrough.browser } : null;
173
+ }
86
174
  function expire() {
87
175
  if (!setup || setup.error) return;
88
176
  bridge.endSetupPairing(); setup.error = { code: 'SETUP_EXPIRED' };
89
177
  }
90
- async function open(browser) {
91
- try { const plan = launchPlan(platform, browser, pageUrl()); await exec(plan.cmd, plan.args); return true; } catch { return false; }
178
+ async function open(browser, url = pageUrl()) {
179
+ try { const plan = launchPlan(platform, browser, url); await exec(plan.cmd, plan.args); return true; } catch { return false; }
92
180
  }
181
+ // Only on the owner's click (POST …/setup/reveal): no start shows the folder by itself.
93
182
  async function reveal() {
94
183
  if (!setup?.folder) fail('SETUP_NOT_ACTIVE');
95
- try { const plan = revealPlan(platform, setup.folder); await exec(plan.cmd, plan.args); return { ok: true, folder: setup.folder }; }
96
- catch { return { ok: false, code: 'REVEAL_FAILED', folder: setup.folder }; }
184
+ const mine = setup;
185
+ try { const plan = revealPlan(platform, mine.folder); await exec(plan.cmd, plan.args); mine.revealed = true; return { ok: true, folder: mine.folder }; }
186
+ catch { return { ok: false, code: 'REVEAL_FAILED', folder: mine.folder }; }
187
+ }
188
+ // The companion page, before the extensions page of the same click: once per setup, only in the setup's own browser
189
+ // and only while the setup still waits for the extension (or downloads it), so the extension finds the page and pairs
190
+ // by itself once it is loaded. True when it was opened now.
191
+ async function openCompanion(browser) {
192
+ const mine = setup;
193
+ if (!mine || mine.opened || mine.companionOpening || mine.browser?.id !== browser.id || !['downloading', 'waiting-for-extension'].includes(state())) return false;
194
+ mine.companionOpening = true;
195
+ try { const opened = await open(browser); if (opened) mine.opened = true; return opened; }
196
+ finally { mine.companionOpening = false; }
97
197
  }
98
198
  function view() {
99
199
  const current = state(), bridgeStatus = bridge.status();
100
- const version = folderVersion(), pkg = packageStatus() || {};
200
+ const pkg = packageStatus() || {};
201
+ const version = Object.hasOwn(pkg, 'folderVersion') ? pkg.folderVersion : folderVersion();
101
202
  const pinnedVersion = typeof pkg.pinnedVersion === 'string' ? pkg.pinnedVersion : null;
102
203
  return {
103
204
  state: current,
104
- ...(setup ? { setupId: setup.id, browser: describe(setup.browser), defaultBrowser: describe(setup.defaultBrowser), installedBrowsers: setup.installed.map(describe),
205
+ ...(updateStatus ? { update: updateStatus(bridgeStatus, pkg) } : {}),
206
+ ...(setup ? { setupId: setup.id, guided: setup.guided === true, browser: describe(setup.browser), defaultBrowser: describe(setup.defaultBrowser), installedBrowsers: setup.installed.map(describe),
105
207
  folder: setup.folder, extensionsUrl: setup.browser?.extensionsUrl || null, opened: setup.opened, revealed: setup.revealed, expiresAt: setup.until } : {}),
106
208
  ...(setup?.error ? { code: setup.error.code } : {}),
107
209
  connected: bridgeStatus.connected, paired: bridgeStatus.paired, bridgePort: bridgeStatus.port,
210
+ // Which browser's setup made the current pairing: the guide calls a bridge "ready" for the browser it set up only.
211
+ pairedThrough: pairedNow(bridgeStatus),
108
212
  extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version, pinnedVersion,
109
213
  // The bytes so far while the pinned package is on its way (the setup's own download, or an update's).
110
214
  ...(pkg.phase === 'downloading' ? { download: { received: Number(pkg.received) || 0, total: Number(pkg.total) || 0 } } : {}),
@@ -117,10 +221,14 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
117
221
  /**
118
222
  * Starts (or restarts) a setup. `browserId`: one of the installed supported browsers, for "open in X instead";
119
223
  * without it the default browser, which may be unsupported (then the page is not opened and the state is
120
- * `unsupported` with the installed browsers to choose from).
224
+ * `unsupported` with the installed browsers to choose from). `present: 'none'` (the Settings guide): the folder
225
+ * and the pairing session only, nothing opened (`guided` in the status); without it the page opens in the browser
226
+ * once the folder is ready. Neither shows the folder: that is reveal(), on the owner's click.
121
227
  */
122
- async start({ browserId } = {}) {
228
+ async start({ browserId, present } = {}) {
123
229
  if (browserId !== undefined && browserId !== null && !SUPPORTED_BROWSER_IDS.includes(browserId)) fail('INVALID_MESSAGE');
230
+ if (present !== undefined && present !== null && !PRESENT_MODES.includes(present)) fail('INVALID_MESSAGE');
231
+ const guided = present === 'none';
124
232
  if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); }
125
233
  // This start is the current one before its first wait: a cancel during the browser detection, or a later start
126
234
  // whose detection ends first, leaves this one nothing to do when its own detection ends.
@@ -128,31 +236,29 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
128
236
  const own = { stop: new AbortController() };
129
237
  attempt = own;
130
238
  const superseded = () => attempt !== own || own.stop.signal.aborted;
131
- let detected;
132
- try { detected = await detect(); } catch { detected = { browser: null, installedBrowsers: [] }; }
239
+ // Always a fresh look: the owner may have installed a browser since the guide last asked.
240
+ const detected = await look();
133
241
  if (superseded()) return view();
134
- const installed = Array.isArray(detected?.installedBrowsers) ? detected.installedBrowsers.filter(b => b?.supported) : [];
135
- const defaultBrowser = detected?.browser || { id: 'unknown', name: 'Unknown browser', supported: false, extensionsUrl: null };
242
+ const installed = detected.installedBrowsers;
243
+ const defaultBrowser = detected.browser || { ...UNKNOWN_BROWSER, extensionsUrl: null };
136
244
  let browser = defaultBrowser;
137
245
  if (browserId) {
138
246
  browser = installed.find(b => b.id === browserId);
139
247
  if (!browser) fail('BROWSER_NOT_INSTALLED');
140
248
  }
141
- setup = { id: randomBytes(12).toString('hex'), startedAt: now(), until: now() + windowMs, browser, defaultBrowser, installed,
249
+ setup = { id: randomBytes(12).toString('hex'), startedAt: now(), until: now() + windowMs, browser, defaultBrowser, installed, guided,
142
250
  folder: null, opened: false, revealed: false, tickets: 0, pairedBefore: bridge.status().pairedAt || 0, error: null };
143
251
  const mine = setup;
144
252
  mine.stop = own.stop;
145
253
  // A browser that cannot run the extension gets no download: the page offers the installed ones, and choosing one
146
254
  // starts the setup again.
147
255
  if (!browser.supported && (packageStatus() || {}).needs) return view();
148
- // Once the folder is ready: the page in the browser, the folder in the file manager (never for a start that was
149
- // cancelled or replaced meanwhile).
150
- const present = async () => {
151
- if (!browser.supported || setup !== mine || superseded()) return;
256
+ // Once the folder is ready, the older way opens the page in the browser (never for a start that was cancelled or
257
+ // replaced meanwhile). The guide opens nothing: each of its steps is the owner's click.
258
+ const presentPage = async () => {
259
+ if (guided || !browser.supported || setup !== mine || superseded()) return;
152
260
  mine.opened = await open(browser);
153
- if (setup !== mine) return;
154
- mine.revealed = (await reveal()).ok === true;
155
- if (!mine.opened) mine.error = { code: 'OPEN_FAILED' };
261
+ if (setup === mine && !mine.opened) mine.error = { code: 'OPEN_FAILED' };
156
262
  };
157
263
  // Started in this step, so the answer below already carries a download's progress.
158
264
  let preparing;
@@ -165,15 +271,77 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
165
271
  const needed = packageStatus() || {};
166
272
  if (needed.needs || needed.phase === 'downloading') {
167
273
  mine.preparing = true;
168
- mine.settled = ready.then(async () => { mine.preparing = false; if (setup === mine && !mine.error) await present(); }).catch(() => { mine.preparing = false; });
274
+ mine.settled = ready.then(async () => { mine.preparing = false; if (setup === mine && !mine.error) await presentPage(); }).catch(() => { mine.preparing = false; });
169
275
  return view();
170
276
  }
171
277
  await ready;
172
278
  if (setup !== mine || mine.error) return view();
173
- await present();
279
+ await presentPage();
174
280
  return view();
175
281
  },
176
- status: view,
282
+ status: view, state,
283
+ /**
284
+ * The browsers for the Settings guide (GET …/setup/browsers): { platform, defaultBrowser: { id, name, supported },
285
+ * installedBrowsers: [{ id, name, extensionsUrl }], suggested }. Names and addresses come from the catalog
286
+ * (browser-default.js BROWSERS); no program, bundle id, path or desktop file is ever in it. `suggested`: the default
287
+ * when it is supported and installed, else the first installed one, else null. `refresh`: look again now.
288
+ */
289
+ async browsers({ refresh = false } = {}) {
290
+ const found = await browsers({ refresh });
291
+ const known = found.browser && typeof found.browser.id === 'string' && Object.hasOwn(BROWSERS, found.browser.id) ? BROWSERS[found.browser.id] : null;
292
+ const defaultBrowser = known ? { id: known.id, name: known.name, supported: known.supported } : { ...UNKNOWN_BROWSER };
293
+ const installedBrowsers = found.installedBrowsers.map(b => ({ id: b.id, name: BROWSERS[b.id].name, extensionsUrl: BROWSERS[b.id].extensionsUrl }));
294
+ const suggested = defaultBrowser.supported && installedBrowsers.some(b => b.id === defaultBrowser.id) ? defaultBrowser.id : installedBrowsers[0]?.id ?? null;
295
+ return { platform: PLATFORM_NAMES[platform] || 'linux', defaultBrowser, installedBrowsers, suggested };
296
+ },
297
+ /**
298
+ * Opens an installed browser's own extensions page (POST …/setup/open-extensions, body exactly `{ browser }`). The
299
+ * address is the catalog's for that browser and the program the one its detected install names
300
+ * (browser-default.js extensionsPagePlan). When a setup for that browser has not opened its companion page yet, that
301
+ * page opens first. Answers { ok, code?, browser: { id, name }, extensionsUrl, companion }: `companion` says the
302
+ * companion page was opened by this click. `ok: false, code: 'OPEN_FAILED'` when the program could not be started.
303
+ */
304
+ async openExtensions(body) {
305
+ const browser = await installedBrowser(requestedBrowser(body));
306
+ const shown = named(browser), extensionsUrl = BROWSERS[browser.id].extensionsUrl;
307
+ const companion = await openCompanion(browser);
308
+ if (companion) await pause(companionGapMs);
309
+ // `ok` means the program that hands the address to the browser started, never that the page appeared: a launch
310
+ // cannot see the browser's window, and a browser may refuse an address of its own scheme given from outside. The
311
+ // guide keeps its "Page didn't open?" way (copy the address) for that.
312
+ try { const plan = extensionsPagePlan(platform, browser); await exec(plan.cmd, plan.args); return { ok: true, browser: shown, extensionsUrl, companion }; }
313
+ catch { return { ok: false, code: 'OPEN_FAILED', browser: shown, extensionsUrl, companion }; }
314
+ },
315
+ /**
316
+ * Brings an installed browser forward for "Copy address & open <Browser>" (POST …/setup/focus, body exactly
317
+ * `{ browser }`): the owner pastes the copied extensions address into the tab this opens, which replaces it. So that
318
+ * tab is the focus-only page (SETUP_PAGE_PATH?focus=1), which never asks for a token: the paste takes no pairing with
319
+ * it. As with openExtensions, an active setup of that browser that has not opened its companion page yet opens it
320
+ * first, once, behind the focus page; nothing else counts as the companion. Answers { ok, code?, browser: { id, name },
321
+ * extensionsUrl, companion } (`ok` says the launch started, not that the window came forward).
322
+ */
323
+ async focus(body) {
324
+ const browser = await installedBrowser(requestedBrowser(body));
325
+ const shown = named(browser), extensionsUrl = BROWSERS[browser.id].extensionsUrl;
326
+ const companion = await openCompanion(browser);
327
+ if (companion) await pause(companionGapMs);
328
+ const opened = await open(browser, focusUrl());
329
+ return opened ? { ok: true, browser: shown, extensionsUrl, companion } : { ok: false, code: 'OPEN_FAILED', browser: shown, extensionsUrl, companion };
330
+ },
331
+ /**
332
+ * What the paired extension can do now (POST …/capabilities/check, body `{}`): the bridge's probe, which asks the
333
+ * connected extension and never throws ({ ok, code?, capabilities, legacy }). A bridge without a probe is an older
334
+ * one: { ok: true, capabilities: null, legacy: true }.
335
+ */
336
+ async capabilities(body) {
337
+ if (body !== undefined && body !== null && (typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length)) fail('INVALID_MESSAGE');
338
+ if (typeof bridge.probe !== 'function') return { ok: true, capabilities: null, legacy: true };
339
+ let result = null;
340
+ try { result = await bridge.probe({ timeoutMs: probeTimeoutMs }); } catch {}
341
+ if (!result || typeof result !== 'object') return { ok: false, code: 'CAPABILITIES_CHECK_FAILED', capabilities: null, legacy: false };
342
+ // The probe's own fields only, so nothing else the bridge may carry reaches the page.
343
+ return { ok: result.ok === true, ...(typeof result.code === 'string' ? { code: result.code } : {}), capabilities: result.capabilities ?? null, legacy: result.legacy === true };
344
+ },
177
345
  /**
178
346
  * The setup page saw the extension's content script on this server's port (POST …/setup/seen): the browser runs
179
347
  * the folder's manifest for this port, so the Reload a port change asked for is done. A repair's Reload is not: the
@@ -201,7 +369,8 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
201
369
  settled: () => setup?.settled || Promise.resolve(),
202
370
  reveal,
203
371
  /** Opens the setup page again (in the setup's browser). */
204
- async reopen() { if (!setup?.browser?.supported) fail('SETUP_NOT_ACTIVE'); setup.opened = await open(setup.browser); return view(); },
372
+ // (The pairing page, never the focus-only one: the guide's Pair in <Browser> asks for this. `opened` is this launch's.)
373
+ async reopen() { const mine = setup; if (!mine?.browser?.supported) fail('SETUP_NOT_ACTIVE'); const opened = await open(mine.browser); if (setup === mine && opened) mine.opened = true; return { ...view(), opened }; },
205
374
  };
206
375
  }
207
376
 
@@ -217,8 +386,9 @@ export const SETUP_ERROR_TEXT = Object.freeze({
217
386
  EXTENSION_DOWNLOAD_OFFLINE: 'SynaBun could not reach synabun.ai to download the extension. Check the internet connection, then start "Connect your browser" again.',
218
387
  EXTENSION_DOWNLOAD_UNAVAILABLE: 'synabun.ai did not have the extension this SynaBun version needs. Try again later, or update SynaBun.',
219
388
  EXTENSION_VERIFY_FAILED: 'The downloaded extension was not the file this SynaBun version expects, so it was not installed. Try again; if it keeps failing, update SynaBun.',
220
- OPEN_FAILED: 'SynaBun could not open the setup page in the browser. Open it yourself from Settings → Browser.',
221
- REVEAL_FAILED: 'SynaBun could not show the folder. Copy its path from the setup page.',
389
+ OPEN_FAILED: 'SynaBun could not open the page in the browser. Copy its address from Settings → Browser and open it yourself.',
390
+ REVEAL_FAILED: 'SynaBun could not show the folder. Copy its path from Settings → Browser.',
391
+ CAPABILITIES_CHECK_FAILED: 'SynaBun could not ask the extension what it can do. Try again.',
222
392
  INVALID_MESSAGE: 'Invalid setup request.',
223
393
  });
224
394
  export function setupError(error) {
@@ -0,0 +1,104 @@
1
+ // Update progress for the owner. The durable install marker survives a restart. An attempt lives only in
2
+ // the process that sent the command. An acknowledgement is never proof that the new copy is running.
3
+ import { compareVersions } from './browser-extension-folder.js';
4
+ import { SELF_RELOAD_SINCE } from './browser-extension-protocol.js';
5
+ import { extensionVersions } from './browser-extension-setup.js';
6
+
7
+ export const RECONNECT_WAIT_MS = 45_000;
8
+ export function createExtensionUpdate({ bridge, pkg, runsActive, now = Date.now }) {
9
+ let attempt = null, observed = null;
10
+
11
+ function status(peer = bridge.status(), disk = pkg.status()) {
12
+ const { connected, extensionVersion: runningVersion } = peer;
13
+ const { folderVersion, pinnedVersion } = disk;
14
+ const targetVersion = disk.needs === 'update' ? pinnedVersion : folderVersion || pinnedVersion;
15
+ if (attempt?.target !== targetVersion) attempt = null;
16
+ if (observed?.target !== targetVersion) observed = null;
17
+ // Explicit repair confirmation (or the setup page's port check) also clears the prompt while offline.
18
+ if (attempt && attempt.reason !== 'version' && !disk.reloadPending) attempt = null;
19
+ if (!connected && observed?.reason && observed.reason !== 'version' && !disk.reloadPending) observed = null;
20
+ const flags = extensionVersions({ ...disk, connected, extensionVersion: runningVersion });
21
+ const reason = disk.reloadReason || 'version';
22
+ const view = { phase: 'idle', runningVersion, folderVersion, pinnedVersion, targetVersion, reason,
23
+ fromVersion: runningVersion || observed?.from || disk.fromVersion || (disk.needs === 'update' ? folderVersion : null),
24
+ canReload: false, runsActive: runsActive(), claimedTabs: peer.tabs.filter(tab => tab.owner).length };
25
+ if (disk.needs === 'update' || flags.updateNeeded || (disk.needs === 'unsafe' && (peer.paired || folderVersion))) {
26
+ observed = { target: targetVersion, from: runningVersion || disk.fromVersion || folderVersion };
27
+ attempt = null;
28
+ if (disk.phase === 'failed') return { ...view, phase: 'failed', recovery: 'download', code: disk.code };
29
+ const percent = disk.total > 0 ? Math.min(100, Math.max(0, Math.floor(100 * disk.received / disk.total))) : 0;
30
+ return { ...view, phase: 'downloading', pending: disk.phase === 'idle', percent };
31
+ }
32
+ if (disk.needs || !folderVersion) return view; // a first install belongs to setup
33
+ if (flags.reloadNeeded && (observed?.reason !== reason || observed.done)) {
34
+ observed = { target: targetVersion, reason, from: runningVersion || disk.fromVersion };
35
+ }
36
+ if (attempt && !attempt.code && now() >= attempt.until) attempt.code = 'RELOAD_TIMEOUT';
37
+ if (attempt?.code) return { ...view, phase: 'failed', recovery: 'guided', code: attempt.code };
38
+ if (attempt) return { ...view, phase: 'reloading' };
39
+ if (flags.reloadNeeded || (observed && peer.paired && !connected && !observed.done)) {
40
+ return { ...view, phase: 'ready', confirmBusy: !!observed?.confirmBusy, canReload: connected && !observed?.verify && compareVersions(runningVersion, SELF_RELOAD_SINCE) >= 0 };
41
+ }
42
+ if (observed && connected && runningVersion === targetVersion) {
43
+ observed.done = true;
44
+ return { ...view, phase: 'done' };
45
+ }
46
+ return view;
47
+ }
48
+
49
+ // Called once for the first authenticated inventory on each socket, even with no owner page open.
50
+ function connected(version) {
51
+ const disk = pkg.status();
52
+ if (disk.needs || version !== disk.folderVersion) {
53
+ if (attempt) attempt.code = 'RELOAD_OLD_VERSION';
54
+ return;
55
+ }
56
+ if (disk.reloadReason === 'version' && pkg.confirmVersion(version)) {
57
+ observed = { target: version, from: disk.fromVersion, done: true };
58
+ } else if (attempt) {
59
+ // A same-version repair still needs the owner's confirmation. A port change needs setup/seen.
60
+ observed = { target: version, from: attempt.from, reason: attempt.reason, verify: !!disk.reloadPending, done: !disk.reloadPending };
61
+ }
62
+ attempt = null;
63
+ }
64
+
65
+ function reload({ targetVersion, allowBusy = false }) {
66
+ const view = status();
67
+ const refuse = code => ({ ok: false, code, update: view });
68
+ if (!targetVersion || targetVersion !== view.targetVersion) return refuse('UPDATE_CHANGED');
69
+ if (view.phase === 'reloading' || view.phase === 'done') return { ok: true, update: view };
70
+ if (!view.canReload) return refuse('EXTENSION_RELOAD_REQUIRED');
71
+ if (!allowBusy && (view.claimedTabs || view.runsActive)) return refuse('RELOAD_BUSY');
72
+ const own = { target: targetVersion, reason: view.reason, from: view.runningVersion, until: now() + RECONNECT_WAIT_MS };
73
+ attempt = own;
74
+ const failed = code => {
75
+ if (attempt !== own) return;
76
+ // The old worker can close its socket just after the ack was queued. Only the new hello settles that case.
77
+ if (code === 'NOT_CONNECTED' || code === 'EXTENSION_NOT_CONNECTED') return;
78
+ if (code === 'RELOAD_BUSY') { observed.confirmBusy = true; attempt = null; return; }
79
+ own.code = 'RELOAD_FAILED';
80
+ };
81
+ bridge.publishUpdate?.();
82
+ bridge.request('selfReload', null, 'owner', { allowBusy }).then(result => {
83
+ if (!result.ok) failed(result.code);
84
+ }, error => failed(error?.code));
85
+ return { ok: true, update: { ...view, phase: 'reloading', canReload: false } };
86
+ }
87
+ return { status, connected, reload };
88
+ }
89
+
90
+ // Mounted behind the bridge's owner/page-secret middleware. Even a browser granted general automation owner
91
+ // access cannot send this command. A read or a request missing the explicit click's target has no effect.
92
+ export function ownerReloadHandler({ update, isAutomationBrowser }) {
93
+ return (req, res) => {
94
+ const headers = req.headers;
95
+ if (isAutomationBrowser(req) || !/^https?:\/\//i.test(headers.origin || '') || headers['x-synabun-ui'] !== '1'
96
+ || (headers['sec-fetch-site'] !== undefined && headers['sec-fetch-site'] !== 'same-origin')) {
97
+ return res.status(403).json({ ok: false, code: 'OWNER_ROUTE' });
98
+ }
99
+ const { targetVersion, allowBusy } = req.body || {};
100
+ if (typeof targetVersion !== 'string' || typeof allowBusy !== 'boolean') return res.status(400).json({ ok: false, code: 'INVALID_MESSAGE' });
101
+ const result = update.reload({ targetVersion, allowBusy });
102
+ return res.status(result.ok ? 200 : 409).json(result);
103
+ };
104
+ }
@@ -44,7 +44,7 @@ export function budgetExtractionItems(items, { fields, maxItems = 50, maxChars }
44
44
  // `script-src` has no 'unsafe-eval', refused the second poll of every scrolled
45
45
  // extraction with an EvalError ("the tweet extractor doesn't work on X").
46
46
 
47
- const BUSY_SELECTOR = '[aria-busy="true"], [role="progressbar"]';
47
+ export const BUSY_SELECTOR = '[aria-busy="true"], [role="progressbar"]';
48
48
 
49
49
  /** An extractor or a scroll target is one JavaScript expression (statements go in an IIFE). */
50
50
  function expressionSource(source, what) {
@@ -232,21 +232,45 @@ export async function runBrowserExtraction(page, script, opts = {}, runtime = {}
232
232
  };
233
233
  }
234
234
 
235
+ /**
236
+ * The main content of a page (or of one element) as HTML, for the Markdown reader. A page function: Playwright sends
237
+ * its source to the page (readBrowserContentHtml), and the browser extension ships the same source as one of its fixed
238
+ * readers ('page.html', generated by scripts/extension/build-browser-readers.mjs). It clones before cleaning, drops
239
+ * navigation, chrome and scripts, resolves link and image addresses, and prefers <main>, <article> or [role=main].
240
+ * `dense` (the extension's reader only; Playwright never passes it, so its output is as before): on a page with none
241
+ * of those, the block that holds most of the page's paragraph text, when one block holds at least 60 % of it.
242
+ */
243
+ export function contentHtmlOf(element, scoped, dense) {
244
+ const clone = element.cloneNode(true);
245
+ const noise = scoped
246
+ ? 'script,style,noscript,iframe'
247
+ : 'nav,header,footer,aside,[role="navigation"],[role="banner"],[role="contentinfo"],[role="complementary"],.sidebar,.nav,.footer,.header,.advertisement,.ad,.ads,[class*="cookie"],[class*="popup"],[class*="modal"],[class*="overlay"],script,style,noscript,iframe';
248
+ clone.querySelectorAll(noise).forEach(node => node.remove());
249
+ clone.querySelectorAll('a[href],img[src]').forEach(node => {
250
+ const attr = node.tagName === 'A' ? 'href' : 'src';
251
+ try { node.setAttribute(attr, new URL(node.getAttribute(attr), document.baseURI).href); } catch { /* Keep unresolvable links verbatim. */ }
252
+ });
253
+ let main = scoped ? clone : (clone.querySelector('main') || clone.querySelector('article') || clone.querySelector('[role="main"]') || clone);
254
+ if (dense === true && !scoped && main === clone) {
255
+ const prose = node => { let n = 0; for (const p of node.querySelectorAll('p')) n += (p.textContent || '').trim().length; return n; };
256
+ const total = prose(clone);
257
+ if (total >= 500) {
258
+ let best = null, bestDensity = 0;
259
+ for (const block of clone.querySelectorAll('div,section')) {
260
+ const inside = prose(block);
261
+ if (inside < total * 0.6) continue;
262
+ const density = inside / Math.max(1, (block.textContent || '').length);
263
+ if (density >= bestDensity) { best = block; bestDensity = density; }
264
+ }
265
+ if (best) main = best;
266
+ }
267
+ }
268
+ return scoped ? main.outerHTML : main.innerHTML;
269
+ }
270
+
235
271
  /** Scoped HTML reader: clone before cleaning, and retain link source URLs. */
236
272
  export async function readBrowserContentHtml(page, selector) {
237
273
  const target = page.locator(selector || 'body');
238
274
  if (selector && await target.count() !== 1) throw new Error('Content selector must match exactly one element.');
239
- return target.evaluate((element, scoped) => {
240
- const clone = element.cloneNode(true);
241
- const noise = scoped
242
- ? 'script,style,noscript,iframe'
243
- : 'nav,header,footer,aside,[role="navigation"],[role="banner"],[role="contentinfo"],[role="complementary"],.sidebar,.nav,.footer,.header,.advertisement,.ad,.ads,[class*="cookie"],[class*="popup"],[class*="modal"],[class*="overlay"],script,style,noscript,iframe';
244
- clone.querySelectorAll(noise).forEach(node => node.remove());
245
- clone.querySelectorAll('a[href],img[src]').forEach(node => {
246
- const attr = node.tagName === 'A' ? 'href' : 'src';
247
- try { node.setAttribute(attr, new URL(node.getAttribute(attr), document.baseURI).href); } catch { /* Keep unresolvable links verbatim. */ }
248
- });
249
- const main = scoped ? clone : (clone.querySelector('main') || clone.querySelector('article') || clone.querySelector('[role="main"]') || clone);
250
- return scoped ? main.outerHTML : main.innerHTML;
251
- }, !!selector);
275
+ return target.evaluate(contentHtmlOf, !!selector);
252
276
  }