@yuriai/web 0.2.0-beta.1 → 0.2.0-beta.11

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 (224) hide show
  1. package/README.md +5 -1
  2. package/dist/assets/{AgentAvatar-k7s0gPMz.js → AgentAvatar-BeM4lXfE.js} +1 -1
  3. package/dist/assets/{AssistantView-CKSBN9HQ.js → AssistantView-CuYOySq7.js} +3 -3
  4. package/dist/assets/DiagramView-Dg3mmHBS.js +1 -0
  5. package/dist/assets/{FadeInOnReveal-DuelAGXz.js → FadeInOnReveal-B8BCjwPb.js} +1 -1
  6. package/dist/assets/GuiPluginLoadingNotice-DjO_uy_0.js +1 -0
  7. package/dist/assets/GuiPluginSurface-yIOzahfo.js +1 -0
  8. package/dist/assets/GuiPluginWindow-jUuZl9JF.js +1 -0
  9. package/dist/assets/{Icon-BX4GW-k_.js → Icon-DofI60x2.js} +1 -1
  10. package/dist/assets/{ImageLoadingPlaceholder-OnlbaJBG.js → ImageLoadingPlaceholder-CZSbfJci.js} +1 -1
  11. package/dist/assets/{LoadingImage-DDEN3tpH.js → LoadingImage-BA2Cwg_Q.js} +1 -1
  12. package/dist/assets/MarkdownRenderer-CXQc3p23.js +2 -0
  13. package/dist/assets/MarkdownRendererImpl-Bik13Wcr.js +10 -0
  14. package/dist/assets/MarkstreamRendererImpl-DULutx8r.js +3 -0
  15. package/dist/assets/{MobileDetailNavigation-K8AyOZUE.js → MobileDetailNavigation-C6-wtXZH.js} +1 -1
  16. package/dist/assets/MobileResizableSheet-CuRgnS-k.js +1 -0
  17. package/dist/assets/MobileShareBridge-m6bxtE6w.js +4 -0
  18. package/dist/assets/MobileTabPageHeader-Cm0sKyHi.js +2 -0
  19. package/dist/assets/{MultiRunWindow-CLGnrnLn.js → MultiRunWindow-uYxVeVne.js} +1 -1
  20. package/dist/assets/OnboardingScreen-hvLlaoKt.js +1 -0
  21. package/dist/assets/{OverlayScrollbar-C-Od80p5.js → OverlayScrollbar-Bi17Olmj.js} +1 -1
  22. package/dist/assets/SettingsView-B2YuF8r0.js +26 -0
  23. package/dist/assets/{SettingsWindow-B-z25PVS.js → SettingsWindow--qnxFujm.js} +1 -1
  24. package/dist/assets/TerminalView-6gTVdIYb.js +8 -0
  25. package/dist/assets/{ToolOutputDialog-CMiPmx7q.js → ToolOutputDialog-C5kcd8b5.js} +3 -3
  26. package/dist/assets/{YuriLogo-DvKVga_x.js → YuriLogo-D9cfwLdW.js} +1 -1
  27. package/dist/assets/appThemeRegistry-BnfnOg7_.js +1 -0
  28. package/dist/assets/{assistant-attachment-cache-BIxi1vPM.js → assistant-attachment-cache-Cqs65voA.js} +1 -1
  29. package/dist/assets/button-CT7WL0lp.js +1 -0
  30. package/dist/assets/{capgoAdapter-CEzjhZ15.js → capgoAdapter-BPj5WQuJ.js} +1 -1
  31. package/dist/assets/clipboard-Bj6jZiuP.js +1 -0
  32. package/dist/assets/{collapsible-BT03pxhm.js → collapsible-UDWFNcbF.js} +1 -1
  33. package/dist/assets/desktop-CfMDfs6c.js +1 -0
  34. package/dist/assets/desktopHosts-BEzVZGiW.js +1 -0
  35. package/dist/assets/desktopRelayRestore-aNSNYVEB.js +1 -0
  36. package/dist/assets/device-BDrEmxBm.js +2 -0
  37. package/dist/assets/{diagram-1AdssMXJ.js → diagram-BxF_wECt.js} +1 -1
  38. package/dist/assets/dialog-BpsbJk8Y.js +1 -0
  39. package/dist/assets/download-progress-MobTWf23.js +1 -0
  40. package/dist/assets/dropdown-menu.styles-D6MTYFvx.js +1 -0
  41. package/dist/assets/{es-BQC0Cjvs.js → es-iuy57SFI.js} +2 -2
  42. package/dist/assets/{fileMentionTouchSelection-BCTXha9_.js → fileMentionTouchSelection-mWJrsy1N.js} +2 -2
  43. package/dist/assets/{path-utils-QNmCUIdP.js → fileQueries-voABZL1r.js} +1 -1
  44. package/dist/assets/fileReferenceActions-CgsqIeIM.js +1 -0
  45. package/dist/assets/{fileReferenceParser-D6pFtXag.js → fileReferenceParser-1HHDBUum.js} +1 -1
  46. package/dist/assets/{fr-BEs3arTt.js → fr-LyrJa2Qb.js} +2 -2
  47. package/dist/assets/gitApi-_0x9rm4Q.js +10 -0
  48. package/dist/assets/gitApiHttp-BKM9BbT8.js +7 -0
  49. package/dist/assets/gui-CTKa6rbU.js +1 -0
  50. package/dist/assets/host-1RDqqL9w.js +1 -0
  51. package/dist/assets/{image-loading-ClwkpTt4.js → image-loading-ClQZD7Z9.js} +1 -1
  52. package/dist/assets/{input-BhopRvzu.js → input-D86Oqf3B.js} +1 -1
  53. package/dist/assets/insertionBoundaries-DK8Nfduw.js +1 -0
  54. package/dist/assets/{ja-DwjQqURQ.js → ja-QqNYiTeY.js} +2 -2
  55. package/dist/assets/{ko-5ebvOeiM.js → ko-CL-s2hwZ.js} +2 -2
  56. package/dist/assets/main-CtUjac3v.js +169 -0
  57. package/dist/assets/main-mDmZG5F3.js +2 -0
  58. package/dist/assets/{markdownHeightCache-Ci4Phpkv.js → markdownHeightCache-DB_NzPGt.js} +1 -1
  59. package/dist/assets/mcpQueries-CzVXx1pS.js +1 -0
  60. package/dist/assets/miniChat-B1m57jX8.js +2 -0
  61. package/dist/assets/mobile-CwqGwE_K.js +2 -0
  62. package/dist/assets/{mobileBackNavigation-htjL23a2.js → mobileBackNavigation-BGpGSVKE.js} +1 -1
  63. package/dist/assets/multirun-LSYLvvZF.js +3 -0
  64. package/dist/assets/native-BMAEg2E6.js +1 -0
  65. package/dist/assets/native-config-PMhVH43d.js +1 -0
  66. package/dist/assets/native-errors-06if6eu-.js +1 -0
  67. package/dist/assets/path-utils-jGozTg9d.js +1 -0
  68. package/dist/assets/persistence-Ck0wskDR.js +3 -0
  69. package/dist/assets/{pl-ptv06x7p.js → pl-AKGY_sFU.js} +2 -2
  70. package/dist/assets/platform-kv0OsX45.js +1 -0
  71. package/dist/assets/{projectMeta-tXx77gZG.js → projectMeta-Ds630MLq.js} +1 -1
  72. package/dist/assets/{pt-BR-DREchPJf.js → pt-BR-BFRFGU_b.js} +2 -2
  73. package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-CpsVmMzy.js} +1 -1
  74. package/dist/assets/readiness-79gVgf9B.js +1 -0
  75. package/dist/assets/reasoning-projection-client-BEhVknv9.js +1 -0
  76. package/dist/assets/renderElectronMiniChatApp-yEPiD9np.js +2 -0
  77. package/dist/assets/renderMobileApp-6XHYSl6x.js +28 -0
  78. package/dist/assets/runtime-fetch-BclMrQHc.js +1 -0
  79. package/dist/assets/{runtime-file-download-CwMwe_O9.js → runtime-file-download-CZ2qtdn9.js} +1 -1
  80. package/dist/assets/runtime-file-resource-CEkq2Pj2.js +2 -0
  81. package/dist/assets/runtime-file-store-BVRgEtI-.js +1 -0
  82. package/dist/assets/runtime-switch-WzPG6NMR.js +1 -0
  83. package/dist/assets/runtimeConfig-CNms027t.js +2 -0
  84. package/dist/assets/runtimeEndpointReset-CiSl3D_G.js +149 -0
  85. package/dist/assets/{runtimeEndpointReset-DmY_4gYI.css → runtimeEndpointReset-HYSytKO-.css} +1 -1
  86. package/dist/assets/{scheduledTaskNavigation-B71VHwFK.js → scheduledTaskNavigation-tOa4Azh_.js} +1 -1
  87. package/dist/assets/scheduling-DCTDfxV-.js +1 -0
  88. package/dist/assets/sessionChangeSummary-BU-_7fX2.js +1 -0
  89. package/dist/assets/sessionLookup-B8YOzsKe.js +1 -0
  90. package/dist/assets/{sortable-tabs-strip-CnaQoAAB.js → sortable-tabs-strip-CSXgXPyP.js} +1 -1
  91. package/dist/assets/speechSettingsQueries-DXe6PVAa.js +4 -0
  92. package/dist/assets/src-D3pZqEZM.css +2 -0
  93. package/dist/assets/{store-Dy_l1m3m.js → store-CGMD02tA.js} +3 -3
  94. package/dist/assets/terminalApi-DbFIyF-J.js +1 -0
  95. package/dist/assets/{textarea-CaGuTnhs.js → textarea-CMvxcQhR.js} +1 -1
  96. package/dist/assets/{tooltip-Bxj4llmx.js → tooltip-CnIKZ6bg.js} +1 -1
  97. package/dist/assets/types-xdR_RNnd.js +2 -0
  98. package/dist/assets/{uk-HcldNNPe.js → uk-C21_nQhw.js} +2 -2
  99. package/dist/assets/{useAppFontEffects-DDdQeaoM.js → useAppFontEffects-BWa0kmau.js} +53 -53
  100. package/dist/assets/{useAssistantUIStore-D7JZlg_Q.js → useAssistantUIStore-4a569vpy.js} +1 -1
  101. package/dist/assets/useDesktopWindowControlsLayout-DlxAzo2A.js +1 -0
  102. package/dist/assets/useEffectiveDirectory-PrUfhsEz.js +1 -0
  103. package/dist/assets/{useFontPreferences-D-XYUHOV.js → useFontPreferences-Dx-plsme.js} +1 -1
  104. package/dist/assets/useMobileNavigationStore-_TdcYM33.js +417 -0
  105. package/dist/assets/useUIStore-DqtgX2FB.js +1 -0
  106. package/dist/assets/{useWorkerHighlightedLines-OsRfq7LD.js → useWorkerHighlightedLines-CQTgx3GG.js} +1 -1
  107. package/dist/assets/{vendor-effect-DXlObQuU.js → vendor-effect-DV9F8PTZ.js} +1 -1
  108. package/dist/assets/vendor-opencode-client-fxfj4IA_.js +12 -0
  109. package/dist/assets/{vendor-opencode-plugin-DhwD3Tat.js → vendor-opencode-plugin-CQ5ogY33.js} +1 -1
  110. package/dist/assets/vendor-solid-js-Dmt4_-Zk.js +1 -0
  111. package/dist/assets/yuri-mark-black-DxEnMyCE.svg +1 -0
  112. package/dist/assets/{zh-CN-Dg3fYgX1.js → zh-CN-C7PVNr9_.js} +2 -2
  113. package/dist/assets/{zh-TW-FIWAmsGT.js → zh-TW-DLLoB3-e.js} +2 -2
  114. package/dist/index.html +27 -23
  115. package/dist/mini-chat.html +30 -34
  116. package/dist/mobile.html +33 -23
  117. package/package.json +3 -3
  118. package/server/index.d.ts +2 -0
  119. package/server/index.js +9 -13
  120. package/server/lib/content-search/DOCUMENTATION.md +33 -13
  121. package/server/lib/content-search/event-ingest.integration.test.js +52 -0
  122. package/server/lib/content-search/event-repair.test.js +48 -0
  123. package/server/lib/content-search/index.js +3 -2
  124. package/server/lib/content-search/runtime.js +75 -10
  125. package/server/lib/content-search/runtime.test.js +91 -1
  126. package/server/lib/content-search/service.js +19 -2
  127. package/server/lib/fs/DOCUMENTATION.md +1 -0
  128. package/server/lib/fs/binary-file.d.ts +3 -0
  129. package/server/lib/fs/binary-file.js +21 -0
  130. package/server/lib/fs/routes.js +1 -21
  131. package/server/lib/fs/routes.test.js +43 -0
  132. package/server/lib/opencode/DOCUMENTATION.md +14 -9
  133. package/server/lib/opencode/ensure-cli.js +12 -14
  134. package/server/lib/opencode/ensure-cli.test.js +8 -8
  135. package/server/lib/opencode/env-runtime.test.js +1 -1
  136. package/server/lib/opencode/gui-plugin-source.js +14 -0
  137. package/server/lib/opencode/gui-plugin-source.test.js +28 -0
  138. package/server/lib/opencode/lifecycle.js +19 -1
  139. package/server/lib/opencode/opencode2-pin.js +3 -4
  140. package/server/lib/opencode/opencode2-pin.test.js +5 -4
  141. package/server/lib/opencode/owned-runtime-upgrade.js +4 -11
  142. package/server/lib/opencode/owned-runtime-upgrade.test.js +4 -0
  143. package/server/lib/opencode/plugin-gui-response.d.ts +7 -0
  144. package/server/lib/opencode/plugin-gui-response.js +62 -0
  145. package/server/lib/opencode/plugin-gui-response.test.js +89 -0
  146. package/server/lib/opencode/proxy.js +32 -0
  147. package/server/lib/opencode/routes.js +2 -1
  148. package/server/lib/opencode/routes.test.js +1 -1
  149. package/server/lib/opencode/runtime-contract.js +3 -4
  150. package/server/lib/opencode/session-directory-runtime.js +2 -13
  151. package/server/lib/opencode/session-directory-runtime.test.js +69 -4
  152. package/server/lib/opencode/upgrade-screen.js +9 -5
  153. package/server/lib/opencode/upgrade-screen.test.js +20 -0
  154. package/server/lib/opencode/version-alignment.test.js +6 -6
  155. package/server/lib/question-auto-delegate/DOCUMENTATION.md +5 -1
  156. package/server/lib/question-auto-delegate/core.d.ts +2 -2
  157. package/server/lib/question-auto-delegate/runtime.js +11 -27
  158. package/server/lib/question-auto-delegate/runtime.test.js +25 -0
  159. package/server/lib/relay/DOCUMENTATION.md +1 -0
  160. package/server/lib/request-cors.js +2 -2
  161. package/server/lib/request-cors.test.js +3 -0
  162. package/server/lib/scheduled-tasks/DOCUMENTATION.md +5 -0
  163. package/server/lib/scheduled-tasks/runtime.js +16 -0
  164. package/server/lib/scheduled-tasks/runtime.test.js +33 -0
  165. package/server/lib/session-index/DOCUMENTATION.md +22 -8
  166. package/server/lib/session-index/routes.js +3 -1
  167. package/server/lib/session-index/routes.test.js +2 -0
  168. package/server/lib/session-index/service.js +23 -0
  169. package/server/lib/session-index/sync-runtime.js +78 -20
  170. package/server/lib/session-index/sync-runtime.test.js +23 -5
  171. package/server/plugin-gui-proxy.test.js +134 -0
  172. package/dist/assets/DiagramView-RmE0gXVx.js +0 -1
  173. package/dist/assets/GuiPluginSurface-DWGYdQLr.js +0 -1
  174. package/dist/assets/GuiPluginWindow-CLgceKTX.js +0 -1
  175. package/dist/assets/MarkdownRenderer-7zj1J9EY.js +0 -2
  176. package/dist/assets/MarkdownRendererImpl-lXwdc-kG.js +0 -10
  177. package/dist/assets/MarkstreamRendererImpl-B5or38qI.js +0 -3
  178. package/dist/assets/MobileResizableSheet-THVjYOSA.js +0 -1
  179. package/dist/assets/MobileShareBridge-9RP7ni2F.js +0 -4
  180. package/dist/assets/MobileTabPageHeader-ZZTO3phT.js +0 -2
  181. package/dist/assets/OnboardingScreen-BHomvleJ.js +0 -1
  182. package/dist/assets/SettingsView-BlruenEQ.js +0 -26
  183. package/dist/assets/TerminalView-CRyh7cpp.js +0 -8
  184. package/dist/assets/appThemeRegistry-e1zU7R2C.js +0 -1
  185. package/dist/assets/button-4sNruiRJ.js +0 -1
  186. package/dist/assets/desktopHosts-DNc_ga0E.js +0 -1
  187. package/dist/assets/desktopRelayRestore-BWl7Zy8M.js +0 -1
  188. package/dist/assets/device-CCFr0Aht.js +0 -2
  189. package/dist/assets/dialog-DLc0nKV7.js +0 -1
  190. package/dist/assets/dropdown-menu.styles-4tACRbYU.js +0 -1
  191. package/dist/assets/fileReferenceActions-B0iaTe0c.js +0 -1
  192. package/dist/assets/gitApi-DIwsfb2k.js +0 -10
  193. package/dist/assets/gui-CTnzY_cr.js +0 -1
  194. package/dist/assets/host-CEMl6ZlP.js +0 -1
  195. package/dist/assets/insertionBoundaries-CFDcBxaK.js +0 -1
  196. package/dist/assets/main-DBJ19laz.js +0 -169
  197. package/dist/assets/main-XMhFdW0K.js +0 -2
  198. package/dist/assets/mcpQueries-f0cDQQKu.js +0 -1
  199. package/dist/assets/miniChat-BVTtOggs.js +0 -2
  200. package/dist/assets/mobile-0X6dYZAB.js +0 -2
  201. package/dist/assets/multirun-mBD1Y3Eb.js +0 -3
  202. package/dist/assets/native-config-B9V18QgV.js +0 -1
  203. package/dist/assets/persistence-CcGnI3Ek.js +0 -3
  204. package/dist/assets/platform-HIkm-CHn.js +0 -7
  205. package/dist/assets/readiness-Da7jHHss.js +0 -1
  206. package/dist/assets/renderElectronMiniChatApp-DwIydDUm.js +0 -2
  207. package/dist/assets/renderMobileApp-TNkNM5Zx.js +0 -28
  208. package/dist/assets/runtime-fetch-BAN5Gnnp.js +0 -1
  209. package/dist/assets/runtime-file-resource-yx0xpKe-.js +0 -2
  210. package/dist/assets/runtime-switch-CAZiOV2G.js +0 -1
  211. package/dist/assets/runtimeConfig-ChR1FQv1.js +0 -2
  212. package/dist/assets/runtimeEndpointReset-CxMEqgDx.js +0 -149
  213. package/dist/assets/sessionChangeSummary-DDbB-N5p.js +0 -1
  214. package/dist/assets/sessionLookup-CsJ8Vrq8.js +0 -1
  215. package/dist/assets/speechSettingsQueries-X0jStYkm.js +0 -4
  216. package/dist/assets/src-CZA3gFyl.css +0 -2
  217. package/dist/assets/terminalApi-DVZUO2Uv.js +0 -1
  218. package/dist/assets/types-Dfj_Rn0L.js +0 -2
  219. package/dist/assets/useDesktopWindowControlsLayout-BFyKfmUX.js +0 -1
  220. package/dist/assets/useEffectiveDirectory-CST6AXTm.js +0 -1
  221. package/dist/assets/useMobileNavigationStore-BdWv0Da4.js +0 -417
  222. package/dist/assets/useUIStore-NMQx_cnG.js +0 -1
  223. package/dist/assets/vendor-opencode-client-Eb-_7KbZ.js +0 -23
  224. package/dist/assets/vendor-solid-js-CXSXbuQO.js +0 -1
@@ -8,13 +8,15 @@
8
8
  */
9
9
 
10
10
  import {
11
- PINNED_OPENCODE2_VERSION,
12
11
  MINIMUM_OPENCODE2_VERSION,
13
12
  isAcceptableOpenCode2HealthVersion,
14
13
  isOpenCode1xVersion,
15
14
  isOpenCode2VersionAtLeast,
16
15
  npmPackageForOpenCode2,
17
16
  } from './opencode2-pin.js';
17
+ import { createOpenCodeUpdateDiscovery } from './update-discovery.js';
18
+
19
+ const discoverLatestVersion = createOpenCodeUpdateDiscovery();
18
20
 
19
21
  /** Oldest OpenCode this Yuri build will enter a session against. */
20
22
  export const REQUIRED_OPENCODE_VERSION = MINIMUM_OPENCODE2_VERSION;
@@ -26,11 +28,10 @@ const normalizeVersion = (value) => {
26
28
  };
27
29
 
28
30
  /**
29
- * Install target is the pin when the pin already satisfies the screen, otherwise
30
- * the screen minimum. A pin still at 2.0.12 must not be what this screen installs.
31
+ * Describe the minimum until an installation resolves its remote stable target.
31
32
  * @param {string} [pin]
32
33
  */
33
- export function resolveUpgradeScreenTarget(pin = PINNED_OPENCODE2_VERSION) {
34
+ export function resolveUpgradeScreenTarget(pin = REQUIRED_OPENCODE_VERSION) {
34
35
  if (isOpenCode2VersionAtLeast(pin, REQUIRED_OPENCODE_VERSION)) return pin;
35
36
  return REQUIRED_OPENCODE_VERSION;
36
37
  }
@@ -181,7 +182,10 @@ export async function installRequiredOpenCode(deps) {
181
182
  409,
182
183
  );
183
184
  }
184
- const target = status.targetVersion;
185
+ const target = await (deps.resolveLatestVersion || discoverLatestVersion)();
186
+ if (!/^2\.\d+\.\d+$/.test(target) || !isUpgradeScreenSatisfied(target)) {
187
+ throw failure('No compatible stable OpenCode release was found.', 'UPGRADE_TARGET_INVALID');
188
+ }
185
189
  const previousBinary = typeof deps.getResolvedBinary === 'function' ? deps.getResolvedBinary() : null;
186
190
  const previousSource = typeof deps.getResolvedBinarySource === 'function' ? deps.getResolvedBinarySource() : null;
187
191
  const ownership = typeof deps.resolveOwnership === 'function' ? await deps.resolveOwnership() : null;
@@ -108,12 +108,31 @@ describe('installRequiredOpenCode', () => {
108
108
  calls.push('ready');
109
109
  }),
110
110
  readConfiguredBinary: async () => null,
111
+ resolveLatestVersion: async () => '2.0.23',
111
112
  isSharedService: () => false,
112
113
  ...overrides,
113
114
  };
114
115
  return { deps, calls };
115
116
  };
116
117
 
118
+ it('resolves a newer stable release instead of installing a compiled-in pin', async () => {
119
+ const { deps } = createDeps({
120
+ resolveLatestVersion: vi.fn(async () => '2.2.0'),
121
+ readBinaryVersion: () => '2.2.0',
122
+ readServeVersion: vi.fn().mockResolvedValueOnce('2.0.14').mockResolvedValueOnce('2.2.0'),
123
+ });
124
+ await expect(installRequiredOpenCode(deps)).resolves.toMatchObject({ upgraded: true, version: '2.2.0' });
125
+ expect(deps.install).toHaveBeenCalledWith({ version: '2.2.0' });
126
+ });
127
+
128
+ it('does not mutate installation or selection when release discovery fails', async () => {
129
+ const { deps } = createDeps({ resolveLatestVersion: async () => { throw new Error('offline'); } });
130
+ await expect(installRequiredOpenCode(deps)).rejects.toThrow('offline');
131
+ expect(deps.install).not.toHaveBeenCalled();
132
+ expect(deps.persistBinary).not.toHaveBeenCalled();
133
+ expect(deps.restart).not.toHaveBeenCalled();
134
+ });
135
+
117
136
  it('installs 2.0.23 and only succeeds after the running serve is verified', async () => {
118
137
  const { deps, calls } = createDeps({
119
138
  readServeVersion: vi.fn()
@@ -190,6 +209,7 @@ describe('upgrade screen routes', () => {
190
209
  resolveOwnership: async () => ({ ownership: 'owned-cache', guidance: null }),
191
210
  readServeVersion,
192
211
  readCliVersion: () => '2.0.12',
212
+ resolveLatestVersion: async () => '2.0.23',
193
213
  platformCanInstall: true,
194
214
  install: vi.fn(async () => {
195
215
  throw new Error('registry unreachable');
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
- import { MINIMUM_OPENCODE2_VERSION, PINNED_OPENCODE2_VERSION } from './opencode2-pin.js';
2
+ import { MINIMUM_OPENCODE2_VERSION } from './opencode2-pin.js';
3
3
  import { evaluateRuntimeContract } from './runtime-contract.js';
4
4
  import { describeUpgradeScreen, installRequiredOpenCode, resolveUpgradeScreenTarget } from './upgrade-screen.js';
5
5
  import { ensurePinnedOpenCode2Cli } from './ensure-cli.js';
@@ -13,24 +13,24 @@ describe('v2 version alignment', () => {
13
13
  expect(evaluateRuntimeContract({ serveVersion: version, cliVersion: '2.0.15', reachable: true, authenticated: true })).toMatchObject({ executionAllowed: true, versionMismatch: true, minVerifiedVersion: '2.0.20' });
14
14
  expect(describeUpgradeScreen({ version }).state).toBe('compatible');
15
15
  });
16
- it('installs the audited pin on first install and preserves newer discovered CLIs', async () => {
16
+ it('installs the discovered stable release and preserves existing CLIs', async () => {
17
17
  expect(MINIMUM_OPENCODE2_VERSION).toBe('2.0.20');
18
- expect(PINNED_OPENCODE2_VERSION).toBe('2.0.23');
19
- expect(resolveUpgradeScreenTarget()).toBe('2.0.23');
18
+ expect(resolveUpgradeScreenTarget()).toBe(MINIMUM_OPENCODE2_VERSION);
20
19
  const install = vi.fn(async () => '/owned/opencode');
21
- await expect(ensurePinnedOpenCode2Cli({ readVersion: (path) => path === '/owned/opencode' ? '2.0.23' : '', install })).resolves.toMatchObject({ version: '2.0.23', installed: true });
20
+ await expect(ensurePinnedOpenCode2Cli({ resolveLatestVersion: async () => '2.0.23', readVersion: (path) => path === '/owned/opencode' ? '2.0.23' : '', install })).resolves.toMatchObject({ version: '2.0.23', installed: true });
22
21
  expect(install).toHaveBeenCalledWith(expect.objectContaining({ version: '2.0.23' }));
23
22
  install.mockClear();
24
23
  await expect(ensurePinnedOpenCode2Cli({ discoveredPath: '/global/opencode', readVersion: () => '2.1.0', install })).resolves.toMatchObject({ version: '2.1.0', installed: false });
25
24
  expect(install).not.toHaveBeenCalled();
26
25
  });
27
26
  it('does not infer a successful installation from an unreadable binary', async () => {
28
- await expect(ensurePinnedOpenCode2Cli({ readVersion: () => '', install: async () => '/owned/opencode' })).rejects.toThrow('got unknown');
27
+ await expect(ensurePinnedOpenCode2Cli({ resolveLatestVersion: async () => '2.2.0', readVersion: () => '', install: async () => '/owned/opencode' })).rejects.toThrow('got unknown');
29
28
  });
30
29
  it('verifies the live service after explicit install, and rolls selection back on failure', async () => {
31
30
  const persistBinary = vi.fn();
32
31
  const restart = vi.fn();
33
32
  const deps = { resolveOwnership: async () => ({ ownership: 'shared-service', binaryOwnership: 'owned-cache' }), readServeVersion: vi.fn().mockResolvedValueOnce('2.0.19').mockResolvedValueOnce('2.0.23'), readCliVersion: () => '2.0.23', platformCanInstall: true, install: async () => '/owned/opencode', readBinaryVersion: () => '2.0.23', persistBinary, restart, isSharedService: () => true };
33
+ deps.resolveLatestVersion = async () => '2.0.23';
34
34
  await expect(installRequiredOpenCode(deps)).resolves.toMatchObject({ upgraded: true, version: '2.0.23' });
35
35
  expect(restart).toHaveBeenCalledWith({ binaryPath: '/owned/opencode' });
36
36
  deps.readServeVersion.mockResolvedValue('2.0.19');
@@ -98,7 +98,11 @@ form IO and core, restoring `/api` for origin-only upstream URLs.
98
98
 
99
99
  ## Reconcile
100
100
 
101
- - Inventory = projects + session-index directories + observed request/event dirs.
101
+ - Inventory = live upstream Locations (`GET /api/debug/location`) + observed request/event dirs.
102
+ Forms live in Location memory, so other directories cannot hold pending forms;
103
+ a scoped `form.list` there would boot a Location that upstream never evicts.
104
+ Never enumerate settings projects or session-index directories. An unreadable
105
+ live set is an inventory failure, not an empty catalog.
102
106
  - Track `successfulDirectories`; only those may settle missing requests.
103
107
  - Unscoped list discovers unknowns only; never means “all directories empty”.
104
108
  - Unscoped / directory-less pending triggers `ensureSessionLineage(sessionID, hint, requestID)`
@@ -181,8 +181,8 @@ export interface QuestionAutoDelegateIO {
181
181
  body: unknown,
182
182
  sessionID: string,
183
183
  ): Promise<QuestionAutoDelegateUpstreamResult>;
184
- /** Project directories used for reconnect/start reconcile. */
185
- listDirectories(): Promise<string[]>;
184
+ /** Live upstream Location directories for reconnect/start reconcile; null when unreadable. */
185
+ listDirectories(): Promise<string[] | null>;
186
186
  /**
187
187
  * Persist-backed enabled flag.
188
188
  * - `true` / `false` when readable (absent key ⇒ default true)
@@ -28,9 +28,6 @@ export function createQuestionAutoDelegateRuntime({
28
28
  buildOpenCodeUrl,
29
29
  getOpenCodeAuthHeaders,
30
30
  readSettingsFromDiskMigrated,
31
- sanitizeProjects,
32
- /** Optional: session-index / worktree inventory directories. */
33
- listIndexedDirectories,
34
31
  broadcastGlobalUiEvent,
35
32
  broadcastYuriEvent,
36
33
  fetchImpl = fetch,
@@ -124,32 +121,19 @@ export function createQuestionAutoDelegateRuntime({
124
121
  return null;
125
122
  }
126
123
  },
124
+ /**
125
+ * Forms live in Location memory, so only live Locations can hold pending
126
+ * forms. A scoped `/form` on any other directory boots a full Location
127
+ * that upstream never evicts; never list projects or indexed directories.
128
+ * @returns {Promise<string[]|null>} null when the live set is unreadable.
129
+ */
127
130
  async listDirectories() {
131
+ const result = await upstream('/debug/location');
132
+ if (!result.ok || !Array.isArray(result.body)) return null;
128
133
  const dirs = new Set();
129
- try {
130
- const settings = await readSettingsFromDiskMigrated();
131
- const projects = typeof sanitizeProjects === 'function'
132
- ? (sanitizeProjects(settings?.projects ?? []) || [])
133
- : (Array.isArray(settings?.projects) ? settings.projects : []);
134
- for (const project of projects) {
135
- const path = asTrimmedString(project?.path);
136
- if (path) dirs.add(path);
137
- }
138
- } catch {
139
- // Project list failure is not fatal when index inventory exists.
140
- }
141
- if (typeof listIndexedDirectories === 'function') {
142
- try {
143
- const indexed = await listIndexedDirectories();
144
- if (Array.isArray(indexed)) {
145
- for (const directory of indexed) {
146
- const path = asTrimmedString(directory);
147
- if (path) dirs.add(path);
148
- }
149
- }
150
- } catch {
151
- // ignore index failures — core marks partial when inventory empty+failed
152
- }
134
+ for (const entry of result.body) {
135
+ const path = asTrimmedString(entry?.directory);
136
+ if (path) dirs.add(path);
153
137
  }
154
138
  return Array.from(dirs);
155
139
  },
@@ -26,6 +26,7 @@ const setup = async (pending = []) => {
26
26
  let onEvent;
27
27
  const fetchImpl = vi.fn(async (url, options) => {
28
28
  const path = url.pathname;
29
+ if (path === '/api/debug/location') return Response.json([{ directory: '/project' }]);
29
30
  if (path === '/api/form') return Response.json({ data: pending });
30
31
  if (path === '/api/session/ses_test') return Response.json({ data: { id: 'ses_test', location: { directory: '/project' } } });
31
32
  if (path === '/api/session/ses_test/form/frm_question') return Response.json({ data: form });
@@ -52,6 +53,30 @@ const setup = async (pending = []) => {
52
53
  };
53
54
  };
54
55
 
56
+ it('reconciles only live Locations and never boots project or indexed directories', async () => {
57
+ vi.useFakeTimers();
58
+ const fetchImpl = vi.fn(async (url) => {
59
+ if (url.pathname === '/api/debug/location') return Response.json([{ directory: '/live' }]);
60
+ if (url.pathname === '/api/form') return Response.json({ data: [] });
61
+ return Response.json({ error: 'Not found' }, { status: 404 });
62
+ });
63
+ const runtime = createQuestionAutoDelegateRuntime({
64
+ globalEventHub: { subscribeEvent: () => () => {} },
65
+ buildOpenCodeUrl: (path) => `http://opencode.test/api${path}`,
66
+ getOpenCodeAuthHeaders: () => ({}),
67
+ readSettingsFromDiskMigrated: async () => ({ projects: [{ path: '/project' }, { path: '/other' }] }),
68
+ fetchImpl,
69
+ pauseStore: createQuestionPauseStore(pauseDirectory),
70
+ });
71
+ runtimes.push(runtime);
72
+ runtime.start();
73
+ await vi.advanceTimersByTimeAsync(0);
74
+ const scoped = fetchImpl.mock.calls
75
+ .map(([url]) => url.searchParams.get('location[directory]'))
76
+ .filter(Boolean);
77
+ expect(scoped).toEqual(['/live']);
78
+ });
79
+
55
80
  it('auto-delegates a native question form after exactly 30 seconds without a UI', async () => {
56
81
  const { emit, posts, runtime } = await setup();
57
82
  emit('form.created', { sessionID: form.sessionID, form });
@@ -55,6 +55,7 @@ Private Relay is transparent for allowlisted HTTP paths, so most “works on LAN
55
55
 
56
56
  - **Same path, real Host route required.** Clients call the ordinary `/api/...` path through the tunnel. If that route is missing on the Host process currently holding the relay claim (wrong git worktree, stale packaged Desktop build, or a backend that never registered the Yuri route before the OpenCode proxy/SPA fallback), the tunnel still returns HTTP 200 with SPA HTML or proxied OpenCode content. Symptom: chat and status work, Provider/model catalog does not.
57
57
  - **HTTP allowlist is prefix-based for `/api/`.** New REST/SSE APIs under `/api/` do not need a tunnel-host allowlist edit. New **WebSocket** paths still need both tunnel-host allowlisting (`isTunnelWsPathAllowed` / exact `ALLOWED_WS_PATHS`, plus the **`/api/preview/proxy/` prefix** for Preview HMR only) and `isUrlAuthWebSocketPath` (see the `relay-transport` skill). Config sync (`/api/yuri/config-sync/*`, ticket 05/06) therefore works over Relay without a tunnel-host allowlist change; identity and credential grants remain endpoint concerns (`relay:<serverId>`, pairing-settings / inbound host grant).
58
+ - GUI code reuse uses the same `GET /api/plugin/gui?id=…` path: the tunnel preserves `X-Yuri-Gui-Revision` requests and `X-Yuri-Gui-Revision` / `X-Yuri-Gui-Code` responses. The authenticated Host still fetches upstream on each call; matching responses are 200 with current options and empty code, never a tunnel-cached bundle or 304. `Cache-Control: private, no-store` crosses unchanged. The Web GUI proxy integration test exercises this actual dispatcher path.
58
59
  - **Transport identity ≠ runtime key.** After LAN⇄relay swaps, UI catalog loaders commit only when `useConfigStore.catalogTransportIdentity` matches `getRuntimeTransportIdentity()`. `runtimeEndpointReset.ts` must write that transport fingerprint on both full endpoint reset and in-place transport reconnect. Writing `runtimeKey` instead leaves Providers empty because the stable device/instance id is shared across LAN and relay.
59
60
  - **Safe catalog projection stays Host-owned.** Provider credentials never cross the browser; Relay only carries the already-allowlisted `GET /api/config/catalog/providers` JSON. Keep Host projection, client parser bounds, and `partial` rules in sync (empty `release_date` is absent, not partial).
60
61
 
@@ -4,12 +4,12 @@ export const applyRuntimeCorsHeaders = ({ origin, setHeader }) => {
4
4
  setHeader('Access-Control-Allow-Origin', origin);
5
5
  setHeader('Access-Control-Allow-Credentials', 'true');
6
6
  setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
7
- setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding,X-Message-Queue-Upload-Token,X-Message-Queue-Sha256,X-Message-Queue-Content-Length,X-Yuri-Content-Length,X-Yuri-Sha256,X-Yuri-Mime,X-Yuri-Filename');
7
+ setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding,X-Message-Queue-Upload-Token,X-Message-Queue-Sha256,X-Message-Queue-Content-Length,X-Yuri-Content-Length,X-Yuri-Sha256,X-Yuri-Mime,X-Yuri-Filename,X-Yuri-Gui-Revision');
8
8
  // Packaged clients (Electron yuri-ui://app, Capacitor, Vite HMR) are
9
9
  // cross-origin to the runtime API. Without an expose list, browsers hide
10
10
  // custom response headers from JS — including the optional-read existence
11
11
  // marker that FilesAPI.readFile({ optional: true }) requires.
12
- setHeader('Access-Control-Expose-Headers', 'x-next-cursor, x-yuri-file-exists, x-speech-pitch, x-speech-volume');
12
+ setHeader('Access-Control-Expose-Headers', 'x-next-cursor, x-yuri-file-exists, x-speech-pitch, x-speech-volume, x-yuri-gui-revision, x-yuri-gui-code');
13
13
  setHeader('Access-Control-Max-Age', PREFLIGHT_CACHE_SECONDS);
14
14
  setHeader('Vary', 'Origin');
15
15
  };
@@ -18,6 +18,9 @@ describe('applyRuntimeCorsHeaders', () => {
18
18
  expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Sha256');
19
19
  expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Content-Length');
20
20
  expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Filename');
21
+ expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Gui-Revision');
22
+ expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-gui-revision');
23
+ expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-gui-code');
21
24
  expect(headers.get('Access-Control-Expose-Headers')).toContain('x-next-cursor');
22
25
  expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-file-exists');
23
26
  });
@@ -220,6 +220,7 @@ executions and rows without a session; missing session association is not proof
220
220
  of execution failure. Such rows remain unresolved rather than inventing a result.
221
221
  Recovery checks live `session.active` before examining terminal messages or Host
222
222
  goal state. Active, unavailable, malformed, and incomplete results remain pending.
223
+ A session OpenCode confirms deleted (`SessionNotFoundError`) settles as `error`.
223
224
  Only confirmed terminal evidence finalizes history, with duration through the
224
225
  time recovery observes completion. It neither dispatches a new prompt nor sends
225
226
  a second completion notification.
@@ -358,6 +359,10 @@ Every actual run (timer or manual):
358
359
  after multiple incomplete idle probes.
359
360
  - `session.active` / `message.list` failures stay **unknown** (keep
360
361
  polling under the watchdog); they never masquerade as idle success.
362
+ Exception: a declared `SessionNotFoundError` (or HTTP 404) from
363
+ `message.list` / `session.get` is confirmed terminal evidence and
364
+ finalizes as `error: 'session not found'`, so recovery stops polling
365
+ deleted sessions. Transport failures never match.
361
366
  - Assistant `error` (and terminal finish `error` / `length` /
362
367
  `content-filter`) finalizes as `error`.
363
368
  - Goal-enabled runs: settle via Host goal terminal status when the store
@@ -400,6 +400,15 @@ const extractGoalFromSession = (session) => {
400
400
  * must be a real terminal (finish tool-calls / incomplete / model-switch ≠
401
401
  * success). History rows are never rewritten here.
402
402
  */
403
+ const SESSION_NOT_FOUND_ERROR = 'session not found';
404
+
405
+ // Real `@opencode/client` throws declared errors by `_tag`; transport failures never match.
406
+ const isSessionNotFoundError = (error) => {
407
+ if (!error || typeof error !== 'object') return false;
408
+ if ((error._tag ?? error.name) === 'SessionNotFoundError') return true;
409
+ return Number(error.status ?? error.statusCode ?? error.response?.status) === 404;
410
+ };
411
+
403
412
  const snapshotSessionOutcome = async ({
404
413
  client,
405
414
  sessionID,
@@ -474,6 +483,9 @@ const snapshotSessionOutcome = async ({
474
483
  }
475
484
  } catch (error) {
476
485
  if (signal?.aborted) throw error;
486
+ if (isSessionNotFoundError(error)) {
487
+ return { outcome: 'error', error: SESSION_NOT_FOUND_ERROR };
488
+ }
477
489
  }
478
490
  }
479
491
  return { outcome: 'busy' };
@@ -490,6 +502,10 @@ const snapshotSessionOutcome = async ({
490
502
  }
491
503
  } catch (error) {
492
504
  if (signal?.aborted) throw error;
505
+ // Upstream confirmed the session is gone: terminal, or recovery polls it forever.
506
+ if (isSessionNotFoundError(error)) {
507
+ return { outcome: 'error', error: SESSION_NOT_FOUND_ERROR };
508
+ }
493
509
  }
494
510
 
495
511
  return { outcome: 'busy' };
@@ -223,6 +223,39 @@ describe('scheduled-tasks history recovery', () => {
223
223
  }
224
224
  });
225
225
 
226
+ it('settles running history whose session was deleted upstream and stops polling it', async () => {
227
+ vi.useFakeTimers();
228
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scheduled-missing-'));
229
+ const store = createScheduledTaskRunHistoryStore({ dbPath: path.join(dir, 'runs.sqlite') });
230
+ for (const id of ['missing', 'offline']) {
231
+ store.startRun({ id, projectId: 'project-1', taskId: id, startedAt: Date.now() - 1000 });
232
+ store.attachSession(id, `ses_${id}`);
233
+ }
234
+ const messageList = vi.fn(async ({ sessionID }) => {
235
+ if (sessionID === 'ses_missing') {
236
+ throw Object.assign(new Error('SessionNotFoundError'), { _tag: 'SessionNotFoundError', name: 'SessionNotFoundError', sessionID });
237
+ }
238
+ throw new TypeError('fetch failed');
239
+ });
240
+ makeOpenCodeV2Client.mockReturnValue({ session: { active: vi.fn(async () => ({})) }, message: { list: messageList } });
241
+ const runtime = createRuntime(vi.fn(async () => ({ task: null })), { runHistoryStore: store });
242
+ try {
243
+ await runtime.start();
244
+ await vi.advanceTimersByTimeAsync(0);
245
+ const runs = () => Object.fromEntries(store.listRuns().runs.map((run) => [run.id, run]));
246
+ expect(runs().missing).toMatchObject({ status: 'error', error: 'session not found' });
247
+ expect(runs().offline.status).toBe('running');
248
+ await vi.advanceTimersByTimeAsync(10_000);
249
+ expect(messageList.mock.calls.filter(([args]) => args.sessionID === 'ses_missing')).toHaveLength(1);
250
+ expect(runs().offline.status).toBe('running');
251
+ } finally {
252
+ runtime.stop();
253
+ store.close();
254
+ fs.rmSync(dir, { recursive: true, force: true });
255
+ vi.useRealTimers();
256
+ }
257
+ });
258
+
226
259
  it('discards recovery results arriving after stop', async () => {
227
260
  let resolveMessages;
228
261
  const messages = new Promise((resolve) => { resolveMessages = resolve; });
@@ -1,5 +1,9 @@
1
1
  # Session Index Runtime
2
2
 
3
+ Directory refresh retains its previous snapshot when the pagination budget is
4
+ exhausted before filling the visible root limit. Filtered global pages with a
5
+ continuation are partial results, not authoritative empty directories.
6
+
3
7
  ## Missing local directories
4
8
 
5
9
  The Host probes local directory existence asynchronously before background root
@@ -8,15 +12,15 @@ with an empty result. Remote upstreams never use the Host filesystem as evidence
8
12
  permission and I/O errors are not deletion. Checks are not negatively cached, so
9
13
  a recreated directory participates in the next requested sync.
10
14
 
11
- Once at startup, the sync runtime checks empty, exhausted indexed
12
- directories. It removes only directory shells with no summary rows, no child rows,
15
+ Startup does not probe indexed directories. An explicitly requested directory
16
+ refresh removes only missing directory shells with no summary rows, no child rows,
13
17
  and no more pages, using one conditional SQLite deletion. Session history and pins
14
18
  are preserved. This maintenance does not touch code files or upstream projects.
15
19
  Runtime switches and shutdown discard pending checks; successful cleanup publishes
16
20
  a revision tip. Snapshot GETs do not perform filesystem scans. Old project paths
17
21
  may still be submitted by clients, but pre-scan checks prevent recreating empty
18
22
  shells for missing paths. App or external worktree deletion is picked up by the
19
- next requested sync or startup pass; there is no periodic filesystem polling.
23
+ next requested sync; there is no startup or periodic filesystem polling.
20
24
 
21
25
  ## Physical directory identity
22
26
 
@@ -33,8 +37,8 @@ child membership follows the directory, and the merged head stays bounded to 20.
33
37
  Reconciliation failure rolls back the entire index conversion. Rechecking on reads
34
38
  also recovers paths unavailable during startup.
35
39
 
36
- Directory lists resolve the upstream location/project, fetch project-scoped pages
37
- and retain only records whose physical directory matches the requested directory.
40
+ Explicit directory lists fetch session pages without initializing an upstream
41
+ Location and retain only records whose physical directory matches the request.
38
42
  This discovers old aliases outside the index without admitting sibling worktrees.
39
43
  Opaque next/previous cursors stay upstream-owned; filtered short/empty pages with
40
44
  a continuation are partial, not exhausted. The existing five-page sync budget and
@@ -121,9 +125,19 @@ Repeated session summary events whose bounded root summary or child membership
121
125
  is unchanged leave directory recency and the public revision unchanged. Root
122
126
  events that remain outside the newest-20 bound follow the same no-op path.
123
127
 
124
- `sync-runtime.js` owns cold-start synchronization. The renderer submits all
125
- known project directories once to `POST /api/yuri/session-index/sync`.
126
- The runtime processes them sequentially. OpenCode 2.x list is cursor-only (no
128
+ `sync-runtime.js` owns cold-start synchronization. The renderer sends
129
+ `{ startup: true }` to `POST /api/yuri/session-index/sync`, without project paths.
130
+ The Host backfills sessions updated within the last 30 days using a single global
131
+ descending session-list cursor, stopping at the time boundary. It never requests
132
+ Location/config/plugin APIs or probes project paths. Each page and its cursor are
133
+ committed atomically in SQLite under the runtime key; empty success also records
134
+ completion. Subsequent launches perform no upstream history reads after completion.
135
+ Failure/shutdown preserves the last committed cursor for retry. Existing summaries
136
+ win over backfill, and normal create/update/archive/delete events maintain the index.
137
+ Existing databases without this marker receive one bounded backfill without being
138
+ cleared. Manual directory refresh remains a separate explicit operation.
139
+
140
+ The runtime processes explicit directory refreshes sequentially. OpenCode 2.x list is cursor-only (no
127
141
  `start` incremental); each directory fetches active-only pages (`limit=20`)
128
142
  after optional Host `projectSessions` overlay. Consecutive archived rows may
129
143
  consume further pages within a small page budget so the newest-20 **active**
@@ -55,7 +55,9 @@ export const registerSessionIndexRoutes = (app, {
55
55
  app.post('/api/yuri/session-index/sync', async (req, res) => {
56
56
  if (!sessionIndexSyncRuntime) return unsupported(res);
57
57
  const directories = Array.isArray(req.body?.directories) ? req.body.directories : [];
58
- const base = sessionIndexSyncRuntime.enqueue(directories);
58
+ const base = req.body?.startup === true
59
+ ? sessionIndexSyncRuntime.enqueue([], { startup: true })
60
+ : sessionIndexSyncRuntime.enqueue(directories);
59
61
  if (!hostStoreWired) return res.status(202).json(base);
60
62
  // Clients apply this body as a snapshot: same Host archive gate as GET.
61
63
  const host = await readHostMap();
@@ -79,6 +79,8 @@ describe('session index routes', () => {
79
79
  expect(res.statusCode).toBe(202);
80
80
  expect(enqueue).toHaveBeenCalledWith(['/repo/a', '/repo/b']);
81
81
  expect(res.body).toMatchObject({ revision: 1, sync: { active: true } });
82
+ route('POST', '/api/yuri/session-index/sync')({ body: { startup: true, directories: ['/ignored'] } }, res);
83
+ expect(enqueue).toHaveBeenLastCalledWith([], { startup: true });
82
84
  });
83
85
 
84
86
  it('does not register a long-poll changes route', () => {
@@ -688,7 +688,30 @@ export const createSessionIndexService = ({ dbPath, getRuntimeConfig = () => nul
688
688
  `).run(runtimeKey(), directory).changes > 0;
689
689
 
690
690
  try { reconcileDirectoryAliases(runtimeKey()); } catch (error) { db.close(); throw error; }
691
+ const historyKey = () => `history_backfill:${runtimeKey()}`;
692
+ const getHistoryBackfill = () => {
693
+ const row = db.prepare('SELECT value FROM session_index_meta WHERE key = ?').get(historyKey());
694
+ return row ? JSON.parse(row.value) : null;
695
+ };
696
+ const commitHistoryPage = db.transaction(({ sessions, progress, expectedRuntimeKey }) => {
697
+ if (expectedRuntimeKey !== runtimeKey()) return false;
698
+ for (const session of sessions) {
699
+ // Live events and already indexed summaries win over historical reads.
700
+ if (!findBySessionId(session.id)) {
701
+ upsert(session);
702
+ const directory = normalizeDirectory(session?.location?.directory ?? session?.directory);
703
+ // The bounded 30-day import is not proof that older history is empty.
704
+ db.prepare('UPDATE runtime_directory SET has_more = 1 WHERE runtime_key = ? AND directory = ? AND last_full_synced_at = 0')
705
+ .run(expectedRuntimeKey, directory);
706
+ }
707
+ }
708
+ db.prepare('INSERT OR REPLACE INTO session_index_meta(key, value) VALUES (?, ?)')
709
+ .run(historyKey(), JSON.stringify(progress));
710
+ return true;
711
+ });
691
712
  return {
713
+ getHistoryBackfill,
714
+ commitHistoryPage,
692
715
  replaceDirectory,
693
716
  removeEmptyDirectory,
694
717
  replaceDirectories,