synabun 2.4.0 → 2.4.2

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 (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. package/setup.js +18 -4
@@ -0,0 +1,241 @@
1
+ // ═══════════════════════════════════════════
2
+ // SETTINGS — What to back up
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // Settings → Memory & backups → Backups → What to back up. A backup is made of groups (lib/backup-groups.js) and the
6
+ // owner switches each on or off, with its size beside it; the choice is the server's (lib/backup-contents.js, GET and
7
+ // PUT /api/system/backup/contents) and applies to every manual and scheduled backup. The sizes are measured on a
8
+ // worker thread there: this page reads what is measured and asks again while a measurement runs.
9
+ // Pure: no DOM and no import, so node runs it (tests/settings-backup-contents.test.mjs).
10
+ //
11
+ // readBackupContentsResponse({ status, body, error }) what the server answered → a reading
12
+ // describeBackupContents(model, { tx }) the list as ui-settings.js draws it
13
+ // describeRestoreContents(contents, { tx }) what a backup holds, for the restore dialog
14
+ // createBackupContentsController({ fetch, render, … }) load, switch a group, measure again
15
+ //
16
+ // `tx(key, params)` is the caller's translate function over the settings.redesign.* strings (the kit's `tx`).
17
+ // A server started before these routes existed answers 404: the list then says a restart is missing, and until
18
+ // then every backup holds everything, as it always did.
19
+
20
+ const K = 'settings.redesign.server';
21
+
22
+ export const BACKUP_CONTENTS_URL = '/api/system/backup/contents';
23
+
24
+ // Every key written out: the settings copy tools find a key by its literal.
25
+ const GROUP_COPY = {
26
+ memories: { label: `${K}.backupGroupMemories`, help: `${K}.backupGroupMemoriesHelp` },
27
+ settings: { label: `${K}.backupGroupSettings`, help: `${K}.backupGroupSettingsHelp` },
28
+ conversations: { label: `${K}.backupGroupConversations`, help: `${K}.backupGroupConversationsHelp` },
29
+ media: { label: `${K}.backupGroupMedia`, help: `${K}.backupGroupMediaHelp` },
30
+ caches: { label: `${K}.backupGroupCaches`, help: `${K}.backupGroupCachesHelp` },
31
+ scratch: { label: `${K}.backupGroupScratch`, help: `${K}.backupGroupScratchHelp` },
32
+ };
33
+ const KIND_COPY = {
34
+ irreplaceable: `${K}.backupKindIrreplaceable`,
35
+ regenerable: `${K}.backupKindRegenerable`,
36
+ temporary: `${K}.backupKindTemporary`,
37
+ };
38
+
39
+ const clean = (value, max = 400) => {
40
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
41
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
42
+ };
43
+
44
+ /** A size with its unit: KB below a megabyte, MB below a gigabyte, GB from there. '' for what is not a size. */
45
+ export function formatContentsSize(bytes) {
46
+ const size = Number(bytes);
47
+ if (bytes == null || !Number.isFinite(size) || size < 0) return '';
48
+ if (size >= 1024 ** 3) return `${(size / 1024 ** 3).toFixed(2)} GB`;
49
+ if (size >= 1024 ** 2) return `${(size / 1024 ** 2).toFixed(size >= 100 * 1024 ** 2 ? 0 : 1)} MB`;
50
+ return `${Math.max(size > 0 ? 1 : 0, Math.round(size / 1024))} KB`;
51
+ }
52
+
53
+ /** The name of a group as the page says it; a group this page does not know keeps its id. */
54
+ export function backupGroupLabel(id, tx) {
55
+ return GROUP_COPY[id] ? tx(GROUP_COPY[id].label) : String(id);
56
+ }
57
+
58
+ /**
59
+ * What the server answered.
60
+ * ready `groups` [{ id, kind, enabled, files, bytes, archiveBytes }], `totals`, `never`, `irreplaceableOff`,
61
+ * `estimate` { state: 'none' | 'measuring' | 'ready' | 'failed', error }
62
+ * old-server 404: the running server was started before these routes existed
63
+ * refused an answer with an error and no state (`message`, `code`)
64
+ * unreadable anything else; `message`
65
+ */
66
+ export function readBackupContentsResponse({ status = 0, body = null, error = null } = {}) {
67
+ const code = Number(status) || 0;
68
+ if (code === 404) return { state: 'old-server' };
69
+ if (body && typeof body === 'object' && Array.isArray(body.groups) && code >= 200 && code < 300) {
70
+ // An id is used in the rows' element ids: only the shape a group id has is let through.
71
+ const groups = body.groups.filter(group => group && typeof group.id === 'string' && /^[a-z][a-z0-9-]{0,39}$/.test(group.id)).map(group => ({
72
+ id: group.id,
73
+ kind: typeof group.kind === 'string' ? group.kind : 'irreplaceable',
74
+ enabled: group.enabled === true,
75
+ files: Number.isFinite(group.files) ? group.files : null,
76
+ bytes: Number.isFinite(group.bytes) ? group.bytes : null,
77
+ archiveBytes: Number.isFinite(group.archiveBytes) ? group.archiveBytes : null,
78
+ }));
79
+ const estimate = body.estimate && typeof body.estimate === 'object' ? body.estimate : {};
80
+ return {
81
+ state: 'ready', groups,
82
+ totals: body.totals && typeof body.totals === 'object' ? body.totals : null,
83
+ never: body.never && typeof body.never === 'object' ? body.never : null,
84
+ irreplaceableOff: Array.isArray(body.irreplaceableOff) ? body.irreplaceableOff.filter(id => typeof id === 'string') : [],
85
+ estimate: { state: typeof estimate.state === 'string' ? estimate.state : 'none', error: clean(estimate.error) || null },
86
+ };
87
+ }
88
+ if (body && typeof body === 'object' && body.error) return { state: 'refused', message: clean(body.error), code: body.code || null };
89
+ return { state: 'unreadable', message: clean(error?.message || error) || (code ? `HTTP ${code}` : '') };
90
+ }
91
+
92
+ /**
93
+ * The list. `model`: `{ reading, notice, saving }`, the controller's. →
94
+ * available the server has the choice (false: `note` says why not, and no row is drawn)
95
+ * rows [{ id, label, help, kind, kindLabel, enabled, size, busy }] `size` '' while it is not measured
96
+ * total the size of a backup made with this choice ('' while it is not measured)
97
+ * everything the size with every group on, when that is more ('' otherwise)
98
+ * warning which irreplaceable groups are switched off (null: none)
99
+ * never what no backup holds, with its size (null while it is not measured)
100
+ * note a refusal, a failed save or a failed measurement (null: nothing)
101
+ * measuring a measurement runs
102
+ */
103
+ export function describeBackupContents({ reading = null, notice = null, saving = null } = {}, { tx }) {
104
+ if (reading?.state === 'old-server') return { available: false, rows: [], total: '', everything: '', warning: null, never: null, measuring: false, note: tx(`${K}.backupContentsNeedsRestart`) };
105
+ if (!reading || reading.state === 'loading') return { available: false, rows: [], total: '', everything: '', warning: null, never: null, measuring: false, note: null };
106
+ if (reading.state !== 'ready') {
107
+ return { available: false, rows: [], total: '', everything: '', warning: null, never: null, measuring: false, note: tx(`${K}.backupContentsUnreadable`, { message: reading.message || '' }) };
108
+ }
109
+ const rows = reading.groups.map((group) => {
110
+ const copy = GROUP_COPY[group.id];
111
+ const measured = group.bytes != null;
112
+ return {
113
+ id: group.id,
114
+ label: copy ? tx(copy.label) : group.id,
115
+ help: copy ? tx(copy.help) : '',
116
+ kind: group.kind,
117
+ kindLabel: KIND_COPY[group.kind] ? tx(KIND_COPY[group.kind]) : '',
118
+ enabled: group.enabled,
119
+ size: !measured ? '' : group.files === 0 ? tx(`${K}.backupGroupEmpty`)
120
+ : tx(`${K}.backupGroupSize`, { size: formatContentsSize(group.bytes), archive: formatContentsSize(group.archiveBytes) }),
121
+ busy: saving === group.id,
122
+ };
123
+ });
124
+ const selected = reading.totals?.selected;
125
+ const everything = reading.totals?.everything;
126
+ const off = reading.irreplaceableOff.map(id => backupGroupLabel(id, tx));
127
+ let note = null;
128
+ if (notice?.kind === 'save') note = tx(`${K}.backupContentsSaveFailed`, { message: notice.message });
129
+ else if (reading.estimate.state === 'failed') note = tx(`${K}.backupContentsMeasureFailed`, { message: reading.estimate.error || '' });
130
+ return {
131
+ available: true,
132
+ rows,
133
+ total: selected ? tx(`${K}.backupContentsTotal`, { archive: formatContentsSize(selected.archiveBytes), size: formatContentsSize(selected.bytes), files: selected.files }) : '',
134
+ everything: selected && everything && everything.bytes > selected.bytes ? tx(`${K}.backupContentsEverything`, { archive: formatContentsSize(everything.archiveBytes) }) : '',
135
+ warning: off.length ? tx(`${K}.backupContentsWarning`, { groups: off.join(', ') }) : null,
136
+ never: reading.never ? tx(`${K}.backupContentsNever`, { size: formatContentsSize(reading.never.bytes) }) : null,
137
+ measuring: reading.estimate.state === 'measuring',
138
+ note,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * What a backup holds, for the restore dialog, from the server's reading of its manifest (`contents` of POST
144
+ * /api/system/restore/preview: { recorded, included, excluded, complete, legacy }). →
145
+ * contains the groups in it, by name ('' when none is known)
146
+ * missing the groups it does not contain, by name: a restore leaves them as they are ('' when it holds all)
147
+ * stateOnly a pre-update snapshot: state without generated media
148
+ * null when the server said nothing about groups (a server from before).
149
+ */
150
+ export function describeRestoreContents(contents, { tx }) {
151
+ if (!contents || typeof contents !== 'object' || !Array.isArray(contents.included)) return null;
152
+ const names = (list) => (Array.isArray(list) ? list : []).filter(id => typeof id === 'string').map(id => backupGroupLabel(id, tx)).join(', ');
153
+ const contains = names(contents.included);
154
+ const missing = contents.complete === true ? '' : names(contents.excluded);
155
+ return {
156
+ contains: contains ? tx(`${K}.restoreContains`, { groups: contains }) : '',
157
+ missing: missing ? tx(`${K}.restoreNotContained`, { groups: missing }) : '',
158
+ stateOnly: contents.legacy === 'state-only' ? tx(`${K}.restoreStateOnly`) : '',
159
+ };
160
+ }
161
+
162
+ /**
163
+ * The list's behaviour, without a DOM. `render(model)` is called with `{ reading, notice, saving }` after every change.
164
+ * @param {object} o
165
+ * @param {typeof fetch} o.fetch
166
+ * @param {(model: object) => void} o.render
167
+ * @param {(ms: number) => Promise<void>} [o.wait] the pause between two looks at a running measurement
168
+ * @param {number} [o.pollMs]
169
+ * @param {number} [o.maxPolls] a measurement that long is no longer followed
170
+ * @param {() => boolean} [o.alive] false once the list is gone
171
+ */
172
+ export function createBackupContentsController({
173
+ fetch, render, wait = (ms) => new Promise((done) => setTimeout(done, ms)), pollMs = 1000, maxPolls = 180, alive = () => true,
174
+ } = {}) {
175
+ let reading = { state: 'loading' };
176
+ let notice = null;
177
+ let saving = null;
178
+ let following = false;
179
+
180
+ const show = () => { try { render({ reading, notice, saving }); } catch { /* a list that cannot be drawn changes nothing here */ } };
181
+
182
+ async function ask(method, url, body) {
183
+ try {
184
+ const init = { method };
185
+ if (body !== undefined) { init.headers = { 'Content-Type': 'application/json' }; init.body = JSON.stringify(body); }
186
+ const res = await fetch(url, init);
187
+ let json = null;
188
+ try { json = await res.json(); } catch { json = null; }
189
+ return readBackupContentsResponse({ status: res.status, body: json });
190
+ } catch (error) {
191
+ return readBackupContentsResponse({ error });
192
+ }
193
+ }
194
+
195
+ const measuring = () => reading.state === 'ready' && reading.estimate.state === 'measuring';
196
+
197
+ // Ask again while the server measures. A look that fails keeps what was known.
198
+ async function follow() {
199
+ if (following) return;
200
+ following = true;
201
+ try {
202
+ for (let polls = 0; measuring() && alive() && polls < maxPolls; polls++) {
203
+ await wait(pollMs);
204
+ if (saving) continue; // the answer to the switch under way is the newer state
205
+ const next = await ask('GET', BACKUP_CONTENTS_URL);
206
+ if (next.state === 'ready' && !saving) reading = next;
207
+ show();
208
+ }
209
+ } finally { following = false; }
210
+ }
211
+
212
+ async function load({ refresh = false } = {}) {
213
+ const next = await ask('GET', refresh ? `${BACKUP_CONTENTS_URL}?refresh=1` : BACKUP_CONTENTS_URL);
214
+ // A refresh that fails keeps the list that was there.
215
+ if (next.state === 'ready' || reading.state !== 'ready') reading = next;
216
+ show();
217
+ if (measuring()) await follow();
218
+ }
219
+
220
+ /** Switch one group. The switch shows the choice at once; a refusal puts it back and says why. */
221
+ async function toggle(id, enabled) {
222
+ if (reading.state !== 'ready' || saving) { show(); return false; }
223
+ const before = reading;
224
+ saving = id;
225
+ notice = null;
226
+ reading = { ...reading, groups: reading.groups.map(group => (group.id === id ? { ...group, enabled: !!enabled } : group)) };
227
+ show();
228
+ const next = await ask('PUT', BACKUP_CONTENTS_URL, { groups: { [id]: !!enabled } });
229
+ saving = null;
230
+ if (next.state === 'ready') reading = next;
231
+ else {
232
+ reading = before;
233
+ notice = { kind: 'save', message: next.state === 'old-server' ? 'HTTP 404' : next.message || '' };
234
+ }
235
+ show();
236
+ if (measuring()) follow();
237
+ return next.state === 'ready';
238
+ }
239
+
240
+ return { load, toggle, refresh: () => load({ refresh: true }), model: () => ({ reading, notice, saving }) };
241
+ }
@@ -0,0 +1,298 @@
1
+ // ═══════════════════════════════════════════
2
+ // SETTINGS — Download backup, into a folder
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // Settings → Memory & backups → Backups → Download full backup. The server builds the archive in a folder of this
6
+ // computer and the page only starts it and asks how far it is (lib/backup-download.js; GET / POST
7
+ // /api/system/backup/job, POST /api/system/backup/job/cancel, PUT /api/system/backup/destination, POST
8
+ // /api/system/backup/reveal). The page never holds
9
+ // the archive: reading a multi-GB response into a Blob is what made the old download take forever and never land.
10
+ // Pure: no DOM and no import, so node runs it (tests/settings-backup-download-view.test.mjs).
11
+ //
12
+ // readBackupDownloadResponse({ status, body, error }) what the server answered → a reading
13
+ // describeBackupDownload(model, { tx }) the row as ui-settings.js draws it
14
+ // createBackupDownloadController({ fetch, render, … }) load, choose a folder, start, follow, cancel, reveal
15
+ // createBackupEndWatcher() (model) → true when a backup ended while the page looked
16
+ //
17
+ // `tx(key, params)` is the caller's translate function over the settings.redesign.* strings (the kit's `tx`).
18
+ // A server started before the job routes existed answers 404: the row then says a restart is missing and the
19
+ // button downloads through the browser, which every server can do.
20
+
21
+ const K = 'settings.redesign.server';
22
+
23
+ export const BACKUP_JOB_URL = '/api/system/backup/job';
24
+ export const BACKUP_CANCEL_URL = '/api/system/backup/job/cancel';
25
+ export const BACKUP_DESTINATION_URL = '/api/system/backup/destination';
26
+ export const BACKUP_REVEAL_URL = '/api/system/backup/reveal';
27
+ export const BACKUP_BROWSER_URL = '/api/system/backup';
28
+ export const FOLDER_PICKER_URL = '/api/browse-folder';
29
+
30
+ const clean = (value, max = 400) => {
31
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
32
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
33
+ };
34
+
35
+ /** A size with its unit: MB below a gigabyte, GB from there. '' for what is not a size. */
36
+ export function formatBackupSize(bytes) {
37
+ const size = Number(bytes);
38
+ if (bytes == null || !Number.isFinite(size) || size < 0) return '';
39
+ return size >= 1024 ** 3 ? `${(size / 1024 ** 3).toFixed(2)} GB` : `${(size / 1024 / 1024).toFixed(1)} MB`;
40
+ }
41
+
42
+ /**
43
+ * What the server answered.
44
+ *
45
+ * ready the state: `folderPath`, `isDefault`, `folderError`, `job` (or null), `canReveal`, `busy`
46
+ * old-server 404: the running server was started before the job routes existed
47
+ * refused an answer with an error and no state (`message`, `code`)
48
+ * unreadable anything else (no answer, a body that is not the payload); `message`
49
+ *
50
+ * A 409 BACKUP_RUNNING carries the state too: it reads as `ready` with `alreadyRunning`.
51
+ */
52
+ export function readBackupDownloadResponse({ status = 0, body = null, error = null } = {}) {
53
+ const code = Number(status) || 0;
54
+ if (code === 404) return { state: 'old-server' };
55
+ const destination = body && typeof body === 'object' ? body.destination : null;
56
+ if (destination && typeof destination.folderPath === 'string' && ((code >= 200 && code < 300) || code === 409)) {
57
+ const job = body.job && typeof body.job === 'object' && typeof body.job.state === 'string' ? body.job : null;
58
+ return {
59
+ state: 'ready', folderPath: destination.folderPath, isDefault: destination.isDefault === true,
60
+ folderError: clean(destination.error) || null, job, canReveal: body.canReveal === true, busy: body.busy === true,
61
+ alreadyRunning: code === 409,
62
+ };
63
+ }
64
+ if (body && typeof body === 'object' && body.error) return { state: 'refused', message: clean(body.error), code: body.code || null };
65
+ return { state: 'unreadable', message: clean(error?.message || error) || (code ? `HTTP ${code}` : '') };
66
+ }
67
+
68
+ function runningText(job, tx) {
69
+ const files = job.files ?? 0;
70
+ switch (job.phase) {
71
+ case 'queued': return tx(`${K}.backupQueued`);
72
+ case 'collect': return tx(`${K}.backupCollecting`);
73
+ case 'copy': return tx(`${K}.backupCopying`, { files, size: formatBackupSize(job.bytes) });
74
+ case 'checksum': return tx(`${K}.backupChecksumming`, { files });
75
+ case 'archive': return job.writtenBytes ? tx(`${K}.backupArchiving`, { size: formatBackupSize(job.writtenBytes) }) : tx(`${K}.backupArchivingStart`);
76
+ case 'verify': return tx(`${K}.backupVerifying`);
77
+ default: return tx(`${K}.creatingBackup`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The row. `model`: `{ reading, notice, acting }`, the controller's. →
83
+ * folder the folder shown in the field ('' when it is not known)
84
+ * folderNote what is wrong with it, or what stands in the way (null: nothing)
85
+ * status `{ dot: 'spin' | 'green' | 'red' | '', text }` or null (nothing to say)
86
+ * running a backup of this server is being made
87
+ * waiting the buttons wait: a backup runs, or a request of this row is on its way
88
+ * canChoose the folder can be chosen
89
+ * canReveal a finished backup can be shown in the file manager
90
+ * canCancel the running backup can be cancelled (a server that has the cancel route says `cancelling` on its job)
91
+ * viaBrowser the button downloads through the browser (a server from before)
92
+ */
93
+ export function describeBackupDownload({ reading = null, notice = null, acting = false } = {}, { tx }) {
94
+ const ready = reading?.state === 'ready';
95
+ const job = ready ? reading.job : null;
96
+ const running = job?.state === 'running';
97
+ const viaBrowser = reading?.state === 'old-server';
98
+
99
+ let folderNote = null;
100
+ if (viaBrowser) folderNote = tx(`${K}.backupNeedsRestart`);
101
+ else if (notice?.kind === 'folder') folderNote = tx(`${K}.backupFolderRefused`, { message: notice.message });
102
+ else if (ready && reading.folderError) folderNote = reading.folderError;
103
+ else if (reading && !ready && reading.state !== 'loading') folderNote = tx(`${K}.backupStateUnreadable`, { message: reading.message || '' });
104
+
105
+ let status = null;
106
+ if (running && job.cancelling) status = { dot: 'spin', text: tx(`${K}.backupCancelling`) };
107
+ else if (running) {
108
+ const text = runningText(job, tx);
109
+ status = { dot: 'spin', text: notice?.kind === 'running' ? `${tx(`${K}.backupAlreadyRunning`)} ${text}` : text };
110
+ } else if (notice?.kind === 'cancel') status = { dot: 'red', text: tx(`${K}.backupCancelFailed`, { message: notice.message }) };
111
+ else if (job?.state === 'cancelled') status = { dot: '', text: tx(`${K}.backupCancelled`) };
112
+ else if (notice?.kind === 'start') status = { dot: 'red', text: tx(`${K}.backupFailed`, { message: notice.message }) };
113
+ else if (notice?.kind === 'reveal') status = { dot: 'red', text: tx(`${K}.backupRevealFailed`, { message: notice.message }) };
114
+ else if (notice?.kind === 'browser') status = { dot: '', text: tx(`${K}.backupBrowserStarted`) };
115
+ else if (job?.state === 'done') status = { dot: 'green', text: tx(`${K}.backupSavedTo`, { path: job.path, size: formatBackupSize(job.sizeBytes) }) };
116
+ else if (job?.state === 'failed') status = { dot: 'red', text: tx(`${K}.backupFailed`, { message: job.error || '' }) };
117
+
118
+ return {
119
+ folder: ready ? reading.folderPath : '',
120
+ folderNote,
121
+ status,
122
+ running,
123
+ waiting: running || !!acting,
124
+ canChoose: ready,
125
+ canReveal: ready && reading.canReveal && job?.state === 'done' && !notice,
126
+ canCancel: running && job.cancelling === false,
127
+ viaBrowser,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Says when a backup has ended since the row was first drawn, so the list of recent backups can be read again:
133
+ * call the function it returns with every model the controller renders. True once per backup that ended (saved,
134
+ * failed or cancelled) while this page was looking, never for the state the page found when it opened, and never
135
+ * while a backup runs. A backup that began and ended between two looks counts too: its job is another one. A job is
136
+ * known by its id (by its file for an answer without one), so a later answer about the same ended job, with a time
137
+ * it did not carry before, is not another ending.
138
+ */
139
+ export function createBackupEndWatcher() {
140
+ let seen = false;
141
+ let last = '';
142
+ return ({ reading = null } = {}) => {
143
+ if (reading?.state !== 'ready') return false;
144
+ const job = reading.job;
145
+ const mark = !job ? 'none' : job.state === 'running' ? 'running' : `${job.state}:${job.id ?? job.path ?? ''}`;
146
+ const first = !seen;
147
+ const changed = mark !== last;
148
+ seen = true;
149
+ last = mark;
150
+ return !first && changed && mark !== 'running' && mark !== 'none';
151
+ };
152
+ }
153
+
154
+ /**
155
+ * The row's behaviour, without a DOM. `render(model)` is called with `{ reading, notice, acting }` after every change.
156
+ *
157
+ * @param {object} o
158
+ * @param {typeof fetch} o.fetch
159
+ * @param {(model: { reading: object, notice: object | null, acting: boolean }) => void} o.render
160
+ * @param {(ms: number) => Promise<void>} [o.wait] the pause between two looks at a running backup
161
+ * @param {number} [o.pollMs]
162
+ * @param {() => boolean} [o.alive] false once the row is gone: the following stops
163
+ * @param {() => void} [o.browserDownload] start the download through the browser (GET /api/system/backup)
164
+ */
165
+ export function createBackupDownloadController({
166
+ fetch, render, wait = (ms) => new Promise((done) => setTimeout(done, ms)), pollMs = 1000, alive = () => true,
167
+ browserDownload = () => {},
168
+ } = {}) {
169
+ let reading = { state: 'loading' };
170
+ let notice = null;
171
+ let following = false;
172
+ let acting = false;
173
+
174
+ const show = () => { try { render({ reading, notice, acting }); } catch { /* a row that cannot be drawn changes nothing here */ } };
175
+
176
+ async function ask(method, url, body) {
177
+ try {
178
+ const init = { method };
179
+ if (body !== undefined) { init.headers = { 'Content-Type': 'application/json' }; init.body = JSON.stringify(body); }
180
+ const res = await fetch(url, init);
181
+ let json = null;
182
+ try { json = await res.json(); } catch { json = null; }
183
+ return readBackupDownloadResponse({ status: res.status, body: json });
184
+ } catch (error) {
185
+ return readBackupDownloadResponse({ error });
186
+ }
187
+ }
188
+
189
+ const isRunning = () => reading.state === 'ready' && reading.job?.state === 'running';
190
+
191
+ // Ask again while the backup runs. A look that fails keeps what was known; five in a row end the following.
192
+ async function follow() {
193
+ if (following) return;
194
+ following = true;
195
+ let failures = 0;
196
+ try {
197
+ while (isRunning() && alive()) {
198
+ await wait(pollMs);
199
+ const next = await ask('GET', BACKUP_JOB_URL);
200
+ if (next.state === 'ready') { failures = 0; reading = next; }
201
+ else if (++failures >= 5) reading = next;
202
+ if (!isRunning() && notice?.kind === 'running') notice = null;
203
+ show();
204
+ }
205
+ } finally { following = false; }
206
+ }
207
+
208
+ /** The state as the server has it now; follows a backup that is already running. */
209
+ async function load() {
210
+ reading = await ask('GET', BACKUP_JOB_URL);
211
+ show();
212
+ if (isRunning()) await follow();
213
+ }
214
+
215
+ /** The system's folder dialog, then the choice saved. Returns true when a folder was saved. */
216
+ async function choose(description) {
217
+ if (acting) return false;
218
+ acting = true;
219
+ show();
220
+ try { return await pickAndSave(description); }
221
+ finally { acting = false; show(); }
222
+ }
223
+
224
+ async function pickAndSave(description) {
225
+ let picked = null;
226
+ try {
227
+ const res = await fetch(FOLDER_PICKER_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ description }) });
228
+ picked = (await res.json())?.path || null;
229
+ } catch { picked = null; }
230
+ if (!picked) return false;
231
+ const next = await ask('PUT', BACKUP_DESTINATION_URL, { folderPath: picked });
232
+ if (next.state === 'ready') { reading = next; notice = null; }
233
+ else notice = { kind: 'folder', message: next.message || '' };
234
+ return next.state === 'ready';
235
+ }
236
+
237
+ /** Start the backup (or, on a server from before, the browser's download) and follow it to its end. */
238
+ async function start() {
239
+ if (reading.state === 'old-server') {
240
+ notice = { kind: 'browser' };
241
+ show();
242
+ browserDownload();
243
+ return;
244
+ }
245
+ if (isRunning()) { notice = { kind: 'running' }; show(); return follow(); }
246
+ if (acting) return;
247
+ acting = true;
248
+ notice = null;
249
+ show();
250
+ let next;
251
+ try { next = await ask('POST', BACKUP_JOB_URL); }
252
+ finally { acting = false; }
253
+ if (next.state === 'ready') {
254
+ reading = next;
255
+ if (next.alreadyRunning) notice = { kind: 'running' };
256
+ } else if (next.state === 'old-server') {
257
+ reading = next;
258
+ return start();
259
+ } else notice = { kind: 'start', message: next.message || '' };
260
+ show();
261
+ if (isRunning()) await follow();
262
+ }
263
+
264
+ /** Stop the running backup: nothing is saved. The row then follows it to its end. */
265
+ async function cancel() {
266
+ if (!isRunning()) return false;
267
+ const next = await ask('POST', BACKUP_CANCEL_URL, {});
268
+ if (next.state === 'ready') { reading = next; notice = null; }
269
+ else notice = { kind: 'cancel', message: next.state === 'old-server' ? 'HTTP 404' : next.message || '' };
270
+ show();
271
+ if (isRunning()) await follow();
272
+ return next.state === 'ready';
273
+ }
274
+
275
+ /** Show the finished backup in the system's file manager. */
276
+ async function reveal() {
277
+ try {
278
+ const res = await fetch(BACKUP_REVEAL_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
279
+ if (res.ok) return true;
280
+ let message = '';
281
+ try { message = clean((await res.json())?.error); } catch { message = ''; }
282
+ notice = { kind: 'reveal', message: message || `HTTP ${res.status}` };
283
+ } catch (error) {
284
+ notice = { kind: 'reveal', message: clean(error?.message || error) };
285
+ }
286
+ show();
287
+ return false;
288
+ }
289
+
290
+ /** The browser's own download, for a page on another computer than the server. */
291
+ function downloadInBrowser() {
292
+ notice = { kind: 'browser' };
293
+ show();
294
+ browserDownload();
295
+ }
296
+
297
+ return { load, choose, start, cancel, reveal, downloadInBrowser, model: () => ({ reading, notice, acting }) };
298
+ }