synabun 2.4.2 → 2.4.4

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 (220) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +83 -34
  4. package/lib/release-npm-ci.mjs +23 -1
  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 +11 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -18
  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 +3 -1
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +11 -6
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  35. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  37. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-observe.js +113 -27
  39. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  40. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  41. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  42. package/mcp-server/dist/tools/browser-readers.js +17 -0
  43. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  44. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/remember.js +6 -2
  46. package/mcp-server/dist/tools/remember.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  48. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  50. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  52. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  54. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  56. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  57. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  58. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  59. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  60. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  61. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  62. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  64. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  65. package/mcp-server/package-lock.json +5 -5
  66. package/mcp-server/package.json +1 -1
  67. package/mcp-server/src/http.ts +8 -1
  68. package/mcp-server/src/services/identity.ts +5 -0
  69. package/mcp-server/src/services/memory-client.ts +32 -12
  70. package/mcp-server/src/services/memory-writer.ts +5 -2
  71. package/mcp-server/src/services/neural-interface.ts +66 -19
  72. package/mcp-server/src/services/typesafe-config.ts +268 -7
  73. package/mcp-server/src/tools/agents.ts +12 -6
  74. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  75. package/mcp-server/src/tools/browser-observe.ts +117 -28
  76. package/mcp-server/src/tools/browser-readers.ts +19 -0
  77. package/mcp-server/src/tools/remember.ts +6 -1
  78. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  79. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  80. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  81. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  82. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  83. package/neural-interface/i18n/en.json +189 -1
  84. package/neural-interface/i18n/pt-BR.json +196 -8
  85. package/neural-interface/lib/assistant-api.js +123 -0
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  88. package/neural-interface/lib/assistant-dispatch.js +302 -44
  89. package/neural-interface/lib/assistant-envelope.js +40 -0
  90. package/neural-interface/lib/assistant-memory.js +3 -1
  91. package/neural-interface/lib/assistant-persona.js +6 -0
  92. package/neural-interface/lib/assistant-router.js +18 -8
  93. package/neural-interface/lib/assistant-runtime.js +182 -11
  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-extension-adapter.js +221 -17
  97. package/neural-interface/lib/browser-extension-archive.js +149 -0
  98. package/neural-interface/lib/browser-extension-bridge.js +46 -10
  99. package/neural-interface/lib/browser-extension-folder.js +635 -76
  100. package/neural-interface/lib/browser-extension-package.js +201 -0
  101. package/neural-interface/lib/browser-extension-pin.js +84 -0
  102. package/neural-interface/lib/browser-extension-pin.json +35 -0
  103. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
  104. package/neural-interface/lib/browser-extension-setup.js +108 -19
  105. package/neural-interface/lib/browser-extension-update.js +104 -0
  106. package/neural-interface/lib/browser-extraction.js +38 -14
  107. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  108. package/neural-interface/lib/claude-history.js +12 -1
  109. package/neural-interface/lib/cli-install.js +23 -3
  110. package/neural-interface/lib/cli-update-planner.js +67 -4
  111. package/neural-interface/lib/confined-fs.js +25 -0
  112. package/neural-interface/lib/coordination/operations.js +2 -0
  113. package/neural-interface/lib/db.js +39 -16
  114. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  115. package/neural-interface/lib/git-bash/manager.js +28 -3
  116. package/neural-interface/lib/git-status-runner.js +31 -3
  117. package/neural-interface/lib/loop-inventory.js +162 -0
  118. package/neural-interface/lib/loop-stall.js +74 -4
  119. package/neural-interface/lib/memory-session-capture.js +157 -66
  120. package/neural-interface/lib/native-loop-providers.js +82 -13
  121. package/neural-interface/lib/native-loop-runtime.js +23 -2
  122. package/neural-interface/lib/opencode-protocol.js +4 -2
  123. package/neural-interface/lib/opencode-shell-read.js +107 -0
  124. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  125. package/neural-interface/lib/opencode-turn-release.js +173 -0
  126. package/neural-interface/lib/opencode-v2-client.js +4 -1
  127. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  128. package/neural-interface/lib/opencode2-client.js +341 -6
  129. package/neural-interface/lib/opencode2-translate.js +161 -4
  130. package/neural-interface/lib/peer-identity.js +62 -16
  131. package/neural-interface/lib/session-cache-builder.js +66 -18
  132. package/neural-interface/lib/session-capture-gate.js +42 -0
  133. package/neural-interface/lib/session-indexer.js +28 -20
  134. package/neural-interface/lib/teams/scheduler.js +3 -2
  135. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  136. package/neural-interface/lib/ui-blob-api.js +14 -5
  137. package/neural-interface/lib/ui-blob-store.js +302 -39
  138. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  139. package/neural-interface/package-lock.json +5 -5
  140. package/neural-interface/package.json +1 -1
  141. package/neural-interface/public/extension-setup.html +6 -2
  142. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  143. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  144. package/neural-interface/public/shared/assistant/asst-api.js +67 -0
  145. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  146. package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
  147. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  148. package/neural-interface/public/shared/assistant/asst-render.js +343 -10
  149. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  150. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  151. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  152. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  153. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  154. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  155. package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
  156. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  157. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  158. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  159. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  160. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  161. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  162. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  163. package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
  164. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  165. package/neural-interface/public/shared/extension-update-view.js +34 -0
  166. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  167. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  168. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  169. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  170. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  171. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  172. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  173. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  174. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  175. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
  176. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  177. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  178. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  179. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  180. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  181. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  182. package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
  183. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  184. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  185. package/neural-interface/public/shared/styles.css +4 -0
  186. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  187. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  188. package/neural-interface/public/shared/ui-claude-panel.js +130 -1
  189. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  190. package/neural-interface/public/shared/ui-notifications.js +23 -4
  191. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  192. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  193. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  194. package/neural-interface/public/shared/worker-end.js +18 -0
  195. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  196. package/neural-interface/scripts/rebuild-pty.js +10 -0
  197. package/neural-interface/server.js +725 -308
  198. package/npm-shrinkwrap.json +5 -5
  199. package/package.json +1 -2
  200. package/browser-extension/content.js +0 -231
  201. package/browser-extension/engine.js +0 -658
  202. package/browser-extension/icons/icon-128.png +0 -0
  203. package/browser-extension/icons/icon-16.png +0 -0
  204. package/browser-extension/icons/icon-32.png +0 -0
  205. package/browser-extension/icons/icon-48.png +0 -0
  206. package/browser-extension/icons/status-off-16.png +0 -0
  207. package/browser-extension/icons/status-off-32.png +0 -0
  208. package/browser-extension/icons/status-off-48.png +0 -0
  209. package/browser-extension/icons/status-on-16.png +0 -0
  210. package/browser-extension/icons/status-on-32.png +0 -0
  211. package/browser-extension/icons/status-on-48.png +0 -0
  212. package/browser-extension/manifest.json +0 -58
  213. package/browser-extension/popup-strings.js +0 -250
  214. package/browser-extension/popup-view.js +0 -151
  215. package/browser-extension/popup.css +0 -166
  216. package/browser-extension/popup.html +0 -108
  217. package/browser-extension/popup.js +0 -359
  218. package/browser-extension/service-worker.js +0 -283
  219. package/browser-extension/setup-content.js +0 -36
  220. package/browser-extension/tokens.css +0 -326
@@ -134,6 +134,7 @@ import * as fsp from 'fs/promises';
134
134
  import { createInterface as createReadlineInterface } from 'readline';
135
135
  import { jsonlLines } from './lib/jsonl-lines.js';
136
136
  import { createHistoryCache } from './lib/claude-history-cache.js';
137
+ import { createClaudeBgTasks, claudeOutputRoots } from './lib/claude-bg-tasks.js';
137
138
  import { createRolloutReader } from './lib/codex-rollout-reader.js';
138
139
  import { randomBytes, randomUUID, createHash, pbkdf2Sync, createDecipheriv } from 'crypto';
139
140
  import { exec, execFile, execSync, spawn, spawnSync } from 'child_process';
@@ -167,7 +168,9 @@ import {
167
168
  buildInstallCommand,
168
169
  buildUpdateCommand,
169
170
  isBrewSource,
171
+ OPENCODE_WINGET_SEARCH_ARGS,
170
172
  parseBrewOutdated,
173
+ parseWingetSearchVersion,
171
174
  quoteCommandPath,
172
175
  resolveBrewToken,
173
176
  resolveLatest,
@@ -213,6 +216,7 @@ import * as opencodeV2Client from './lib/opencode-v2-client.js';
213
216
  import { OPENCODE_MIN_VERSION, basicAuthHeader, checkPrivateOpencodeServer as checkOpencodeServer, createServeLogRedactor, opencodeInstallCommands, opencodeProblemText, opencodeSupportFor, redactServeOutput, servePasswordReader, serveSpecFor, serveUnsetCommand, withServeEnv } from './lib/opencode-protocol.js';
214
217
  import { SERVE_TOKEN_ENV } from './lib/process-identity.js';
215
218
  import { commandArgs, createServeRecords } from './lib/opencode-serve-records.js';
219
+ import { activeOpencodeSessions, binaryFileKey as opencodeBinaryFileKey, createServeEnds, staleServePlan } from './lib/opencode-turn-release.js';
216
220
  import { opencode2Proxy } from './lib/opencode2-proxy.js';
217
221
  import { macScreenshotDir } from './lib/screenshot-location.js';
218
222
  import { integrationCredentialIds, integrationsWithCredentials } from './lib/opencode2-translate.js';
@@ -228,6 +232,7 @@ import {
228
232
  handleOpencodeV2Request, opencodeV2WsCapabilities,
229
233
  buildSessionListQuery, mapSessionListRow, OPENCODE_V2_WS_MUTATION_TYPES, guardOpencodeV2Request, folderIsGone,
230
234
  } from './lib/opencode-v2-ws-requests.js';
235
+ import { createStopFailures } from './lib/opencode-stop-failures.js';
231
236
  import { NativeLoopRuntime, isNativeLoopProfile } from './lib/native-loop-runtime.js';
232
237
  import { scheduleScratchRetention } from './lib/scratch-retention.js';
233
238
  import { migrateAutomationContextFiles, normalizeAutomationRecord } from './lib/automation-storage-migration.js';
@@ -313,8 +318,9 @@ import {
313
318
  import * as moreLogin from './lib/browser-profiles.js';
314
319
  import { createStyleGuideStore } from './lib/style-guide/store.js';
315
320
  import { registerStyleGuideRoutes } from './lib/style-guide/api.js';
316
- import { initBlobStore, blobGetNamespace, blobGet, blobPut, blobDelete, blobClearNamespace, blobPrune, closeBlobStore } from './lib/ui-blob-store.js';
321
+ import { initBlobStore, blobGetNamespace, blobGetNamespaceJsonAsync, blobGet, blobPut, blobDelete, blobClearNamespace, blobPrune, closeBlobStore } from './lib/ui-blob-store.js';
317
322
  import { createUiBlobRouter } from './lib/ui-blob-api.js';
323
+ import { createLoopInventoryScanner } from './lib/loop-inventory.js';
318
324
  import { memoCache, asyncPool } from './lib/memo-cache.js';
319
325
  import {
320
326
  buildAntigravityMcpEntry,
@@ -697,11 +703,14 @@ import { createOpencodeCompletionEngine } from './lib/editor-completion-opencode
697
703
  import { createEndpointCompletionEngine } from './lib/editor-completion-endpoint.js';
698
704
  import { ownerRouteGuard } from './lib/http-guards.js';
699
705
  import { createBridgeStore, createExtensionBridge } from './lib/browser-extension-bridge.js';
700
- import { createExtensionAdapter, EXTENSION_FOLDER } from './lib/browser-extension-adapter.js';
706
+ import { createExtensionAdapter } from './lib/browser-extension-adapter.js';
701
707
  import { detectBrowsers } from './lib/browser-default.js';
702
- import { extensionFolderState, prepareExtensionFolder } from './lib/browser-extension-folder.js';
703
- import { createExtensionSetup, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
704
- import { safeError as extensionSafeError } from '../browser-extension/protocol.js';
708
+ import { compareVersions } from './lib/browser-extension-folder.js';
709
+ import { createExtensionPackage } from './lib/browser-extension-package.js';
710
+ import { createExtensionUpdate, ownerReloadHandler } from './lib/browser-extension-update.js';
711
+ import { createExtensionSetup, extensionVersions, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
712
+ import { stoppedProfileAdvice } from './lib/browser-connection-state.js';
713
+ import { safeError as extensionSafeError } from './lib/browser-extension-protocol.js';
705
714
  import { setUntrustedFileHeaders } from './lib/untrusted-file-headers.js';
706
715
  import { BUNDLED_LOGO_FILES, UPLOADED_IMAGE_PATH } from './lib/request-gate.js';
707
716
  import { createCloudflaredManager } from './lib/cloudflared/manager.js';
@@ -2583,6 +2592,10 @@ async function runGracefulShutdown(reason) {
2583
2592
 
2584
2593
  // 1. opencode sidecar — has its own teardown that handles managed PID + ollama.
2585
2594
  try { stopOpencodeServer(); } catch (err) { console.warn(' opencode stop err:', err?.message); }
2595
+ // The serves stopped above interrupt the turns still running on them before their processes end
2596
+ // (lib/opencode-turn-release.js). Waited for here, bounded, so that the exit does not cut that short and leave a
2597
+ // session claimed for OpenCode's own background service to resume.
2598
+ try { await _ocpServeEnds.settled(); } catch (err) { console.warn(' opencode serve end err:', err?.message); }
2586
2599
 
2587
2600
  // 2. Agents in agentRegistry — use platform-native tree kill so descendants die too.
2588
2601
  try {
@@ -3800,8 +3813,12 @@ function claudeChildEnv(env = process.env) {
3800
3813
  try { return gitBash.childEnv(ordered); } catch { return ordered; }
3801
3814
  }
3802
3815
  // SynaBun's own git features (the terminal's branch and checkout, the File Explorer's and the code editor's git,
3803
- // the git routes) run the copy's git.exe on a PC without git: its path for spawnGit, its folder for every read.
3804
- setGitFallbackFolder(() => { const git = gitBash.gitExecutable(); return git ? dirname(git) : null; });
3816
+ // the git routes) resolve git through one resolver (bundled → managed → system) for both startup and the runner.
3817
+ setGitFallbackFolder(() => {
3818
+ const git = gitBash.managedGitExecutable?.() || gitBash.gitExecutable({ includeSystem: true });
3819
+ return git ? dirname(git) : null;
3820
+ });
3821
+ gitStatusRunner.setBinaryResolver(() => resolveGitPathInBackground());
3805
3822
  // The user's own `claude`, started in another terminal: ~/.claude/settings.json names SynaBun's copy while it is
3806
3823
  // the one in use and loses that value when it is not; a value of the user's own is never touched. Windows only.
3807
3824
  function syncGitBashSettings(resolution = gitBash.resolution()) {
@@ -3991,9 +4008,10 @@ async function detectOpencode({ force = false } = {}) {
3991
4008
  // OpenCode 2). Every start path throws it or answers with it: isolated serves, loops and schedules, workers.
3992
4009
  async function opencodeStartRefusal() {
3993
4010
  const detected = await detectOpencode();
3994
- if (detected.major == null || detected.supported) return null;
3995
- const refusal = new Error(detected.reason);
3996
- refusal.code = 'OPENCODE_UNSUPPORTED';
4011
+ if (detected.supported) return null;
4012
+ if (detected.major == null && (detected.path || detected.commandLine)) return null;
4013
+ const refusal = new Error(detected.reason || 'OpenCode is not installed.');
4014
+ refusal.code = detected.major == null ? 'OPENCODE_NOT_INSTALLED' : 'OPENCODE_UNSUPPORTED';
3997
4015
  return refusal;
3998
4016
  }
3999
4017
 
@@ -8423,6 +8441,16 @@ const opencodeServeRecords = createServeRecords({
8423
8441
  migrateOpencodeManagedPid();
8424
8442
  let _ocpBootReconcileTried = false;
8425
8443
  let _ocpLastBootAt = 0; // Date.now() when serve process last became ready
8444
+ // The file SynaBun's shared serve was started from (lib/opencode-turn-release.js binaryFileKey), while SynaBun's own
8445
+ // child runs it: an OpenCode update replaces the file on disk and leaves this serve on the old program.
8446
+ let _ocpServeFileKey = null;
8447
+ // The end of the shared serve while its turns are still being released: a new start waits for it, so that it never
8448
+ // finds the serve that is being stopped still answering on the port.
8449
+ let _ocpSharedEnd = null;
8450
+ // How SynaBun ends its serves (lib/opencode-turn-release.js): the turns still running on a serve are interrupted
8451
+ // before its process is stopped. A turn left in flight stays claimed in OpenCode's database, and OpenCode's own
8452
+ // background service (a plain `opencode` in a terminal starts it) resumes every such session at its boot.
8453
+ const _ocpServeEnds = createServeEnds({ log: (line) => console.log(`[opencode] ${line}`) });
8426
8454
 
8427
8455
  // ── Verbose trace logging (opt-in: OCP_VERBOSE=1 to enable) ──
8428
8456
  const OCP_VERBOSE = process.env.OCP_VERBOSE === '1';
@@ -9074,6 +9102,8 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
9074
9102
  });
9075
9103
  entry.proc = proc;
9076
9104
  entry.password = launch.password || null;
9105
+ // The file this serve runs: an update of OpenCode makes it a serve of the old program (retireStaleOpencodeServes).
9106
+ entry.fileKey = opencodeBinaryFileKey(launch.nativeServe?.identity);
9077
9107
  // On record from its spawn: a crash of SynaBun from here on does not leave it running for good.
9078
9108
  const tracked = trackOpencodeServe(proc, { kind: 'isolated', id: termId, port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe });
9079
9109
  // While it boots, its start sees an exit itself (another server on the port is a collision); afterwards
@@ -9191,7 +9221,10 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
9191
9221
  }
9192
9222
  }
9193
9223
 
9194
- function stopIsolatedServe(termId, { preserveBindings = false } = {}) {
9224
+ // `immediate`: the process's exit handler, where nothing can be awaited: the serve's process is ended at once.
9225
+ // Otherwise the turns still running on the serve are interrupted first (lib/opencode-turn-release.js, a bounded
9226
+ // wait), so that none of its sessions stays claimed in OpenCode's database; everything else here is done at once.
9227
+ function stopIsolatedServe(termId, { preserveBindings = false, immediate = false } = {}) {
9195
9228
  const entry = _ocpIsoServes.get(termId);
9196
9229
  if (entry?.xdgRoot) _externalMcpLogValues.delete(entry.xdgRoot);
9197
9230
  if (!entry) return;
@@ -9208,12 +9241,20 @@ function stopIsolatedServe(termId, { preserveBindings = false } = {}) {
9208
9241
  }
9209
9242
  try { entry.unsub?.(); } catch {}
9210
9243
  try { entry.client?.stop(); } catch {}
9211
- killIsolatedServeProcess(entry.proc);
9244
+ const proc = entry.proc;
9245
+ _ocpServeEnds.end({
9246
+ port: entry.ready ? entry.port : null,
9247
+ password: entry.password || null,
9248
+ alive: () => !!proc && proc.exitCode == null && proc.signalCode == null,
9249
+ kill: () => killIsolatedServeProcess(proc),
9250
+ label: `serve ${String(termId).slice(-8)}`,
9251
+ immediate,
9252
+ });
9212
9253
  try { if (!entry.persistentData && entry.xdgRoot && existsSync(entry.xdgRoot)) rmSync(entry.xdgRoot, { recursive: true, force: true }); } catch {}
9213
9254
  }
9214
9255
 
9215
- function stopAllIsolatedServes() {
9216
- for (const termId of [..._ocpIsoServes.keys()]) stopIsolatedServe(termId);
9256
+ function stopAllIsolatedServes({ immediate = false } = {}) {
9257
+ for (const termId of [..._ocpIsoServes.keys()]) stopIsolatedServe(termId, { immediate });
9217
9258
  }
9218
9259
 
9219
9260
  // Resolve the client to run a TURN for a session. Every sidepanel session gets
@@ -9393,7 +9434,62 @@ setInterval(() => {
9393
9434
  }
9394
9435
  }, 60 * 1000).unref?.();
9395
9436
 
9396
- process.once('exit', stopAllIsolatedServes);
9437
+ // Whether an isolated serve is in use right now (the reaper's own rule): a live run or brain keeps it, a turn runs
9438
+ // on it, or it is still starting.
9439
+ function isolatedServeBusy(termId, entry) {
9440
+ if (entry.keepAlive && (_nativeLoopRuntime?.isAlive(termId) || _assistantRuntime?.ownsIsolatedServe?.(termId))) return true;
9441
+ if (entry.starting || !entry.ready) return true;
9442
+ if ([..._ocpSessionServeStarts.values()].some((pending) => pending.termId === termId)) return true;
9443
+ return [...entry.sessions].some((sessionId) => _ocpActiveSessionTurns.has(sessionId));
9444
+ }
9445
+
9446
+ // The file of the OpenCode SynaBun would start now, as a key. null (nothing is decided) when Settings names a
9447
+ // command line (which runs whatever it names), while the file has not answered `--version` yet (an update still
9448
+ // being written; the resolver asks in the background and the next look knows), and for an OpenCode SynaBun does not
9449
+ // drive: a serve that works is never stopped for one that would be refused.
9450
+ function currentOpencodeFileKey() {
9451
+ if (configuredCommandLine('opencode')) return null;
9452
+ const found = cliResolver.launcher('opencode');
9453
+ if (found.state !== 'installed' || !opencodeSupportFor(found.version, { path: found.path }).supported) return null;
9454
+ return opencodeBinaryFileKey(opencodeBinaryIdentity(found.launchPath || found.path || null));
9455
+ }
9456
+
9457
+ // OpenCode was updated while SynaBun runs (its badge, `opencode upgrade` in a terminal, OpenCode's own updater):
9458
+ // the file on disk is the new program, and the serves SynaBun started before still run the old one. The shared
9459
+ // serve is restarted once it runs no turn, and a session's serve that is not in use is stopped (the session's next
9460
+ // message starts one, as after the idle reaper). A serve in use is left for the next look. Looked at after every
9461
+ // check of the CLI versions and once a minute while a serve of SynaBun's runs.
9462
+ let _ocpRetireInFlight = null;
9463
+ function retireStaleOpencodeServes(reason = 'watch') {
9464
+ if (_ocpRetireInFlight) return _ocpRetireInFlight;
9465
+ _ocpRetireInFlight = (async () => {
9466
+ if (_ocpHistoryClearInProgress || (!_ocpProc && _ocpIsoServes.size === 0)) return null;
9467
+ let current = null;
9468
+ try { current = currentOpencodeFileKey(); } catch { current = null; }
9469
+ const plan = staleServePlan({
9470
+ current,
9471
+ shared: { key: _ocpServeFileKey, managed: !!_ocpProc, ready: _ocpReady, starting: _ocpStarting },
9472
+ isolated: [..._ocpIsoServes].map(([termId, entry]) => ({ termId, key: entry.fileKey || null, busy: isolatedServeBusy(termId, entry) })),
9473
+ });
9474
+ for (const termId of plan.isolated) {
9475
+ console.log(`[ocp-iso] OpenCode on disk changed: stopping serve ${String(termId).slice(-8)}, which runs the earlier program (${reason}); its session's next message starts a new one`);
9476
+ stopIsolatedServe(termId);
9477
+ }
9478
+ if (plan.shared === 'restart') {
9479
+ const turns = await activeOpencodeSessions({ port: _ocpPort, password: _ocpPassword });
9480
+ // Asked again after the wait: a stop or a restart meanwhile has already replaced it.
9481
+ if (turns.ok && !turns.ids.length && _ocpProc && _ocpReady && !_ocpStarting && _ocpServeFileKey && _ocpServeFileKey !== current) {
9482
+ console.log(`[opencode] OpenCode on disk changed: restarting SynaBun's shared serve, which runs the earlier program (v${_ocpVersion || '?'}; ${reason})`);
9483
+ try { await takeoverOpencodeServer(); } catch (error) { console.warn(`[opencode] shared serve restart after an OpenCode update failed: ${error?.message || error}`); }
9484
+ }
9485
+ }
9486
+ return plan;
9487
+ })().catch(() => null).finally(() => { _ocpRetireInFlight = null; });
9488
+ return _ocpRetireInFlight;
9489
+ }
9490
+ setInterval(() => { retireStaleOpencodeServes('watch'); }, 60 * 1000).unref?.();
9491
+
9492
+ process.once('exit', () => { stopAllIsolatedServes({ immediate: true }); _ocpServeEnds.killNow(); });
9397
9493
 
9398
9494
  // ── Antigravity side panel (/ws/antigravity) ──
9399
9495
  // One `agy acp` (Google's Antigravity ACP server) per panel socket, one ACP session per tab
@@ -9468,6 +9564,10 @@ function handleOpencodeV2Ws(ws) {
9468
9564
 
9469
9565
  // Track in-flight prompts so a fresh send can abort the previous turn cleanly.
9470
9566
  const sendAborts = new Map(); // sessionID → AbortController
9567
+ // Stops that could not end a command of the turn (lib/opencode-stop-failures.js): from the second one on the panel
9568
+ // offers "Stop anyway" (message:abort with `force`). A new turn starts the count again; an entry goes with its
9569
+ // turn, its session and this socket.
9570
+ const stopFailures = createStopFailures({ activeTurn: (sid) => _ocpActiveSessionTurns.get(sid) });
9471
9571
 
9472
9572
  const send = (data) => {
9473
9573
  if (ws.readyState === 1) {
@@ -9507,6 +9607,7 @@ function handleOpencodeV2Ws(ws) {
9507
9607
  end() {
9508
9608
  if (_ocpActiveSessionTurns.get(sid) === token) _ocpActiveSessionTurns.delete(sid);
9509
9609
  if (sendAborts.get(sid) === ctrl) sendAborts.delete(sid);
9610
+ stopFailures.prune();
9510
9611
  },
9511
9612
  };
9512
9613
  },
@@ -9632,6 +9733,7 @@ function handleOpencodeV2Ws(ws) {
9632
9733
  _ocpSessionToServe.delete(msg.sessionId);
9633
9734
  _ocpSessionTools.delete(msg.sessionId);
9634
9735
  _ocpActiveSessionTurns.delete(msg.sessionId);
9736
+ stopFailures.clear(msg.sessionId);
9635
9737
  if (entry && entry.sessions.size === 0) stopIsolatedServe(termId);
9636
9738
  send({ type: 'session:delete:result', id, status: r.status, data: r.data });
9637
9739
  break;
@@ -9734,19 +9836,43 @@ function handleOpencodeV2Ws(ws) {
9734
9836
  _ocpActiveSessionTurns.delete(sid);
9735
9837
  }
9736
9838
  if (sendAborts.get(sid) === ctrl) sendAborts.delete(sid);
9839
+ // A turn that ended (or was replaced by this one) takes its failed Stops along.
9840
+ stopFailures.prune();
9737
9841
  }
9738
9842
  break;
9739
9843
  }
9740
9844
  case 'message:abort': {
9741
9845
  const sid = msg.sessionId;
9742
- const ctrl = sendAborts.get(sid);
9743
- if (ctrl) { try { ctrl.abort(); } catch {} sendAborts.delete(sid); }
9846
+ // `force`: "Stop anyway", offered after a second failed Stop. The turn ends even while a command OpenCode
9847
+ // could not end may still run (its removal goes on in the background, lib/opencode2-client.js).
9848
+ const force = msg.force === true;
9849
+ const bound = boundIsoClient(sid);
9850
+ const endSend = () => {
9851
+ const ctrl = sendAborts.get(sid);
9852
+ if (ctrl) { try { ctrl.abort(); } catch {} sendAborts.delete(sid); }
9853
+ };
9854
+ // A Stop with a command to end can fail, and then the turn goes on: the prompt's wait (`sendAborts`) is
9855
+ // ended only once the stop worked. With none, as always: the wait ends first.
9856
+ const mayFail = !force && bound?.getClient?.()?.stopNeedsKill?.(sid) === true;
9857
+ if (!mayFail) endSend();
9744
9858
  try {
9745
- await boundIsoClient(sid).session.abort({ sessionID: sid });
9859
+ const r = await bound.session.abort({ sessionID: sid, ...(force ? { force: true } : {}) });
9860
+ endSend();
9746
9861
  _ocpActiveSessionTurns.delete(sid);
9747
- send({ type: 'message:abort:result', id, ok: true });
9862
+ stopFailures.clear(sid);
9863
+ const abandoned = Array.isArray(r?.data?.abandoned) ? r.data.abandoned : [];
9864
+ send({ type: 'message:abort:result', id, ok: true, ...(abandoned.length ? { abandoned } : {}) });
9748
9865
  } catch (err) {
9749
- send({ type: 'message:abort:result', id, ok: false, error: err?.message });
9866
+ if (err?.cause?.name === 'ShellStopFailed') {
9867
+ // A command Stop could not end still runs (lib/opencode2-client.js abortSession): the turn goes on,
9868
+ // and the panel says so instead of showing it stopped; from the second failure it offers Stop anyway.
9869
+ const count = stopFailures.fail(sid);
9870
+ const shells = Array.isArray(err?.data?.shells) ? err.data.shells : [];
9871
+ send({ type: 'message:abort:result', id, ok: false, error: err?.message, code: 'SHELL_STOP_FAILED', shells, failures: count, canForce: count >= 2 });
9872
+ } else {
9873
+ endSend();
9874
+ send({ type: 'message:abort:result', id, ok: false, error: err?.message });
9875
+ }
9750
9876
  }
9751
9877
  break;
9752
9878
  }
@@ -9790,6 +9916,7 @@ function handleOpencodeV2Ws(ws) {
9790
9916
  _ocpV2WsClients.delete(ws);
9791
9917
  for (const ctrl of sendAborts.values()) { try { ctrl.abort(); } catch {} }
9792
9918
  sendAborts.clear();
9919
+ stopFailures.clearAll();
9793
9920
  console.log(`[ocp-v2-ws] close conn=${connId} total=${_ocpV2WsClients.size}`);
9794
9921
  });
9795
9922
 
@@ -9804,7 +9931,7 @@ function handleOpencodeV2Ws(ws) {
9804
9931
  // `_ocpLastCheck` keeps the whole answer (what answered, and why it is not usable).
9805
9932
  let _ocpLastCheck = null;
9806
9933
  async function checkOpencodeHealth() {
9807
- const check = await checkOpencodeServer({ port: _ocpPort, password: _ocpPassword, timeoutMs: 3000 });
9934
+ const check = await checkOpencodeServer({ port: _ocpPort, password: _ocpPassword, timeoutMs: 3000, signal: arguments[0]?.signal || null });
9808
9935
  _ocpLastCheck = check;
9809
9936
  if (check.ok) _ocpVersion = check.version || null;
9810
9937
  return check.ok;
@@ -9923,13 +10050,15 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9923
10050
  return false;
9924
10051
  }
9925
10052
  _ocpStarting = true;
10053
+ if (_ocpSharedEnd) await _ocpSharedEnd;
9926
10054
 
9927
10055
  // 0. Which OpenCode is installed. One SynaBun does not drive (OpenCode 1, an OpenCode 2 older than the
9928
- // minimum) is refused here, with a sentence the panel and Settings show, instead of failing call by call later.
10056
+ // minimum) or a missing CLI is refused here, with a sentence the panel and Settings show, instead of
10057
+ // spawning a shell that exits immediately and waiting 15 s for health.
9929
10058
  const detected = await detectOpencode();
9930
- if (detected.major != null && !detected.supported) {
10059
+ if (!detected.supported && (detected.major != null || (!detected.path && !detected.commandLine))) {
9931
10060
  _ocpStarting = false;
9932
- reportOpencodeProblem(detected.reason);
10061
+ reportOpencodeProblem(detected.reason || 'OpenCode is not installed.');
9933
10062
  return false;
9934
10063
  }
9935
10064
  _ocpProblem = null;
@@ -9971,6 +10100,17 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9971
10100
  outcome = await oneOpencodeStartAtATime(async () => {
9972
10101
  let proc = null;
9973
10102
  let tracked = null;
10103
+ let procExited = false;
10104
+ let procExitCode = null;
10105
+ let procExitSignal = null;
10106
+ let procError = null;
10107
+ const exitWaiters = new Set();
10108
+ const exitAbort = new AbortController();
10109
+ const wakeExitWaiters = () => {
10110
+ if (!exitAbort.signal.aborted) exitAbort.abort();
10111
+ for (const fn of exitWaiters) fn();
10112
+ exitWaiters.clear();
10113
+ };
9974
10114
  try {
9975
10115
  // A token of this spawn in its environment: what tells its processes from any other (lib/opencode-serve-records.js).
9976
10116
  const token = opencodeServeRecords.newToken();
@@ -9986,6 +10126,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
9986
10126
  shell: false,
9987
10127
  });
9988
10128
  _ocpProc = proc;
10129
+ _ocpServeFileKey = opencodeBinaryFileKey(launch.nativeServe?.identity);
9989
10130
  // On record from its spawn: a crash of SynaBun from here on does not leave it running for good.
9990
10131
  tracked = trackOpencodeServe(proc, { kind: 'shared', id: 'shared', port: _ocpPort, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe });
9991
10132
  const readPassword = servePasswordReader();
@@ -10000,12 +10141,27 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10000
10141
  proc.stdout?.on('end', () => outLog.flush());
10001
10142
  proc.stderr?.on('end', () => errLog.flush());
10002
10143
  proc.on('close', () => { outLog.flush(); errLog.flush(); });
10003
- proc.on('exit', (code) => {
10144
+ const childExited = () => proc.exitCode != null || proc.signalCode != null;
10145
+ proc.on('error', (err) => {
10146
+ // Match trackOpencodeServe's rule: a spawn that failed (no pid) may never exit,
10147
+ // whereas an error on a live child (e.g. failed kill) leaves the process running.
10148
+ if (!proc.pid || childExited()) {
10149
+ procExited = true;
10150
+ procError = err;
10151
+ wakeExitWaiters();
10152
+ }
10153
+ });
10154
+ proc.on('exit', (code, signal) => {
10155
+ procExited = true;
10156
+ procExitCode = code;
10157
+ procExitSignal = signal;
10158
+ wakeExitWaiters();
10004
10159
  console.log(`[opencode] Process exited with code ${code}`);
10005
10160
  // A serve stopped or replaced meanwhile says nothing about the one running now. (Its record goes with
10006
10161
  // its process either way: trackOpencodeServe.)
10007
10162
  if (_ocpProc !== proc) return;
10008
10163
  _ocpProc = null;
10164
+ _ocpServeFileKey = null;
10009
10165
  _ocpReady = false;
10010
10166
  opencodeV2Client.disconnect().catch(() => {});
10011
10167
  broadcastToOpencodeV2Clients({ type: 'server:status', status: 'offline', port: _ocpPort });
@@ -10019,9 +10175,19 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10019
10175
  }
10020
10176
  return 'not-spawned';
10021
10177
  }
10178
+ const isGone = () => procExited || proc.exitCode != null || proc.signalCode != null;
10179
+ const waitStep = (ms) => new Promise((done) => {
10180
+ if (isGone()) { done(); return; }
10181
+ const onEnd = () => { clearTimeout(t); done(); };
10182
+ const t = setTimeout(() => { exitWaiters.delete(onEnd); done(); }, ms);
10183
+ exitWaiters.add(onEnd);
10184
+ });
10185
+ let exitedEarly = false;
10022
10186
  for (let i = 0; i < 30; i++) {
10023
- await new Promise(r => setTimeout(r, 500));
10024
- if (await checkOpencodeHealth()) {
10187
+ await waitStep(500);
10188
+ if (isGone()) { exitedEarly = true; break; }
10189
+ if (await checkOpencodeHealth({ signal: exitAbort.signal })) {
10190
+ if (isGone()) { exitedEarly = true; break; }
10025
10191
  // Only SynaBun's own process counts (the spawned one, or one it started): another server that took the
10026
10192
  // port meanwhile answers for itself.
10027
10193
  if (await tracked.answering({ password: _ocpPassword }) !== 'foreign') return 'ready';
@@ -10030,9 +10196,17 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10030
10196
  await endOpencodeChild(proc);
10031
10197
  return 'collision';
10032
10198
  }
10199
+ if (isGone()) { exitedEarly = true; break; }
10033
10200
  // Something answers, but not as SynaBun expects (a version it does not drive, a web page): no use waiting.
10034
10201
  if (_ocpLastCheck && ['unsupported', 'html', 'locked'].includes(_ocpLastCheck.state) && i >= 3) break;
10035
10202
  }
10203
+ if (exitedEarly) {
10204
+ if (_ocpProc === proc) _ocpProc = null;
10205
+ const detail = procError
10206
+ ? (procError.code || procError.message || 'spawn error')
10207
+ : (procExitCode != null ? `code ${procExitCode}` : (procExitSignal || 'exited'));
10208
+ return `exited:${detail}`;
10209
+ }
10036
10210
  stopOpencodeServer();
10037
10211
  await endOpencodeChild(proc);
10038
10212
  return 'unhealthy';
@@ -10057,21 +10231,28 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10057
10231
  return true;
10058
10232
  }
10059
10233
 
10234
+ const exitedDetail = typeof outcome === 'string' && outcome.startsWith('exited:') ? outcome.slice('exited:'.length) : null;
10060
10235
  const why = outcome === 'collision'
10061
10236
  ? `Another server took port ${_ocpPort} while SynaBun's OpenCode serve was starting, on every port it tried; it is left running.`
10062
- : _ocpLastCheck && _ocpLastCheck.state !== 'down'
10063
- ? opencodeProblemText({ check: _ocpLastCheck, port: _ocpPort })
10064
- : 'OpenCode did not start within 15 seconds.';
10237
+ : exitedDetail != null
10238
+ ? `OpenCode exited before becoming healthy (${exitedDetail}).`
10239
+ : _ocpLastCheck && _ocpLastCheck.state !== 'down'
10240
+ ? opencodeProblemText({ check: _ocpLastCheck, port: _ocpPort })
10241
+ : 'OpenCode did not start within 15 seconds.';
10065
10242
  console.error(`[opencode] Server did not become healthy: ${why}`);
10066
10243
  _ocpStarting = false;
10067
10244
  reportOpencodeProblem(why);
10068
10245
  return false;
10069
10246
  }
10070
10247
 
10071
- function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10248
+ // Returns a promise of the end of SynaBun's own child when its turns are released first (a bounded wait,
10249
+ // lib/opencode-turn-release.js), else null: its process was ended at once. `immediate`: the process's exit handler,
10250
+ // where nothing can be awaited.
10251
+ function stopOpencodeServer({ stopManagedOllama = true, immediate = false } = {}) {
10072
10252
  opencodeV2Client.disconnect().catch(() => {});
10073
10253
  const procPid = _ocpProc?.pid || null;
10074
10254
  const isWin = process.platform === 'win32';
10255
+ let ended = null;
10075
10256
 
10076
10257
  // On Windows `process.kill(pid, 'SIGTERM')` is unreliable for non-Node
10077
10258
  // children (cmd.exe shells, opencode native binaries). Use taskkill /T /F
@@ -10088,12 +10269,26 @@ function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10088
10269
  };
10089
10270
 
10090
10271
  if (_ocpProc && !_ocpProc.killed) {
10091
- if (isWin && procPid) {
10092
- winKill(procPid);
10093
- } else {
10094
- try { _ocpProc.kill(); } catch {}
10272
+ const proc = _ocpProc;
10273
+ ended = _ocpServeEnds.end({
10274
+ // Only a serve that answered can be asked for its turns; one that never became healthy has none.
10275
+ port: _ocpReady ? _ocpPort : null,
10276
+ password: _ocpPassword,
10277
+ alive: () => proc.exitCode == null && proc.signalCode == null,
10278
+ kill: () => {
10279
+ if (isWin && procPid) winKill(procPid);
10280
+ else { try { proc.kill(); } catch {} }
10281
+ },
10282
+ label: 'shared serve',
10283
+ immediate,
10284
+ });
10285
+ if (ended) {
10286
+ const ending = ended;
10287
+ _ocpSharedEnd = ending;
10288
+ ending.finally(() => { if (_ocpSharedEnd === ending) _ocpSharedEnd = null; });
10095
10289
  }
10096
10290
  _ocpProc = null;
10291
+ _ocpServeFileKey = null;
10097
10292
  }
10098
10293
  // SynaBun's recorded serves (a process its child started that answers on the port; one of an earlier run whose
10099
10294
  // SynaBun has ended), only while the OS still reports each as that very process: a pid another program has by now,
@@ -10112,6 +10307,7 @@ function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10112
10307
  if (stopManagedOllama) {
10113
10308
  try { stopOllama(); } catch {}
10114
10309
  }
10310
+ return ended;
10115
10311
  }
10116
10312
 
10117
10313
  // Takeover: a fresh shared serve that boots from the updated auth/config files. A serve is stopped only when it
@@ -10124,8 +10320,9 @@ function stopOpencodeServer({ stopManagedOllama = true } = {}) {
10124
10320
  async function takeoverOpencodeServer() {
10125
10321
  if (_ocpHistoryClearInProgress) throw new Error('OpenCode history is being cleared');
10126
10322
  if (_ocpProc) {
10127
- // Already managed — simple restart
10128
- stopOpencodeServer();
10323
+ // Already managed — simple restart. The old serve's end is waited for (its turns are released first): the new
10324
+ // start must never find the old one still answering on the port.
10325
+ await stopOpencodeServer();
10129
10326
  await new Promise(r => setTimeout(r, 1000));
10130
10327
  return ensureOpencodeServer();
10131
10328
  }
@@ -12197,7 +12394,7 @@ const editorOwnerGuard = ownerRouteGuard({ isGuestRequest, port: PORT, allowedOr
12197
12394
  // whatever order they arrive; the editor's namespace asks the owner's guard on every route.
12198
12395
  app.use(createUiBlobRouter({
12199
12396
  namespaces: BLOB_NS_ALLOWLIST,
12200
- store: { getNamespace: blobGetNamespace, get: blobGet, put: blobPut, delete: blobDelete, prune: blobPrune },
12397
+ store: { getNamespace: blobGetNamespace, getNamespaceJsonAsync: blobGetNamespaceJsonAsync, get: blobGet, put: blobPut, delete: blobDelete, prune: blobPrune },
12201
12398
  ownerNamespace: EDITOR_BACKUP_NAMESPACE,
12202
12399
  ownerGuard: editorOwnerGuard,
12203
12400
  }));
@@ -14728,60 +14925,10 @@ app.get('/api/loop/active', (req, res) => {
14728
14925
  // Unlike /api/loop/active, this returns ALL loop files (active + inactive)
14729
14926
  // classified by state so the UI can show stale/finished/orphaned entries
14730
14927
  // alongside running ones. Does NOT delete anything (read-only).
14731
- app.get('/api/loop/list', (_req, res) => {
14928
+ app.get('/api/loop/list', async (_req, res) => {
14732
14929
  try {
14733
- if (!existsSync(LOOP_DIR)) return res.json({ loops: [], staleCount: 0 });
14734
- const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep' && !f.startsWith('pending-') && f !== 'active-pointer.json');
14735
- const now = Date.now();
14736
- const loops = [];
14737
- let staleCount = 0;
14738
- for (const f of files) {
14739
- try {
14740
- const filePath = resolve(LOOP_DIR, f);
14741
- const data = JSON.parse(readFileSync(filePath, 'utf-8'));
14742
- const startedAtMs = data.startedAt ? new Date(data.startedAt).getTime() : 0;
14743
- const lastIterAtMs = data.lastIterationAt ? new Date(data.lastIterationAt).getTime() : startedAtMs;
14744
- const elapsedMs = startedAtMs ? now - startedAtMs : 0;
14745
- const stalledMs = lastIterAtMs ? now - lastIterAtMs : 0;
14746
- const terminalAlive = isLoopRuntimeAlive(data);
14747
- const iterDone = (data.currentIteration || 0) >= (data.totalIterations || 0) && (data.totalIterations || 0) > 0;
14748
- let state;
14749
- if (data.active === false) {
14750
- state = 'stale-inactive';
14751
- staleCount++;
14752
- } else if (data.terminalSessionId && !terminalAlive) {
14753
- state = data.runtimeType === 'native' ? 'orphaned-native' : 'orphaned-pty';
14754
- } else if (iterDone) {
14755
- state = 'finished';
14756
- } else {
14757
- state = 'active';
14758
- }
14759
- loops.push({
14760
- sessionId: f.replace('.json', ''),
14761
- terminalSessionId: data.terminalSessionId || null,
14762
- terminalAlive,
14763
- runId: data.runId || null,
14764
- profile: data.profile || null,
14765
- runtimeType: data.runtimeType || 'pty',
14766
- surface: data.surface || 'terminal',
14767
- task: typeof data.task === 'string' ? data.task.slice(0, 200) : '',
14768
- currentIteration: data.currentIteration || 0,
14769
- totalIterations: data.totalIterations || 0,
14770
- startedAt: data.startedAt || null,
14771
- lastIterationAt: data.lastIterationAt || null,
14772
- elapsedMinutes: Math.round(elapsedMs / 60000),
14773
- stalledMinutes: Math.round(stalledMs / 60000),
14774
- stalledMs,
14775
- state,
14776
- browserSessionId: data.browserSessionId || null,
14777
- browserTabId: data.browserTabId || null,
14778
- usesBrowser: !!data.usesBrowser,
14779
- });
14780
- } catch { /* skip corrupt */ }
14781
- }
14782
- // Newest first
14783
- loops.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
14784
- res.json({ loops, staleCount });
14930
+ const inventory = await scanLoopInventory({ includeExtraFields: true });
14931
+ res.json(inventory);
14785
14932
  } catch (err) {
14786
14933
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
14787
14934
  }
@@ -15455,7 +15602,19 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15455
15602
  const fresh = req.body?.reason === 'create';
15456
15603
  // A create that takes over one of the owner's tabs in the everyday browser (extension mode only).
15457
15604
  const takeOverTab = fresh && typeof req.body?.takeOverTab === 'string' && loadBrowserConfig().connectMode === 'extension' ? req.body.takeOverTab : null;
15458
- if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh) {
15605
+ let requestedBrowserSessionId = null;
15606
+ const initial = req.body?.reason === 'initial';
15607
+ if (initial) {
15608
+ const worker = who.status === 'verified' && named && _assistantDispatcher?.optionalBrowserRoute?.(named);
15609
+ if (!worker) return res.status(403).json({ code: 'NOT_OWNED', error: 'Only the active worker can open its first browser tab.' });
15610
+ requestedBrowserSessionId = worker.requestedBrowserSessionId || null;
15611
+ if (worker.sessionId) {
15612
+ const current = liveAutomationRoute(named);
15613
+ if (!current) return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
15614
+ return res.json({ ok: true, sessionId: current.browserSessionId, tabId: current.browserTabId, current: true });
15615
+ }
15616
+ }
15617
+ if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh && !initial) {
15459
15618
  return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
15460
15619
  }
15461
15620
  const lost = req.body?.lost && typeof req.body.lost === 'object' ? req.body.lost : null;
@@ -15466,7 +15625,7 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15466
15625
  }
15467
15626
  }
15468
15627
  const start = async () => {
15469
- const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
15628
+ const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId, terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
15470
15629
  // Its profile was closed outside SynaBun under it and is not started again for it: the loop ends when its turn
15471
15630
  // ends, never asking again iteration after iteration.
15472
15631
  if (acq.code === 'MORELOGIN_CLOSED_OUTSIDE') finishBlockedLoop(owner, acq);
@@ -18937,6 +19096,32 @@ async function probeBrewOutdated(env) {
18937
19096
  }
18938
19097
  }
18939
19098
 
19099
+ // Ask WinGet which version of OpenCode it can install (`winget search`, as OpenCode's own updater does: a release
19100
+ // reaches WinGet's repository days after OpenCode publishes it, and some never do). `{ version }`, or null when
19101
+ // WinGet could not be asked or lists no version: the caller fails closed, like the brew probe.
19102
+ async function probeWingetOpencode(env) {
19103
+ try {
19104
+ const { stdout } = await execFileAsync('winget', [...OPENCODE_WINGET_SEARCH_ARGS], {
19105
+ encoding: 'utf-8',
19106
+ timeout: 20000,
19107
+ env,
19108
+ windowsHide: true,
19109
+ maxBuffer: 1024 * 1024,
19110
+ });
19111
+ const version = parseWingetSearchVersion(stdout);
19112
+ return version ? { version } : null;
19113
+ } catch {
19114
+ return null;
19115
+ }
19116
+ }
19117
+
19118
+ // The Git Bash this PC has, for OpenCode's own installer (`opencode upgrade --method curl` on Windows runs it with
19119
+ // Git Bash): the one Claude Code gets (lib/git-bash/). null anywhere else, and where there is none.
19120
+ function opencodeGitBashPath() {
19121
+ if (process.platform !== 'win32') return null;
19122
+ try { return gitBash.resolution()?.path || null; } catch { return null; }
19123
+ }
19124
+
18940
19125
  // Resolve SynaBun's own install roots so we can reject any tool binary that
18941
19126
  // lives inside our bundled node_modules — bulletproof guard for the recurring
18942
19127
  // phantom-version bug (e.g. stale @anthropic-ai/claude-code left over from
@@ -19000,6 +19185,10 @@ async function checkToolVersions({ force = false } = {}) {
19000
19185
  const brewOutdated = Object.values(statuses).some((status) => status.state === 'installed' && isBrewSource(status.installSource))
19001
19186
  ? await probeBrewOutdated(cleanEnv)
19002
19187
  : null;
19188
+ // A WinGet install of OpenCode is measured against what WinGet can install (`undefined`: not such an install).
19189
+ const wingetOpencode = process.platform === 'win32' && statuses.opencode?.state === 'installed' && statuses.opencode.installSource === 'winget'
19190
+ ? await probeWingetOpencode(cleanEnv)
19191
+ : undefined;
19003
19192
 
19004
19193
  const checkOneTool = async (tool) => {
19005
19194
  const status = statuses[tool.key];
@@ -19046,12 +19235,13 @@ async function checkToolVersions({ force = false } = {}) {
19046
19235
  npmLatest: upstreamLatest,
19047
19236
  brewUpstream,
19048
19237
  installed,
19238
+ ...(tool.key === 'opencode' ? { winget: wingetOpencode } : {}),
19049
19239
  });
19050
19240
  const refreshBrew = brewNeedsRefresh({ installSource, brewToken, brewOutdated, brewUpstream, installed });
19051
19241
  // A self-updater is started by the path found, so the update reaches this
19052
19242
  // very installation even where a terminal's PATH does not name its folder.
19053
19243
  const updateCommand = installed
19054
- ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform, refreshBrew })
19244
+ ? buildUpdateCommand(tool.key, installSource, { brewToken, binPath: status.path, platform: process.platform, refreshBrew, installedVersion: installed, gitBash: tool.key === 'opencode' ? opencodeGitBashPath() : null })
19055
19245
  : null;
19056
19246
 
19057
19247
  return [tool.key, {
@@ -19106,6 +19296,9 @@ async function checkToolVersions({ force = false } = {}) {
19106
19296
  // A check started before a newer refresh must never publish its stale answer.
19107
19297
  if (generation !== _toolVersionGeneration) return;
19108
19298
  _toolVersionCache = { checkedAt: new Date().toISOString(), tools: results };
19299
+ // An update that just landed (the badge's own poll asks every 10 s until it has): SynaBun's serves that still run
19300
+ // the earlier program are replaced now, not at the next restart of SynaBun.
19301
+ try { retireStaleOpencodeServes('version check'); } catch { /* the once-a-minute look tries again */ }
19109
19302
 
19110
19303
  const updates = Object.entries(results).filter(([, v]) => v.updateAvailable);
19111
19304
  const broken = Object.entries(results).filter(([, v]) => v.state === 'broken');
@@ -23724,6 +23917,86 @@ app.get('/api/claude-code/sessions/:sessionId/messages', async (req, res) => {
23724
23917
  }
23725
23918
  });
23726
23919
 
23920
+ // --- Background tasks of a session (the panels' Background tasks view, lib/claude-bg-tasks.js) ---
23921
+ // The session's background shells and watches, rebuilt from its own transcript, and a page of what one printed.
23922
+ // The owner's page alone reads them (this boot's page secret, no agent header, no guest, one of this server's
23923
+ // Hosts): what a command printed is display data, never a model's. A task's output is read only from the file the
23924
+ // session reported for it, inside Claude Code's own task folders of that session.
23925
+ const claudeBgTasks = createClaudeBgTasks({ roots: (found) => claudeOutputRoots({ configDirs: [found.configDir] }) });
23926
+ function bgTasksOwnerPage(req, res, next) {
23927
+ if (AGENT_HEADERS.some((name) => req.headers[name] !== undefined) || req.headers['x-synabun-brain-token'] !== undefined) {
23928
+ return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'A background task\'s output is shown in the owner\'s own panel only.' });
23929
+ }
23930
+ let owner = false;
23931
+ try { owner = _pageSession.verify(req) === true; } catch { owner = false; }
23932
+ if (!owner) return res.status(403).json({ ok: false, code: 'PAGE_SECRET_REQUIRED', error: 'A background task\'s output is shown in SynaBun\'s own page only. Reload the page and try again.' });
23933
+ next();
23934
+ }
23935
+ // The transcript a Claude panel tab names (its project and account), found as GET …/messages finds it.
23936
+ function claudeBgTranscript(req, res) {
23937
+ const homeDir = process.env.USERPROFILE || process.env.HOME;
23938
+ let accountHome = null;
23939
+ const wantedAccount = typeof req.query.account === 'string' ? req.query.account : '';
23940
+ if (wantedAccount && wantedAccount !== 'default') {
23941
+ try { accountHome = _panelClaudeAccounts().homeFor(wantedAccount); } catch { accountHome = null; }
23942
+ if (!accountHome) { res.status(404).json({ ok: false, code: 'account_unavailable', error: 'That Claude account is no longer set up in SynaBun.' }); return null; }
23943
+ }
23944
+ const configDir = accountHome || join(homeDir, '.claude');
23945
+ const project = typeof req.query.project === 'string' ? req.query.project : '';
23946
+ const found = findSessionTranscript({ sessionId: req.params.sessionId, project, projects: loadHookProjects(), projectsDir: join(configDir, 'projects'), pathToKey: pathToClaudeKey });
23947
+ if (!found) { res.status(404).json({ ok: false, code: 'TRANSCRIPT_NOT_FOUND', error: 'No transcript of that session was found.', tasks: [] }); return null; }
23948
+ return { ...found, configDir };
23949
+ }
23950
+ const bgNumber = (value) => (typeof value === 'string' && /^\d{1,15}$/.test(value) ? Number(value) : undefined);
23951
+ // An Assistant Claude brain's transcript: its conversation id under its account, in the folder it runs in
23952
+ // (runtime.backgroundTaskSource). Nothing a request says is a path here.
23953
+ function assistantBgTranscript(source) {
23954
+ if (!source?.providerSessionId) return null;
23955
+ const homeDir = process.env.USERPROFILE || process.env.HOME;
23956
+ let configDir = join(homeDir, '.claude');
23957
+ if (source.accountId && source.accountId !== 'default') {
23958
+ let home = null;
23959
+ try { home = _panelClaudeAccounts().homeFor(source.accountId); } catch { home = null; }
23960
+ if (!home) return null;
23961
+ configDir = home;
23962
+ }
23963
+ const cwd = source.cwd || PACKAGE_ROOT;
23964
+ let found = null;
23965
+ try { found = findSessionTranscript({ sessionId: source.providerSessionId, project: cwd, projects: [{ path: cwd }], projectsDir: join(configDir, 'projects'), pathToKey: pathToClaudeKey }); } catch { found = null; }
23966
+ return found ? { ...found, configDir } : null;
23967
+ }
23968
+ const assistantBackgroundTasks = {
23969
+ list: (source) => { const found = assistantBgTranscript(source); return found ? claudeBgTasks.list(found) : { tasks: [] }; },
23970
+ output: async (source, q) => {
23971
+ const found = assistantBgTranscript(source);
23972
+ if (!found) return { ok: false, status: 404, code: 'TRANSCRIPT_NOT_FOUND', error: 'No transcript of this conversation was found.' };
23973
+ return claudeBgTasks.output(found, { ...q, sessionId: source.providerSessionId });
23974
+ },
23975
+ };
23976
+ app.get('/api/claude-code/sessions/:sessionId/background-tasks', editorOwnerGuard, bgTasksOwnerPage, (req, res) => {
23977
+ try {
23978
+ res.set('Cache-Control', 'no-store');
23979
+ const found = claudeBgTranscript(req, res);
23980
+ if (!found) return;
23981
+ res.json({ ok: true, ...claudeBgTasks.list(found) });
23982
+ } catch (err) {
23983
+ res.status(err instanceof PathConfineError ? err.status : 500).json({ ok: false, error: err.message, tasks: [] });
23984
+ }
23985
+ });
23986
+ app.get('/api/claude-code/sessions/:sessionId/background-tasks/:taskId/output', editorOwnerGuard, bgTasksOwnerPage, async (req, res) => {
23987
+ try {
23988
+ res.set('Cache-Control', 'no-store');
23989
+ const found = claudeBgTranscript(req, res);
23990
+ if (!found) return;
23991
+ const running = req.query.running === '1' ? true : (req.query.running === '0' ? false : null);
23992
+ const page = await claudeBgTasks.output(found, { sessionId: req.params.sessionId, taskId: String(req.params.taskId || ''), cursor: bgNumber(req.query.cursor), tail: bgNumber(req.query.tail), limit: bgNumber(req.query.limit), running });
23993
+ if (!page || page.ok === false) return res.status(Number(page?.status) >= 400 ? Number(page.status) : 502).json({ ok: false, code: page?.code || 'OUTPUT_FAILED', error: page?.error || 'The output could not be read.' });
23994
+ res.json({ ok: true, ...page.data });
23995
+ } catch (err) {
23996
+ res.status(err instanceof PathConfineError ? err.status : 500).json({ ok: false, error: err.message });
23997
+ }
23998
+ });
23999
+
23727
24000
  // --- Session Indexing ---
23728
24001
 
23729
24002
  let _indexingJob = null; // { jobId, cancelled, promise }
@@ -30447,6 +30720,8 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30447
30720
  automationBrowserOwnerAccess: _automationBrowserOwnerAccess,
30448
30721
  // A request without an agent pin is the owner's page only with this boot's page secret (lib/page-session.js).
30449
30722
  pageSession: _pageSession,
30723
+ // The Background tasks view of a Claude brain: its own transcript (lib/claude-bg-tasks.js).
30724
+ backgroundTasks: assistantBackgroundTasks,
30450
30725
  // A pin counts only with its proof (lib/terminal-tokens.js): a worker's run id, a brain's id.
30451
30726
  terminalVerdict: (pin, req) => _terminalTokens.verdict(pin, presentedTerminalProof(req)),
30452
30727
  }));
@@ -31133,7 +31408,7 @@ function syncRegistryFromTerminals() {
31133
31408
 
31134
31409
  // ── Leak Detection ──
31135
31410
 
31136
- function scanForLeaks() {
31411
+ async function scanForLeaks({ loopInventory = null, cleanupSnapshots = null } = {}) {
31137
31412
  const leaks = [];
31138
31413
  const now = Date.now();
31139
31414
  const activeSessionIds = new Set(sessionRegistry.keys());
@@ -31141,42 +31416,37 @@ function scanForLeaks() {
31141
31416
  if (s.claudeSessionId) activeSessionIds.add(s.claudeSessionId);
31142
31417
  }
31143
31418
 
31144
- // 1. Orphaned pending-remember files
31419
+ // 1. Orphaned pending-remember files (async off-main-thread FS I/O)
31145
31420
  try {
31146
- if (existsSync(PENDING_REMEMBER_DIR)) {
31147
- const files = readdirSync(PENDING_REMEMBER_DIR).filter(f => f.endsWith('.json') && !f.startsWith('test-'));
31148
- for (const f of files) {
31149
- const filePath = join(PENDING_REMEMBER_DIR, f);
31150
- try {
31151
- const fstat = statSync(filePath);
31152
- const ageMs = now - fstat.mtimeMs;
31153
- if (ageMs < 5 * 60 * 1000) continue;
31154
- const sid = f.replace('.json', '');
31155
- if (!activeSessionIds.has(sid)) {
31156
- leaks.push({ type: 'orphaned-state', severity: ageMs > 30 * 60 * 1000 ? 'warning' : 'info', description: `Orphaned pending-remember flag (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: sid, ageMs });
31157
- }
31158
- } catch { /* skip */ }
31159
- }
31421
+ const files = (await fsp.readdir(PENDING_REMEMBER_DIR)).filter(f => f.endsWith('.json') && !f.startsWith('test-'));
31422
+ for (const f of files) {
31423
+ const filePath = join(PENDING_REMEMBER_DIR, f);
31424
+ try {
31425
+ const fstat = await fsp.stat(filePath);
31426
+ const ageMs = now - fstat.mtimeMs;
31427
+ if (ageMs < 5 * 60 * 1000) continue;
31428
+ const sid = f.replace('.json', '');
31429
+ if (!activeSessionIds.has(sid)) {
31430
+ cleanupSnapshots?.set(filePath, fstat);
31431
+ leaks.push({ type: 'orphaned-state', severity: ageMs > 30 * 60 * 1000 ? 'warning' : 'info', description: `Orphaned pending-remember flag (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: sid, ageMs });
31432
+ }
31433
+ } catch { /* skip */ }
31160
31434
  }
31161
- } catch { /* ok */ }
31435
+ } catch { /* missing or unreadable directory */ }
31162
31436
 
31163
- // 2. Orphaned loop files
31437
+ // 2. Orphaned loop files — share the async stat-cached loop inventory instead of re-reading loop files
31164
31438
  try {
31165
- if (existsSync(LOOP_DIR_MONITOR)) {
31166
- const files = readdirSync(LOOP_DIR_MONITOR).filter(f => f.endsWith('.json') && !f.startsWith('pending-'));
31167
- for (const f of files) {
31168
- const filePath = join(LOOP_DIR_MONITOR, f);
31169
- try {
31170
- const data = JSON.parse(readFileSync(filePath, 'utf-8'));
31171
- if (data.stopped || data.finishedAt) continue;
31172
- const fstat = statSync(filePath);
31173
- const ageMs = now - fstat.mtimeMs;
31174
- if (ageMs < 2 * 60 * 1000) continue;
31175
- const sid = f.replace('.json', '');
31176
- if (!activeSessionIds.has(sid) && data.active) {
31177
- leaks.push({ type: 'orphaned-loop', severity: 'warning', description: `Active loop with no session (${data.template || 'custom'}, ${Math.round(ageMs / 60000)}m stale)`, file: filePath, sessionId: sid, ageMs, loopData: { template: data.template, currentIteration: data.currentIteration, maxIterations: data.maxIterations } });
31178
- }
31179
- } catch { /* skip */ }
31439
+ const inv = loopInventory?.rawEntries
31440
+ ? loopInventory
31441
+ : await scanLoopInventory({ includeRaw: true }).catch(() => ({ rawEntries: [] }));
31442
+ for (const entry of inv.rawEntries || []) {
31443
+ const { data, filePath, sessionId: sid, mtimeMs } = entry;
31444
+ if (!data || data.stopped || data.finishedAt) continue;
31445
+ const ageMs = now - mtimeMs;
31446
+ if (ageMs < 2 * 60 * 1000) continue;
31447
+ if (!activeSessionIds.has(sid) && data.active) {
31448
+ cleanupSnapshots?.set(filePath, entry.stat);
31449
+ leaks.push({ type: 'orphaned-loop', severity: 'warning', description: `Active loop with no session (${data.template || 'custom'}, ${Math.round(ageMs / 60000)}m stale)`, file: filePath, sessionId: sid, ageMs, loopData: { template: data.template, currentIteration: data.currentIteration, maxIterations: data.maxIterations } });
31180
31450
  }
31181
31451
  }
31182
31452
  } catch { /* ok */ }
@@ -31199,105 +31469,73 @@ function scanForLeaks() {
31199
31469
  }
31200
31470
  }
31201
31471
 
31202
- // 4. Stale precompact flags
31472
+ // 4. Stale precompact flags (async off-main-thread FS I/O)
31203
31473
  const precompactDir = resolve(DATA_HOME, 'data', 'precompact');
31204
31474
  try {
31205
- if (existsSync(precompactDir)) {
31206
- const files = readdirSync(precompactDir).filter(f => f.endsWith('.json'));
31207
- for (const f of files) {
31208
- const filePath = join(precompactDir, f);
31209
- try {
31210
- const fstat = statSync(filePath);
31211
- const ageMs = now - fstat.mtimeMs;
31212
- if (ageMs > 10 * 60 * 1000) {
31213
- leaks.push({ type: 'stale-precompact', severity: 'info', description: `Stale precompact cache (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: f.replace('.json', ''), ageMs });
31214
- }
31215
- } catch { /* skip */ }
31216
- }
31475
+ const files = (await fsp.readdir(precompactDir)).filter(f => f.endsWith('.json'));
31476
+ for (const f of files) {
31477
+ const filePath = join(precompactDir, f);
31478
+ try {
31479
+ const fstat = await fsp.stat(filePath);
31480
+ const ageMs = now - fstat.mtimeMs;
31481
+ if (ageMs > 10 * 60 * 1000) {
31482
+ cleanupSnapshots?.set(filePath, fstat);
31483
+ leaks.push({ type: 'stale-precompact', severity: 'info', description: `Stale precompact cache (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: f.replace('.json', ''), ageMs });
31484
+ }
31485
+ } catch { /* skip */ }
31217
31486
  }
31218
- } catch { /* ok */ }
31487
+ } catch { /* missing or unreadable directory */ }
31219
31488
 
31220
31489
  return leaks;
31221
31490
  }
31222
31491
 
31223
- let _lastLeakHash = '';
31224
- setInterval(() => {
31225
- markActivity('timer:session-leaks');
31226
- syncRegistryFromTerminals();
31227
- const leaks = scanForLeaks();
31228
- // Strip ageMs AND description (which embeds age as "Xm old") to prevent
31229
- // broadcasts every ~60s when the minute counter ticks in descriptions
31230
- const hash = JSON.stringify(leaks.map(l => { const { ageMs, description, ...stable } = l; return stable; }));
31231
- if (hash !== _lastLeakHash) {
31232
- _lastLeakHash = hash;
31233
- if (leaks.length > 0) broadcastSessionEvent({ type: 'session:leaks', leaks });
31234
- }
31235
- }, LEAK_SCAN_INTERVAL_MS);
31236
-
31237
- // Inline scan of LOOP_DIR matching the GET /api/loop/list shape. Used by both
31238
- // the WS init payload and the periodic broadcast so the Session Monitor stays
31239
- // in sync with the Loops tab without a separate fetch.
31240
- function scanLoopInventory() {
31241
- const result = { loops: [], staleCount: 0 };
31242
- try {
31243
- if (!existsSync(LOOP_DIR)) return result;
31244
- const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep' && !f.startsWith('pending-') && f !== 'active-pointer.json');
31245
- const now = Date.now();
31246
- for (const f of files) {
31247
- try {
31248
- const filePath = resolve(LOOP_DIR, f);
31249
- const data = JSON.parse(readFileSync(filePath, 'utf-8'));
31250
- const startedAtMs = data.startedAt ? new Date(data.startedAt).getTime() : 0;
31251
- const lastIterAtMs = data.lastIterationAt ? new Date(data.lastIterationAt).getTime() : startedAtMs;
31252
- const elapsedMs = startedAtMs ? now - startedAtMs : 0;
31253
- const stalledMs = lastIterAtMs ? now - lastIterAtMs : 0;
31254
- const terminalAlive = isLoopRuntimeAlive(data);
31255
- const iterDone = (data.currentIteration || 0) >= (data.totalIterations || 0) && (data.totalIterations || 0) > 0;
31256
- let state;
31257
- if (data.active === false) { state = 'stale-inactive'; result.staleCount++; }
31258
- else if (data.terminalSessionId && !terminalAlive) state = data.runtimeType === 'native' ? 'orphaned-native' : 'orphaned-pty';
31259
- else if (iterDone) state = 'finished';
31260
- else state = 'active';
31261
- result.loops.push({
31262
- sessionId: f.replace('.json', ''),
31263
- terminalSessionId: data.terminalSessionId || null,
31264
- terminalAlive,
31265
- task: typeof data.task === 'string' ? data.task.slice(0, 200) : '',
31266
- currentIteration: data.currentIteration || 0,
31267
- totalIterations: data.totalIterations || 0,
31268
- startedAt: data.startedAt || null,
31269
- lastIterationAt: data.lastIterationAt || null,
31270
- elapsedMinutes: Math.round(elapsedMs / 60000),
31271
- stalledMinutes: Math.round(stalledMs / 60000),
31272
- stalledMs,
31273
- state,
31274
- browserSessionId: data.browserSessionId || null,
31275
- browserTabId: data.browserTabId || null,
31276
- usesBrowser: !!data.usesBrowser,
31277
- });
31278
- } catch { /* skip corrupt */ }
31279
- }
31280
- result.loops.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
31281
- } catch { /* ok */ }
31282
- return result;
31492
+ // Async, stat-identity-cached scan of LOOP_DIR matching the GET /api/loop/list shape.
31493
+ // Used by the route, leak detection, WS init payload and periodic broadcast so the
31494
+ // Session Monitor stays in sync with the Loops tab without blocking the event loop.
31495
+ const _loopInventoryScanner = createLoopInventoryScanner({
31496
+ loopDir: () => LOOP_DIR,
31497
+ isLoopRuntimeAlive,
31498
+ });
31499
+ function scanLoopInventory(options) {
31500
+ return _loopInventoryScanner.scan(options);
31283
31501
  }
31284
31502
 
31503
+ let _lastLeakHash = '';
31285
31504
  let _lastLoopHash = '';
31505
+ let _loopInventoryInFlight = false;
31286
31506
  setInterval(() => {
31287
- markActivity('timer:loop-inventory');
31288
- const inventory = scanLoopInventory();
31289
- // Hash on stable fields only (drop minute counters that tick every poll)
31290
- const hash = JSON.stringify({
31291
- staleCount: inventory.staleCount,
31292
- loops: inventory.loops.map(l => ({
31293
- sessionId: l.sessionId, state: l.state, terminalAlive: l.terminalAlive,
31294
- currentIteration: l.currentIteration, totalIterations: l.totalIterations,
31295
- })),
31507
+ if (_loopInventoryInFlight) return;
31508
+ _loopInventoryInFlight = true;
31509
+ const endActivity = beginActivity('timer:loop-inventory');
31510
+ syncRegistryFromTerminals();
31511
+ (async () => {
31512
+ const inventory = await scanLoopInventory({ includeRaw: true }).catch(() => null);
31513
+ if (inventory) {
31514
+ // Hash on stable fields only (drop minute counters that tick every poll)
31515
+ const loopHash = JSON.stringify({
31516
+ staleCount: inventory.staleCount,
31517
+ loops: inventory.loops.map(l => ({
31518
+ sessionId: l.sessionId, state: l.state, terminalAlive: l.terminalAlive,
31519
+ currentIteration: l.currentIteration, totalIterations: l.totalIterations,
31520
+ })),
31521
+ });
31522
+ if (loopHash !== _lastLoopHash) {
31523
+ _lastLoopHash = loopHash;
31524
+ broadcastSessionEvent({ type: 'session:loops', loops: inventory.loops, staleCount: inventory.staleCount });
31525
+ }
31526
+ }
31527
+ const leaks = await scanForLeaks({ loopInventory: inventory });
31528
+ // Strip ageMs AND description (which embeds age as "Xm old") to prevent
31529
+ // broadcasts every ~60s when the minute counter ticks in descriptions
31530
+ const leakHash = JSON.stringify(leaks.map(l => { const { ageMs, description, ...stable } = l; return stable; }));
31531
+ if (leakHash !== _lastLeakHash) {
31532
+ _lastLeakHash = leakHash;
31533
+ if (leaks.length > 0) broadcastSessionEvent({ type: 'session:leaks', leaks });
31534
+ }
31535
+ })().catch(() => {}).finally(() => {
31536
+ _loopInventoryInFlight = false;
31537
+ endActivity();
31296
31538
  });
31297
- if (hash !== _lastLoopHash) {
31298
- _lastLoopHash = hash;
31299
- broadcastSessionEvent({ type: 'session:loops', loops: inventory.loops, staleCount: inventory.staleCount });
31300
- }
31301
31539
  }, LEAK_SCAN_INTERVAL_MS);
31302
31540
 
31303
31541
  // ── Session Monitor API ──
@@ -31359,19 +31597,33 @@ app.get('/api/sessions/:id/state', (req, res) => {
31359
31597
  res.json({ session: entry, ownedFiles });
31360
31598
  });
31361
31599
 
31362
- app.get('/api/sessions/leaks', (req, res) => {
31600
+ app.get('/api/sessions/leaks', async (req, res) => {
31363
31601
  syncRegistryFromTerminals();
31364
- res.json({ leaks: scanForLeaks(), scannedAt: Date.now() });
31602
+ res.json({ leaks: await scanForLeaks(), scannedAt: Date.now() });
31365
31603
  });
31366
31604
 
31367
- app.post('/api/sessions/cleanup', express.json(), (req, res) => {
31605
+ async function cleanInactiveFlag(leak, snapshot) {
31606
+ if (!snapshot) return false;
31607
+ const current = await fsp.stat(leak.file);
31608
+ if (current.dev !== snapshot.dev || current.ino !== snapshot.ino || current.size !== snapshot.size
31609
+ || current.mtimeMs !== snapshot.mtimeMs || current.ctimeMs !== snapshot.ctimeMs) return false;
31610
+ if (sessionRegistry.has(leak.sessionId)) return false;
31611
+ for (const session of terminalSessions.values()) {
31612
+ if (session.claudeSessionId === leak.sessionId) return false;
31613
+ }
31614
+ await fsp.unlink(leak.file);
31615
+ return true;
31616
+ }
31617
+
31618
+ app.post('/api/sessions/cleanup', express.json(), async (req, res) => {
31368
31619
  const { types } = req.body || {};
31369
31620
  const allowedTypes = new Set(types || ['orphaned-state', 'stale-precompact']);
31370
- const leaks = scanForLeaks();
31621
+ const snapshots = new Map();
31622
+ const leaks = await scanForLeaks({ cleanupSnapshots: snapshots });
31371
31623
  let cleaned = 0;
31372
31624
  for (const leak of leaks) {
31373
31625
  if (!allowedTypes.has(leak.type) || !leak.file) continue;
31374
- try { unlinkSync(leak.file); cleaned++; } catch { /* skip */ }
31626
+ try { if (await cleanInactiveFlag(leak, snapshots.get(leak.file))) cleaned++; } catch { /* skip */ }
31375
31627
  }
31376
31628
  res.json({ ok: true, cleaned, total: leaks.length });
31377
31629
  });
@@ -31379,9 +31631,9 @@ app.post('/api/sessions/cleanup', express.json(), (req, res) => {
31379
31631
  // GET /api/sessions/pending-remember-prompt — build the prompt that processes
31380
31632
  // orphaned pending-remember flags. The client routes this prompt to the
31381
31633
  // chosen provider sidepanel (Claude Code / Codex / OpenCode) — no agent spawn.
31382
- app.get('/api/sessions/pending-remember-prompt', (req, res) => {
31634
+ app.get('/api/sessions/pending-remember-prompt', async (req, res) => {
31383
31635
  try {
31384
- const leaks = scanForLeaks().filter(l =>
31636
+ const leaks = (await scanForLeaks()).filter(l =>
31385
31637
  l.type === 'orphaned-state' && l.file && l.file.includes('pending-remember') && l.sessionId
31386
31638
  );
31387
31639
  if (leaks.length === 0) return res.json({ ok: true, count: 0, prompt: '', message: 'No pending-remember flags to process.' });
@@ -31433,16 +31685,35 @@ app.get('/api/sessions/pending-remember-prompt', (req, res) => {
31433
31685
  // ── Session Monitor WebSocket ──
31434
31686
 
31435
31687
  function handleSessionMonitorWebSocket(ws) {
31436
- sessionMonitorClients.add(ws);
31437
- syncRegistryFromTerminals();
31438
- const sessions = [...sessionRegistry.values()].map(s => ({
31439
- ...s,
31440
- isAlive: s.terminalSessionId ? terminalSessions.has(s.terminalSessionId) : (Date.now() - s.lastActivity < 5 * 60 * 1000),
31441
- }));
31442
- const loopInv = scanLoopInventory();
31443
- ws.send(JSON.stringify({ type: 'session:init', sessions, leaks: scanForLeaks(), loops: loopInv.loops, staleCount: loopInv.staleCount }));
31444
- ws.on('close', () => sessionMonitorClients.delete(ws));
31445
- ws.on('error', () => sessionMonitorClients.delete(ws));
31688
+ let closed = false;
31689
+ const cleanup = () => {
31690
+ closed = true;
31691
+ sessionMonitorClients.delete(ws);
31692
+ };
31693
+ ws.on('close', cleanup);
31694
+ ws.on('error', cleanup);
31695
+ (async () => {
31696
+ syncRegistryFromTerminals();
31697
+ const loopInv = await scanLoopInventory({ includeRaw: true }).catch(() => ({ loops: [], staleCount: 0, rawEntries: [] }));
31698
+ const leaks = await scanForLeaks({ loopInventory: loopInv }).catch(() => []);
31699
+ if (closed || ws.readyState !== 1) return;
31700
+ // Snapshot active sessions AFTER awaiting the async scans and subscribe in the same
31701
+ // synchronous turn so session:init is always delivered first and never overwrites
31702
+ // sessions registered while the inventory was being scanned.
31703
+ syncRegistryFromTerminals();
31704
+ const sessions = [...sessionRegistry.values()].map(s => ({
31705
+ ...s,
31706
+ isAlive: s.terminalSessionId ? terminalSessions.has(s.terminalSessionId) : (Date.now() - s.lastActivity < 5 * 60 * 1000),
31707
+ }));
31708
+ ws.send(JSON.stringify({
31709
+ type: 'session:init',
31710
+ sessions,
31711
+ leaks,
31712
+ loops: loopInv.loops,
31713
+ staleCount: loopInv.staleCount,
31714
+ }));
31715
+ sessionMonitorClients.add(ws);
31716
+ })().catch(() => {});
31446
31717
  }
31447
31718
 
31448
31719
  const providerPanelTerminalAuth = createProviderPanelTerminalAuth({
@@ -31610,13 +31881,21 @@ let _gitExePath = null; // Cached absolute path — preferring .exe on Windows
31610
31881
  let _gitResolved = false;
31611
31882
  let _gitResolving = null; // the lookup resolveGitPathInBackground() runs, while it runs
31612
31883
 
31613
- // Resolve git's absolute path at first use. On Windows, `where git` lists all matches;
31614
- // prefer .exe so spawnSync works without cmd.exe quoting issues. On Unix, use `command -v`.
31615
- // A Windows PC without git: the git.exe of SynaBun's copy of Git for Windows (lib/git-bash/), asked each time,
31616
- // since a copy that is still being fetched at the first call arrives later.
31884
+ // Resolve git's absolute path for server Git operations in one unified order:
31885
+ // bundled → managed (downloaded) → system (PATH, then standard Windows install roots).
31886
+ // Never dumps raw OEM codepage stderr on Windows.
31617
31887
  function resolveGitPath() {
31618
- if (_gitResolved) return _gitExePath || gitBash.gitExecutable();
31888
+ const managed = gitBash.managedGitExecutable?.() || null;
31889
+ if (managed) {
31890
+ if (!_gitResolved) {
31891
+ _gitResolved = true;
31892
+ console.log(`[git] resolved: ${managed}`);
31893
+ }
31894
+ return managed;
31895
+ }
31896
+ if (_gitResolved) return _gitExePath || gitBash.gitExecutable({ includeSystem: true });
31619
31897
  _gitResolved = true;
31898
+ let resolveErr = null;
31620
31899
  try {
31621
31900
  const cmd = IS_WINDOWS ? 'where git' : 'command -v git';
31622
31901
  const out = execSync(cmd, { encoding: 'utf8', timeout: 3000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
@@ -31626,13 +31905,29 @@ function resolveGitPath() {
31626
31905
  } else {
31627
31906
  _gitExePath = lines[0] || null;
31628
31907
  }
31629
- if (_gitExePath) console.log(`[git] resolved: ${_gitExePath}`);
31630
- else console.warn('[git] resolver returned no paths');
31631
31908
  } catch (err) {
31632
- console.warn('[git] resolution failed:', err?.message || String(err));
31909
+ resolveErr = err;
31633
31910
  _gitExePath = null;
31634
31911
  }
31635
- return _gitExePath || gitBash.gitExecutable();
31912
+ if (_gitExePath) {
31913
+ console.log(`[git] resolved: ${_gitExePath}`);
31914
+ } else {
31915
+ const fallback = gitBash.gitExecutable() || gitBash.gitExecutable({ includeSystem: true });
31916
+ if (fallback) {
31917
+ _gitExePath = fallback;
31918
+ console.log(`[git] resolved: ${fallback}`);
31919
+ } else {
31920
+ const detail = resolveErr?.killed
31921
+ ? 'timed out'
31922
+ : typeof resolveErr?.code === 'string'
31923
+ ? resolveErr.code
31924
+ : typeof resolveErr?.code === 'number' || typeof resolveErr?.status === 'number'
31925
+ ? `not found on PATH (exit ${resolveErr.code ?? resolveErr.status})`
31926
+ : 'resolver returned no paths';
31927
+ console.warn(`[git] resolution failed: ${detail}`);
31928
+ }
31929
+ }
31930
+ return _gitExePath || gitBash.gitExecutable({ includeSystem: true });
31636
31931
  }
31637
31932
 
31638
31933
  // Cross-platform git invocation. Uses resolved absolute path when possible (spawnable
@@ -31648,22 +31943,40 @@ async function spawnGitRead(args, opts = {}) {
31648
31943
  }
31649
31944
 
31650
31945
  function logGitFailure(where, err) {
31651
- const msg = err?.stderr?.toString?.() || err?.message || String(err);
31946
+ const redact = typeof redactSecrets === 'function' ? redactSecrets : (s) => s;
31947
+ const rawStderr = redact(Buffer.isBuffer(err?.stderr)
31948
+ ? err.stderr.toString('utf8')
31949
+ : (typeof err?.stderr === 'string' ? err.stderr : ''));
31950
+ const stderrLine = rawStderr.trim().split(/\r?\n/)[0]?.trim() || '';
31951
+ const errMessage = typeof err?.message === 'string' ? redact(err.message).trim().split(/\r?\n/)[0]?.trim() : '';
31952
+ const code = err?.code != null && err.code !== ''
31953
+ ? String(err.code)
31954
+ : (err?.status != null ? `exit ${err.status}` : '');
31955
+ const fallback = typeof err === 'string' ? redact(err).trim().split(/\r?\n/)[0]?.trim() : '';
31956
+ const msg = stderrLine || errMessage || (code ? `git failed (${code})` : '') || fallback;
31652
31957
  if (!msg || /not a git repository/i.test(msg)) return;
31653
- if (/ENOENT/i.test(msg) || /is not recognized/i.test(msg) || /command not found/i.test(msg)) {
31958
+ if (code === 'ENOENT' || /ENOENT/i.test(msg) || /is not recognized/i.test(msg) || /command not found/i.test(msg)) {
31654
31959
  if (_gitMissingLogged) return;
31655
31960
  _gitMissingLogged = true;
31656
31961
  console.warn(`[git] '${where}' failed: git executable not found on PATH. Install Git and ensure it's on the Node process PATH.`);
31657
31962
  return;
31658
31963
  }
31659
- console.warn(`[git] '${where}' failed:`, msg.trim().split('\n')[0]);
31964
+ const detail = (code && !msg.includes(code)) ? `${msg} (${code})` : msg;
31965
+ console.warn(`[git] '${where}' failed:`, detail);
31660
31966
  }
31661
31967
 
31662
- // resolveGitPath()'s lookup without blocking: `where git` (Windows) or `command -v git`, run once in the
31663
- // background at start-up, so the first git call of a request finds the answer kept instead of running the
31664
- // lookup itself (a synchronous spawn through cmd.exe holds every request on a Windows PC without git).
31968
+ // Unified non-blocking server Git resolver (bundled → managed → system). Shared by
31969
+ // startup probing, spawnGit/spawnGitRead, and gitStatusRunner (status, reads, stage/commit).
31665
31970
  function resolveGitPathInBackground() {
31666
- if (_gitResolved) return Promise.resolve(_gitExePath || gitBash.gitExecutable());
31971
+ const managed = gitBash.managedGitExecutable?.() || null;
31972
+ if (managed) {
31973
+ if (!_gitResolved) {
31974
+ _gitResolved = true;
31975
+ console.log(`[git] resolved: ${managed}`);
31976
+ }
31977
+ return Promise.resolve(managed);
31978
+ }
31979
+ if (_gitResolved) return Promise.resolve(_gitExePath || gitBash.gitExecutable({ includeSystem: true }));
31667
31980
  if (_gitResolving) return _gitResolving;
31668
31981
  _gitResolving = new Promise((done) => {
31669
31982
  const [command, args] = IS_WINDOWS ? ['where', ['git']] : ['/bin/sh', ['-c', 'command -v git']];
@@ -31672,10 +31985,26 @@ function resolveGitPathInBackground() {
31672
31985
  _gitResolved = true;
31673
31986
  const lines = error ? [] : String(stdout || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
31674
31987
  _gitExePath = (IS_WINDOWS ? lines.find((line) => /\.exe$/i.test(line)) : null) || lines[0] || null;
31675
- if (_gitExePath) console.log(`[git] resolved: ${_gitExePath}`);
31676
- else console.warn('[git] resolution failed:', error?.message || 'resolver returned no paths');
31988
+ if (_gitExePath) {
31989
+ console.log(`[git] resolved: ${_gitExePath}`);
31990
+ } else {
31991
+ const fallback = gitBash.gitExecutable() || gitBash.gitExecutable({ includeSystem: true });
31992
+ if (fallback) {
31993
+ _gitExePath = fallback;
31994
+ console.log(`[git] resolved: ${fallback}`);
31995
+ } else {
31996
+ const detail = error?.killed
31997
+ ? 'timed out'
31998
+ : typeof error?.code === 'string'
31999
+ ? error.code
32000
+ : typeof error?.code === 'number'
32001
+ ? `not found on PATH (exit ${error.code})`
32002
+ : 'resolver returned no paths';
32003
+ console.warn(`[git] resolution failed: ${detail}`);
32004
+ }
32005
+ }
31677
32006
  }
31678
- done(_gitExePath || gitBash.gitExecutable());
32007
+ done(gitBash.managedGitExecutable?.() || _gitExePath || gitBash.gitExecutable({ includeSystem: true }));
31679
32008
  });
31680
32009
  }).finally(() => { _gitResolving = null; });
31681
32010
  return _gitResolving;
@@ -31687,8 +32016,8 @@ setImmediate(async () => {
31687
32016
  try {
31688
32017
  const gitPath = await resolveGitPathInBackground();
31689
32018
  const result = await gitStatusRunner.run(['--version'], { binary: gitPath || 'git', timeoutMs: 3000 });
31690
- if (result.ok) console.log(`[git] ${String(result.stdout).trim()} — OK`);
31691
- else console.warn(`[git] startup probe FAILED: ${String(result.stderr).trim() || result.code}. File explorer git UI will be hidden.`);
32019
+ if (result.ok) console.log(`[git] ${redactSecrets(String(result.stdout)).trim()} — OK`);
32020
+ else console.warn(`[git] startup probe FAILED: ${redactSecrets(String(result.stderr)).trim() || result.code}. File explorer git UI will be hidden.`);
31692
32021
  } catch { /* availability is reported on the first read */ }
31693
32022
  });
31694
32023
 
@@ -31806,7 +32135,7 @@ app.get('/api/terminal/branches', async (req, res) => {
31806
32135
 
31807
32136
  const inside = await spawnGitRead(['rev-parse', '--is-inside-work-tree'], { cwd: dir, timeout: 3000 });
31808
32137
  if (inside.status !== 0) {
31809
- logGitFailure('branches: rev-parse', inside.error || { stderr: inside.stderr });
32138
+ logGitFailure('branches: rev-parse', inside.error || inside);
31810
32139
  return res.json({ branches: [], current: null });
31811
32140
  }
31812
32141
 
@@ -31815,7 +32144,7 @@ app.get('/api/terminal/branches', async (req, res) => {
31815
32144
  let current = '';
31816
32145
  const showCurrent = await spawnGitRead(['branch', '--show-current'], { cwd: dir, timeout: 3000 });
31817
32146
  if (showCurrent.status === 0) current = showCurrent.stdout.toString().trim();
31818
- else logGitFailure('branches: show-current', showCurrent.error || { stderr: showCurrent.stderr });
32147
+ else logGitFailure('branches: show-current', showCurrent.error || showCurrent);
31819
32148
  if (!current) {
31820
32149
  const abbrev = await spawnGitRead(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: dir, timeout: 3000 });
31821
32150
  if (abbrev.status === 0) {
@@ -31827,7 +32156,7 @@ app.get('/api/terminal/branches', async (req, res) => {
31827
32156
  // All local branches — plain `git branch` parsed manually; avoids --format=%(refname:short)
31828
32157
  // which can get mangled by cmd.exe variable expansion on Windows even with proper quoting.
31829
32158
  const branchResult = await spawnGitRead(['branch'], { cwd: dir });
31830
- if (branchResult.status !== 0) logGitFailure('branch list', branchResult.error || { stderr: branchResult.stderr });
32159
+ if (branchResult.status !== 0) logGitFailure('branch list', branchResult.error || branchResult);
31831
32160
  const raw = branchResult.status === 0 ? branchResult.stdout.toString() : '';
31832
32161
  // Plain `git branch` output: each line is " branch" or "* branch" (current). Strip
31833
32162
  // marker + whitespace. Skip detached-HEAD lines like "* (HEAD detached at abc1234)".
@@ -31862,8 +32191,8 @@ app.post('/api/terminal/trust-workspace', async (req, res) => {
31862
32191
  const gitPath = normalizeGitPath(abs);
31863
32192
  const r = await spawnGit(['config', '--global', '--add', 'safe.directory', gitPath]);
31864
32193
  if (r.status !== 0) {
31865
- const stderr = r.stderr?.toString?.()?.trim() || r.error?.message || 'git config failed';
31866
- logGitFailure('config --add safe.directory', r.error || { stderr: r.stderr });
32194
+ const stderr = r.stderr?.toString?.()?.trim() || r.error?.message || (r.code ? `git config failed (${r.code})` : 'git config failed');
32195
+ logGitFailure('config --add safe.directory', r.error || r);
31867
32196
  return res.status(500).json({ ok: false, error: stderr });
31868
32197
  }
31869
32198
 
@@ -31884,7 +32213,7 @@ app.post('/api/terminal/checkout', async (req, res) => {
31884
32213
 
31885
32214
  const inside = await spawnGitRead(['rev-parse', '--is-inside-work-tree'], { cwd: dir, timeout: 3000 });
31886
32215
  if (inside.status !== 0) {
31887
- logGitFailure('checkout: rev-parse', inside.error || { stderr: inside.stderr });
32216
+ logGitFailure('checkout: rev-parse', inside.error || inside);
31888
32217
  return res.status(400).json({ error: 'Not a git repository' });
31889
32218
  }
31890
32219
 
@@ -31895,7 +32224,7 @@ app.post('/api/terminal/checkout', async (req, res) => {
31895
32224
  const result = await spawnGit(['checkout', branch], { cwd: dir, timeout: 10000 });
31896
32225
  gitStatusRunner.invalidate(dir);
31897
32226
  if (result.status !== 0) {
31898
- const stderr = result.stderr?.toString?.()?.trim() || result.error?.message || 'Checkout failed';
32227
+ const stderr = result.stderr?.toString?.()?.trim() || result.error?.message || (result.code ? `Checkout failed (${result.code})` : 'Checkout failed');
31899
32228
  return res.status(500).json({ error: stderr });
31900
32229
  }
31901
32230
 
@@ -31903,7 +32232,7 @@ app.post('/api/terminal/checkout', async (req, res) => {
31903
32232
  let current = '';
31904
32233
  const showCurrent = await spawnGitRead(['branch', '--show-current'], { cwd: dir, timeout: 3000 });
31905
32234
  if (showCurrent.status === 0) current = showCurrent.stdout.toString().trim();
31906
- else logGitFailure('checkout: show-current', showCurrent.error || { stderr: showCurrent.stderr });
32235
+ else logGitFailure('checkout: show-current', showCurrent.error || showCurrent);
31907
32236
  const output = result.stderr?.toString?.()?.trim() || `Switched to branch '${current}'`;
31908
32237
  res.json({ ok: true, branch: current, output });
31909
32238
  });
@@ -33068,7 +33397,17 @@ function extensionSelfHosts() {
33068
33397
  try { for (const list of Object.values(os.networkInterfaces())) for (const entry of list || []) if (entry?.address) hosts.add(entry.address.split('%')[0]); } catch {}
33069
33398
  return [...hosts];
33070
33399
  }
33400
+ function extensionRunsActive() {
33401
+ const { assistant, loop } = systemActivitySources();
33402
+ return !collectActivity({ assistant, loop }).idle;
33403
+ }
33071
33404
  const extensionBridge = createExtensionBridge({
33405
+ runsActive: extensionRunsActive,
33406
+ onConnected: version => extensionUpdate.connected(version),
33407
+ updateStatus: version => {
33408
+ const disk = extensionPackage.status();
33409
+ return { version: !disk.needs && disk.folderVersion && compareVersions(version, disk.folderVersion) < 0 ? disk.folderVersion : null };
33410
+ },
33072
33411
  forbiddenOrigins: publicWebOrigins,
33073
33412
  blockedPorts: extensionBlockedPorts,
33074
33413
  selfHosts: extensionSelfHosts,
@@ -33097,18 +33436,31 @@ const extensionEvaluateGate = {
33097
33436
  };
33098
33437
  const extensionAdapter = createExtensionAdapter({
33099
33438
  bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
33439
+ // The bridge handshake identifies the connection. Local profile settings belong to mirror/attach.
33100
33440
  caller: browserCaller, ownerPage: browserOwnerPageOnly, evaluateGate: extensionEvaluateGate,
33441
+ // browser_content markdown in extension mode: the Playwright route's own converter (nhm, below), called per request.
33442
+ htmlToMarkdown: html => nhm.translate(html),
33101
33443
  selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
33102
33444
  });
33103
- // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
33104
- // extension changed and is not older (lib/browser-extension-folder.js). The browser then needs the extension's Reload,
33105
- // which Settings and the setup page say (`reloadNeeded`). Never fatal: a folder that cannot be written is prepared
33106
- // again by the one-button setup, which says so.
33107
- const prepareOwnerExtensionFolder = () => prepareExtensionFolder({ source: EXTENSION_FOLDER, home: DATA_HOME, appPort: Number(PORT) || 3344 });
33108
- try { const prepared = prepareOwnerExtensionFolder(); if (prepared.changed) console.log(`[extension-bridge] extension folder ${prepared.previousVersion ? `refreshed ${prepared.previousVersion} → ${prepared.version}` : `prepared (${prepared.version})`}; reload the extension in the browser`); }
33109
- catch (error) { console.warn(`[extension-bridge] extension folder not prepared (${error?.code || 'error'})`); }
33445
+ // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked). Its files are the one package this
33446
+ // release pins (lib/browser-extension-pin.js), downloaded from synabun.ai and verified (lib/browser-extension-package.js):
33447
+ // nothing of the extension is inside the app, and nothing here needs it or the network to start. At start only the
33448
+ // folder's own setup content script is brought to this server's port (no network). A folder older than the pin is
33449
+ // refreshed after listen, in the background (the old one stays on any failure); a folder that is not there is
33450
+ // downloaded only when the owner starts "Connect your browser". The browser then needs the extension's Reload, which
33451
+ // Settings and the setup page say (`reloadNeeded`). Never fatal.
33452
+ const extensionPackage = createExtensionPackage({
33453
+ home: DATA_HOME, appPort: () => Number(PORT) || 3344,
33454
+ log: record => console.log('[extension-bridge]', JSON.stringify(record)),
33455
+ });
33456
+ // Under the data home's lock: a replacement a stopped process left is finished or taken back, its leftovers removed, the
33457
+ // pinned extension's setup script set to this port from its own verified files, and a changed folder repaired from the
33458
+ // verified package the data home keeps (no network; otherwise the background refresh below downloads it).
33459
+ try { const prepared = extensionPackage.retarget(); if (prepared.changed) console.log(`[extension-bridge] extension folder ${prepared.reason === 'repair' ? 'repaired from the verified package' : "set to this server's port"} (${prepared.version}); reload the extension in the browser`); else if (prepared.state === 'other') console.warn('[extension-bridge] the extension folder is not the pinned extension; it is downloaded again after start-up'); }
33460
+ catch (error) { console.warn(`[extension-bridge] extension folder not checked (${error?.code || 'error'}${error?.code === 'EXTENSION_FOLDER_UNSAFE' && error.reason ? `: ${error.reason}` : ''})`); }
33110
33461
  // The one-button setup (Settings → Browser → "Connect your browser"; docs/browser-extension-bridge.md → One-button
33111
33462
  // setup). Programs are started with execFile/spawn and argument arrays, never a shell; reads time out.
33463
+ const extensionUpdate = createExtensionUpdate({ bridge: extensionBridge, pkg: extensionPackage, runsActive: extensionRunsActive });
33112
33464
  const extensionSetup = createExtensionSetup({
33113
33465
  bridge: extensionBridge,
33114
33466
  detect: () => detectBrowsers({
@@ -33117,13 +33469,15 @@ const extensionSetup = createExtensionSetup({
33117
33469
  exists: path => { try { return existsSync(path); } catch { return false; } },
33118
33470
  list: dir => { try { return readdirSync(dir); } catch { return []; } },
33119
33471
  }),
33120
- prepare: () => prepareOwnerExtensionFolder(),
33472
+ prepare: ({ signal } = {}) => extensionPackage.ensure({ reason: 'setup', signal }),
33473
+ packageStatus: () => extensionPackage.status(),
33474
+ confirmReload: () => extensionPackage.confirmReload(),
33475
+ updateStatus: (peer, disk) => extensionUpdate.status(peer, disk),
33121
33476
  exec: (cmd, args) => new Promise((resolveExec, rejectExec) => {
33122
33477
  const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true, shell: false });
33123
33478
  child.once('error', rejectExec); child.once('spawn', () => { child.unref(); resolveExec(); });
33124
33479
  }),
33125
33480
  appOrigin: () => `http://127.0.0.1:${Number(PORT) || 3344}`,
33126
- folderVersion: () => extensionFolderState(DATA_HOME).version,
33127
33481
  });
33128
33482
  {
33129
33483
  const restored = extensionBridge.restore();
@@ -33448,14 +33802,44 @@ function sessionServesMoreLoginEnv(session, envId) {
33448
33802
  return !!session && session._profileMode === 'morelogin' && String(session._mlEnvId || '') === String(envId);
33449
33803
  }
33450
33804
 
33451
- /** Whether `session` is a browser run `ownerKey` may work in: its pinned profile's, else the default browser's. */
33805
+ /**
33806
+ * Whether `session` is a browser run `ownerKey` may work in: its pinned profile's, else the default browser's.
33807
+ * No session serves. An unpinned run gets a MoreLogin session only while MoreLogin is the default browser (and then
33808
+ * only the default profile's), and a local session (clean, managed, direct, mirror, attach) only when it is the one
33809
+ * Settings → Browser selects, by the rule findReusableBrowserSession reuses by. Before review round 3 any MoreLogin
33810
+ * or local session served a run under a mirror / attach / clean default, so a requested session id reached another
33811
+ * profile in strategy 0 of acquireSharedBrowserTab (which also destroys a requested session that fails its check).
33812
+ */
33452
33813
  function sessionServesRun(session, cfg, ownerKey) {
33814
+ if (!session) return false;
33453
33815
  const pin = runMoreLoginPin(ownerKey);
33454
33816
  // A pin that may not be used (an agent's, its profile off the owner's list) serves in no session at all: not its
33455
33817
  // profile's, and never the default browser's.
33456
33818
  if (pin) return !pinUseRefusal(pin, cfg) && sessionServesMoreLoginEnv(session, pin.envId);
33457
- if (cfg.connectMode === 'extension' || session?._profileMode === 'extension') return cfg.connectMode === 'extension' && session?._profileMode === 'extension';
33458
- return cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg);
33819
+ if (cfg.connectMode === 'extension' || session._profileMode === 'extension') return cfg.connectMode === 'extension' && session._profileMode === 'extension';
33820
+ if (cfg.connectMode === 'morelogin' || session._profileMode === 'morelogin') return cfg.connectMode === 'morelogin' && sessionServesMoreLoginDefault(session, cfg);
33821
+ return sessionServesLocalBrowser(session, cfg);
33822
+ }
33823
+
33824
+ /**
33825
+ * Whether a local session (not MoreLogin, not the extension) is the browser Settings → Browser selects: attach when
33826
+ * attach is active and a launch otherwise, on the selected profile folder, or a clean session when none is selected.
33827
+ * findReusableBrowserSession reuses by this rule, and sessionServesRun holds a requested or recorded session to it.
33828
+ */
33829
+ function sessionServesLocalBrowser(session, cfg) {
33830
+ if (!session || session._profileMode === 'morelogin' || session._profileMode === 'extension') return false;
33831
+ if (isAttachConfigActive(cfg) !== (session._profileMode === 'cdp')) return false;
33832
+ let selectedPath = cfg.userDataDir || '';
33833
+ if (selectedPath && !selectedPath.startsWith('/') && !(/^[A-Z]:/i.test(selectedPath))) {
33834
+ selectedPath = resolve(DATA_HOME, selectedPath);
33835
+ }
33836
+ const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
33837
+ const selectedNorm = normalize(selectedPath);
33838
+ if (!selectedNorm) return session._profileMode === 'clean';
33839
+ const sessionSelected = normalize(session._selectedProfilePath);
33840
+ const sessionRoot = normalize(session._launchUserDataDir);
33841
+ const sessionActiveProfile = normalize(resolve(session._launchUserDataDir || '', session._launchProfileDirectory || 'Default'));
33842
+ return selectedNorm === sessionSelected || selectedNorm === sessionRoot || selectedNorm === sessionActiveProfile;
33459
33843
  }
33460
33844
 
33461
33845
  function describeBrowserSessionForLog(session) {
@@ -33468,17 +33852,7 @@ function describeBrowserSessionForLog(session) {
33468
33852
  async function findReusableBrowserSession(opts = {}) {
33469
33853
  const { excludeAgentOwned = true, excludeLoopOwned = true, moreloginEnvId = null } = opts;
33470
33854
  const cfg = loadBrowserConfig();
33471
- // Don't reuse across connect modes: an attach (cdp) session and a mirror session
33472
- // are not interchangeable. Protects in-flight loops when the mode is switched.
33473
- // Use the same applicability test as session creation to avoid infinite re-spawn.
33474
- const wantAttach = isAttachConfigActive(cfg);
33475
33855
  const wantMoreLogin = cfg.connectMode === 'morelogin';
33476
- let selectedPath = cfg.userDataDir || '';
33477
- if (selectedPath && !selectedPath.startsWith('/') && !(/^[A-Z]:/i.test(selectedPath))) {
33478
- selectedPath = resolve(DATA_HOME, selectedPath);
33479
- }
33480
- const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
33481
- const selectedNorm = normalize(selectedPath);
33482
33856
  for (const [id, session] of browserSessions) {
33483
33857
  if (session._profileMode === 'extension' || cfg.connectMode === 'extension' && !moreloginEnvId) {
33484
33858
  if (session._profileMode === 'extension' && cfg.connectMode === 'extension' && extensionBridge.status().connected && !moreloginEnvId) return { id, session };
@@ -33503,19 +33877,11 @@ async function findReusableBrowserSession(opts = {}) {
33503
33877
  if (!sessionServesMoreLoginEnv(session, moreloginEnvId)) continue;
33504
33878
  } else if (wantMoreLogin || session._profileMode === 'morelogin') {
33505
33879
  if (!wantMoreLogin || !sessionServesMoreLoginDefault(session, cfg)) continue;
33506
- } else {
33507
- if (wantAttach && session._profileMode !== 'cdp') continue;
33508
- if (!wantAttach && session._profileMode === 'cdp') continue;
33509
- if (selectedNorm) {
33510
- const sessionSelected = normalize(session._selectedProfilePath);
33511
- const sessionRoot = normalize(session._launchUserDataDir);
33512
- const sessionActiveProfile = normalize(resolve(session._launchUserDataDir || '', session._launchProfileDirectory || 'Default'));
33513
- if (selectedNorm !== sessionSelected && selectedNorm !== sessionRoot && selectedNorm !== sessionActiveProfile) {
33514
- continue;
33515
- }
33516
- } else if (session._profileMode !== 'clean') {
33517
- continue;
33518
- }
33880
+ } else if (!sessionServesLocalBrowser(session, cfg)) {
33881
+ // Don't reuse across connect modes or profile folders: an attach (cdp) session and a mirror session are not
33882
+ // interchangeable. Protects in-flight loops when the mode is switched. The same applicability test as session
33883
+ // creation (isAttachConfigActive) avoids an infinite re-spawn.
33884
+ continue;
33519
33885
  }
33520
33886
  try {
33521
33887
  // Do not probe only the mutable `session.page` alias here. A renderer can
@@ -33621,7 +33987,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33621
33987
  if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
33622
33988
  // takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
33623
33989
  try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
33624
- catch (error) { return extensionSafeError(error); }
33990
+ catch (error) { return extensionAdapter.describeError(error); }
33625
33991
  }
33626
33992
  const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
33627
33993
  const acquired = await withLoopBrowserLock(lockKey, async () => {
@@ -33692,6 +34058,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33692
34058
  // createBrowserSession is strict: with MoreLogin as the default it either attaches
33693
34059
  // to MoreLogin (auto-launching the app) or throws — never a Chrome fallback.
33694
34060
  let createError = null;
34061
+ let createdHere = false;
33695
34062
  if (!browserSessionId) {
33696
34063
  try {
33697
34064
  // The start guard: a profile closed outside SynaBun is not started again by this acquisition (an attach to the
@@ -33703,6 +34070,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33703
34070
  ? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true, moreloginStartGuard, moreloginAfterOutsideClose }
33704
34071
  : { url: 'about:blank', moreloginStartGuard, moreloginAfterOutsideClose });
33705
34072
  browserSessionId = result.sessionId;
34073
+ createdHere = true;
33706
34074
  loopLog(ownerKey, logTag, 'strategy 2: created shared browser session', {
33707
34075
  browserSessionId, profileMode: result.profileMode, profileSource: result.profileSource,
33708
34076
  });
@@ -33722,9 +34090,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33722
34090
  // The run's own profile (its pin, else the MoreLogin default) failed to start or connect in this run: from now on
33723
34091
  // it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
33724
34092
  // profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
34093
+ let profileAdvice = '';
33725
34094
  if (createError) {
33726
34095
  const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
33727
34096
  noteRunProfileFailure(ownerKey, own, createError);
34097
+ if (own && !createError.code) {
34098
+ profileAdvice = await stoppedProfileAdvice(own.envId, own.name || _moreLoginEnvNames.get(own.envId),
34099
+ id => moreLogin.profileStatus(id, { savedCfg: policyCfg, timeout: 1500 }));
34100
+ }
33728
34101
  }
33729
34102
  // The profile was closed outside SynaBun: the sentence says it all (which profile, when, that SynaBun does not
33730
34103
  // reopen it, how to go on); no "could not start" around it.
@@ -33744,9 +34117,9 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33744
34117
  ? `this needs the user, not a retry: ${createError.planLimit ? 'wait for MoreLogin\'s daily reset, upgrade the MoreLogin plan, or keep the profile open so runs need no new start' : 'fix what MoreLogin names in the MoreLogin app'}.`
33745
34118
  : createError?.code === 'MORELOGIN_PROFILE_WINDOWLESS'
33746
34119
  ? 'this needs the user, not a retry: open the profile\'s window again in MoreLogin (or close it fully there and start it again).'
33747
- : 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
34120
+ : profileAdvice || 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
33748
34121
  : createError
33749
- ? `Could not start the shared browser session: ${createError.error}`
34122
+ ? `Could not start the shared browser session: ${createError.error}${profileAdvice ? `${/[.!?]$/.test(String(createError.error || '').trim()) ? '' : '.'} ${profileAdvice}` : ''}`
33750
34123
  : 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
33751
34124
  ...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
33752
34125
  ...(createError?.needsUser ? { needsUser: true } : {}),
@@ -33762,7 +34135,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33762
34135
  browserSessionId, ...describeBrowserSessionForLog(chosenSession), wantMoreLoginEnvId: pin.envId,
33763
34136
  });
33764
34137
  return {
33765
- error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): this run is set to ${describeMoreLoginPin(pin)} and never falls back to another profile or browser.`,
34138
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): this run is set to ${describeMoreLoginPin(pin)} and never falls back to another profile or browser. Open the profile configured for this run.`,
33766
34139
  };
33767
34140
  }
33768
34141
  if (!pin && moreLoginDefault && chosenSession && !sessionServesMoreLoginDefault(chosenSession, policyCfg)) {
@@ -33770,7 +34143,18 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33770
34143
  browserSessionId, ...describeBrowserSessionForLog(chosenSession),
33771
34144
  });
33772
34145
  return {
33773
- error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode): MoreLogin env ${moreLoginDefaultEnvId(policyCfg) || '(default)'} is the default browser, and automations never fall back to another browser.`,
34146
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode): MoreLogin env ${moreLoginDefaultEnvId(policyCfg) || '(default)'} is the default browser, and automations never fall back to another browser. Open the configured AI browser profile.`,
34147
+ };
34148
+ }
34149
+ // A reused or requested session for a run on SynaBun's own browser (mirror, attach, clean) is the one its settings
34150
+ // select, and never a MoreLogin profile or another local profile (sessionServesRun; review round 3, X1). The
34151
+ // session this acquisition just created is that browser by construction.
34152
+ if (!pin && !moreLoginDefault && chosenSession && !createdHere && !sessionServesRun(chosenSession, policyCfg, ownerKey)) {
34153
+ loopLog(ownerKey, logTag, 'ABORT: acquired session is not the default browser', {
34154
+ browserSessionId, ...describeBrowserSessionForLog(chosenSession),
34155
+ });
34156
+ return {
34157
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): it is not the browser selected in Settings → Browser, and automations never fall back to another browser or profile.`,
33774
34158
  };
33775
34159
  }
33776
34160
 
@@ -37364,7 +37748,7 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
37364
37748
  }
37365
37749
  const envId = moreLoginDefaultEnvId(cfg);
37366
37750
  res.status(409).json({
37367
- error: `Session ${req.params.id} is not the default browser (${session._profileMode || 'unknown'} mode${session._mlEnvId ? `, MoreLogin env ${session._mlEnvId}` : ''}; the default is MoreLogin${envId ? ` env ${envId}` : ''}), so SynaBun's browser tools do not act on it. Leave sessionId out: browser_navigate opens the page in the default browser.`,
37751
+ error: `Session ${req.params.id} is not the default browser (${session._profileMode || 'unknown'} mode${session._mlEnvId ? `, MoreLogin env ${session._mlEnvId}` : ''}; the default is ${cfg.connectMode === 'morelogin' ? `MoreLogin${envId ? ` env ${envId}` : ''}` : cfg.connectMode === 'extension' ? 'the SynaBun browser extension' : 'the browser selected in Settings → Browser'}), so SynaBun's browser tools do not act on it. Leave sessionId out: browser_navigate opens the page in the default browser.`,
37368
37752
  code: 'NOT_DEFAULT_BROWSER',
37369
37753
  });
37370
37754
  };
@@ -37386,12 +37770,18 @@ app.use('/api/browser/extension', extensionOwnerGuard, (req, res, next) => {
37386
37770
  res.setHeader('Cache-Control', 'no-store'); next();
37387
37771
  });
37388
37772
  app.get('/api/browser/extension', (_req, res) => {
37389
- const folderState = extensionFolderState(DATA_HOME), status = extensionBridge.status();
37390
- // `folder`: the folder the owner loads (the prepared copy; the bundled one only when none could be prepared).
37391
- res.json({ ...status, folder: folderState.prepared ? folderState.folder : EXTENSION_FOLDER, bundledFolder: EXTENSION_FOLDER, uploadFolder: extensionUploadRoot,
37392
- folderVersion: folderState.version, reloadNeeded: !!(status.connected && folderState.version && status.extensionVersion !== folderState.version),
37393
- setup: extensionSetup.status().state });
37394
- });
37773
+ const status = extensionBridge.status();
37774
+ // `folder`: the folder the owner loads, once it is there (null until "Connect your browser" downloaded the extension).
37775
+ // `package`: the pinned package and its download (pinnedVersion, needs, phase, received, total, code).
37776
+ const pkg = extensionPackage.status();
37777
+ res.json({ ...status, folder: pkg.folder, uploadFolder: extensionUploadRoot,
37778
+ folderVersion: pkg.folderVersion, pinnedVersion: pkg.pinnedVersion, package: pkg,
37779
+ ...extensionVersions({ connected: status.connected, extensionVersion: status.extensionVersion, folderVersion: pkg.folderVersion, pinnedVersion: pkg.pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
37780
+ update: extensionUpdate.status(status, pkg), setup: extensionSetup.state() });
37781
+ });
37782
+ // A summary without paths, tab inventories or pairing data for the owner's proactive notices.
37783
+ app.get('/api/browser/extension/update/status', (_req, res) => res.json(extensionUpdate.status()));
37784
+ app.post('/api/browser/extension/reload', ownerReloadHandler({ update: extensionUpdate, isAutomationBrowser: req => _pageSession.isAutomationBrowser(req) }));
37395
37785
  // The one-button setup. Owner only: these sit under the guard above (ownerRouteGuard, the page secret, no automation
37396
37786
  // caller), like pairing and the mode. The token (ticket) goes to SynaBun's own setup page only, never into a log or URL.
37397
37787
  const sendSetup = (res, run) => Promise.resolve().then(run).then(value => res.json({ ok: true, ...value }),
@@ -37402,6 +37792,20 @@ app.post('/api/browser/extension/setup/ticket', (_req, res) => { res.setHeader('
37402
37792
  app.post('/api/browser/extension/setup/cancel', (_req, res) => sendSetup(res, () => extensionSetup.cancel()));
37403
37793
  app.post('/api/browser/extension/setup/reveal', (_req, res) => sendSetup(res, () => extensionSetup.reveal()));
37404
37794
  app.post('/api/browser/extension/setup/reopen', (_req, res) => sendSetup(res, () => extensionSetup.reopen()));
37795
+ // The setup page saw the extension's content script on this port: the Reload a port change asked for is done. A
37796
+ // repair's Reload is not (the copy the browser still runs answers the page just the same): see reload/confirm.
37797
+ app.post('/api/browser/extension/setup/seen', (_req, res) => sendSetup(res, () => extensionSetup.seen()));
37798
+ // The owner's click in Settings ("I reloaded the extension"): the one way a repair's Reload is cleared. Behind the
37799
+ // guard above like `seen` (ownerRouteGuard with its own Origin required, this boot's page secret, no agent or guest),
37800
+ // and also refused here for a request from an extension's own origin, one the browser does not mark same-origin, or
37801
+ // one without the app's X-SynaBun-UI header. The body must say so (`reloaded: true`): nothing the page loads or polls
37802
+ // sends it.
37803
+ app.post('/api/browser/extension/reload/confirm', (req, res) => {
37804
+ const origin = String(req.headers.origin || ''), site = req.headers['sec-fetch-site'];
37805
+ if (/^[a-z-]*extension:/i.test(origin) || (site !== undefined && site !== 'same-origin') || req.headers['x-synabun-ui'] !== '1') return res.status(403).json({ code: 'OWNER_ROUTE', error: 'Only the owner\'s SynaBun Settings can confirm the Reload.' });
37806
+ if (req.body?.reloaded !== true) return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Send { "reloaded": true } once the extension was reloaded in the browser.' });
37807
+ return sendSetup(res, () => ({ cleared: extensionPackage.confirmRepairReload(), ...extensionSetup.status() }));
37808
+ });
37405
37809
  app.post('/api/browser/extension/:action', async (req, res) => {
37406
37810
  try {
37407
37811
  const action = req.params.action;
@@ -37413,6 +37817,8 @@ app.post('/api/browser/extension/:action', async (req, res) => {
37413
37817
  else if (action === 'revoke-site') await extensionBridge.revokeSite(req.body?.site);
37414
37818
  // The owner's mode: full control (any site and tab of the paired browser) or only what the owner shares.
37415
37819
  else if (action === 'mode') await extensionBridge.setMode(req.body?.fullControl);
37820
+ // The owner's retry of an update that did not download (Settings): only for a folder that is already there.
37821
+ else if (action === 'update') { if (extensionPackage.needs() === 'update') extensionPackage.ensure({ reason: 'update' }).then(() => extensionBridge.publishUpdate(), () => {}); }
37416
37822
  else return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Unknown extension action.' });
37417
37823
  return res.json({ ok: true, ...extensionBridge.status() });
37418
37824
  } catch (error) { return res.status(400).json(extensionSafeError(error)); }
@@ -37484,6 +37890,7 @@ app.get('/api/browser/sessions', (req, res) => {
37484
37890
  // A run's own route as the server last recorded it (a recovery or a browser_session create moved it): the MCP
37485
37891
  // follows it even after its process restarted and forgot (mcp-server neural-interface.ts resolveSessionUncached).
37486
37892
  const yourRoute = caller ? liveAutomationRoute(caller, { cfg: policyCfg }) : null;
37893
+ const workerBrowser = who.status === 'verified' && _assistantDispatcher?.optionalBrowserRoute?.(caller);
37487
37894
  res.json({
37488
37895
  sessions,
37489
37896
  defaultBrowser: callerPin
@@ -37491,6 +37898,7 @@ app.get('/api/browser/sessions', (req, res) => {
37491
37898
  : moreLoginDefault
37492
37899
  ? { connectMode: 'morelogin', moreloginEnvId: moreLoginDefaultEnvId(policyCfg) }
37493
37900
  : { connectMode: policyCfg.connectMode || null },
37901
+ ...(workerBrowser ? { workerBrowser } : {}),
37494
37902
  ...(yourRoute ? { yourRoute: { sessionId: yourRoute.browserSessionId, tabId: yourRoute.browserTabId } } : {}),
37495
37903
  // The MoreLogin profile this caller works in when it is not the default (its launch's, or its own choice: POST
37496
37904
  // /api/morelogin/use). The MCP reads it to move a run whose pinned tab is in a browser it left.
@@ -39971,6 +40379,14 @@ const httpServer = app.listen(PORT, async () => {
39971
40379
  // The lists windows, menus and Settings wait for, read once in the background (see LAUNCH_TASKS above).
39972
40380
  startLaunchWarmup();
39973
40381
 
40382
+ // The owner's extension folder, when it holds an older extension than this release pins: the pinned package is
40383
+ // fetched and verified in the background (lib/browser-extension-package.js). Nothing is downloaded for somebody who
40384
+ // never set the extension up, and a failure keeps the folder that is there.
40385
+ setTimeout(() => {
40386
+ try { markActivity('startup:extension-package'); extensionPackage.refreshInBackground()?.then(() => extensionBridge.publishUpdate(), () => {}); }
40387
+ catch (error) { console.warn(`[extension-bridge] extension update not started (${error?.code || 'error'})`); }
40388
+ }, 4000).unref?.();
40389
+
39974
40390
  // Windows: the Git Bash every Claude Code gets (lib/git-bash/). Looked for now (the settings of the user's own
39975
40391
  // claude follow it); a PC with none, and an app that carries none, gets SynaBun's copy, fetched in the background.
39976
40392
  setTimeout(() => {
@@ -40972,7 +41388,8 @@ process.on('exit', () => {
40972
41388
  try { _whatsapp?.killNow(); } catch {}
40973
41389
  try { tunnel.killNow(); } catch {}
40974
41390
  try { gitBash.cancel(); } catch {}
40975
- try { stopOpencodeServer(); } catch {}
41391
+ try { stopOpencodeServer({ immediate: true }); } catch {}
41392
+ try { _ocpServeEnds.killNow(); } catch {}
40976
41393
  try { editorCompletionServe.stop('exit'); } catch {}
40977
41394
  try { _claudeBridge?.shutdownAllBridges?.(); } catch {}
40978
41395
  try { antigravityPanel.closeAll(); } catch {}