@aiworker/web 1.22.2 → 1.23.1

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 (217) hide show
  1. package/bin/cli.js +7 -0
  2. package/dist/assets/{CodeMirrorCommentWidgets-CSICpWQD.js → CodeMirrorCommentWidgets-teB3HmBT.js} +1 -1
  3. package/dist/assets/DiffView-DC9RX3MF.js +4 -0
  4. package/dist/assets/{DirtyBranchSwitchDialog-C22HdWj4.js → DirtyBranchSwitchDialog-DwPkzXsS.js} +1 -1
  5. package/dist/assets/FilesView-BFZkuu4O.js +13 -0
  6. package/dist/assets/{GitView-VQQkYuUw.js → GitView-B_x52MHY.js} +4 -4
  7. package/dist/assets/{JsonTreeView-6lrhwD3q.js → JsonTreeView-cmAzUTiw.js} +1 -1
  8. package/dist/assets/{LinearIssuesView-Ba6Q9569.js → LinearIssuesView-Dehh5afm.js} +1 -1
  9. package/dist/assets/MarkdownImageGallery-DgNOqqhE.js +1 -0
  10. package/dist/assets/MarkdownRendererImpl-DusmMZ_p.js +12 -0
  11. package/dist/assets/OnboardingScreen-B8fm1H4m.js +1 -0
  12. package/dist/assets/{PatchDiff-BzcZPlOq.js → PatchDiff-BVr7gJU0.js} +1 -1
  13. package/dist/assets/PierreDiffViewer-DzLt-nel.js +161 -0
  14. package/dist/assets/PlanView-BmQUYT_z.js +5 -0
  15. package/dist/assets/SettingsView-ChWmAcZT.js +28 -0
  16. package/dist/assets/{SettingsWindow-DDQYaKWQ.js → SettingsWindow-Dy3M6ZB9.js} +1 -1
  17. package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
  18. package/dist/assets/{ToolOutputDialog-iYF8Y2bz.js → ToolOutputDialog-cTl_eLIH.js} +5 -5
  19. package/dist/assets/{ToolPartDiffPreview-CdjbOVMM.js → ToolPartDiffPreview-C_3iYNJQ.js} +1 -1
  20. package/dist/assets/{VirtualizedFileDiff-fFFm2QgH.js → VirtualizedFileDiff-CAWthkoy.js} +4 -4
  21. package/dist/assets/WalkthroughView-C7AHOpCA.js +4 -0
  22. package/dist/assets/{computeVirtualFileMetrics-CzgLum_K.js → computeVirtualFileMetrics-BkiDSlTW.js} +2 -2
  23. package/dist/assets/contextPanelEmbeddedChat-BdA6bdky.js +1 -0
  24. package/dist/assets/de-DJsQr-p7.js +10 -0
  25. package/dist/assets/es-BuYMlA9g.js +16 -0
  26. package/dist/assets/fr-ePDay33C.js +14 -0
  27. package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
  28. package/dist/assets/index-BD8ILbxF.js +40 -0
  29. package/dist/assets/{index-Bl3LSbjn.js → index-n6O3hklM.js} +1 -1
  30. package/dist/assets/index-zhgg-SDz.css +1 -0
  31. package/dist/assets/{isDiffPlainText-Dx-dB_8l.js → isDiffPlainText-GMdPz-71.js} +1 -1
  32. package/dist/assets/{isFilePlainText-CWFPwmnU.js → isFilePlainText-BVuH1zH9.js} +1 -1
  33. package/dist/assets/ja-BzR9xOY_.js +16 -0
  34. package/dist/assets/ko-BEjHAm14.js +16 -0
  35. package/dist/assets/main-BydQ1tr_.js +930 -0
  36. package/dist/assets/{main-DnBAoktx.js → main-D3ZDQglc.js} +2 -2
  37. package/dist/assets/markdownCore-Cb2MdZnV.js +5 -0
  38. package/dist/assets/{miniChat-BKyvLseN.js → miniChat-d01k801U.js} +2 -2
  39. package/dist/assets/{mobile-DKjeFgMN.js → mobile-D7VV-Ufz.js} +2 -2
  40. package/dist/assets/patchFileDiff-CdztVMz0.js +13 -0
  41. package/dist/assets/pl-rQmpxNIF.js +16 -0
  42. package/dist/assets/pt-BR-CorbsSW-.js +16 -0
  43. package/dist/assets/renderElectronMiniChatApp-BGG9UIlh.js +2 -0
  44. package/dist/assets/renderMobileApp-BRP3J1iv.js +25 -0
  45. package/dist/assets/runtimeEndpointReset-BhT_-c52.js +41 -0
  46. package/dist/assets/scheduledTasksApi-BEuUF_cj.js +1 -0
  47. package/dist/assets/{shikiHighlight-TEQCmzW8.js → shikiHighlight-BzXUjlby.js} +1 -1
  48. package/dist/assets/surface-COKb77Ua.js +1 -0
  49. package/dist/assets/tr-CoAMXPtI.js +7 -0
  50. package/dist/assets/uk-YlAX0rRU.js +16 -0
  51. package/dist/assets/{useAppFontEffects-D7sNpuL2.js → useAppFontEffects-Cwyhjfl5.js} +141 -140
  52. package/dist/assets/useGitComparison-BCZVefdE.js +1 -0
  53. package/dist/assets/useInlineCommentController-DDkpBEU8.js +2 -0
  54. package/dist/assets/useRootScrollLock-CwjoWuC4.js +1 -0
  55. package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-BY_5qla_.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-language-data-Dp3KMRQG.js → vendor-codemirror-language-data-Cb1YnICj.js} +2 -2
  57. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  58. package/dist/assets/vendor-zod-B6551dwG.js +39 -0
  59. package/dist/assets/{web-components-_mNEMjFY.js → web-components-LV3vjTxy.js} +1 -1
  60. package/dist/assets/zh-CN-DDYg0Jl7.js +16 -0
  61. package/dist/assets/zh-TW-CQKaCayr.js +16 -0
  62. package/dist/index.html +5 -43
  63. package/dist/mini-chat.html +4 -4
  64. package/dist/mobile.html +4 -4
  65. package/package.json +2 -3
  66. package/server/index.d.ts +15 -0
  67. package/server/index.js +48 -22
  68. package/server/lib/agent-memory/runtime.js +7 -2
  69. package/server/lib/agent-memory/runtime.test.js +22 -0
  70. package/server/lib/data-dir-migration.js +40 -0
  71. package/server/lib/data-dir-migration.test.js +59 -0
  72. package/server/lib/event-stream/DOCUMENTATION.md +3 -0
  73. package/server/lib/event-stream/global-hub.js +29 -4
  74. package/server/lib/event-stream/global-hub.test.js +22 -0
  75. package/server/lib/event-stream/global-ws-bridge.js +15 -18
  76. package/server/lib/event-stream/protocol.js +21 -7
  77. package/server/lib/event-stream/runtime.js +9 -6
  78. package/server/lib/event-stream/runtime.test.js +72 -12
  79. package/server/lib/fs/DOCUMENTATION.md +3 -0
  80. package/server/lib/fs/routes.js +31 -0
  81. package/server/lib/fs/routes.test.js +110 -1
  82. package/server/lib/git/DOCUMENTATION.md +39 -6
  83. package/server/lib/git/routes.js +45 -12
  84. package/server/lib/git/routes.test.js +78 -0
  85. package/server/lib/git/service.js +343 -202
  86. package/server/lib/git/service.test.js +496 -25
  87. package/server/lib/github/DOCUMENTATION.md +5 -0
  88. package/server/lib/github/routes.js +2 -2
  89. package/server/lib/inherited-env.js +16 -9
  90. package/server/lib/inherited-env.test.js +8 -9
  91. package/server/lib/message-queue/DOCUMENTATION.md +11 -1
  92. package/server/lib/message-queue/runtime.js +13 -0
  93. package/server/lib/message-queue/runtime.test.js +31 -1
  94. package/server/lib/network-defaults.js +23 -0
  95. package/server/lib/network-defaults.test.js +52 -0
  96. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  97. package/server/lib/notifications/emitter-runtime.js +4 -3
  98. package/server/lib/opencode/DOCUMENTATION.md +35 -5
  99. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  100. package/server/lib/opencode/env-runtime.js +5 -1
  101. package/server/lib/opencode/env-runtime.test.js +72 -0
  102. package/server/lib/opencode/feature-routes-runtime.js +17 -1
  103. package/server/lib/opencode/lifecycle.js +4 -3
  104. package/server/lib/opencode/lifecycle.test.js +29 -0
  105. package/server/lib/opencode/managed-plugin-config.js +1 -1
  106. package/server/lib/opencode/openchamber-routes.js +64 -4
  107. package/server/lib/opencode/openchamber-routes.test.js +128 -1
  108. package/server/lib/opencode/proxy.js +33 -0
  109. package/server/lib/opencode/routes.js +5 -3
  110. package/server/lib/opencode/settings-files.js +214 -0
  111. package/server/lib/opencode/settings-helpers.js +88 -41
  112. package/server/lib/opencode/settings-helpers.test.js +176 -1
  113. package/server/lib/opencode/settings-registry.json +750 -0
  114. package/server/lib/opencode/settings-runtime.js +175 -27
  115. package/server/lib/opencode/settings-runtime.test.js +321 -7
  116. package/server/lib/project-context/DOCUMENTATION.md +38 -4
  117. package/server/lib/project-context/routes.http.test.js +18 -0
  118. package/server/lib/project-context/routes.js +15 -0
  119. package/server/lib/project-context/runtime.js +256 -25
  120. package/server/lib/project-context/runtime.test.js +160 -3
  121. package/server/lib/projects/DOCUMENTATION.md +77 -0
  122. package/server/lib/projects/project-config.js +179 -17
  123. package/server/lib/projects/project-config.test.js +97 -0
  124. package/server/lib/projects/project-id.js +43 -0
  125. package/server/lib/projects/project-setup.js +409 -0
  126. package/server/lib/projects/project-setup.test.js +557 -0
  127. package/server/lib/projects/routes.js +59 -0
  128. package/server/lib/quota/DOCUMENTATION.md +31 -1
  129. package/server/lib/quota/providers/cline-pass.js +125 -0
  130. package/server/lib/quota/providers/cline-pass.test.js +103 -0
  131. package/server/lib/quota/providers/index.js +7 -0
  132. package/server/lib/quota/providers/neuralwatt.js +3 -6
  133. package/server/lib/quota/providers/neuralwatt.test.js +7 -7
  134. package/server/lib/quota/providers/ollama-cloud.js +31 -0
  135. package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
  136. package/server/lib/quota/providers/opencode-go.js +1 -1
  137. package/server/lib/quota/providers/opencode-go.test.js +26 -1
  138. package/server/lib/quota/providers/openrouter.js +119 -24
  139. package/server/lib/quota/providers/openrouter.test.js +330 -0
  140. package/server/lib/relay/DOCUMENTATION.md +75 -0
  141. package/server/lib/relay/cross-compat.test.js +26 -0
  142. package/server/lib/relay/downstream-scheduler.js +154 -0
  143. package/server/lib/relay/downstream-scheduler.test.js +162 -0
  144. package/server/lib/relay/e2ee.js +10 -8
  145. package/server/lib/relay/flow-control.test.js +177 -0
  146. package/server/lib/relay/host-client.js +44 -8
  147. package/server/lib/relay/host-client.test.js +14 -0
  148. package/server/lib/relay/tunnel-codec.js +9 -0
  149. package/server/lib/relay/tunnel-host.js +66 -17
  150. package/server/lib/scheduled-tasks/DOCUMENTATION.md +9 -1
  151. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +28 -0
  152. package/server/lib/scheduled-tasks/runtime.js +12 -2
  153. package/server/lib/scheduled-tasks/runtime.test.js +53 -0
  154. package/server/lib/session-assist/DOCUMENTATION.md +131 -66
  155. package/server/lib/session-assist/context.js +127 -0
  156. package/server/lib/session-assist/context.test.js +132 -0
  157. package/server/lib/session-assist/prompt.js +54 -0
  158. package/server/lib/session-assist/runtime.js +117 -267
  159. package/server/lib/session-assist/runtime.test.js +203 -0
  160. package/server/lib/session-goal/runtime.js +4 -9
  161. package/server/lib/small-model/DOCUMENTATION.md +3 -2
  162. package/server/lib/small-model/call.js +9 -4
  163. package/server/lib/small-model/call.test.js +29 -0
  164. package/server/lib/small-model/index.js +5 -10
  165. package/server/lib/small-model/runtime-providers.js +15 -7
  166. package/server/lib/small-model/runtime-providers.test.js +7 -1
  167. package/server/lib/terminal/DOCUMENTATION.md +4 -4
  168. package/server/lib/terminal/runtime.js +11 -6
  169. package/server/lib/terminal/runtime.test.js +20 -13
  170. package/server/lib/walkthrough/DOCUMENTATION.md +49 -20
  171. package/server/lib/walkthrough/model-settings.js +8 -12
  172. package/server/lib/walkthrough/pr-source.test.js +21 -0
  173. package/server/lib/walkthrough/prompt.js +3 -1
  174. package/server/lib/walkthrough/pull-request.js +7 -4
  175. package/server/lib/walkthrough/pull-request.test.js +16 -0
  176. package/server/lib/walkthrough/routes.js +19 -0
  177. package/server/lib/walkthrough/routes.test.js +26 -0
  178. package/server/lib/walkthrough/sources.js +36 -4
  179. package/server/opencode-worktree-readiness.test.js +130 -0
  180. package/dist/assets/DiffView-hDBKesA_.js +0 -4
  181. package/dist/assets/FilesView-CdWzeOp9.js +0 -17
  182. package/dist/assets/MarkdownImageGallery-Czv_mhvS.js +0 -1
  183. package/dist/assets/MarkdownRendererImpl-BrMcswiy.js +0 -12
  184. package/dist/assets/OnboardingScreen-ChxQoAkx.js +0 -1
  185. package/dist/assets/PierreDiffViewer-BchBtZlp.js +0 -157
  186. package/dist/assets/PlanView-DyDt_nZ_.js +0 -5
  187. package/dist/assets/SettingsView-BKf5xBsP.js +0 -28
  188. package/dist/assets/WalkthroughView-DOeCsMju.js +0 -4
  189. package/dist/assets/contextPanelEmbeddedChat-C0ZLAepL.js +0 -1
  190. package/dist/assets/de-B5JaA3SA.js +0 -10
  191. package/dist/assets/es-EPIH88ii.js +0 -16
  192. package/dist/assets/fr-CAMfxUdZ.js +0 -14
  193. package/dist/assets/index-DF5kMP-i.js +0 -39
  194. package/dist/assets/index-Dl3xbAB_.css +0 -1
  195. package/dist/assets/ja-CifOE1VN.js +0 -16
  196. package/dist/assets/ko-BBDyAyYQ.js +0 -16
  197. package/dist/assets/main-MhSaOZoB.js +0 -930
  198. package/dist/assets/markdownCore-BrBwOOMn.js +0 -3
  199. package/dist/assets/patchFileDiff-o8ms1me8.js +0 -10
  200. package/dist/assets/pl-DgEHYfFM.js +0 -16
  201. package/dist/assets/pt-BR-DuWHojUw.js +0 -16
  202. package/dist/assets/renderElectronMiniChatApp-CDgBwwCS.js +0 -2
  203. package/dist/assets/renderMobileApp-DJIKIK1r.js +0 -25
  204. package/dist/assets/runtimeEndpointReset-CYJ9O_xX.js +0 -17
  205. package/dist/assets/scheduledTasksApi-D8yamh1b.js +0 -1
  206. package/dist/assets/tr-D5m2yIWL.js +0 -7
  207. package/dist/assets/uk-D_q60oog.js +0 -16
  208. package/dist/assets/useInlineCommentController-Brz_cLcQ.js +0 -2
  209. package/dist/assets/useRootScrollLock-lXEnWlaU.js +0 -1
  210. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
  211. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  212. package/dist/assets/vendor-zod-CK21ihK-.js +0 -39
  213. package/dist/assets/zh-CN-D8QvsVeg.js +0 -16
  214. package/dist/assets/zh-TW-B9t7rQQO.js +0 -16
  215. package/server/lib/mcp-reconnect/DOCUMENTATION.md +0 -55
  216. package/server/lib/mcp-reconnect/runtime.js +0 -122
  217. package/server/lib/mcp-reconnect/runtime.test.js +0 -140
@@ -39,11 +39,17 @@ const startFakeRelay = () => {
39
39
  clients: new Map(), // connectionId -> ws
40
40
  buffered: new Map(), // connectionId -> [[data, isBinary]] awaiting host-data
41
41
  relayFrames: [], // observed forwarded frames (for plaintext assertions)
42
+ apps: new Map(),
42
43
  };
43
44
 
44
45
  wss.on('connection', (ws, req) => {
45
46
  const url = new URL(req.url, 'http://localhost');
46
47
  const role = url.searchParams.get('role');
48
+ state.apps.set(role, {
49
+ appId: url.searchParams.get('appId'),
50
+ appVersion: url.searchParams.get('appVersion'),
51
+ platform: url.searchParams.get('platform'),
52
+ });
47
53
  const connectionId = url.searchParams.get('connectionId');
48
54
 
49
55
  if (role === 'host-control') {
@@ -101,6 +107,7 @@ const startFakeRelay = () => {
101
107
  // A socket a failed test left open would hold server.close() until
102
108
  // the hook timeout; drop them so a failure is reported once.
103
109
  for (const client of wss.clients) client.terminate();
110
+ server.closeAllConnections();
104
111
  wss.close();
105
112
  server.close(() => r());
106
113
  }),
@@ -286,6 +293,13 @@ describe('relay host-client integration', () => {
286
293
  });
287
294
 
288
295
  expect(result.status).toBe(200);
296
+ for (const role of ['host-control', 'host-data']) {
297
+ expect(relay.state.apps.get(role)).toEqual({
298
+ appId: 'aiworker',
299
+ appVersion: expect.stringMatching(/^\d+\.\d+\.\d+/),
300
+ platform: process.env.AIWORKER_RUNTIME || 'web',
301
+ });
302
+ }
289
303
  expect(result.body.ok).toBe(true);
290
304
  expect(result.body.relayConn).toBe('conn-test-1');
291
305
  expect(result.body.origin).toBe(`http://127.0.0.1:${origin.port}`);
@@ -34,6 +34,7 @@ export const TunnelFrameType = {
34
34
  WsClose: 10,
35
35
  Ping: 11,
36
36
  Pong: 12,
37
+ DeliveryAck: 13,
37
38
  };
38
39
 
39
40
  const TUNNEL_FRAME_TYPE_VALUES = new Set(Object.values(TunnelFrameType));
@@ -43,6 +44,14 @@ export const isTunnelFrameType = (value) => TUNNEL_FRAME_TYPE_VALUES.has(value);
43
44
 
44
45
  const MAX_STREAM_ID = 0xffffffff;
45
46
 
47
+ /** Decode the client's cumulative raw tunnel-frame byte count. */
48
+ export const decodeDeliveryAck = (payload) => {
49
+ if (payload.length !== 8) throw new Error('invalid delivery acknowledgement');
50
+ const bytes = Number(new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getBigUint64(0));
51
+ if (!Number.isSafeInteger(bytes)) throw new Error('invalid delivery acknowledgement');
52
+ return bytes;
53
+ };
54
+
46
55
  export class TunnelCodecError extends Error {
47
56
  constructor(message) {
48
57
  super(message);
@@ -15,7 +15,6 @@ import {
15
15
  createFragmentAssembler,
16
16
  decodeJsonPayload,
17
17
  decodeTunnelFrame,
18
- encodeFragmentedMessage,
19
18
  encodeJsonPayload,
20
19
  encodeTunnelFrame,
21
20
  } from './tunnel-codec.js';
@@ -74,6 +73,11 @@ const BODY_BUFFER_MAX_BYTES = 512 * 1024;
74
73
  // completes, so a stalled tunnel converts into an ambiguous transport failure
75
74
  // (which the client already retries) instead of a hung loopback request.
76
75
  const BODY_DELIVERY_TIMEOUT_MS = 15_000;
76
+ const MAX_PENDING_WS_BYTES = 16 * 1024 * 1024;
77
+ const MAX_PENDING_WS_MESSAGES = 1024;
78
+ // Node ws supports read backpressure. Bun's ws shim does not implement pause;
79
+ // there the bounded queue fails the affected substream explicitly on overflow.
80
+ const CAN_PAUSE_WS_READS = !process.versions.bun;
77
81
 
78
82
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
79
83
 
@@ -99,13 +103,17 @@ const isWsClosePayload = (parsed) => Boolean(parsed && typeof parsed === 'object
99
103
  * sendFrame: (plaintextFrame: Uint8Array) => void | Promise<void>,
100
104
  * getBufferedAmount: () => number,
101
105
  * bodyDeliveryTimeoutMs?: number,
106
+ * responseChunkBytes?: number,
107
+ * cancelPendingFrames?: (streamId: number) => void,
102
108
  * }} deps
103
109
  */
104
- export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBufferedAmount, bodyDeliveryTimeoutMs = BODY_DELIVERY_TIMEOUT_MS }) => {
110
+ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBufferedAmount, bodyDeliveryTimeoutMs = BODY_DELIVERY_TIMEOUT_MS, responseChunkBytes = MAX_TUNNEL_PAYLOAD_BYTES, cancelPendingFrames = () => {} }) => {
105
111
  /** @type {Map<number, { kind: 'http', abort: AbortController, body: { enqueue(payload: Uint8Array): void, close(): void, error(error: Error): void } | null, noBody: boolean } | { kind: 'ws', socket: WebSocket, opened: boolean }>} */
106
112
  const streams = new Map();
107
113
  const assembler = createFragmentAssembler();
108
114
  let closed = false;
115
+ let pendingWsBytes = 0;
116
+ let pendingWsMessages = 0;
109
117
 
110
118
  const send = async (frame) => {
111
119
  if (closed) return;
@@ -128,6 +136,7 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
128
136
  const stream = streams.get(streamId);
129
137
  if (!stream) return;
130
138
  dropStream(streamId);
139
+ cancelPendingFrames(streamId);
131
140
  if (stream.kind === 'http') {
132
141
  try {
133
142
  stream.body?.error(new Error(String(reason ?? 'aborted')));
@@ -205,17 +214,27 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
205
214
  if (STRIPPED_RESPONSE_HEADERS.has(name)) continue;
206
215
  responseHeaders[name] = value;
207
216
  }
208
- await sendJson(TunnelFrameType.HttpResponse, streamId, { status: response.status, headers: responseHeaders });
217
+ if (closed || stream.abort.signal.aborted) {
218
+ await response.body?.cancel();
219
+ return;
220
+ }
209
221
 
210
222
  try {
223
+ await sendJson(TunnelFrameType.HttpResponse, streamId, { status: response.status, headers: responseHeaders });
211
224
  if (response.body) {
212
225
  for await (const chunk of response.body) {
213
226
  if (closed || stream.abort.signal.aborted) return;
214
227
  const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
215
- for (const piece of chunkPayload(bytes, MAX_TUNNEL_PAYLOAD_BYTES)) {
228
+ const pieces = chunkPayload(bytes, responseChunkBytes);
229
+ // Offer at most one plaintext-frame budget at a time. The scheduler
230
+ // can batch small slices and interleave streams without buffering the
231
+ // entire source or encrypting hundreds of tiny messages separately.
232
+ const groupSize = Math.max(1, Math.floor(MAX_TUNNEL_PAYLOAD_BYTES / responseChunkBytes));
233
+ for (let offset = 0; offset < pieces.length; offset += groupSize) {
216
234
  await waitForBackpressure(stream.abort.signal);
217
235
  if (closed || stream.abort.signal.aborted) return;
218
- await send(encodeTunnelFrame(TunnelFrameType.HttpBody, streamId, piece));
236
+ await Promise.all(pieces.slice(offset, offset + groupSize).map(piece =>
237
+ send(encodeTunnelFrame(TunnelFrameType.HttpBody, streamId, piece))));
219
238
  }
220
239
  }
221
240
  }
@@ -448,6 +467,7 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
448
467
  try {
449
468
  socket = new WebSocket(url, open.protocols, {
450
469
  headers: dialHeaders,
470
+ maxPayload: MAX_PENDING_WS_BYTES,
451
471
  });
452
472
  } catch (error) {
453
473
  void sendAbort(streamId, error?.message ?? 'ws dial failed');
@@ -455,6 +475,8 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
455
475
  }
456
476
  const stream = { kind: 'ws', socket, opened: false };
457
477
  streams.set(streamId, stream);
478
+ let outputChain = Promise.resolve();
479
+ let socketPendingMessages = 0;
458
480
 
459
481
  socket.on('open', () => {
460
482
  if (streams.get(streamId) !== stream) return;
@@ -465,23 +487,47 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
465
487
  if (streams.get(streamId) !== stream || closed) return;
466
488
  const bytes = Buffer.isBuffer(data) ? new Uint8Array(data) : new Uint8Array(Buffer.concat(data));
467
489
  const frameType = isBinary ? TunnelFrameType.WsBinary : TunnelFrameType.WsText;
468
- void (async () => {
469
- for (const frame of encodeFragmentedMessage(frameType, streamId, bytes)) {
490
+ if (pendingWsBytes + bytes.length > MAX_PENDING_WS_BYTES || pendingWsMessages >= MAX_PENDING_WS_MESSAGES) {
491
+ abortLocalStream(streamId, 'upstream WebSocket exceeded downstream queue limit');
492
+ void sendAbort(streamId, 'upstream WebSocket exceeded downstream queue limit');
493
+ return;
494
+ }
495
+ pendingWsBytes += bytes.length;
496
+ pendingWsMessages += 1;
497
+ socketPendingMessages += 1;
498
+ if (CAN_PAUSE_WS_READS) socket.pause();
499
+ outputChain = outputChain.then(async () => {
500
+ // Serialize entire messages, including their fragments. A later close
501
+ // must also wait here or it can overtake the final output.
502
+ const chunks = chunkPayload(bytes, responseChunkBytes);
503
+ const groupSize = Math.max(1, Math.floor(MAX_TUNNEL_PAYLOAD_BYTES / responseChunkBytes));
504
+ for (let offset = 0; offset < chunks.length; offset += groupSize) {
470
505
  await waitForBackpressure(null);
471
506
  if (streams.get(streamId) !== stream || closed) return;
472
- await send(frame);
507
+ await Promise.all(chunks.slice(offset, offset + groupSize).map((chunk, index) =>
508
+ send(encodeTunnelFrame(frameType, streamId, chunk, offset + index < chunks.length - 1))));
473
509
  }
474
- })();
510
+ }).catch(() => {
511
+ abortLocalStream(streamId, 'upstream WebSocket forwarding failed');
512
+ void sendAbort(streamId, 'upstream WebSocket forwarding failed');
513
+ }).finally(() => {
514
+ pendingWsBytes -= bytes.length;
515
+ pendingWsMessages -= 1;
516
+ socketPendingMessages -= 1;
517
+ if (CAN_PAUSE_WS_READS && socketPendingMessages === 0 && streams.get(streamId) === stream && socket.readyState === WebSocket.OPEN) socket.resume();
518
+ });
475
519
  });
476
520
  socket.on('close', (code, reasonBuffer) => {
477
- if (streams.get(streamId) !== stream) return;
478
- dropStream(streamId);
479
- const reason = reasonBuffer ? reasonBuffer.toString('utf8') : '';
480
- if (stream.opened) {
481
- void sendJson(TunnelFrameType.WsClose, streamId, { code: code || 1000, reason });
482
- } else {
483
- void sendAbort(streamId, reason || `upstream ws closed (${code || 'no code'})`);
484
- }
521
+ void outputChain.then(async () => {
522
+ if (streams.get(streamId) !== stream) return;
523
+ dropStream(streamId);
524
+ const reason = reasonBuffer ? reasonBuffer.toString('utf8') : '';
525
+ if (stream.opened) {
526
+ await sendJson(TunnelFrameType.WsClose, streamId, { code: code || 1000, reason });
527
+ } else {
528
+ await sendAbort(streamId, reason || `upstream ws closed (${code || 'no code'})`);
529
+ }
530
+ });
485
531
  });
486
532
  socket.on('error', (error) => {
487
533
  if (streams.get(streamId) !== stream) return;
@@ -512,6 +558,7 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
512
558
  const stream = streams.get(streamId);
513
559
  if (!stream || stream.kind !== 'ws') return;
514
560
  dropStream(streamId);
561
+ cancelPendingFrames(streamId);
515
562
  let close = { code: 1000, reason: '' };
516
563
  try {
517
564
  close = decodeJsonPayload(payload, isWsClosePayload);
@@ -520,6 +567,8 @@ export const createTunnelHost = ({ connectionId, getLocalPort, sendFrame, getBuf
520
567
  }
521
568
  const code = Number.isInteger(close.code) && close.code >= 1000 && close.code <= 4999 ? close.code : 1000;
522
569
  try {
570
+ // A paused receiver still needs to read the peer's close handshake.
571
+ if (CAN_PAUSE_WS_READS) stream.socket.resume();
523
572
  stream.socket.close(code, typeof close.reason === 'string' ? close.reason : '');
524
573
  } catch {
525
574
  stream.socket.terminate();
@@ -25,6 +25,12 @@ in shared project config under the project write lock:
25
25
  from the winner's persisted `nextRunAt`.
26
26
  - Project config writes also take a cross-process `.json.lock` file so the
27
27
  read-modify-write is serialized across processes, not only within one process.
28
+ - `syncAllProjects` (startup and every full resync) syncs each registered
29
+ project on its own: a project whose config cannot be read or written (a
30
+ broken file, a lock timeout) is logged with its id and skipped, and every
31
+ other project's tasks are still scheduled. Only `listProjects` failing
32
+ aborts the sync as a whole. `syncProject` for one project still throws, so
33
+ a route for that project reports the failure.
28
34
  - The sharing processes may run different AiWorker versions. Normalization
29
35
  keeps only the fields a build knows, so every writer persists tasks it did
30
36
  not change verbatim from disk and swaps only `state` onto a task whose state
@@ -63,7 +69,9 @@ in shared project config under the project write lock:
63
69
  - Claiming always writes `nextRunAt` (including `undefined`) so a past once-slot
64
70
  is cleared when there is no following occurrence.
65
71
 
66
- Manual `runNow` does not claim a schedule occurrence.
72
+ Manual `runNow` does not claim a schedule occurrence. It also runs paused
73
+ (`enabled: false`) tasks — that is the point of the button — while scheduled
74
+ dispatches still skip disabled tasks, and completion never re-arms a paused task.
67
75
 
68
76
  ## Files
69
77
 
@@ -485,4 +485,32 @@ describe('issue 2710: daily scheduled task double execution at the configured ti
485
485
 
486
486
  runtime.stop();
487
487
  });
488
+
489
+ it('manual runNow runs a paused task but does not schedule future runs', async () => {
490
+ vi.setSystemTime(UTC(2026, 0, 1, 14, 0, 0));
491
+ const task = { ...makeTask({ kind: 'daily', times: ['15:00'] }), enabled: false };
492
+ const projectConfigRuntime = createSharedProjectConfigRuntime(task);
493
+
494
+ const runtime = createScheduledTasksRuntime(createRuntimeDeps(projectConfigRuntime));
495
+ await runtime.start();
496
+
497
+ // The scheduler must not fire a disabled task on its own.
498
+ await vi.advanceTimersByTimeAsync(HOUR + 3_000);
499
+ expect(sdk.sessionCreates.length).toBe(0);
500
+
501
+ const manual = await runtime.runNow('p1', 'task-1');
502
+ expect(manual.ok).toBe(true);
503
+ expect(manual.sessionID).toBeTruthy();
504
+ expect(sdk.sessionCreates.length).toBe(1);
505
+ expect(runtime.getStatus().runningScheduledTasksCount).toBe(0);
506
+
507
+ // Completion records state but leaves the task paused with no next run.
508
+ const tasks = await projectConfigRuntime.listScheduledTasks('p1');
509
+ expect(tasks[0].enabled).toBe(false);
510
+ expect(tasks[0].state.lastStatus).toBe('success');
511
+ expect(tasks[0].state.lastSessionId).toBe('sess-1');
512
+ expect(tasks[0].state.nextRunAt).toBeUndefined();
513
+
514
+ runtime.stop();
515
+ });
488
516
  });
@@ -426,7 +426,16 @@ export const createScheduledTasksRuntime = (deps) => {
426
426
  }
427
427
 
428
428
  for (const projectID of activeProjectIDs) {
429
- await syncProject(projectID);
429
+ try {
430
+ await syncProject(projectID);
431
+ } catch (error) {
432
+ // One project's config being unusable (a broken file, a lock timeout)
433
+ // must not keep every other project's tasks from being scheduled.
434
+ logger.warn?.('[ScheduledTasks] failed to sync project', {
435
+ projectID,
436
+ error: error?.message ?? String(error),
437
+ });
438
+ }
430
439
  }
431
440
  };
432
441
 
@@ -676,7 +685,8 @@ export const createScheduledTasksRuntime = (deps) => {
676
685
  const runTask = async (projectID, taskID, reason, scheduledFor) => {
677
686
  const taskMap = tasksByProject.get(projectID);
678
687
  const task = taskMap?.get(taskID);
679
- if (!task || !task.enabled) {
688
+ // Manual runNow runs paused tasks too; only scheduled dispatches skip them.
689
+ if (!task || (reason !== 'manual' && !task.enabled)) {
680
690
  return { ok: false, skipped: true };
681
691
  }
682
692
 
@@ -206,3 +206,56 @@ Run daily.
206
206
  }
207
207
  });
208
208
  });
209
+
210
+ describe('scheduled-tasks runtime syncAllProjects', () => {
211
+ it('keeps scheduling the other projects when one project cannot be synced', async () => {
212
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'oc-runtime-sync-all-'));
213
+ try {
214
+ const brokenPath = path.join(tempRoot, 'broken');
215
+ const healthyPath = path.join(tempRoot, 'healthy');
216
+ await mkdir(path.join(healthyPath, '.agents', 'loops'), { recursive: true });
217
+ await mkdir(brokenPath, { recursive: true });
218
+ await writeFile(path.join(healthyPath, '.agents', 'loops', 'daily.md'), `---
219
+ name: daily
220
+ schedule: "0 9 * * *"
221
+ enabled: true
222
+ model: openai/gpt-5
223
+ ---
224
+ Run daily.
225
+ `, 'utf8');
226
+
227
+ const projectConfigRuntime = createProjectConfigRuntime({
228
+ fsPromises: await import('fs/promises'),
229
+ path,
230
+ projectsDirPath: path.join(tempRoot, 'config'),
231
+ createTaskID: () => 'task-fixed-id',
232
+ });
233
+ await mkdir(path.join(tempRoot, 'config'), { recursive: true });
234
+ await writeFile(projectConfigRuntime.resolveProjectConfigPath('broken'), '{ not json', 'utf8');
235
+
236
+ const warnings = [];
237
+ const runtime = createScheduledTasksRuntime({
238
+ buildOpenCodeUrl: () => 'http://localhost',
239
+ getOpenCodeAuthHeaders: () => ({}),
240
+ waitForOpenCodeReady: async () => {},
241
+ projectConfigRuntime,
242
+ listProjects: async () => [
243
+ { id: 'broken', path: brokenPath },
244
+ { id: 'healthy', path: healthyPath },
245
+ ],
246
+ logger: { warn: (...args) => warnings.push(args) },
247
+ });
248
+
249
+ await expect(runtime.start()).resolves.toBeUndefined();
250
+
251
+ expect(runtime.getStatus().enabledScheduledTasksCount).toBe(1);
252
+ const healthyTasks = await projectConfigRuntime.listScheduledTasks('healthy');
253
+ expect(healthyTasks.map((task) => task.id)).toEqual(['loop:project:daily']);
254
+ expect(warnings).toHaveLength(1);
255
+ expect(warnings[0][1]).toMatchObject({ projectID: 'broken' });
256
+ runtime.stop();
257
+ } finally {
258
+ await rm(tempRoot, { recursive: true, force: true });
259
+ }
260
+ });
261
+ });
@@ -1,66 +1,131 @@
1
- # Session Assist
2
-
3
- Server-side watcher that generates a short recap of the agent's last reply
4
- and one suggested user follow-up with the small model
5
- (`lib/small-model`), storing both on the session's metadata under
6
- `metadata.aiworker.assist`.
7
-
8
- ## Flow
9
-
10
- 1. `createSessionAssistRuntime` is a consumer of the server's global SSE
11
- fan-out (`index.js` `onPayload`), riding the same upstream connection as
12
- notifications. Purely event-driven dormant sessions never generate
13
- anything, there is no backfill and no session scanning.
14
- 2. `session.status: idle` arms a 60-second per-session timer; any `busy`/
15
- `retry` status or a user `message.updated` clears it (the "1 minute of
16
- quiet" rule).
17
- 3. On fire: fetch the session (skip sub-agent sessions with `parentID`),
18
- take the LAST exchange only — the final assistant reply plus the user
19
- message it answered (assistant `parentID` → user id) — and call
20
- `generateSmallModelText` with the
21
- session's own provider/model taken from the last assistant message so
22
- the utility call spends the same subscription as the conversation.
23
- `restrictToPreferredProvider` forbids the resolver's global fallback:
24
- conversation content never goes to a provider the user didn't pick for
25
- the session, unless the small model was chosen explicitly (settings
26
- override or opencode config). A resolver 404 is silently skipped.
27
- 4. The requested JSON fields (`recap`, `suggestion`, or both) are clamped and
28
- PATCHed onto the session metadata together with `forMessageID` (the last
29
- assistant message id) and `generatedAt`. Before writing, the session tail is
30
- re-checked (a stale result is dropped) and the metadata is merged from a
31
- fresh session read so concurrent metadata writes made during generation are
32
- preserved.
33
-
34
- ## Settings gate
35
-
36
- `sessionRecapEnabled` and `sessionSuggestionEnabled` in AiWorker settings
37
- (Settings Chat, default on) are hard generation switches checked at fire
38
- time. When both are off, no small-model calls run and nothing is written. When
39
- one is on, the runtime still makes at most one small-model call and asks only
40
- for that field. The UI also hides disabled payload types immediately.
41
-
42
- ## Freshness contract (no clearing writes)
43
-
44
- Clients do not need the payload to be deleted: they render it only while
45
- `assist.forMessageID` still equals the session's last assistant message id
46
- (and the session is idle). Any new message invalidates the payload
47
- everywhere instantly and offline; the next idle cycle overwrites it.
48
-
49
- ## UI consumers (packages/ui)
50
-
51
- - `lib/sessionAssistMetadata.ts` payload parsing.
52
- - `hooks/useSessionAssist.ts` freshness gating + the 1-minute quiet window
53
- for the recap (single timeout to the boundary, no polling).
54
- - `components/chat/SessionRecapSpacer.tsx` renders the recap inside the
55
- fixed-height reserved gap under the last message (height never changes).
56
- - `components/chat/SessionSuggestionChip.tsx` — one tappable suggestion chip
57
- near the composer (desktop chips row + above the mobile pill); hidden as
58
- soon as the composer has any content. Tap fills the input, never sends.
59
-
60
- ## Limitations
61
-
62
- - The watcher lives in the web server, so VS Code (extension-only, no web
63
- server) does not generate assists; it still renders payloads produced by a
64
- web/desktop instance of the same OpenCode server via `session.updated`.
65
- - Metadata payloads ride every `session.updated` event — keep the clamps
66
- (`RECAP_CHAR_LIMIT`, `SUGGESTION_CHAR_LIMIT`) small.
1
+ # Session assist
2
+
3
+ The server generates a short reminder of recent work and an optional next user
4
+ message with Small Model. Results live in `metadata.aiworker.assist` with
5
+ `recap`, `suggestion`, `forMessageID`, and `generatedAt`. The payload shape is
6
+ unchanged; an empty suggestion is a successful outcome.
7
+
8
+ ## Ownership
9
+
10
+ - `runtime.js` owns idle timers, cancellation, provider selection, SDK reads,
11
+ freshness checks, settings gates, and metadata writes.
12
+ - `context.js` reads bounded history and constructs human turns. It removes
13
+ tool payloads and injected prompts before retaining message text.
14
+ - `prompt.js` owns the generation instructions and total input budget.
15
+ - `../small-model/DOCUMENTATION.md` owns provider/auth resolution, generation,
16
+ output limits, and overflow behavior.
17
+
18
+ ## What the model receives
19
+
20
+ Read backward through the official SDK in pages of 50 messages until three
21
+ human turns are covered, history ends, or eight pages have been read. A failed
22
+ page or repeated cursor aborts generation; it is not treated as complete history.
23
+ At the page limit, use fewer available human turns. If the latest answer's human
24
+ request has not been found, skip generation rather than invent its context.
25
+
26
+ Three turns retain the substance behind short commit confirmations without
27
+ bringing an entire old task back into the prompt. This was compared against
28
+ one, five, ten, and full-history contexts on long maintainer sessions. There
29
+ is no full-history cache and no assumed provider prefix-cache behavior.
30
+
31
+ The latest record must be a completed, successful, non-summary assistant answer
32
+ with visible text. Child, archived, and reverted sessions are skipped. A new
33
+ prompt clears the revert boundary before its next idle event.
34
+
35
+ Human turns follow chronological message intervals. OpenCode can insert
36
+ synthetic continuation users during compaction, so a final answer's `parentID`
37
+ need not point directly at the original human request. These continuations stay
38
+ within their human turn; compaction summaries are excluded. An interrupted
39
+ request remains context with its last visible progress explicitly labeled as
40
+ unfinished, rather than being dropped or called a final answer.
41
+ An answer must still reference that human user or one of its continuation
42
+ users; a late answer for an older request cannot be assigned to a newer request.
43
+
44
+ ### Attached context and language
45
+
46
+ The persisted attachment contract is owned by
47
+ `packages/ui/src/lib/messages/contextParts.ts`. Its user-facing Markdown
48
+ formatter is `packages/ui/src/lib/messages/messageMarkdown.ts`.
49
+
50
+ The server projects those persisted parts into model context without importing
51
+ the UI runtime: code comments, file/chat quotes, browser annotations, PR comments,
52
+ checks, terminal selections, and linked GitHub/Linear items remain attached to
53
+ the user turn even when their transport part is synthetic. The OpenCode
54
+ `opencodeComment` mirror is also accepted. Unrecognized synthetic prompts and
55
+ ignored parts are excluded. Malformed attached text fails the generation.
56
+
57
+ Quoted material and the user's own comment are separate blocks. The user's
58
+ authored text is also supplied separately for language selection. Quoted source,
59
+ logs, assistant replies, and injected memory instructions do not choose the
60
+ language. A language-neutral final acknowledgment can use recent authored text.
61
+ The existing Cyrillic/CJK mismatch guard uses that authored sample per field;
62
+ it is not a complete language detector, and it is skipped if no sample exists.
63
+
64
+ ### Input bounds
65
+
66
+ User text is bounded to 8,000 characters and each assistant answer to 16,000.
67
+ Attached quote bodies have their own 4,000-character limit so a large quote
68
+ does not consume the user's comment. Excerpts preserve both ends with an
69
+ explicit omission marker, including the conclusion of a long final report.
70
+
71
+ The complete user prompt is limited to 32,000 characters and the resolved small
72
+ model's input allowance, reserving space for the system prompt. Under pressure,
73
+ drop older whole turns first. If the latest pair itself is too large, excerpt
74
+ both its user request and answer rather than discarding either side. If even
75
+ the minimum prompt cannot fit, skip generation. `onOverflow: 'error'` prevents
76
+ the Small Model service from silently cutting off the instructions. Expected
77
+ context/output-budget failures are quiet and do not write metadata.
78
+
79
+ OpenCode message pages still contain complete tool payloads on the wire. A
80
+ single long turn can therefore require substantial I/O even though its retained
81
+ model context is small. Page/count bounds are not a network-byte quota.
82
+
83
+ ## Generation and lifecycle
84
+
85
+ 1. The server's existing global event fan-out calls `processPayload`. An idle
86
+ event arms the 60-second quiet window. No history scan or startup backfill runs.
87
+ 2. Busy/retry events and newly created user messages clear pending work and
88
+ abort in-flight reads/generation. Re-emitted old user updates do not cancel it.
89
+ 3. One generation runs per session. If a newer quiet window expires while an
90
+ old canceled request is still settling, retain that pending run and start it
91
+ after the old one finishes. Later activity cancels the pending run as well.
92
+ 4. Resolve the small model using the last answer's provider/model and the
93
+ existing explicit settings/config overrides. `restrictToPreferredProvider`
94
+ prevents an implicit cross-provider fallback. Production does not pin the
95
+ experimental model. Generation accepts an abort signal and a 120-second limit.
96
+ 5. Recap describes the substantive work and its current result, including the
97
+ work behind a closing commit or acknowledgment. Suggestion is independent:
98
+ only unfinished requested agent work should produce a sendable user message.
99
+ Completed work, optional offers, or a decision/action belonging to the user
100
+ should return an empty suggestion. This is model judgment, not authorization
101
+ enforcement or a guarantee that every generated field is factually correct.
102
+ 6. Re-read the latest message and fresh session before writing. A moved tail,
103
+ canceled run, changed endpoint/directory, archive, revert, or failed fresh
104
+ read discards the result. Never merge from the old pre-generation metadata.
105
+ 7. Re-check settings, clamp the enabled fields, and merge into fresh metadata.
106
+ The OpenCode update endpoint has no compare-and-set operation; another
107
+ writer after the final read is not guarded atomically.
108
+
109
+ Stopping the runtime clears pending timers/runs and aborts in-flight operations.
110
+ No failed session blocks another session.
111
+
112
+ ## Settings and consumers
113
+
114
+ `sessionRecapEnabled` and `sessionSuggestionEnabled` default on and are checked
115
+ before work and before writing. With both off there are no reads, model calls,
116
+ or writes. With one on, the shared recent context is still available, but only
117
+ that field is requested. An empty suggestion does not erase a valid recap.
118
+
119
+ Clients render an assist only while its `forMessageID` is the last message and
120
+ the session is idle. A new message invalidates it without clearing writes.
121
+
122
+ - `packages/ui/src/lib/sessionAssistMetadata.ts` parses the payload.
123
+ - `packages/ui/src/hooks/useSessionAssist.ts` owns freshness/settings gating.
124
+ - `SessionRecapSpacer` shows the reminder in the reserved gap under the reply.
125
+ - `SessionSuggestionChip` fills the composer; it never sends automatically.
126
+
127
+ Web, Electron, hosted mobile, and Capacitor use the server watcher. VS Code's
128
+ extension-only runtime does not generate assists; shared UI can render payloads
129
+ produced by a server. The background watcher cannot use the browser's message
130
+ store when the UI is closed. Manual AI rename uses that store through
131
+ `SessionMessageLoader`; these are intentionally different retrieval lifecycles.