@yuriai/web 0.2.36-beta.7 → 0.2.37

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 (226) hide show
  1. package/README.md +6 -0
  2. package/dist/assets/AgentAvatar-Dpot7DG_.js +1 -0
  3. package/dist/assets/AssistantContactStatus-DBUeAOcC.js +3 -0
  4. package/dist/assets/AssistantUnreadBadge-uMPRfRqu.js +1 -0
  5. package/dist/assets/AssistantView-9v8wufOH.js +1 -0
  6. package/dist/assets/DiagramView-D317a0U8.js +1 -0
  7. package/dist/assets/FadeInOnReveal-DlU4WRpc.js +1 -0
  8. package/dist/assets/GuiPluginSurface-DHMppLxf.js +1 -0
  9. package/dist/assets/GuiPluginWindow-CWP-ZcJj.js +1 -0
  10. package/dist/assets/Icon-3udlHlix.js +1 -0
  11. package/dist/assets/ImageLoadingPlaceholder-D2CKCkHe.js +1 -0
  12. package/dist/assets/LoadingImage-CzTb95Cn.js +1 -0
  13. package/dist/assets/MarkdownRenderer-C1KveBTm.js +2 -0
  14. package/dist/assets/{MarkdownRendererImpl-DIvSv3Rv.js → MarkdownRendererImpl-Dfj5yBQH.js} +2 -2
  15. package/dist/assets/MarkstreamRendererImpl-DBWfVjRS.js +3 -0
  16. package/dist/assets/MobileDetailNavigation-D6pHFCLd.js +1 -0
  17. package/dist/assets/MobileResizableSheet-B9lJQT-Q.js +1 -0
  18. package/dist/assets/MobileShareBridge-BJDkko0y.js +4 -0
  19. package/dist/assets/MobileTabPageHeader-BdZ4z7qY.js +2 -0
  20. package/dist/assets/MultiRunWindow-C4sUyQMj.js +1 -0
  21. package/dist/assets/OnboardingScreen-tF0G9FoO.js +1 -0
  22. package/dist/assets/OverlayScrollbar-BhUMMoCN.js +1 -0
  23. package/dist/assets/SettingsView-Dk2vpPHM.js +29 -0
  24. package/dist/assets/SettingsWindow-Cl_MVXqd.js +1 -0
  25. package/dist/assets/SetupTourDialog-BGvxww7E.js +1 -0
  26. package/dist/assets/TerminalView-DCVU9yPv.js +8 -0
  27. package/dist/assets/{ToolOutputDialog-CxlFIAQ4.js → ToolOutputDialog-BSNWZM5u.js} +4 -4
  28. package/dist/assets/VoiceSettings-C3KZYlyP.js +2 -0
  29. package/dist/assets/YuriLogo-CMoJ3Apd.js +1 -0
  30. package/dist/assets/{YuriWordmark-CGDlDvEH.js → YuriWordmark-DiB7p_ho.js} +1 -1
  31. package/dist/assets/{appThemeRegistry-Bz6WZldU.js → appThemeRegistry-axRbeIwY.js} +1 -1
  32. package/dist/assets/{assistant-attachment-cache-oatc8F4t.js → assistant-attachment-cache-B7NHgRWA.js} +1 -1
  33. package/dist/assets/bootstrap-CH0Mo2ok.js +9 -0
  34. package/dist/assets/{capgoAdapter-BpF4euDL.js → capgoAdapter-C8QhPFlX.js} +1 -1
  35. package/dist/assets/checkbox-C641Uk-q.js +1 -0
  36. package/dist/assets/collapsible-YNp0uGvK.js +1 -0
  37. package/dist/assets/context-menu-BHe5nbZ0.js +1 -0
  38. package/dist/assets/desktop-DLxQTjzu.js +1 -0
  39. package/dist/assets/desktopHosts-Dk0D5ATF.js +1 -0
  40. package/dist/assets/desktopRelayRestore-COTsQw8C.js +1 -0
  41. package/dist/assets/{device-w1ioiqv3.js → device-BGox1QjM.js} +1 -1
  42. package/dist/assets/diagram-DZJvm12J.js +1 -0
  43. package/dist/assets/dialog-So-nuji1.js +1 -0
  44. package/dist/assets/{es-DDcXvUON.js → es-BC7jaA0J.js} +2 -2
  45. package/dist/assets/{fileMentionTouchSelection-CJtFYKAV.js → fileMentionTouchSelection-CcBab6jA.js} +1 -1
  46. package/dist/assets/fileQueries-BBcsALlC.js +1 -0
  47. package/dist/assets/{fileReferenceActions-DrAZHld4.js → fileReferenceActions-DRECILCs.js} +1 -1
  48. package/dist/assets/{fileReferenceParser-1HHDBUum.js → fileReferenceParser-BayaidRM.js} +1 -1
  49. package/dist/assets/{fr-pUULu88g.js → fr-BIvcfHvS.js} +2 -2
  50. package/dist/assets/{gitApi-CJS823P8.js → gitApi-CXUPuRTB.js} +5 -5
  51. package/dist/assets/historyImportQueries-MpkoiK56.js +1 -0
  52. package/dist/assets/host-CzMYcPbz.js +1 -0
  53. package/dist/assets/image-loading-2ppAWcFZ.js +1 -0
  54. package/dist/assets/input-BK1Dm9vD.js +1 -0
  55. package/dist/assets/insertionBoundaries-DQRAPE-y.js +1 -0
  56. package/dist/assets/{ja-C7MjLXCG.js → ja-Dx_d9fYc.js} +2 -2
  57. package/dist/assets/{ko-U4JK9TxK.js → ko-CLQ_FtRR.js} +2 -2
  58. package/dist/assets/main-BVl-5tBj.js +169 -0
  59. package/dist/assets/main-CM26G9n0.js +2 -0
  60. package/dist/assets/{markdownHeightCache-CLiBBW4n.js → markdownHeightCache-DMZ5GgoP.js} +1 -1
  61. package/dist/assets/mcpQueries-BFbulSUU.js +1 -0
  62. package/dist/assets/miniChat-CD9Pz0ZW.js +2 -0
  63. package/dist/assets/mobile-B3bArIND.js +2 -0
  64. package/dist/assets/{mobileBackNavigation-BMaLnPn4.js → mobileBackNavigation-D3-dwiiY.js} +1 -1
  65. package/dist/assets/multirun-CEyNjbIS.js +3 -0
  66. package/dist/assets/{native-config-C8AlS30O.js → native-config-stLNU1o7.js} +1 -1
  67. package/dist/assets/path-utils-HRmerlyU.js +1 -0
  68. package/dist/assets/{pl-Cy7NC-CJ.js → pl-BkPum7Gu.js} +3 -3
  69. package/dist/assets/platform-h8km2dnF.js +1 -0
  70. package/dist/assets/projectActions-C-9Z8R7y.js +1 -0
  71. package/dist/assets/projectMeta-2FoNc0nP.js +1 -0
  72. package/dist/assets/{pt-BR-qCU-EBEs.js → pt-BR-DfT7YLHn.js} +2 -2
  73. package/dist/assets/pwa-CCJwn58X.js +2 -0
  74. package/dist/assets/queue-abort-optimistic-BZd3gflI.js +1 -0
  75. package/dist/assets/readiness-Djew2NvN.js +1 -0
  76. package/dist/assets/renderElectronMiniChatApp-DdvkzG1o.js +2 -0
  77. package/dist/assets/renderMobileApp-D4aaygxO.js +28 -0
  78. package/dist/assets/runtime-file-download-Bz4NbKDi.js +1 -0
  79. package/dist/assets/runtime-file-resource-Btl3euLf.js +2 -0
  80. package/dist/assets/runtimeConfig-D4pEnoIh.js +2 -0
  81. package/dist/assets/runtimeEndpointReset-6jhYadQt.css +1 -0
  82. package/dist/assets/runtimeEndpointReset-DvSz9Dmf.js +149 -0
  83. package/dist/assets/{scheduledTaskNavigation-7dD6PWMD.js → scheduledTaskNavigation-BhsMoXS3.js} +1 -1
  84. package/dist/assets/select-IPdYq29J.js +1 -0
  85. package/dist/assets/sessionLookup-7Ux2A4fS.js +1 -0
  86. package/dist/assets/sortable-tabs-strip-pQbSLRMg.js +1 -0
  87. package/dist/assets/{speechSettingsQueries-4gKyXBgi.js → speechSettingsQueries-Cl_-LtPL.js} +1 -1
  88. package/dist/assets/src-BHDTEDdR.css +2 -0
  89. package/dist/assets/{store-CVmc1U19.js → store-BKKodkCp.js} +4 -4
  90. package/dist/assets/terminalApi-D2kNkPrJ.js +1 -0
  91. package/dist/assets/textarea-DSOIfiVX.js +1 -0
  92. package/dist/assets/tooltip-BuZUnYeV.js +1 -0
  93. package/dist/assets/types-DAssRFbW.js +2 -0
  94. package/dist/assets/{uk-D5ulQPhM.js → uk-DgzBKB1K.js} +2 -2
  95. package/dist/assets/url-DO6Zrx1P.js +1 -0
  96. package/dist/assets/{useAppFontEffects-mxyvl0gj.js → useAppFontEffects-Cjtcc4Sq.js} +58 -58
  97. package/dist/assets/{useAssistantUIStore-cHle1U5H.js → useAssistantUIStore-Jmh6rESU.js} +1 -1
  98. package/dist/assets/useDesktopWindowControlsLayout-BJx2ijlY.js +1 -0
  99. package/dist/assets/useDictation-BafHajO_.js +1 -0
  100. package/dist/assets/useEffectiveDirectory-AQOtdYdf.js +1 -0
  101. package/dist/assets/{useFontPreferences-D-AOjd9H.js → useFontPreferences-OCLG7Btz.js} +1 -1
  102. package/dist/assets/useMobileNavigationStore-l2L-r3RJ.js +17 -0
  103. package/dist/assets/usePluginsStore-DaZr5OE_.js +1 -0
  104. package/dist/assets/{useStreamingTextThrottle-DLR8xP-j.js → useStreamingTextThrottle-C1Dm4frL.js} +1 -1
  105. package/dist/assets/{useUIStore-B61bCFEM.js → useUIStore-DPo791La.js} +1 -1
  106. package/dist/assets/useWorkerHighlightedLines-DhJbTxdK.js +7 -0
  107. package/dist/assets/vendor-reactuses-core-CuTmqEMK.js +1 -0
  108. package/dist/assets/{zh-CN-C3SRM0mS.js → zh-CN-DTKScxtm.js} +2 -2
  109. package/dist/assets/{zh-TW-CZD-9AC2.js → zh-TW-JOn8l2o2.js} +2 -2
  110. package/dist/index.html +19 -23
  111. package/dist/mini-chat.html +19 -23
  112. package/dist/mobile.html +19 -23
  113. package/package.json +1 -1
  114. package/server/index.js +4 -3
  115. package/server/lib/assistants/DOCUMENTATION.md +37 -5
  116. package/server/lib/assistants/contact-store.js +8 -1
  117. package/server/lib/assistants/contact-tools.js +6 -6
  118. package/server/lib/assistants/contact-tools.test.js +4 -2
  119. package/server/lib/assistants/harness.js +14 -8
  120. package/server/lib/assistants/harness.test.js +33 -0
  121. package/server/lib/assistants/pi-tools.js +15 -2
  122. package/server/lib/assistants/pi-tools.test.js +35 -1
  123. package/server/lib/assistants/service.js +6 -9
  124. package/server/lib/assistants/service.test.js +90 -12
  125. package/server/lib/assistants/summary.js +2 -0
  126. package/server/lib/assistants/tool-execution.js +53 -0
  127. package/server/lib/assistants/tool-execution.test.js +82 -0
  128. package/server/lib/assistants/yuri-project.http.test.js +2 -3
  129. package/server/lib/assistants/yuri-tools.js +1 -1
  130. package/server/lib/git/DOCUMENTATION.md +3 -0
  131. package/server/lib/git/service.js +9 -3
  132. package/server/lib/git/worktrees.catalog.test.js +31 -0
  133. package/server/lib/notifications/DOCUMENTATION.md +34 -0
  134. package/server/lib/notifications/session-unread-runtime.js +101 -0
  135. package/server/lib/notifications/session-unread-store.js +93 -0
  136. package/server/lib/notifications/session-unread.test.js +176 -0
  137. package/server/lib/opencode/feature-routes-runtime.js +22 -1
  138. package/server/lib/opencode/session-directory-runtime.js +29 -3
  139. package/server/lib/opencode/session-directory-runtime.test.js +78 -0
  140. package/server/lib/scheduled-tasks/DOCUMENTATION.md +12 -0
  141. package/server/lib/scheduled-tasks/runtime.js +24 -0
  142. package/server/lib/scheduled-tasks/runtime.test.js +41 -0
  143. package/server/lib/session-index/DOCUMENTATION.md +9 -0
  144. package/server/lib/session-index/sync-runtime.js +10 -1
  145. package/dist/assets/AgentAvatar-D4JLZ7IL.js +0 -1
  146. package/dist/assets/AssistantContactStatus-CqANenYS.js +0 -3
  147. package/dist/assets/AssistantUnreadBadge-j-O3lnH_.js +0 -1
  148. package/dist/assets/AssistantView-DXibp8Nh.js +0 -1
  149. package/dist/assets/DiagramView-BRW8DdSg.js +0 -1
  150. package/dist/assets/FadeInOnReveal-CY1UuS2D.js +0 -1
  151. package/dist/assets/GuiPluginSurface-BOWSgNtP.js +0 -1
  152. package/dist/assets/GuiPluginWindow-DlnxZgDZ.js +0 -1
  153. package/dist/assets/Icon-D7VxRqha.js +0 -1
  154. package/dist/assets/ImageLoadingPlaceholder-ClzN4oGS.js +0 -1
  155. package/dist/assets/LoadingImage-QfRXuKTy.js +0 -1
  156. package/dist/assets/MarkdownRenderer-DjSn61IL.js +0 -2
  157. package/dist/assets/MarkstreamRendererImpl-AJvljij3.js +0 -3
  158. package/dist/assets/MobileDetailNavigation-CaO-fGvE.js +0 -1
  159. package/dist/assets/MobileResizableSheet-CNn25qxG.js +0 -1
  160. package/dist/assets/MobileShareBridge-D8oRgnuW.js +0 -4
  161. package/dist/assets/MobileTabPageHeader-CkuLCAUz.js +0 -2
  162. package/dist/assets/MultiRunWindow-PFfaS1N3.js +0 -1
  163. package/dist/assets/OnboardingScreen-BmAImZZZ.js +0 -1
  164. package/dist/assets/OverlayScrollbar-dxKlRNuH.js +0 -1
  165. package/dist/assets/SettingsView-Ci7GRXnm.js +0 -29
  166. package/dist/assets/SettingsWindow-DjqjH8zU.js +0 -1
  167. package/dist/assets/SetupTourDialog-yJq3b29w.js +0 -1
  168. package/dist/assets/TerminalView-DsqOYj1E.js +0 -8
  169. package/dist/assets/VoiceSettings-BEtahqoU.js +0 -2
  170. package/dist/assets/YuriLogo-DADSHd1H.js +0 -1
  171. package/dist/assets/bootstrap-Bi91NjXG.js +0 -3
  172. package/dist/assets/button-B7w-b2yV.js +0 -1
  173. package/dist/assets/checkbox-DTPgJBK_.js +0 -1
  174. package/dist/assets/collapsible-DZ4ykYM2.js +0 -1
  175. package/dist/assets/context-menu-BXHMb3Q-.js +0 -1
  176. package/dist/assets/desktop-BAmoc_34.js +0 -1
  177. package/dist/assets/desktopHosts-BLU1tGSX.js +0 -1
  178. package/dist/assets/desktopRelayRestore-2BIIs8mZ.js +0 -1
  179. package/dist/assets/diagram-CldUPV-Z.js +0 -1
  180. package/dist/assets/dialog-gc3n4NXh.js +0 -1
  181. package/dist/assets/fileQueries-C2Rs6TPz.js +0 -1
  182. package/dist/assets/gitApiHttp-CKrsk1tw.js +0 -7
  183. package/dist/assets/historyImportQueries-C8VK9R5_.js +0 -1
  184. package/dist/assets/host-z9PU8q1e.js +0 -1
  185. package/dist/assets/image-loading-DKQOYtti.js +0 -1
  186. package/dist/assets/input-B7yPcQsA.js +0 -1
  187. package/dist/assets/insertionBoundaries-D9Vc7ZK5.js +0 -1
  188. package/dist/assets/main-DD5kDabV.js +0 -2
  189. package/dist/assets/main-Da12pxuy.js +0 -169
  190. package/dist/assets/mcpQueries-JrS0Bvb3.js +0 -1
  191. package/dist/assets/miniChat-lRi18Hvu.js +0 -2
  192. package/dist/assets/mobile-8eKyWn8a.js +0 -2
  193. package/dist/assets/multirun-Cui2oFM-.js +0 -3
  194. package/dist/assets/path-utils-jGozTg9d.js +0 -1
  195. package/dist/assets/pathNormalization-ewtPqJWn.js +0 -1
  196. package/dist/assets/platform-sEg2IOLZ.js +0 -1
  197. package/dist/assets/projectActions-BX0cjZoq.js +0 -1
  198. package/dist/assets/projectMeta-A8jJRQk7.js +0 -1
  199. package/dist/assets/pwa-CbR9DKyA.js +0 -2
  200. package/dist/assets/queryRuntime-2dx7jbt9.js +0 -1
  201. package/dist/assets/queue-abort-optimistic-B_crtkQx.js +0 -1
  202. package/dist/assets/readiness-BpeOajK9.js +0 -1
  203. package/dist/assets/renderElectronMiniChatApp-DqJy20-t.js +0 -2
  204. package/dist/assets/renderMobileApp-C9OxYnMu.js +0 -28
  205. package/dist/assets/runtime-file-download-D6bwc3Kj.js +0 -1
  206. package/dist/assets/runtime-file-resource-BP4P52ry.js +0 -2
  207. package/dist/assets/runtimeAPIRegistry-C2VogTny.js +0 -1
  208. package/dist/assets/runtimeConfig-7LsY--_g.js +0 -2
  209. package/dist/assets/runtimeEndpointReset-BP4JwHFJ.css +0 -1
  210. package/dist/assets/runtimeEndpointReset-NZMW9r3D.js +0 -149
  211. package/dist/assets/select-WCptRb7Z.js +0 -1
  212. package/dist/assets/sessionLookup-CxjYSDU2.js +0 -1
  213. package/dist/assets/sortable-tabs-strip-DFKCoZZF.js +0 -1
  214. package/dist/assets/src-B_i0g2Ca.css +0 -2
  215. package/dist/assets/terminalApi-Bo6KWljy.js +0 -1
  216. package/dist/assets/textarea-CMVUhwQ2.js +0 -1
  217. package/dist/assets/tooltip-L2xweVkb.js +0 -1
  218. package/dist/assets/types-djs5o8aQ.js +0 -2
  219. package/dist/assets/url-MRa-FtQa.js +0 -1
  220. package/dist/assets/useDesktopWindowControlsLayout-ZHw0VsJh.js +0 -1
  221. package/dist/assets/useDictation-DO12CgDE.js +0 -1
  222. package/dist/assets/useEffectiveDirectory-B6ny9aem.js +0 -1
  223. package/dist/assets/useMobileNavigationStore-DRBFwjAg.js +0 -17
  224. package/dist/assets/usePluginsStore-Bav6NFUH.js +0 -1
  225. package/dist/assets/useWorkerHighlightedLines-DdYDj9PN.js +0 -7
  226. package/dist/assets/vendor-reactuses-core-DWo5Wn6R.js +0 -1
@@ -0,0 +1,101 @@
1
+ import express from 'express';
2
+ import { isVisibleSession } from '../session-index/service.js';
3
+
4
+ /** Only lifecycle boundaries do work; token, part and message deltas never read or write. */
5
+ export function createSessionUnreadRuntime({ store, loadSession, hub, resolveDirectory = value => value, retryMs = 1000 }) {
6
+ const flights = new Map();
7
+ const queues = new Map();
8
+ let disposed = false;
9
+ const directoryOf = session => resolveDirectory(session.location?.directory ?? session.directory ?? '');
10
+ const visible = session => session && !session.parentID && isVisibleSession(session);
11
+ const apply = async ({ payload, id, kind }) => {
12
+ if (kind === 'deleted') { store.remove(id); return; }
13
+ const session = await loadSession(id);
14
+ if (disposed || !visible(session)) return;
15
+ store.observe({ id, directory: directoryOf(session), kind, eventAt: payload.created, sequence: payload.durable?.seq });
16
+ };
17
+ const drain = (id, queue) => {
18
+ if (disposed || flights.has(id) || queue.timer) return;
19
+ const flight = (async () => {
20
+ while (!disposed && queue.items.length) {
21
+ try {
22
+ await apply(queue.items[0]);
23
+ queue.items.shift().resolve();
24
+ queue.attempt = 0;
25
+ } catch {
26
+ // Preserve the failed boundary and its following run boundaries in order.
27
+ // Other sessions have independent queues and can continue normally.
28
+ const delay = Math.min(retryMs * 2 ** Math.min(queue.attempt++, 5), 30000);
29
+ queue.timer = setTimeout(() => { queue.timer = null; drain(id, queue); }, delay);
30
+ queue.timer.unref?.();
31
+ console.warn('[session-unread] lifecycle update deferred; retrying');
32
+ return;
33
+ }
34
+ }
35
+ if (!queue.items.length) queues.delete(id);
36
+ })();
37
+ flights.set(id, flight);
38
+ void flight.finally(() => {
39
+ if (flights.get(id) === flight) flights.delete(id);
40
+ const pending = queues.get(id);
41
+ if (pending) drain(id, pending);
42
+ });
43
+ };
44
+ const processEvent = (envelope) => {
45
+ const raw = envelope?.payload ?? envelope;
46
+ const payload = raw?.payload ?? raw;
47
+ const type = payload?.type?.replace(/\.\d+$/, '');
48
+ const body = payload?.data ?? payload?.properties ?? {};
49
+ const id = body.sessionID ?? body.sessionId ?? body.info?.id ?? body.id;
50
+ if (typeof id !== 'string' || !id) return Promise.resolve();
51
+ const kind = type === 'session.execution.started' || (type === 'session.status' && body.status?.type === 'busy') ? 'running'
52
+ : type === 'session.execution.succeeded' || type === 'session.idle' ? 'complete'
53
+ : type === 'session.execution.failed' || type === 'session.error' ? 'error'
54
+ : type === 'session.deleted' ? 'deleted' : null;
55
+ if (!kind || disposed) return Promise.resolve();
56
+ const queue = queues.get(id) ?? { items: [], timer: null, attempt: 0 };
57
+ queues.set(id, queue);
58
+ const completion = new Promise(resolve => {
59
+ queue.items.push({ payload, id, kind, resolve });
60
+ });
61
+ drain(id, queue);
62
+ return completion;
63
+ };
64
+ const unsubscribe = hub?.subscribeEvent(event => {
65
+ void processEvent(event).catch(() => console.warn('[session-unread] lifecycle update failed'));
66
+ });
67
+ return {
68
+ processEvent,
69
+ registerRoutes(app) {
70
+ app.get('/api/yuri/session-unread', (_req, res) => {
71
+ try { res.json(store.snapshot()); }
72
+ catch { res.status(503).json({ error: 'Session unread state unavailable' }); }
73
+ });
74
+ app.put('/api/yuri/session-unread/:id', express.json({ limit: '8kb' }), async (req, res) => {
75
+ const { unread, expectedRevision } = req.body ?? {};
76
+ const id = req.params.id;
77
+ if (!id || id.length > 512 || typeof unread !== 'boolean'
78
+ || (!unread && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0))) {
79
+ return res.status(400).json({ error: 'Invalid session unread mutation' });
80
+ }
81
+ try {
82
+ const session = await loadSession(id);
83
+ if (!session) return res.status(404).json({ error: 'Session not found' });
84
+ if (!visible(session)) return res.status(400).json({ error: 'Session is not a visible root conversation' });
85
+ res.json(store.mark({ id, directory: directoryOf(session), unread, expectedRevision }));
86
+ } catch { res.status(503).json({ error: 'Session unread state unavailable' }); }
87
+ });
88
+ },
89
+ async close() {
90
+ disposed = true;
91
+ unsubscribe?.();
92
+ for (const queue of queues.values()) {
93
+ clearTimeout(queue.timer);
94
+ for (const item of queue.items) item.resolve();
95
+ }
96
+ await Promise.allSettled(flights.values());
97
+ queues.clear();
98
+ store.close();
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,93 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+
5
+ const require = createRequire(import.meta.url);
6
+
7
+ /** Durable attention, independent of notification delivery settings and client presence. */
8
+ export function createSessionUnreadStore({ dbPath, onChanged = () => {} }) {
9
+ if (dbPath !== ':memory:') fs.mkdirSync(path.dirname(dbPath), { recursive: true });
10
+ const Database = require('better-sqlite3');
11
+ const db = new Database(dbPath);
12
+ db.pragma('journal_mode = WAL');
13
+ db.exec(`
14
+ CREATE TABLE IF NOT EXISTS unread_meta (id INTEGER PRIMARY KEY CHECK(id = 1), revision INTEGER NOT NULL);
15
+ INSERT OR IGNORE INTO unread_meta VALUES (1, 0);
16
+ CREATE TABLE IF NOT EXISTS session_unread (
17
+ id TEXT PRIMARY KEY, directory TEXT NOT NULL DEFAULT '',
18
+ unreadCount INTEGER NOT NULL DEFAULT 0, hasError INTEGER NOT NULL DEFAULT 0,
19
+ manual INTEGER NOT NULL DEFAULT 0, revision INTEGER NOT NULL DEFAULT 0,
20
+ terminal INTEGER NOT NULL DEFAULT 0, eventAt INTEGER NOT NULL DEFAULT 0,
21
+ sequence INTEGER NOT NULL DEFAULT 0
22
+ );
23
+ `);
24
+ const find = db.prepare('SELECT * FROM session_unread WHERE id = ?');
25
+ const revision = () => db.prepare('SELECT revision FROM unread_meta WHERE id = 1').get().revision;
26
+ const publicRow = (row) => ({
27
+ directory: row.directory, unreadCount: row.unreadCount, hasError: Boolean(row.hasError),
28
+ manual: Boolean(row.manual), revision: row.revision,
29
+ });
30
+ const snapshot = () => ({
31
+ revision: revision(),
32
+ sessions: Object.fromEntries(db.prepare('SELECT * FROM session_unread').all().map(row => [row.id, publicRow(row)])),
33
+ });
34
+ const writeRow = db.prepare(`INSERT OR REPLACE INTO session_unread
35
+ (id, directory, unreadCount, hasError, manual, revision, terminal, eventAt, sequence)
36
+ VALUES (@id, @directory, @unreadCount, @hasError, @manual, @revision, @terminal, @eventAt, @sequence)`);
37
+ const empty = (id) => ({ id, directory: '', unreadCount: 0, hasError: 0, manual: 0, revision: 0, terminal: 0, eventAt: 0, sequence: 0 });
38
+ const commit = (decide) => {
39
+ const changed = db.transaction(() => {
40
+ const next = decide();
41
+ if (!next) return false;
42
+ if (next.publish) {
43
+ db.prepare('UPDATE unread_meta SET revision = revision + 1 WHERE id = 1').run();
44
+ next.row.revision = revision();
45
+ }
46
+ writeRow.run(next.row);
47
+ return next.publish;
48
+ })();
49
+ if (changed) onChanged(revision());
50
+ };
51
+ return {
52
+ snapshot,
53
+ observe({ id, directory = '', kind, eventAt = 0, sequence = 0 }) {
54
+ commit(() => {
55
+ const current = find.get(id) ?? empty(id);
56
+ if (sequence && sequence <= current.sequence) return null;
57
+ if (!sequence && eventAt && eventAt < current.eventAt) return null;
58
+ const row = { ...current, directory: directory || current.directory,
59
+ eventAt: Math.max(eventAt, current.eventAt), sequence: Math.max(sequence, current.sequence) };
60
+ if (kind === 'running') {
61
+ row.terminal = 0;
62
+ if (row.hasError) row.unreadCount = Math.max(0, row.unreadCount - 1);
63
+ row.hasError = 0;
64
+ } else if (!row.terminal) {
65
+ row.terminal = 1;
66
+ row.unreadCount += 1;
67
+ if (kind === 'error') row.hasError = 1;
68
+ }
69
+ return { row, publish: row.unreadCount !== current.unreadCount || row.hasError !== current.hasError };
70
+ });
71
+ },
72
+ mark({ id, directory = '', unread, expectedRevision }) {
73
+ commit(() => {
74
+ const current = find.get(id) ?? empty(id);
75
+ // Read only the exact state the client observed, never a newer completion or manual mark.
76
+ if (!unread && (expectedRevision !== current.revision || current.unreadCount === 0)) return null;
77
+ return { row: { ...current, directory: directory || current.directory,
78
+ unreadCount: unread ? Math.max(1, current.unreadCount) : 0,
79
+ hasError: unread ? current.hasError : 0, manual: unread ? 1 : 0 }, publish: true };
80
+ });
81
+ return snapshot();
82
+ },
83
+ remove(id) {
84
+ const changed = db.transaction(() => {
85
+ if (!db.prepare('DELETE FROM session_unread WHERE id = ?').run(id).changes) return false;
86
+ db.prepare('UPDATE unread_meta SET revision = revision + 1 WHERE id = 1').run();
87
+ return true;
88
+ })();
89
+ if (changed) onChanged(revision());
90
+ },
91
+ close: () => db.close(),
92
+ };
93
+ }
@@ -0,0 +1,176 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { createRequire } from 'node:module';
6
+ import express from 'express';
7
+ import request from 'supertest';
8
+ import { createSessionUnreadStore } from './session-unread-store.js';
9
+ import { createSessionUnreadRuntime } from './session-unread-runtime.js';
10
+
11
+ const cleanup = [];
12
+ afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); });
13
+ const fixture = (options = {}) => {
14
+ const changed = vi.fn();
15
+ const store = createSessionUnreadStore({ dbPath: ':memory:', onChanged: changed });
16
+ const loadSession = vi.fn(async id => ({ id, title: 'Conversation', location: { directory: '/project' } }));
17
+ const runtime = createSessionUnreadRuntime({ store, loadSession, ...options });
18
+ cleanup.push(() => runtime.close());
19
+ const event = (type, sessionID = 'one', created = undefined, seq = undefined) => runtime.processEvent({
20
+ payload: { type, data: { sessionID }, created, ...(seq ? { durable: { seq } } : {}) },
21
+ });
22
+ const app = express();
23
+ runtime.registerRoutes(app);
24
+ return { store, runtime, event, app, loadSession, changed };
25
+ };
26
+
27
+ describe('shared session unread', () => {
28
+ it('records completion with no clients, deduplicates succeeded/idle, and rearms on a new run', async () => {
29
+ const { store, event, changed } = fixture();
30
+ await event('session.execution.succeeded');
31
+ await event('session.idle');
32
+ expect(store.snapshot().sessions.one).toMatchObject({ unreadCount: 1, hasError: false, directory: '/project' });
33
+ expect(changed).toHaveBeenCalledTimes(1);
34
+ await event('session.execution.started');
35
+ await event('session.execution.succeeded');
36
+ expect(store.snapshot().sessions.one.unreadCount).toBe(2);
37
+ });
38
+
39
+ it('shares read/unread across clients and stale reads cannot erase newer manual marks or completions', async () => {
40
+ const { app, event } = fixture();
41
+ await event('session.execution.succeeded');
42
+ const a = (await request(app).get('/api/yuri/session-unread')).body;
43
+ const b = (await request(app).get('/api/yuri/session-unread')).body;
44
+ expect(a).toEqual(b);
45
+ const read = await request(app).put('/api/yuri/session-unread/one').send({ unread: false, expectedRevision: a.sessions.one.revision });
46
+ expect(read.body.sessions.one.unreadCount).toBe(0);
47
+ const manual = await request(app).put('/api/yuri/session-unread/one').send({ unread: true });
48
+ expect(manual.body.sessions.one).toMatchObject({ unreadCount: 1, manual: true });
49
+ const stale = await request(app).put('/api/yuri/session-unread/one').send({ unread: false, expectedRevision: b.sessions.one.revision });
50
+ expect(stale.body).toEqual(manual.body);
51
+ await event('session.execution.started');
52
+ await event('session.execution.succeeded');
53
+ const staleAgain = await request(app).put('/api/yuri/session-unread/one').send({ unread: false, expectedRevision: manual.body.sessions.one.revision });
54
+ expect(staleAgain.body.sessions.one.unreadCount).toBe(2);
55
+ });
56
+
57
+ it('retains committed state and deduplication after a server restart', () => {
58
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-unread-'));
59
+ cleanup.push(() => fs.rmSync(dir, { recursive: true, force: true }));
60
+ const dbPath = path.join(dir, 'state.sqlite');
61
+ const first = createSessionUnreadStore({ dbPath });
62
+ first.observe({ id: 'one', directory: '/project', kind: 'complete', sequence: 20 });
63
+ first.mark({ id: 'two', unread: true, directory: '/other' });
64
+ const expected = first.snapshot();
65
+ first.close();
66
+ const second = createSessionUnreadStore({ dbPath });
67
+ cleanup.push(() => second.close());
68
+ expect(second.snapshot()).toEqual(expected);
69
+ second.observe({ id: 'one', kind: 'complete', sequence: 20 });
70
+ second.observe({ id: 'one', kind: 'running', sequence: 19 });
71
+ second.observe({ id: 'one', kind: 'complete', sequence: 21 });
72
+ expect(second.snapshot()).toEqual(expected);
73
+ });
74
+
75
+ it('isolates failures, subagents and system sessions; new execution clears only its error', async () => {
76
+ const { store, event, loadSession } = fixture();
77
+ loadSession.mockImplementation(async id => ({ id, directory: '/project',
78
+ ...(id === 'child' ? { parentID: 'root' } : {}),
79
+ ...(id === 'system' ? { metadata: { yuri: { llm: { purpose: 'summary' } } } } : {}),
80
+ }));
81
+ await event('session.execution.failed');
82
+ await event('session.error');
83
+ await event('session.idle');
84
+ await event('session.execution.failed', 'two');
85
+ await event('session.execution.succeeded', 'child');
86
+ await event('session.execution.succeeded', 'system');
87
+ await event('session.execution.started', 'child');
88
+ await event('session.execution.started', 'system');
89
+ expect(Object.keys(store.snapshot().sessions).sort()).toEqual(['one', 'two']);
90
+ expect(store.snapshot().sessions.one).toMatchObject({ unreadCount: 1, hasError: true });
91
+ await event('session.execution.started');
92
+ expect(store.snapshot().sessions.one).toMatchObject({ unreadCount: 0, hasError: false });
93
+ expect(store.snapshot().sessions.two).toMatchObject({ unreadCount: 1, hasError: true });
94
+ });
95
+
96
+ it('skips 10000 streaming events without metadata reads, writes or revision bumps', async () => {
97
+ const { runtime, store, loadSession, changed } = fixture();
98
+ for (let i = 0; i < 10000; i++) {
99
+ await runtime.processEvent({ type: 'message.part.updated', data: { sessionID: 'one' } });
100
+ }
101
+ expect(loadSession).not.toHaveBeenCalled();
102
+ expect(changed).not.toHaveBeenCalled();
103
+ expect(store.snapshot()).toEqual({ revision: 0, sessions: {} });
104
+ });
105
+
106
+ it('rejects old and duplicate native boundaries even before the first completion', async () => {
107
+ const { store, event } = fixture();
108
+ await event('session.execution.started', 'one', 20, 20);
109
+ await event('session.execution.succeeded', 'one', 10, 10);
110
+ expect(store.snapshot().sessions.one.unreadCount).toBe(0);
111
+ await event('session.execution.succeeded', 'one', 30, 30);
112
+ await event('session.execution.started', 'one', 20, 20);
113
+ await event('session.idle', 'one', 31, 31);
114
+ expect(store.snapshot().sessions.one.unreadCount).toBe(1);
115
+ });
116
+
117
+ it('validates mutations and does not convert upstream failure into empty success', async () => {
118
+ const { app, event, loadSession, store } = fixture();
119
+ await event('session.execution.succeeded');
120
+ const previous = store.snapshot();
121
+ for (const body of [{}, { unread: 'yes' }, { unread: false }, { unread: false, expectedRevision: -1 }]) {
122
+ expect((await request(app).put('/api/yuri/session-unread/one').send(body)).status).toBe(400);
123
+ }
124
+ loadSession.mockRejectedValue(new Error('unavailable'));
125
+ expect((await request(app).put('/api/yuri/session-unread/one').send({ unread: true })).status).toBe(503);
126
+ expect(store.snapshot()).toEqual(previous);
127
+ });
128
+
129
+ it('rolls back both state and revision when durable commit fails', () => {
130
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-unread-rollback-'));
131
+ cleanup.push(() => fs.rmSync(dir, { recursive: true, force: true }));
132
+ const dbPath = path.join(dir, 'state.sqlite');
133
+ const changed = vi.fn();
134
+ const store = createSessionUnreadStore({ dbPath, onChanged: changed });
135
+ cleanup.push(() => store.close());
136
+ store.mark({ id: 'one', unread: true });
137
+ const previous = store.snapshot();
138
+ const Database = createRequire(import.meta.url)('better-sqlite3');
139
+ const db = new Database(dbPath);
140
+ db.exec("CREATE TRIGGER reject_write BEFORE INSERT ON session_unread BEGIN SELECT RAISE(ABORT, 'write failed'); END");
141
+ expect(() => store.mark({ id: 'one', unread: false, expectedRevision: 1 })).toThrow('write failed');
142
+ expect(store.snapshot()).toEqual(previous);
143
+ expect(changed).toHaveBeenCalledTimes(1);
144
+ db.exec('DROP TRIGGER reject_write'); db.close();
145
+ expect(store.mark({ id: 'one', unread: false, expectedRevision: 1 }).sessions.one.unreadCount).toBe(0);
146
+ });
147
+
148
+ it('retries a failed identity read in order without blocking other sessions', async () => {
149
+ const { event, loadSession, store } = fixture({ retryMs: 5 });
150
+ loadSession.mockRejectedValueOnce(new Error('temporary failure'));
151
+ const first = event('session.execution.succeeded', 'one', 10, 10);
152
+ const next = event('session.execution.started', 'one', 20, 20);
153
+ const last = event('session.execution.succeeded', 'one', 30, 30);
154
+ await event('session.execution.succeeded', 'two', 10, 10);
155
+ expect(store.snapshot().sessions.two.unreadCount).toBe(1);
156
+ await Promise.all([first, next, last]);
157
+ expect(store.snapshot().sessions.one.unreadCount).toBe(2);
158
+ });
159
+
160
+ it('serializes a terminal identity read with the next run and deletes only the selected session', async () => {
161
+ const { event, store, loadSession } = fixture();
162
+ let release;
163
+ loadSession.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
164
+ const complete = event('session.execution.succeeded', 'one', 10, 10);
165
+ const started = event('session.execution.started', 'one', 20, 20);
166
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
167
+ release({ id: 'one', title: '', directory: '/project' });
168
+ await Promise.all([complete, started]);
169
+ await event('session.execution.succeeded', 'one', 30, 30);
170
+ await event('session.execution.succeeded', 'two');
171
+ expect(store.snapshot().sessions.one.unreadCount).toBe(2);
172
+ await event('session.deleted', 'one');
173
+ expect(store.snapshot().sessions.one).toBeUndefined();
174
+ expect(store.snapshot().sessions.two.unreadCount).toBe(1);
175
+ });
176
+ });
@@ -8,6 +8,10 @@ import { makeOpenCodeV2Client } from './v2-client.js';
8
8
  import { releaseDeletedWorktreeLocation } from './location-release.js';
9
9
  import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
10
10
  import { registerSessionFoldersRoutes } from '../session-folders/routes.js';
11
+ import { createSessionUnreadStore } from '../notifications/session-unread-store.js';
12
+ import { createSessionUnreadRuntime } from '../notifications/session-unread-runtime.js';
13
+ import { readSessionRecordViaClient } from '../session-metadata/opencode-session-record.js';
14
+ import { projectSessionWithHostMetadata } from '../session-metadata/session-projection.js';
11
15
  import { registerPermissionAutoAcceptRoutes } from '../permission-auto-accept/runtime.js';
12
16
  import { registerQuestionAutoDelegateRoutes } from '../question-auto-delegate/routes.js';
13
17
  import { registerConfigEntityRoutes } from './config-entity-routes.js';
@@ -90,6 +94,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
90
94
 
91
95
  let assistantRoutesRuntime = null;
92
96
  let historyImportRuntime = null;
97
+ let sessionUnreadRuntime = null;
93
98
 
94
99
  const registerRoutes = async (app, routeDependencies) => {
95
100
  const {
@@ -482,6 +487,22 @@ export const createFeatureRoutesRuntime = (dependencies) => {
482
487
  getYuriEventClients,
483
488
  writeSseEvent,
484
489
  });
490
+ sessionUnreadRuntime = createSessionUnreadRuntime({
491
+ store: createSessionUnreadStore({
492
+ dbPath: path.join(yuriDataDir, 'session-unread.sqlite'),
493
+ onChanged: revision => broadcastYuriEvent({
494
+ type: 'yuri:session-unread-changed', properties: { revision, occurredAt: Date.now() },
495
+ }),
496
+ }),
497
+ hub: globalMessageStreamHub,
498
+ loadSession: async (sessionID) => {
499
+ const client = makeOpenCodeV2Client({ baseUrl: buildOpenCodeUrl('/', ''), authHeaders: getOpenCodeAuthHeaders() });
500
+ const session = await readSessionRecordViaClient(client, { sessionID, requestOptions: { signal: AbortSignal.timeout(10000) } });
501
+ if (!session) return null;
502
+ return sessionMetadataStore ? projectSessionWithHostMetadata(session, await sessionMetadataStore.get(sessionID)) : session;
503
+ },
504
+ });
505
+ sessionUnreadRuntime.registerRoutes(app);
485
506
  app.on('yuri:speech-settings-changed', () => {
486
507
  broadcastYuriEvent({ type: 'yuri:speech-settings-changed', properties: { occurredAt: Date.now() } });
487
508
  });
@@ -549,6 +570,6 @@ export const createFeatureRoutesRuntime = (dependencies) => {
549
570
 
550
571
  return {
551
572
  registerRoutes,
552
- close: async () => { await historyImportRuntime?.close(); await assistantRoutesRuntime?.close(); },
573
+ close: async () => { await sessionUnreadRuntime?.close(); await historyImportRuntime?.close(); await assistantRoutesRuntime?.close(); },
553
574
  };
554
575
  };
@@ -82,7 +82,7 @@ export const createSessionDirectoryRuntime = ({
82
82
  // v2 directory filters are lexical SQL equality. Read session pages without
83
83
  // booting a Location, then retain only the same physical directory.
84
84
  // This also finds old aliases absent from Yuri's bounded index.
85
- const fetchSessionList = async (input, init) => {
85
+ const fetchSessionList = async (input, init, readPage = fetchFn) => {
86
86
  const url = new URL(input);
87
87
  if (!['/api/session', '/session'].includes(url.pathname) || (init?.method && init.method !== 'GET')) return fetchFn(input, init);
88
88
  const requested = url.searchParams.get('directory');
@@ -92,7 +92,7 @@ export const createSessionDirectoryRuntime = ({
92
92
  }
93
93
  url.searchParams.delete('directory');
94
94
  init?.signal?.throwIfAborted();
95
- const response = await fetchFn(url, init);
95
+ const response = await readPage(url, init);
96
96
  if (!response.ok) return response;
97
97
  const payload = await response.json();
98
98
  init?.signal?.throwIfAborted();
@@ -108,5 +108,31 @@ export const createSessionDirectoryRuntime = ({
108
108
  headers.set('content-type', 'application/json');
109
109
  return new Response(JSON.stringify(body), { status: response.status, headers });
110
110
  };
111
- return { isLocal, resolveDirectory, isDirectoryMissing, projectSession, projectEvent, fetchSessionList };
111
+ const createFetchBatch = () => {
112
+ const pages = new Map();
113
+ const runtime = getRuntimeUrl?.() ?? '';
114
+ let bytes = 0;
115
+ const readPage = async (url, init) => {
116
+ init?.signal?.throwIfAborted();
117
+ if ((getRuntimeUrl?.() ?? '') !== runtime) { pages.clear(); bytes = 0; return fetchFn(url, init); }
118
+ const key = JSON.stringify([String(url), [...new Headers(init?.headers)].sort()]);
119
+ const cached = pages.get(key);
120
+ if (cached) return new Response(cached.body, { status: cached.status, headers: cached.headers });
121
+ const response = await fetchFn(url, init);
122
+ if (!response.ok) return response;
123
+ const body = await response.text();
124
+ init?.signal?.throwIfAborted();
125
+ const size = Buffer.byteLength(body);
126
+ const headers = new Headers(response.headers);
127
+ for (const name of ['content-length', 'content-encoding', 'transfer-encoding', 'etag']) headers.delete(name);
128
+ // A batch retains at most five complete raw pages / 4 MiB, never filtered
129
+ // directory results. Over-budget pages are read normally, not truncated.
130
+ if (pages.size < 5 && bytes + size <= 4 * 1024 * 1024) {
131
+ pages.set(key, { body, status: response.status, headers }); bytes += size;
132
+ }
133
+ return new Response(body, { status: response.status, headers });
134
+ };
135
+ return (input, init) => fetchSessionList(input, init, readPage);
136
+ };
137
+ return { isLocal, resolveDirectory, isDirectoryMissing, projectSession, projectEvent, fetchSessionList, createFetchBatch };
112
138
  };
@@ -24,6 +24,84 @@ const session = (id, directory, updated = 1) => ({ id, title: id, location: { di
24
24
  const json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } });
25
25
 
26
26
  describe('physical session directory identity', () => {
27
+ it.each(['publishChange', 'noteInteractiveRequest'])('discards shared pages on %s before refreshing another directory', async (method) => {
28
+ const { real, other } = fixture();
29
+ let reads = 0;
30
+ let clock = 0;
31
+ const directories = createSessionDirectoryRuntime({ fetchFn: async (input) => {
32
+ if (new URL(input).searchParams.has('parentID')) return json({ data: [], cursor: {} });
33
+ reads++;
34
+ return json({ data: [session('a', real), { ...session('b', other), title: `revision-${reads}` }], cursor: {} });
35
+ } });
36
+ const service = createSessionIndexService({ dbPath: ':memory:' });
37
+ const sync = createSessionIndexSyncRuntime({ sessionIndexService: service, now: () => clock,
38
+ buildOpenCodeUrl: (route) => `http://localhost/api${route}`, getOpenCodeAuthHeaders: () => ({}),
39
+ fetchFn: directories.fetchSessionList, createFetchBatch: directories.createFetchBatch,
40
+ });
41
+ const replace = service.replaceDirectory;
42
+ vi.spyOn(service, 'replaceDirectory').mockImplementation((input) => {
43
+ const result = replace(input);
44
+ if (input.directory === real) { sync[method](); clock += 1_001; }
45
+ return result;
46
+ });
47
+ try {
48
+ sync.enqueue([real, other]);
49
+ await vi.waitFor(() => expect(sync.snapshot().sync.active || sync.snapshot().sync.enriching).toBe(false));
50
+ expect(reads).toBe(2);
51
+ expect(service.findBySessionId('b').title).toBe('revision-2');
52
+ } finally { sync.stop(); service.close(); }
53
+ });
54
+
55
+ it('does not reuse failed, aborted or differently authenticated batch pages', async () => {
56
+ const { real, other } = fixture();
57
+ let endpoint = 'http://localhost';
58
+ const fetchFn = vi.fn(async () => json([session('a', real), session('b', other)]));
59
+ const directories = createSessionDirectoryRuntime({ getRuntimeUrl: () => endpoint, fetchFn });
60
+ const read = directories.createFetchBatch();
61
+ const url = (directory) => `http://localhost/session?directory=${encodeURIComponent(directory)}`;
62
+ fetchFn.mockResolvedValueOnce(json({}, 503));
63
+ expect((await read(url(real))).status).toBe(503);
64
+ expect((await (await read(url(real))).json()).map((entry) => entry.id)).toEqual(['a']);
65
+ expect((await (await read(url(other))).json()).map((entry) => entry.id)).toEqual(['b']);
66
+ expect(fetchFn).toHaveBeenCalledTimes(2);
67
+ const controller = new AbortController(); controller.abort();
68
+ await expect(read(url(other), { signal: controller.signal })).rejects.toThrow();
69
+ await read(url(other), { headers: { Authorization: 'test-other-scope' } });
70
+ expect(fetchFn).toHaveBeenCalledTimes(3);
71
+ endpoint = 'http://127.0.0.1:9999';
72
+ await read(url(other));
73
+ expect(fetchFn).toHaveBeenCalledTimes(4);
74
+ });
75
+ it('shares global pages across 60 explicit directories only within one sync batch', async () => {
76
+ const { real } = fixture();
77
+ const paths = Array.from({ length: 60 }, (_, i) => path.join(real, `scope-${i}`));
78
+ for (const directory of paths) fs.mkdirSync(directory);
79
+ let rootReads = 0;
80
+ const directories = createSessionDirectoryRuntime({ fetchFn: async (input) => {
81
+ const url = new URL(input);
82
+ if (url.searchParams.has('parentID')) return json({ data: [], cursor: {} });
83
+ rootReads++;
84
+ expect(url.searchParams.has('directory')).toBe(false);
85
+ const page = Number(url.searchParams.get('cursor') ?? 0);
86
+ return json({ data: paths.slice(page * 20, (page + 1) * 20).map((directory, i) => session(`s-${page * 20 + i}`, directory)),
87
+ cursor: page < 2 ? { next: String(page + 1) } : {} });
88
+ } });
89
+ const service = createSessionIndexService({ dbPath: ':memory:' });
90
+ const sync = createSessionIndexSyncRuntime({ sessionIndexService: service,
91
+ buildOpenCodeUrl: (route) => `http://localhost/api${route}`, getOpenCodeAuthHeaders: () => ({}),
92
+ fetchFn: directories.fetchSessionList, createFetchBatch: directories.createFetchBatch,
93
+ });
94
+ try {
95
+ sync.enqueue(paths);
96
+ await vi.waitFor(() => expect(sync.snapshot().sync.active || sync.snapshot().sync.enriching).toBe(false));
97
+ expect(service.snapshot().directories).toHaveLength(60);
98
+ expect(service.snapshot().directories.every((entry) => entry.sessions.length === 1)).toBe(true);
99
+ expect(rootReads).toBe(3);
100
+ sync.enqueue(paths);
101
+ await vi.waitFor(() => expect(sync.snapshot().sync.active || sync.snapshot().sync.enriching).toBe(false));
102
+ expect(rootReads).toBe(6);
103
+ } finally { sync.stop(); service.close(); }
104
+ });
27
105
  it('backfills only 30 days once per runtime, resumes failed pages, and never boots locations', async () => {
28
106
  const { real } = fixture();
29
107
  const dbPath = path.join(real, 'index.sqlite');
@@ -10,6 +10,18 @@ Server-owned scheduled task runtime and routes for Yuri-only automation.
10
10
  - This module is Yuri feature logic; it is intentionally separate from OpenCode proxy/runtime internals.
11
11
  - Prompt and goal execution preserve hash-prefixed text literally; no snippet discovery or expansion occurs before dispatch.
12
12
 
13
+ ## Development isolation
14
+
15
+ `NODE_ENV=development` or `YURI_ELECTRON_DEV=1/true` disables the scheduler at
16
+ the owning runtime boundary. The Host does not open the task-run history store
17
+ in this mode. Startup, result/history recovery and upstream session events do
18
+ no work; no timers, worker sessions, task-state writes, result handoffs or
19
+ notifications are created. Manual runs return an explicit disabled failure,
20
+ and per-project synchronization rejects rather than claiming success.
21
+ Production execution and saved task configuration remain unchanged. This does
22
+ not change the independent Bot-channel development isolation or its opt-in test
23
+ configuration; production messages must not be admitted by a default dev Host.
24
+
13
25
  ## Assistant result handoff
14
26
 
15
27
  `setTaskResultHandler(handler)` installs the Host's assistant result consumer and
@@ -495,6 +495,9 @@ const parseSessionEventPhase = (event) => {
495
495
  return { phase: '', sessionID };
496
496
  };
497
497
 
498
+ export const isScheduledTasksRuntimeEnabled = (env = process.env) => env.NODE_ENV !== 'development'
499
+ && !['1', 'true'].includes(String(env.YURI_ELECTRON_DEV ?? '').trim().toLowerCase());
500
+
498
501
  export const createScheduledTasksRuntime = (deps) => {
499
502
  const {
500
503
  projectConfigRuntime,
@@ -505,6 +508,7 @@ export const createScheduledTasksRuntime = (deps) => {
505
508
  emitTaskRunEvent,
506
509
  notifyTaskRun,
507
510
  runHistoryStore = null,
511
+ env = process.env,
508
512
  logger = console,
509
513
  maxGlobalConcurrency = DEFAULT_GLOBAL_CONCURRENCY,
510
514
  maxProjectConcurrency = DEFAULT_PROJECT_CONCURRENCY,
@@ -521,6 +525,26 @@ export const createScheduledTasksRuntime = (deps) => {
521
525
  onSystemSessionPersisted = null,
522
526
  } = deps;
523
527
 
528
+ if (!isScheduledTasksRuntimeEnabled(env)) {
529
+ const disabled = () => { throw new Error('Scheduled tasks are disabled in development.'); };
530
+ return {
531
+ start: async () => {},
532
+ stop: () => {},
533
+ syncAllProjects: async () => {},
534
+ syncProject: async () => disabled(),
535
+ runNow: async () => ({ ok: false, disabled: true, error: 'Scheduled tasks are disabled in development.' }),
536
+ observeSessionEvent: async () => {},
537
+ setTaskResultHandler: () => () => {},
538
+ getStatus: () => ({
539
+ disabled: true,
540
+ hasEnabledScheduledTasks: false,
541
+ hasRunningScheduledTasks: false,
542
+ enabledScheduledTasksCount: 0,
543
+ runningScheduledTasksCount: 0,
544
+ }),
545
+ };
546
+ }
547
+
524
548
  let started = false;
525
549
  let historyRecoveryController = null;
526
550
  let historyRecoveryTimer = null;