litepaseo 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +4 -3
  3. package/dist/server/cli.mjs +17 -15
  4. package/dist/server/{worker-DCp3pZYp.mjs → worker-Bncuyaw7.mjs} +383 -165
  5. package/dist/web/assets/AddProjectDialog-Bftvd3Yz.js +1 -0
  6. package/dist/web/assets/AddProjectDialog-Bftvd3Yz.js.br +0 -0
  7. package/dist/web/assets/AddProjectDialog-Bftvd3Yz.js.gz +0 -0
  8. package/dist/web/assets/{ArchivedWorkspaces-DskP5Tih.js → ArchivedWorkspaces-DAtKiAKb.js} +1 -1
  9. package/dist/web/assets/ArchivedWorkspaces-DAtKiAKb.js.br +0 -0
  10. package/dist/web/assets/ArchivedWorkspaces-DAtKiAKb.js.gz +0 -0
  11. package/dist/web/assets/ChangesPanel-D0GKf0t8.css +1 -0
  12. package/dist/web/assets/ChangesPanel-D0GKf0t8.css.br +0 -0
  13. package/dist/web/assets/{ChangesPanel-BEjmqUew.css.gz → ChangesPanel-D0GKf0t8.css.gz} +0 -0
  14. package/dist/web/assets/ChangesPanel-LDYyiOkA.js +3 -0
  15. package/dist/web/assets/ChangesPanel-LDYyiOkA.js.br +0 -0
  16. package/dist/web/assets/ChangesPanel-LDYyiOkA.js.gz +0 -0
  17. package/dist/web/assets/CodeBlockNode-Ubb_GmEN.js +3 -0
  18. package/dist/web/assets/CodeBlockNode-Ubb_GmEN.js.br +0 -0
  19. package/dist/web/assets/CodeBlockNode-Ubb_GmEN.js.gz +0 -0
  20. package/dist/web/assets/CommandCenter-C9e_MHP7.js +1 -0
  21. package/dist/web/assets/CommandCenter-C9e_MHP7.js.br +0 -0
  22. package/dist/web/assets/CommandCenter-C9e_MHP7.js.gz +0 -0
  23. package/dist/web/assets/{ConversationSearch-Cdqnpodo.js → ConversationSearch-BVkg07Q4.js} +1 -1
  24. package/dist/web/assets/ConversationSearch-BVkg07Q4.js.br +0 -0
  25. package/dist/web/assets/ConversationSearch-BVkg07Q4.js.gz +0 -0
  26. package/dist/web/assets/FileViewer-IobGwtBO.js +2 -0
  27. package/dist/web/assets/FileViewer-IobGwtBO.js.br +0 -0
  28. package/dist/web/assets/FileViewer-IobGwtBO.js.gz +0 -0
  29. package/dist/web/assets/FileViewer-Ykqgrlni.css +1 -0
  30. package/dist/web/assets/FileViewer-Ykqgrlni.css.br +0 -0
  31. package/dist/web/assets/FileViewer-Ykqgrlni.css.gz +0 -0
  32. package/dist/web/assets/FilesPanel-Bv8k97VP.css +1 -0
  33. package/dist/web/assets/FilesPanel-Bv8k97VP.css.br +0 -0
  34. package/dist/web/assets/FilesPanel-Bv8k97VP.css.gz +0 -0
  35. package/dist/web/assets/{FilesPanel-CZQKdUg4.js → FilesPanel-DRE6I9Zu.js} +1 -1
  36. package/dist/web/assets/FilesPanel-DRE6I9Zu.js.br +0 -0
  37. package/dist/web/assets/FilesPanel-DRE6I9Zu.js.gz +0 -0
  38. package/dist/web/assets/HostSettings-6VCu_mXO.css +1 -0
  39. package/dist/web/assets/HostSettings-6VCu_mXO.css.br +0 -0
  40. package/dist/web/assets/HostSettings-6VCu_mXO.css.gz +0 -0
  41. package/dist/web/assets/HostSettings-DUReTPzX.js +5 -0
  42. package/dist/web/assets/HostSettings-DUReTPzX.js.br +0 -0
  43. package/dist/web/assets/HostSettings-DUReTPzX.js.gz +0 -0
  44. package/dist/web/assets/ImportSessionDialog-Bg9XZ_ab.js +1 -0
  45. package/dist/web/assets/ImportSessionDialog-Bg9XZ_ab.js.br +0 -0
  46. package/dist/web/assets/ImportSessionDialog-Bg9XZ_ab.js.gz +0 -0
  47. package/dist/web/assets/KanbanPage-lKwsQfA_.js +1 -0
  48. package/dist/web/assets/KanbanPage-lKwsQfA_.js.br +0 -0
  49. package/dist/web/assets/KanbanPage-lKwsQfA_.js.gz +0 -0
  50. package/dist/web/assets/{LabelsDialog-aECWzRCP.js → LabelsDialog-DgPisIev.js} +1 -1
  51. package/dist/web/assets/LabelsDialog-DgPisIev.js.br +0 -0
  52. package/dist/web/assets/LabelsDialog-DgPisIev.js.gz +0 -0
  53. package/dist/web/assets/MarkdownMessage-4Jj7wE3O.js +195 -0
  54. package/dist/web/assets/MarkdownMessage-4Jj7wE3O.js.br +0 -0
  55. package/dist/web/assets/MarkdownMessage-4Jj7wE3O.js.gz +0 -0
  56. package/dist/web/assets/MarkdownMessage-CUjgbUVl.css +1 -0
  57. package/dist/web/assets/MarkdownMessage-CUjgbUVl.css.br +0 -0
  58. package/dist/web/assets/MarkdownMessage-CUjgbUVl.css.gz +0 -0
  59. package/dist/web/assets/{PreCodeBlock-VABP7RPr.js → PreCodeBlock-CPJuGkN0.js} +1 -1
  60. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DyY0Ilsi.js +1 -0
  61. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DyY0Ilsi.js.br +0 -0
  62. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-DyY0Ilsi.js.gz +0 -0
  63. package/dist/web/assets/SubagentsPanel-BK_Zsxyd.css +1 -0
  64. package/dist/web/assets/SubagentsPanel-BK_Zsxyd.css.br +0 -0
  65. package/dist/web/assets/SubagentsPanel-BK_Zsxyd.css.gz +0 -0
  66. package/dist/web/assets/SubagentsPanel-COknYf0L.js +1 -0
  67. package/dist/web/assets/SubagentsPanel-COknYf0L.js.br +0 -0
  68. package/dist/web/assets/SubagentsPanel-COknYf0L.js.gz +0 -0
  69. package/dist/web/assets/{TerminalPanel-CgwrWov9.css → TerminalPanel-BQ9YR9dM.css} +1 -1
  70. package/dist/web/assets/TerminalPanel-BQ9YR9dM.css.br +0 -0
  71. package/dist/web/assets/TerminalPanel-BQ9YR9dM.css.gz +0 -0
  72. package/dist/web/assets/TerminalPanel-Dbx2lKSi.js +3 -0
  73. package/dist/web/assets/TerminalPanel-Dbx2lKSi.js.br +0 -0
  74. package/dist/web/assets/TerminalPanel-Dbx2lKSi.js.gz +0 -0
  75. package/dist/web/assets/Tooltip-DtQZvsaN.js +1 -0
  76. package/dist/web/assets/Tooltip-DtQZvsaN.js.br +0 -0
  77. package/dist/web/assets/Tooltip-DtQZvsaN.js.gz +0 -0
  78. package/dist/web/assets/highlight-FO7Ekoql.js +5 -0
  79. package/dist/web/assets/highlight-FO7Ekoql.js.br +0 -0
  80. package/dist/web/assets/highlight-FO7Ekoql.js.gz +0 -0
  81. package/dist/web/assets/index--Uzu2A_h.js +45 -0
  82. package/dist/web/assets/index--Uzu2A_h.js.br +0 -0
  83. package/dist/web/assets/index--Uzu2A_h.js.gz +0 -0
  84. package/dist/web/assets/{index-DwxhY3AB.css → index-5kxjCia8.css} +1 -1
  85. package/dist/web/assets/index-5kxjCia8.css.br +0 -0
  86. package/dist/web/assets/index-5kxjCia8.css.gz +0 -0
  87. package/dist/web/assets/{index10-9PQ1qCgE.js → index10-BTkpIIYS.js} +2 -2
  88. package/dist/web/assets/index10-BTkpIIYS.js.br +0 -0
  89. package/dist/web/assets/index10-BTkpIIYS.js.gz +0 -0
  90. package/dist/web/assets/index3-BSWvERvY.js +1 -0
  91. package/dist/web/assets/index4-D6dsLD5o.js +1 -0
  92. package/dist/web/assets/{index5-EvVIUWBE.js → index5-CkCxVfaP.js} +1 -1
  93. package/dist/web/assets/index5-CkCxVfaP.js.br +0 -0
  94. package/dist/web/assets/index5-CkCxVfaP.js.gz +0 -0
  95. package/dist/web/assets/{index6-Dp2tbhQ_.js → index6-SCztOIu6.js} +1 -1
  96. package/dist/web/assets/index6-SCztOIu6.js.br +0 -0
  97. package/dist/web/assets/index6-SCztOIu6.js.gz +0 -0
  98. package/dist/web/assets/{index7-CFOwrJfH.js → index7-HKApXTNK.js} +2 -2
  99. package/dist/web/assets/index7-HKApXTNK.js.br +0 -0
  100. package/dist/web/assets/index7-HKApXTNK.js.gz +0 -0
  101. package/dist/web/assets/{index8-BvMAnsy9.js → index8-CCdHj2vL.js} +1 -1
  102. package/dist/web/assets/index8-CCdHj2vL.js.br +0 -0
  103. package/dist/web/assets/{index8-BvMAnsy9.js.gz → index8-CCdHj2vL.js.gz} +0 -0
  104. package/dist/web/assets/index9-rtEtkGH0.js +1 -0
  105. package/dist/web/assets/index9-rtEtkGH0.js.br +0 -0
  106. package/dist/web/assets/index9-rtEtkGH0.js.gz +0 -0
  107. package/dist/web/assets/vue.runtime.esm-bundler-Dph2MMo9.js +4 -0
  108. package/dist/web/assets/vue.runtime.esm-bundler-Dph2MMo9.js.br +0 -0
  109. package/dist/web/assets/vue.runtime.esm-bundler-Dph2MMo9.js.gz +0 -0
  110. package/dist/web/index.html +3 -3
  111. package/dist/web/index.html.br +0 -0
  112. package/dist/web/index.html.gz +0 -0
  113. package/package.json +16 -14
  114. package/dist/web/assets/AddProjectDialog-KlhTl3pQ.js +0 -1
  115. package/dist/web/assets/AddProjectDialog-KlhTl3pQ.js.br +0 -0
  116. package/dist/web/assets/AddProjectDialog-KlhTl3pQ.js.gz +0 -0
  117. package/dist/web/assets/ArchivedWorkspaces-DskP5Tih.js.br +0 -0
  118. package/dist/web/assets/ArchivedWorkspaces-DskP5Tih.js.gz +0 -0
  119. package/dist/web/assets/ChangesPanel-BEjmqUew.css +0 -1
  120. package/dist/web/assets/ChangesPanel-BEjmqUew.css.br +0 -0
  121. package/dist/web/assets/ChangesPanel-CNFEnH8u.js +0 -3
  122. package/dist/web/assets/ChangesPanel-CNFEnH8u.js.br +0 -0
  123. package/dist/web/assets/ChangesPanel-CNFEnH8u.js.gz +0 -0
  124. package/dist/web/assets/CodeBlockNode-D5UGBgBo.js +0 -3
  125. package/dist/web/assets/CodeBlockNode-D5UGBgBo.js.br +0 -0
  126. package/dist/web/assets/CodeBlockNode-D5UGBgBo.js.gz +0 -0
  127. package/dist/web/assets/CommandCenter-CfbLPl1u.js +0 -1
  128. package/dist/web/assets/CommandCenter-CfbLPl1u.js.br +0 -0
  129. package/dist/web/assets/CommandCenter-CfbLPl1u.js.gz +0 -0
  130. package/dist/web/assets/ConversationSearch-Cdqnpodo.js.br +0 -0
  131. package/dist/web/assets/ConversationSearch-Cdqnpodo.js.gz +0 -0
  132. package/dist/web/assets/FileViewer-BfvWZNL8.js +0 -2
  133. package/dist/web/assets/FileViewer-BfvWZNL8.js.br +0 -0
  134. package/dist/web/assets/FileViewer-BfvWZNL8.js.gz +0 -0
  135. package/dist/web/assets/FileViewer-DgsB2rdj.css +0 -1
  136. package/dist/web/assets/FileViewer-DgsB2rdj.css.br +0 -0
  137. package/dist/web/assets/FileViewer-DgsB2rdj.css.gz +0 -0
  138. package/dist/web/assets/FilesPanel-CZQKdUg4.js.br +0 -0
  139. package/dist/web/assets/FilesPanel-CZQKdUg4.js.gz +0 -0
  140. package/dist/web/assets/FilesPanel-DmPAJwih.css +0 -1
  141. package/dist/web/assets/FilesPanel-DmPAJwih.css.br +0 -0
  142. package/dist/web/assets/FilesPanel-DmPAJwih.css.gz +0 -0
  143. package/dist/web/assets/HostSettings--0Jl-MlL.css +0 -1
  144. package/dist/web/assets/HostSettings--0Jl-MlL.css.br +0 -0
  145. package/dist/web/assets/HostSettings--0Jl-MlL.css.gz +0 -0
  146. package/dist/web/assets/HostSettings-DAa1rg7p.js +0 -5
  147. package/dist/web/assets/HostSettings-DAa1rg7p.js.br +0 -0
  148. package/dist/web/assets/HostSettings-DAa1rg7p.js.gz +0 -0
  149. package/dist/web/assets/ImportSessionDialog-XjbnywIR.js +0 -1
  150. package/dist/web/assets/ImportSessionDialog-XjbnywIR.js.br +0 -0
  151. package/dist/web/assets/ImportSessionDialog-XjbnywIR.js.gz +0 -0
  152. package/dist/web/assets/KanbanPage-6LaK4lAp.js +0 -1
  153. package/dist/web/assets/KanbanPage-6LaK4lAp.js.br +0 -0
  154. package/dist/web/assets/KanbanPage-6LaK4lAp.js.gz +0 -0
  155. package/dist/web/assets/LabelsDialog-aECWzRCP.js.br +0 -0
  156. package/dist/web/assets/LabelsDialog-aECWzRCP.js.gz +0 -0
  157. package/dist/web/assets/MarkdownMessage-Cz2a-heW.js +0 -199
  158. package/dist/web/assets/MarkdownMessage-Cz2a-heW.js.br +0 -0
  159. package/dist/web/assets/MarkdownMessage-Cz2a-heW.js.gz +0 -0
  160. package/dist/web/assets/MarkdownMessage-bqphU8I9.css +0 -1
  161. package/dist/web/assets/MarkdownMessage-bqphU8I9.css.br +0 -0
  162. package/dist/web/assets/MarkdownMessage-bqphU8I9.css.gz +0 -0
  163. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-B4p5wP0S.js +0 -1
  164. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-B4p5wP0S.js.br +0 -0
  165. package/dist/web/assets/PreCodeBlock.vue_vue_type_style_index_0_lang-B4p5wP0S.js.gz +0 -0
  166. package/dist/web/assets/SubagentsPanel-BwR5tVCn.css +0 -1
  167. package/dist/web/assets/SubagentsPanel-BwR5tVCn.css.br +0 -0
  168. package/dist/web/assets/SubagentsPanel-BwR5tVCn.css.gz +0 -0
  169. package/dist/web/assets/SubagentsPanel-DNQ0U-hw.js +0 -1
  170. package/dist/web/assets/SubagentsPanel-DNQ0U-hw.js.br +0 -0
  171. package/dist/web/assets/SubagentsPanel-DNQ0U-hw.js.gz +0 -0
  172. package/dist/web/assets/TerminalPanel-BnjX_223.js +0 -3
  173. package/dist/web/assets/TerminalPanel-BnjX_223.js.br +0 -0
  174. package/dist/web/assets/TerminalPanel-BnjX_223.js.gz +0 -0
  175. package/dist/web/assets/TerminalPanel-CgwrWov9.css.br +0 -0
  176. package/dist/web/assets/TerminalPanel-CgwrWov9.css.gz +0 -0
  177. package/dist/web/assets/Tooltip-DWpicVuG.js +0 -1
  178. package/dist/web/assets/Tooltip-DWpicVuG.js.br +0 -0
  179. package/dist/web/assets/Tooltip-DWpicVuG.js.gz +0 -0
  180. package/dist/web/assets/highlight-BnTrj1LT.js +0 -5
  181. package/dist/web/assets/highlight-BnTrj1LT.js.br +0 -0
  182. package/dist/web/assets/highlight-BnTrj1LT.js.gz +0 -0
  183. package/dist/web/assets/index-Ce8bdxwG.js +0 -45
  184. package/dist/web/assets/index-Ce8bdxwG.js.br +0 -0
  185. package/dist/web/assets/index-Ce8bdxwG.js.gz +0 -0
  186. package/dist/web/assets/index-DwxhY3AB.css.br +0 -0
  187. package/dist/web/assets/index-DwxhY3AB.css.gz +0 -0
  188. package/dist/web/assets/index10-9PQ1qCgE.js.br +0 -0
  189. package/dist/web/assets/index10-9PQ1qCgE.js.gz +0 -0
  190. package/dist/web/assets/index3-D4BmE5z2.js +0 -1
  191. package/dist/web/assets/index4-DqdY9eET.js +0 -1
  192. package/dist/web/assets/index5-EvVIUWBE.js.br +0 -0
  193. package/dist/web/assets/index5-EvVIUWBE.js.gz +0 -0
  194. package/dist/web/assets/index6-Dp2tbhQ_.js.br +0 -0
  195. package/dist/web/assets/index6-Dp2tbhQ_.js.gz +0 -0
  196. package/dist/web/assets/index7-CFOwrJfH.js.br +0 -0
  197. package/dist/web/assets/index7-CFOwrJfH.js.gz +0 -0
  198. package/dist/web/assets/index8-BvMAnsy9.js.br +0 -0
  199. package/dist/web/assets/index9-Bj-VCtON.js +0 -1
  200. package/dist/web/assets/index9-Bj-VCtON.js.br +0 -0
  201. package/dist/web/assets/index9-Bj-VCtON.js.gz +0 -0
  202. package/dist/web/assets/vue.runtime.esm-bundler-DmQNwI70.js +0 -4
  203. package/dist/web/assets/vue.runtime.esm-bundler-DmQNwI70.js.br +0 -0
  204. package/dist/web/assets/vue.runtime.esm-bundler-DmQNwI70.js.gz +0 -0
@@ -12,6 +12,7 @@ import { getParentAgentIdFromLabels } from "@getpaseo/protocol/agent-labels";
12
12
  import { lstat, readFile, realpath } from "node:fs/promises";
13
13
  import { Hono } from "hono";
14
14
  import { bodyLimit } from "hono/body-limit";
15
+ import { HTTPException } from "hono/http-exception";
15
16
  import { serveStatic } from "@hono/node-server/serve-static";
16
17
  import { z } from "zod";
17
18
  import { promisify } from "node:util";
@@ -244,13 +245,20 @@ var HostMirror = class {
244
245
  collection;
245
246
  changed;
246
247
  transition;
247
- constructor(adapter, hostId, driver, collection, changed, transition = () => {}) {
248
+ onSynced;
249
+ _synced = false;
250
+ constructor(adapter, hostId, driver, collection, changed, transition = () => {}, onSynced = () => {}) {
248
251
  this.adapter = adapter;
249
252
  this.hostId = hostId;
250
253
  this.driver = driver;
251
254
  this.collection = collection;
252
255
  this.changed = changed;
253
256
  this.transition = transition;
257
+ this.onSynced = onSynced;
258
+ }
259
+ /** True once the current connection has reconciled its initial or incremental snapshot. */
260
+ get synced() {
261
+ return this._synced;
254
262
  }
255
263
  /** What the adapter retained for a member, from the latest update; O(1). */
256
264
  retained(id) {
@@ -330,6 +338,7 @@ var HostMirror = class {
330
338
  }
331
339
  close() {
332
340
  this.token++;
341
+ this._synced = false;
333
342
  clearTimeout(this.retry);
334
343
  this.liveTouched = null;
335
344
  const subscription = this.subscription;
@@ -363,6 +372,8 @@ var HostMirror = class {
363
372
  afterSeq: Math.max(this.cursor.afterSeq, payload.sync.headSeq)
364
373
  };
365
374
  this.onSnapshotProcessed(payload, false);
375
+ this._synced = true;
376
+ this.onSynced();
366
377
  return;
367
378
  }
368
379
  let entries = payload.entries;
@@ -398,6 +409,8 @@ var HostMirror = class {
398
409
  generation: payload.sync.generation,
399
410
  afterSeq: this.cursor?.generation === payload.sync.generation ? Math.max(this.cursor.afterSeq, payload.sync.headSeq) : payload.sync.headSeq
400
411
  } : void 0;
412
+ this._synced = true;
413
+ this.onSynced();
401
414
  }
402
415
  onUpdate(update) {
403
416
  if (update.generation && this.cursor && update.generation !== this.cursor.generation) {
@@ -571,8 +584,8 @@ const agentAdapter = {
571
584
  };
572
585
  /** One daemon's active agents. */
573
586
  var HostDirectory = class extends HostMirror {
574
- constructor(hostId, driver, collection, changed, transition) {
575
- super(agentAdapter, hostId, driver, collection, changed, transition);
587
+ constructor(hostId, driver, collection, changed, transition, onSynced) {
588
+ super(agentAdapter, hostId, driver, collection, changed, transition, onSynced);
576
589
  }
577
590
  /** Provider and capabilities from the live directory; undefined if the agent is not listed. */
578
591
  facts(agentId) {
@@ -686,13 +699,23 @@ const AGENT_STATE_PRIORITY = {
686
699
  * their full state bucket; same-workspace subagents contribute only while running.
687
700
  */
688
701
  function deriveWorkspaceAgentState(agents) {
689
- const list = Array.isArray(agents) ? agents : [...agents];
690
- if (!list.length) return null;
691
- const byId = /* @__PURE__ */ new Map();
692
- for (const agent of list) byId.set(agent.id, agent);
702
+ let byId;
703
+ let values;
704
+ if (agents instanceof Map) {
705
+ if (!agents.size) return null;
706
+ byId = agents;
707
+ values = agents.values();
708
+ } else {
709
+ const list = Array.isArray(agents) ? agents : [...agents];
710
+ if (!list.length) return null;
711
+ const map = /* @__PURE__ */ new Map();
712
+ for (const agent of list) map.set(agent.id, agent);
713
+ byId = map;
714
+ values = list;
715
+ }
693
716
  let best = null;
694
717
  let bestPriority = AGENT_STATE_PRIORITY.done;
695
- for (const agent of list) {
718
+ for (const agent of values) {
696
719
  const isRoot = !agent.parentAgentId || !byId.has(agent.parentAgentId);
697
720
  let candidate;
698
721
  if (isRoot) candidate = agent.state === "done" && agent.unread ? "unread" : agent.state;
@@ -858,6 +881,7 @@ function rowFingerprint(row) {
858
881
  * all updates including `turnMetrics`.
859
882
  */
860
883
  var TimelineView = class {
884
+ viewId = randomUUID();
861
885
  rows = [];
862
886
  bySeqStart = /* @__PURE__ */ new Map();
863
887
  fingerprints = /* @__PURE__ */ new Map();
@@ -869,10 +893,14 @@ var TimelineView = class {
869
893
  startCursor = null;
870
894
  state = "idle";
871
895
  active = false;
896
+ dirty = false;
897
+ pendingFinalRefresh = false;
898
+ finalRefreshAttempts = 0;
872
899
  watchers = /* @__PURE__ */ new Set();
873
900
  pollTimer;
874
901
  retryTimer;
875
902
  settleTimer;
903
+ finalRetryTimer;
876
904
  fastPollsLeft = 0;
877
905
  inFlight = false;
878
906
  pendingPull = false;
@@ -921,16 +949,27 @@ var TimelineView = class {
921
949
  clearTimeout(this.settleTimer);
922
950
  this.settleTimer = void 0;
923
951
  if (running) {
952
+ clearTimeout(this.finalRetryTimer);
953
+ this.finalRetryTimer = void 0;
954
+ this.pendingFinalRefresh = false;
955
+ this.finalRefreshAttempts = 0;
956
+ if (wasActive) return;
924
957
  if (this.state === "live") {
925
- this.pull(false);
926
- this.schedulePoll();
958
+ if (this.watchers.size) {
959
+ this.pull(false);
960
+ this.schedulePoll();
961
+ } else this.dirty = true;
927
962
  }
928
963
  } else {
929
964
  if (!this.inFastBurst()) {
930
965
  clearTimeout(this.pollTimer);
931
966
  this.pollTimer = void 0;
932
967
  }
933
- if (wasActive && this.state === "live") this.pull(false, true);
968
+ if (wasActive && this.state === "live") {
969
+ this.pendingFinalRefresh = true;
970
+ this.finalRefreshAttempts = 0;
971
+ this.pull(false, true);
972
+ }
934
973
  }
935
974
  }
936
975
  /**
@@ -961,14 +1000,22 @@ var TimelineView = class {
961
1000
  if (ops) {
962
1001
  if (ops.length) watcher(ops);
963
1002
  } else watcher([this.resetOp()]);
964
- if (this.active || this.inFastBurst()) this.schedulePoll();
1003
+ if (this.dirty || this.pendingFinalRefresh) {
1004
+ this.dirty = false;
1005
+ const settle = this.pendingFinalRefresh && !this.active;
1006
+ this.pull(false, settle);
1007
+ if (this.active || this.inFastBurst()) this.schedulePoll();
1008
+ } else if (this.active || this.inFastBurst()) this.schedulePoll();
965
1009
  else if (since && now() - this.lastPullAt >= RESUME_VERIFY_MS) this.wake();
966
- } else if (this.state === "loading" && this.joiners.length < MAX_JOINERS) this.joiners.push(now());
1010
+ } else if (this.state === "failed") this.start();
1011
+ else if (this.state === "loading" && this.joiners.length < MAX_JOINERS) this.joiners.push(now());
967
1012
  return () => {
968
1013
  this.watchers.delete(watcher);
969
1014
  if (!this.watchers.size) {
970
1015
  clearTimeout(this.pollTimer);
971
- this.pollTimer = void 0;
1016
+ clearTimeout(this.retryTimer);
1017
+ clearTimeout(this.finalRetryTimer);
1018
+ this.pollTimer = this.retryTimer = this.finalRetryTimer = void 0;
972
1019
  }
973
1020
  };
974
1021
  }
@@ -976,10 +1023,13 @@ var TimelineView = class {
976
1023
  this.state = "disposed";
977
1024
  this.token++;
978
1025
  this.fastPollsLeft = 0;
1026
+ this.dirty = false;
1027
+ this.pendingFinalRefresh = false;
979
1028
  clearTimeout(this.pollTimer);
980
1029
  clearTimeout(this.retryTimer);
981
1030
  clearTimeout(this.settleTimer);
982
- this.pollTimer = this.retryTimer = this.settleTimer = void 0;
1031
+ clearTimeout(this.finalRetryTimer);
1032
+ this.pollTimer = this.retryTimer = this.settleTimer = this.finalRetryTimer = void 0;
983
1033
  this.watchers.clear();
984
1034
  return Promise.resolve();
985
1035
  }
@@ -1028,6 +1078,13 @@ var TimelineView = class {
1028
1078
  this.lastPullAt = now();
1029
1079
  if (this.timing) this.timing.fetchMs = Math.round(this.lastPullAt - fetchAt);
1030
1080
  this.consecutiveFailures = 0;
1081
+ this.dirty = false;
1082
+ if (checkMetricsSettle && !this.active && !this.pendingSettle) {
1083
+ this.pendingFinalRefresh = false;
1084
+ this.finalRefreshAttempts = 0;
1085
+ clearTimeout(this.finalRetryTimer);
1086
+ this.finalRetryTimer = void 0;
1087
+ }
1031
1088
  if (initial || this.state !== "live" || page.reset || page.epoch !== this.epoch) {
1032
1089
  this.replaceWith(page);
1033
1090
  this.state = "live";
@@ -1064,15 +1121,28 @@ var TimelineView = class {
1064
1121
  message: "Timeline sync interrupted; retrying"
1065
1122
  }]);
1066
1123
  clearTimeout(this.retryTimer);
1067
- this.retryTimer = setTimeout(() => {
1068
- this.retryTimer = void 0;
1069
- if (this.state === "failed" && token === this.token) this.start();
1070
- }, RETRY_MS);
1071
- this.retryTimer.unref?.();
1072
- } else if (this.consecutiveFailures >= 3) this.broadcast([{
1073
- type: "error",
1074
- message: "Timeline sync interrupted; retrying"
1075
- }]);
1124
+ if (this.watchers.size) {
1125
+ this.retryTimer = setTimeout(() => {
1126
+ this.retryTimer = void 0;
1127
+ if (this.state === "failed" && token === this.token && this.watchers.size) this.start();
1128
+ }, RETRY_MS);
1129
+ this.retryTimer.unref?.();
1130
+ }
1131
+ } else {
1132
+ if (this.consecutiveFailures >= 3) this.broadcast([{
1133
+ type: "error",
1134
+ message: "Timeline sync interrupted; retrying"
1135
+ }]);
1136
+ if (this.pendingFinalRefresh && !this.active && this.watchers.size && this.finalRefreshAttempts < 3) {
1137
+ this.finalRefreshAttempts++;
1138
+ clearTimeout(this.finalRetryTimer);
1139
+ this.finalRetryTimer = setTimeout(() => {
1140
+ this.finalRetryTimer = void 0;
1141
+ if (this.state === "live" && this.pendingFinalRefresh && !this.active && this.watchers.size) this.pull(false, true);
1142
+ }, RETRY_MS * this.finalRefreshAttempts);
1143
+ this.finalRetryTimer.unref?.();
1144
+ }
1145
+ }
1076
1146
  } finally {
1077
1147
  clearTimeout(timeoutHandle);
1078
1148
  this.inFlight = false;
@@ -1198,7 +1268,7 @@ var TimelineView = class {
1198
1268
  this.resumeFloor = this.revision;
1199
1269
  }
1200
1270
  resumeOps(since) {
1201
- if (since.epoch !== this.epoch || since.seq < this.resumeFloor || since.seq > this.revision) return null;
1271
+ if (since.epoch !== this.epoch || since.view !== this.viewId || since.seq < this.resumeFloor || since.seq > this.revision) return null;
1202
1272
  const changed = this.rows.filter((row) => row.seqStart >= since.from && (this.rowRev.get(row.seqStart) ?? 0) > since.seq);
1203
1273
  if (changed.length > RESET_ROWS) return null;
1204
1274
  return changed.map((row) => ({
@@ -1213,6 +1283,7 @@ var TimelineView = class {
1213
1283
  return {
1214
1284
  type: "reset",
1215
1285
  epoch: this.epoch,
1286
+ view: this.viewId,
1216
1287
  rows,
1217
1288
  hasOlder: this.hasOlder || start > 0,
1218
1289
  startCursor: start > 0 ? {
@@ -1276,7 +1347,6 @@ const publish = (d) => ({
1276
1347
  */
1277
1348
  var HostSubagents = class {
1278
1349
  parents = /* @__PURE__ */ new Map();
1279
- timelines = /* @__PURE__ */ new Map();
1280
1350
  events = null;
1281
1351
  stopEvents = null;
1282
1352
  snapshots = 0;
@@ -1322,60 +1392,37 @@ var HostSubagents = class {
1322
1392
  statusOf(parentAgentId, subagentId) {
1323
1393
  return this.parents.get(parentAgentId)?.subagents.get(subagentId)?.status;
1324
1394
  }
1325
- /** A TimelineView driver for one subagent conversation. */
1395
+ /** A TimelineView driver for one subagent conversation (Wake + Pull). */
1326
1396
  timelineDriver(parentAgentId, subagentId) {
1327
- const key = `${parentAgentId}\0${subagentId}`;
1328
- return {
1329
- subscribeAgentTimeline: (_agentId, handler) => {
1330
- this.acquire();
1331
- let handlers = this.timelines.get(key);
1332
- if (!handlers) this.timelines.set(key, handlers = /* @__PURE__ */ new Set());
1333
- handlers.add(handler);
1334
- let released = false;
1335
- const release = async () => {
1336
- if (released) return;
1337
- released = true;
1338
- handlers.delete(handler);
1339
- if (!handlers.size && this.timelines.get(key) === handlers) this.timelines.delete(key);
1340
- this.releaseUse();
1341
- };
1342
- const ready = this.events.ready.then(() => void 0);
1343
- return Object.assign(() => void release(), {
1344
- ready,
1345
- release
1346
- });
1347
- },
1348
- fetchAgentTimeline: async (_agentId, options) => {
1349
- const page = await this.driver.fetchProviderSubagentTimeline(parentAgentId, subagentId, {
1350
- direction: options.direction,
1351
- ...options.cursor ? { cursor: options.cursor } : {},
1352
- ...typeof options.limit === "number" ? { limit: options.limit } : {},
1353
- timeout: LIST_TIMEOUT_MS$1
1354
- });
1355
- return {
1356
- epoch: page.epoch,
1357
- reset: page.reset,
1358
- window: page.window,
1359
- startCursor: page.startCursor ?? null,
1360
- endCursor: page.endCursor ?? null,
1361
- hasOlder: page.hasOlder,
1362
- hasNewer: page.hasNewer,
1363
- entries: page.rows.map((row) => ({
1364
- provider: page.provider ?? "",
1365
- item: row.item,
1366
- timestamp: row.timestamp,
1367
- seqStart: row.seqStart ?? row.seq,
1368
- seqEnd: row.seqEnd ?? row.seq
1369
- }))
1370
- };
1371
- }
1372
- };
1397
+ return { fetchAgentTimeline: async (_agentId, options) => {
1398
+ const page = await this.driver.fetchProviderSubagentTimeline(parentAgentId, subagentId, {
1399
+ direction: options.direction,
1400
+ ...options.cursor ? { cursor: options.cursor } : {},
1401
+ ...typeof options.limit === "number" ? { limit: options.limit } : {},
1402
+ timeout: LIST_TIMEOUT_MS$1
1403
+ });
1404
+ return {
1405
+ epoch: page.epoch,
1406
+ reset: page.reset,
1407
+ window: page.window,
1408
+ startCursor: page.startCursor ?? null,
1409
+ endCursor: page.endCursor ?? null,
1410
+ hasOlder: page.hasOlder,
1411
+ hasNewer: page.hasNewer,
1412
+ entries: page.rows.map((row) => ({
1413
+ provider: page.provider ?? "",
1414
+ item: row.item,
1415
+ timestamp: row.timestamp,
1416
+ seqStart: row.seqStart ?? row.seq,
1417
+ seqEnd: row.seqEnd ?? row.seq
1418
+ }))
1419
+ };
1420
+ } };
1373
1421
  }
1374
1422
  async dispose() {
1375
1423
  clearTimeout(this.idle);
1376
1424
  for (const parent of this.parents.values()) clearTimeout(parent.timer);
1377
1425
  this.parents.clear();
1378
- this.timelines.clear();
1379
1426
  await this.close();
1380
1427
  }
1381
1428
  acquire() {
@@ -1417,7 +1464,6 @@ var HostSubagents = class {
1417
1464
  }
1418
1465
  restored() {
1419
1466
  for (const [id, parent] of this.parents) this.load(id, parent);
1420
- for (const handlers of this.timelines.values()) for (const handler of handlers) handler({ type: "agent.timeline.subscription_restored" });
1421
1467
  }
1422
1468
  async load(parentAgentId, parent) {
1423
1469
  const token = ++parent.token;
@@ -1438,26 +1484,7 @@ var HostSubagents = class {
1438
1484
  this.flush(parent);
1439
1485
  }
1440
1486
  receive(payload) {
1441
- if (payload.kind === "timeline") {
1442
- const handlers = this.timelines.get(`${payload.parentAgentId}\0${payload.subagentId}`);
1443
- if (!handlers) return;
1444
- const message = {
1445
- type: "agent_stream",
1446
- payload: {
1447
- agentId: payload.subagentId,
1448
- event: {
1449
- type: "timeline",
1450
- provider: payload.provider,
1451
- item: payload.item
1452
- },
1453
- timestamp: payload.timestamp,
1454
- seq: payload.seq,
1455
- epoch: payload.epoch
1456
- }
1457
- };
1458
- for (const handler of handlers) handler(message);
1459
- return;
1460
- }
1487
+ if (payload.kind === "timeline") return;
1461
1488
  const parentId = payload.kind === "upsert" ? payload.subagent.parentAgentId : payload.parentAgentId;
1462
1489
  const parent = this.parents.get(parentId);
1463
1490
  if (!parent) return;
@@ -1640,6 +1667,7 @@ var HostBackgroundWork = class {
1640
1667
  if (typeof payload.agentId !== "string") return;
1641
1668
  const entry = this.watched.get(payload.agentId);
1642
1669
  if (!entry) return;
1670
+ entry.token++;
1643
1671
  entry.items = sanitize(payload.items);
1644
1672
  entry.loaded = true;
1645
1673
  this.dirty.add(payload.agentId);
@@ -1770,12 +1798,14 @@ var Hosts = class {
1770
1798
  const agentsByWorkspace = /* @__PURE__ */ new Map();
1771
1799
  const workspaceAgentState = (workspaceId) => {
1772
1800
  const bucket = agentsByWorkspace.get(workspaceId);
1773
- return bucket ? deriveWorkspaceAgentState(bucket.values()) : null;
1801
+ return bucket ? deriveWorkspaceAgentState(bucket) : null;
1774
1802
  };
1775
1803
  const workspaces = new HostWorkspaces(hostId, driver, this.workspaces, () => this.emit(this.agentListeners), this.emptyProjects, workspaceAgentState);
1776
1804
  const directory = new HostDirectory(hostId, driver, this.agents, () => this.emit(this.agentListeners), (previous, next) => {
1777
1805
  const touchedWorkspaces = /* @__PURE__ */ new Set();
1778
- if (previous?.workspaceId) {
1806
+ const workspaceChanged = !previous || !next || previous.workspaceId !== next.workspaceId;
1807
+ const stateChanged = workspaceChanged || previous.parentAgentId !== next.parentAgentId || previous.state !== next.state || previous.unread !== next.unread || previous.turnActive !== next.turnActive || previous.status !== next.status;
1808
+ if (workspaceChanged && previous?.workspaceId) {
1779
1809
  const bucket = agentsByWorkspace.get(previous.workspaceId);
1780
1810
  if (bucket) {
1781
1811
  bucket.delete(previous.id);
@@ -1787,7 +1817,7 @@ var Hosts = class {
1787
1817
  let bucket = agentsByWorkspace.get(next.workspaceId);
1788
1818
  if (!bucket) agentsByWorkspace.set(next.workspaceId, bucket = /* @__PURE__ */ new Map());
1789
1819
  bucket.set(next.id, next);
1790
- touchedWorkspaces.add(next.workspaceId);
1820
+ if (stateChanged) touchedWorkspaces.add(next.workspaceId);
1791
1821
  }
1792
1822
  for (const workspaceId of touchedWorkspaces) workspaces.reconcile(workspaceId);
1793
1823
  if (next) {
@@ -1799,7 +1829,7 @@ var Hosts = class {
1799
1829
  }
1800
1830
  }
1801
1831
  notifyListeners(this.transitionListeners, previous, next);
1802
- });
1832
+ }, () => this.emit(this.hostListeners));
1803
1833
  const update = (state) => {
1804
1834
  const previous = this.diagnostics.get(hostId) ?? {};
1805
1835
  if (state.status === "connected") {
@@ -1945,11 +1975,19 @@ var Hosts = class {
1945
1975
  }
1946
1976
  /** The provider subagents of one agent, as they change. */
1947
1977
  watchSubagents(hostId, agentId, listener) {
1978
+ let seen = /* @__PURE__ */ new Set();
1948
1979
  return this.get(hostId).subagents.watch(agentId, (subagents) => {
1980
+ const current = /* @__PURE__ */ new Set();
1949
1981
  for (const s of subagents) {
1982
+ current.add(s.id);
1950
1983
  const subView = this.timelines.get(`${hostId}:${agentId}:subagent:${s.id}`)?.view;
1951
1984
  if (subView) subView.setActive(s.status === "running");
1952
1985
  }
1986
+ for (const id of seen) if (!current.has(id)) {
1987
+ const removedView = this.timelines.get(`${hostId}:${agentId}:subagent:${id}`)?.view;
1988
+ if (removedView) removedView.setActive(false);
1989
+ }
1990
+ seen = current;
1953
1991
  listener(subagents);
1954
1992
  });
1955
1993
  }
@@ -2044,17 +2082,27 @@ var Hosts = class {
2044
2082
  * The conversation as it is now, for a plain request that opens it: the shared view's reset
2045
2083
  * (loaded first if nobody watched it). Its seq lets the browser's stream resume from there.
2046
2084
  */
2047
- timelineSnapshot(hostId, agentId, timeoutMs = SNAPSHOT_TIMEOUT_MS) {
2085
+ timelineSnapshot(hostId, agentId, timeoutMs = SNAPSHOT_TIMEOUT_MS, signal) {
2048
2086
  return new Promise((resolve, reject) => {
2087
+ if (signal?.aborted) return reject(new TimelineTimeoutError());
2049
2088
  let stop = null, done = false, released = false;
2050
2089
  const release = () => {
2051
2090
  if (released || !stop) return;
2052
2091
  released = true;
2053
2092
  stop();
2054
2093
  };
2094
+ const onAbort = () => {
2095
+ if (done) return;
2096
+ done = true;
2097
+ clearTimeout(timer);
2098
+ release();
2099
+ reject(new TimelineTimeoutError());
2100
+ };
2101
+ signal?.addEventListener("abort", onAbort, { once: true });
2055
2102
  const timer = setTimeout(() => {
2056
2103
  if (done) return;
2057
2104
  done = true;
2105
+ signal?.removeEventListener("abort", onAbort);
2058
2106
  release();
2059
2107
  reject(new TimelineTimeoutError());
2060
2108
  }, timeoutMs);
@@ -2065,12 +2113,14 @@ var Hosts = class {
2065
2113
  if (done || !reset) return;
2066
2114
  done = true;
2067
2115
  clearTimeout(timer);
2116
+ signal?.removeEventListener("abort", onAbort);
2068
2117
  resolve(reset);
2069
2118
  queueMicrotask(release);
2070
2119
  });
2071
2120
  } catch (error) {
2072
2121
  done = true;
2073
2122
  clearTimeout(timer);
2123
+ signal?.removeEventListener("abort", onAbort);
2074
2124
  return reject(error);
2075
2125
  }
2076
2126
  if (done) release();
@@ -2082,6 +2132,8 @@ var Hosts = class {
2082
2132
  };
2083
2133
  // src/server/attachments.ts
2084
2134
  const MAX_FILE_BYTES = 8388608;
2135
+ /** Internal scope used for attachments staged while composing a brand-new session. */
2136
+ const DRAFT_AGENT_SCOPE = "__draft__";
2085
2137
  const MAX_TOTAL = 67108864;
2086
2138
  const TTL = 12e5;
2087
2139
  const IMAGE_TYPES = /* @__PURE__ */ new Set([
@@ -2206,6 +2258,18 @@ var Attachments = class {
2206
2258
  note: "Images require a vision-capable model. Other files are uploaded to the daemon for the agent to read with its tools."
2207
2259
  };
2208
2260
  }
2261
+ providerCapabilities(provider) {
2262
+ return {
2263
+ images: [
2264
+ "codex",
2265
+ "claude",
2266
+ "pi"
2267
+ ].includes(provider),
2268
+ files: true,
2269
+ maxBytes: MAX_FILE_BYTES,
2270
+ note: "Images require a vision-capable model. Other files are uploaded to the daemon for the agent to read with its tools."
2271
+ };
2272
+ }
2209
2273
  async prepare(hosts, owner, host, agent, ids) {
2210
2274
  const entries = ids.map((id) => this.get(id, owner, host, agent));
2211
2275
  if (!entries.length) return {
@@ -2215,6 +2279,17 @@ var Attachments = class {
2215
2279
  const caps = await this.capabilities(hosts, host, agent).catch(() => {
2216
2280
  throw new Error("Could not verify attachment support. Reconnect the host and retry.");
2217
2281
  });
2282
+ return this.materializeEntries(hosts, host, entries, caps);
2283
+ }
2284
+ async prepareForProvider(hosts, owner, host, provider, ids) {
2285
+ const entries = ids.map((id) => this.get(id, owner, host, DRAFT_AGENT_SCOPE));
2286
+ if (!entries.length) return {
2287
+ images: [],
2288
+ attachments: []
2289
+ };
2290
+ return this.materializeEntries(hosts, host, entries, this.providerCapabilities(provider));
2291
+ }
2292
+ async materializeEntries(hosts, host, entries, caps) {
2218
2293
  const images = [], attachments = [];
2219
2294
  for (const entry of entries) if (IMAGE_TYPES.has(entry.mime)) {
2220
2295
  if (!caps.images) throw new Error("This provider does not support image attachments.");
@@ -3691,15 +3766,14 @@ var Notifier = class {
3691
3766
  }
3692
3767
  async test(sessionId) {
3693
3768
  const subs = this.store.pushSubscriptions().filter((s) => s.sessionId === sessionId);
3694
- await Promise.all(subs.map((s) => this.deliver(s, {
3769
+ return (await Promise.all(subs.map((s) => this.deliver(s, {
3695
3770
  title: "LitePaseo notifications work",
3696
3771
  body: "You'll hear from your agents when they need you or finish a turn.",
3697
3772
  tag: "litepaseo-test",
3698
3773
  url: "/",
3699
3774
  kind: "test",
3700
3775
  badge: this.waiting.size
3701
- })));
3702
- return subs.length;
3776
+ })))).filter(Boolean).length;
3703
3777
  }
3704
3778
  /** The user dealt with a conversation (opened it, answered, or started a new turn): drop its news. */
3705
3779
  settle(previous, next) {
@@ -3860,18 +3934,20 @@ var Notifier = class {
3860
3934
  };
3861
3935
  }
3862
3936
  async deliver(subscription, message) {
3863
- if (this.closed) return;
3937
+ if (this.closed) return false;
3864
3938
  const session = this.store.sessionById(subscription.sessionId);
3865
3939
  if (!session || session.expires <= this.now()) {
3866
3940
  this.store.removePushSubscription(subscription.endpoint, subscription.sessionId);
3867
- return;
3941
+ return false;
3868
3942
  }
3869
3943
  try {
3870
3944
  await this.sender.send(subscription, JSON.stringify(message));
3945
+ return true;
3871
3946
  } catch (error) {
3872
- if (this.closed) return;
3947
+ if (this.closed) return false;
3873
3948
  const status = error.statusCode;
3874
3949
  if (status === 404 || status === 410) this.store.removePushSubscription(subscription.endpoint);
3950
+ return false;
3875
3951
  }
3876
3952
  }
3877
3953
  };
@@ -4097,7 +4173,7 @@ var ServerSendQueue = class {
4097
4173
  this.tick();
4098
4174
  }
4099
4175
  list(host, agent) {
4100
- return this.entries.filter((e) => e.host === host && e.agent === agent).map(({ prepared, ...entry }) => ({ ...entry }));
4176
+ return this.entries.filter((e) => e.host === host && e.agent === agent).map(({ prepared: _prepared, ...entry }) => ({ ...entry }));
4101
4177
  }
4102
4178
  pruneReceipts() {
4103
4179
  const now = Date.now();
@@ -4171,7 +4247,7 @@ var ServerSendQueue = class {
4171
4247
  seen.add(key);
4172
4248
  const a = this.hosts.agents.get(key);
4173
4249
  const client = this.hosts.clients.get(e.host);
4174
- if (!a || client?.driver.getConnectionState().status !== "connected") continue;
4250
+ if (!a || client?.driver.getConnectionState().status !== "connected" || client.directory?.synced === false) continue;
4175
4251
  if (!(a.turnActive === false || a.turnActive === void 0 && a.status !== "running" && a.status !== "initializing")) {
4176
4252
  this.stopAwaiting(key);
4177
4253
  continue;
@@ -4716,7 +4792,7 @@ function isLocalConnection(connection) {
4716
4792
  if (target.kind !== "socket") return false;
4717
4793
  if (target.socketPath) return true;
4718
4794
  const host = new URL(target.url ?? "").hostname.replace(/^\[|\]$/g, "");
4719
- return host === "localhost" || host === "::1" || /^127\./.test(host);
4795
+ return host === "localhost" || host === "::1" || host.startsWith("127.");
4720
4796
  } catch {
4721
4797
  return false;
4722
4798
  }
@@ -4804,6 +4880,8 @@ function registerDirectoryRoutes(app, { store, hosts, sendQueue, streamValidity,
4804
4880
  const streams = /* @__PURE__ */ new Set();
4805
4881
  let agentFlush;
4806
4882
  let hostFlush;
4883
+ let queueFlush;
4884
+ let queueVersion = 0;
4807
4885
  /** Set on shutdown: closing the hosts still reports changes, but the store is about to close. */
4808
4886
  let disposed = false;
4809
4887
  const hostStates = () => store.hosts().map((h) => ({
@@ -4876,11 +4954,39 @@ function registerDirectoryRoutes(app, { store, hosts, sendQueue, streamValidity,
4876
4954
  });
4877
4955
  stream.last = agents.seq;
4878
4956
  };
4957
+ const deliverQueue = (forceBroadcast = false) => {
4958
+ const summary = sendQueue.summary();
4959
+ const json = JSON.stringify(summary);
4960
+ let bumped = false;
4961
+ for (const stream of streams) {
4962
+ if (!forceBroadcast && stream.lastQueueJson === json) continue;
4963
+ if (!forceBroadcast && !bumped) {
4964
+ queueVersion++;
4965
+ bumped = true;
4966
+ }
4967
+ stream.lastQueueJson = json;
4968
+ stream.send({
4969
+ type: "queue-summary",
4970
+ version: queueVersion,
4971
+ summary
4972
+ });
4973
+ }
4974
+ };
4975
+ const scheduleQueueFlush = () => {
4976
+ queueVersion++;
4977
+ if (disposed || !streams.size || queueFlush) return;
4978
+ queueFlush = setTimeout(() => {
4979
+ queueFlush = void 0;
4980
+ deliverQueue(true);
4981
+ }, AGENT_FLUSH_MS);
4982
+ };
4983
+ const stopQueue = sendQueue.onChange(scheduleQueueFlush);
4879
4984
  const stopAgents = hosts.onAgentsChanged(() => {
4880
- if (disposed || agentFlush || !streams.size) return;
4881
- agentFlush = setTimeout(() => {
4985
+ if (disposed || !streams.size) return;
4986
+ if (!agentFlush) agentFlush = setTimeout(() => {
4882
4987
  agentFlush = void 0;
4883
4988
  for (const stream of streams) deliverAgents(stream);
4989
+ deliverQueue(false);
4884
4990
  }, AGENT_FLUSH_MS);
4885
4991
  });
4886
4992
  const stopHosts = hosts.onHostsChanged(() => {
@@ -4899,18 +5005,27 @@ function registerDirectoryRoutes(app, { store, hosts, sendQueue, streamValidity,
4899
5005
  const psince = Number(c.req.query("psince"));
4900
5006
  const presumable = c.req.query("pgeneration") === hosts.emptyProjects.generation && Number.isInteger(psince);
4901
5007
  return eventStream(c.req.raw.signal, (send) => {
5008
+ const initialQueue = sendQueue.summary();
5009
+ const initialQueueJson = JSON.stringify(initialQueue);
4902
5010
  const stream = {
4903
5011
  last: resumable ? since : -1,
4904
5012
  lastWorkspaces: wresumable ? wsince : -1,
4905
5013
  lastEmptyProjects: presumable ? psince : -1,
5014
+ lastQueueJson: initialQueueJson,
4906
5015
  send
4907
5016
  };
5017
+ const wantsQueue = c.req.query("queues") === "1";
4908
5018
  send(hostsMessage());
4909
5019
  send({
4910
5020
  type: "project-pins",
4911
5021
  pins: projectPins(store)
4912
5022
  });
4913
5023
  deliverAgents(stream);
5024
+ if (wantsQueue || Object.keys(initialQueue).length) send({
5025
+ type: "queue-summary",
5026
+ version: queueVersion,
5027
+ summary: initialQueue
5028
+ });
4914
5029
  streams.add(stream);
4915
5030
  return () => streams.delete(stream);
4916
5031
  }, streamValidity(c), encodingOf(c));
@@ -4990,7 +5105,9 @@ function registerDirectoryRoutes(app, { store, hosts, sendQueue, streamValidity,
4990
5105
  disposed = true;
4991
5106
  clearTimeout(agentFlush);
4992
5107
  clearTimeout(hostFlush);
4993
- agentFlush = hostFlush = void 0;
5108
+ clearTimeout(queueFlush);
5109
+ agentFlush = hostFlush = queueFlush = void 0;
5110
+ stopQueue();
4994
5111
  stopAgents();
4995
5112
  stopHosts();
4996
5113
  }
@@ -4998,7 +5115,7 @@ function registerDirectoryRoutes(app, { store, hosts, sendQueue, streamValidity,
4998
5115
  }
4999
5116
  // src/server/agent-routes.ts
5000
5117
  /** Starting sessions, the composer's model/mode/feature switches, and controlling an agent. */
5001
- function registerAgentRoutes(app, { hosts }) {
5118
+ function registerAgentRoutes(app, { store, hosts, attachments }) {
5002
5119
  /** Providers the host can start right now, read from the daemon's provider snapshot. */
5003
5120
  app.get("/api/hosts/:host/providers", async (c) => {
5004
5121
  const providers = (await hosts.get(c.req.param("host")).api.providers.snapshot()).entries.filter((entry) => entry.enabled !== false && entry.status !== "unavailable").map((entry) => ({
@@ -5068,15 +5185,32 @@ function registerAgentRoutes(app, { hosts }) {
5068
5185
  ]).optional(),
5069
5186
  workspaceId: z.string().trim().min(1).max(200).optional(),
5070
5187
  attachments: z.array(z.object({
5071
- id: z.string().max(200).optional(),
5072
- filename: z.string().min(1).max(300),
5188
+ type: z.literal("text"),
5073
5189
  mimeType: z.literal("text/plain"),
5190
+ contextKind: z.string().max(100).optional(),
5074
5191
  title: z.string().max(300).nullable().optional(),
5075
5192
  text: z.string().max(5e5)
5076
- })).max(5).optional()
5193
+ })).max(5).optional(),
5194
+ attachmentIds: z.array(z.string().uuid()).max(4).refine((ids) => new Set(ids).size === ids.length).optional(),
5195
+ clientMessageId: z.string().uuid().optional()
5077
5196
  }).parse(await c.req.json());
5078
5197
  const hostId = c.req.param("host");
5079
5198
  const { api, driver } = hosts.get(hostId);
5199
+ let prepared = {
5200
+ images: [],
5201
+ attachments: []
5202
+ };
5203
+ if (input.attachmentIds?.length) try {
5204
+ prepared = await attachments.prepareForProvider(hosts, attachmentOwner(c), hostId, input.provider, input.attachmentIds);
5205
+ } catch (error) {
5206
+ return c.json({
5207
+ error: errorMessage(error),
5208
+ delivery: "not-sent"
5209
+ }, 400);
5210
+ }
5211
+ const allAttachments = [...input.attachments ?? [], ...prepared.attachments];
5212
+ const hasInitialInput = !!input.prompt?.trim() || prepared.images.length > 0 || allAttachments.length > 0;
5213
+ const clientMessageId = input.clientMessageId ?? (hasInitialInput && prepared.images.length > 0 ? randomUUID() : void 0);
5080
5214
  try {
5081
5215
  let model = input.model;
5082
5216
  if (!model) {
@@ -5097,8 +5231,10 @@ function registerAgentRoutes(app, { hosts }) {
5097
5231
  ...input.featureValues ? { featureValues: input.featureValues } : {},
5098
5232
  ...input.modeId ? { modeId: input.modeId } : {},
5099
5233
  ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {},
5100
- ...input.prompt?.trim() ? { initialPrompt: input.prompt } : {},
5101
- ...input.attachments?.length ? { attachments: input.attachments } : {}
5234
+ ...hasInitialInput ? { initialPrompt: input.prompt ?? "" } : {},
5235
+ ...clientMessageId ? { clientMessageId } : {},
5236
+ ...prepared.images.length ? { images: prepared.images } : {},
5237
+ ...allAttachments.length ? { attachments: allAttachments } : {}
5102
5238
  }) : await api.agents.create({
5103
5239
  idempotencyKey: input.idempotencyKey,
5104
5240
  cwd: input.cwd,
@@ -5108,10 +5244,14 @@ function registerAgentRoutes(app, { hosts }) {
5108
5244
  ...input.modeId ? { modeId: input.modeId } : {},
5109
5245
  ...input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}
5110
5246
  },
5111
- ...input.prompt?.trim() ? { prompt: input.prompt } : {},
5112
- ...input.attachments?.length ? { attachments: input.attachments } : {},
5247
+ ...hasInitialInput ? { prompt: input.prompt ?? "" } : {},
5248
+ ...clientMessageId ? { clientMessageId } : {},
5249
+ ...prepared.images.length ? { images: prepared.images } : {},
5250
+ ...allAttachments.length ? { attachments: allAttachments } : {},
5113
5251
  ...worktree ? { worktree } : {}
5114
5252
  });
5253
+ if (clientMessageId && prepared.images.length) saveMessageImages(store, hostId, agent.id, clientMessageId, prepared.images);
5254
+ if (input.attachmentIds?.length) attachments.consumed(input.attachmentIds);
5115
5255
  return c.json({
5116
5256
  id: agent.id,
5117
5257
  key: `${hostId}:${agent.id}`
@@ -5404,7 +5544,7 @@ function registerTimelineRoutes(app, { store, hosts, streamValidity, encodingOf
5404
5544
  app.get("/api/hosts/:host/agents/:agent/timeline/latest", async (c) => {
5405
5545
  const hostId = c.req.param("host"), agentId = c.req.param("agent");
5406
5546
  try {
5407
- const reset = await hosts.timelineSnapshot(hostId, agentId);
5547
+ const reset = await hosts.timelineSnapshot(hostId, agentId, void 0, c.req.raw.signal);
5408
5548
  return c.json({
5409
5549
  ...reset,
5410
5550
  rows: reset.rows.map(enrichRow(hostId, agentId))
@@ -5414,14 +5554,19 @@ function registerTimelineRoutes(app, { store, hosts, streamValidity, encodingOf
5414
5554
  throw error;
5415
5555
  }
5416
5556
  });
5417
- app.get("/api/hosts/:host/agents/:agent/timeline/stream", (c) => {
5418
- const hostId = c.req.param("host"), agentId = c.req.param("agent");
5419
- hosts.get(hostId);
5420
- const since = z.object({
5557
+ const parseResume = (query) => {
5558
+ const parsed = z.object({
5421
5559
  epoch: z.string().min(1).max(200),
5560
+ view: z.string().min(1).max(200).optional(),
5422
5561
  seq: z.coerce.number().int().nonnegative(),
5423
5562
  from: z.coerce.number().int().nonnegative()
5424
- }).safeParse(c.req.query());
5563
+ }).safeParse(query);
5564
+ return parsed.success ? parsed.data : void 0;
5565
+ };
5566
+ app.get("/api/hosts/:host/agents/:agent/timeline/stream", (c) => {
5567
+ const hostId = c.req.param("host"), agentId = c.req.param("agent");
5568
+ hosts.get(hostId);
5569
+ const since = parseResume(c.req.query());
5425
5570
  const enrich = enrichRow(hostId, agentId);
5426
5571
  return eventStream(c.req.raw.signal, (send) => {
5427
5572
  const stop = hosts.watchTimeline(hostId, agentId, (ops) => send({
@@ -5433,7 +5578,7 @@ function registerTimelineRoutes(app, { store, hosts, streamValidity, encodingOf
5433
5578
  ...op,
5434
5579
  row: enrich(op.row)
5435
5580
  } : op)
5436
- }), void 0, since.success ? since.data : void 0);
5581
+ }), void 0, since);
5437
5582
  let sent = "";
5438
5583
  let stopSubagents = () => {};
5439
5584
  try {
@@ -5513,10 +5658,11 @@ function registerTimelineRoutes(app, { store, hosts, streamValidity, encodingOf
5513
5658
  });
5514
5659
  app.get("/api/hosts/:host/agents/:agent/subagents/:subagent/timeline/stream", (c) => {
5515
5660
  hosts.get(c.req.param("host"));
5661
+ const since = parseResume(c.req.query());
5516
5662
  return eventStream(c.req.raw.signal, (send) => hosts.watchTimeline(c.req.param("host"), c.req.param("agent"), (ops) => send({
5517
5663
  type: "ops",
5518
5664
  ops
5519
- }), c.req.param("subagent")), streamValidity(c), encodingOf(c));
5665
+ }), c.req.param("subagent"), since), streamValidity(c), encodingOf(c));
5520
5666
  });
5521
5667
  app.get("/api/hosts/:host/agents/:agent/subagents/:subagent/timeline", async (c) => {
5522
5668
  const cursor = pageCursor.parse(parseJson(c.req.query("cursor")));
@@ -5708,6 +5854,29 @@ function registerMessageRoutes(app, { store, hosts, attachments, sendQueue, stre
5708
5854
  }
5709
5855
  return c.json({ ok: true });
5710
5856
  });
5857
+ app.get("/api/hosts/:host/draft/:provider/attachments/capabilities", (c) => {
5858
+ hosts.get(c.req.param("host"));
5859
+ return c.json(attachments.providerCapabilities(c.req.param("provider")));
5860
+ });
5861
+ app.post("/api/hosts/:host/draft/:provider/attachments", async (c) => {
5862
+ const host = c.req.param("host");
5863
+ hosts.get(host);
5864
+ try {
5865
+ const name = decodeURIComponent(c.req.header("x-file-name") ?? "");
5866
+ const mime = c.req.header("content-type")?.split(";")[0].trim().toLowerCase() || "application/octet-stream";
5867
+ return c.json(attachments.put(attachmentOwner(c), host, DRAFT_AGENT_SCOPE, name, mime, Buffer.from(await c.req.arrayBuffer())), 201);
5868
+ } catch (error) {
5869
+ return c.json({ error: errorMessage(error) }, 400);
5870
+ }
5871
+ });
5872
+ app.delete("/api/hosts/:host/draft/:provider/attachments/:id", (c) => {
5873
+ try {
5874
+ attachments.remove(c.req.param("id"), attachmentOwner(c), c.req.param("host"), DRAFT_AGENT_SCOPE);
5875
+ } catch {
5876
+ return c.json({ error: "Attachment already expired or unavailable" }, 404);
5877
+ }
5878
+ return c.json({ ok: true });
5879
+ });
5711
5880
  /** Runs a queue operation; its refusal (being sent, gone, …) is a 409 with the reason. */
5712
5881
  const queueOp = async (c, op) => {
5713
5882
  try {
@@ -5718,10 +5887,27 @@ function registerMessageRoutes(app, { store, hosts, attachments, sendQueue, stre
5718
5887
  return c.json({ ok: true });
5719
5888
  };
5720
5889
  app.get("/api/queue/stream", (c) => eventStream(c.req.raw.signal, (send) => {
5721
- const publish = () => send(sendQueue.summary());
5722
- const stop = sendQueue.onChange(publish), stopHosts = hosts.onAgentsChanged(publish);
5723
- publish();
5890
+ let lastJson = "";
5891
+ let timer;
5892
+ const emitNow = (force = false) => {
5893
+ const summary = sendQueue.summary();
5894
+ const json = JSON.stringify(summary);
5895
+ if (!force && json === lastJson) return;
5896
+ lastJson = json;
5897
+ send(summary);
5898
+ };
5899
+ const schedule = () => {
5900
+ if (timer) return;
5901
+ timer = setTimeout(() => {
5902
+ timer = void 0;
5903
+ emitNow();
5904
+ }, 50);
5905
+ timer.unref?.();
5906
+ };
5907
+ const stop = sendQueue.onChange(() => emitNow()), stopHosts = hosts.onAgentsChanged(schedule);
5908
+ emitNow(true);
5724
5909
  return () => {
5910
+ clearTimeout(timer);
5725
5911
  stop();
5726
5912
  stopHosts();
5727
5913
  };
@@ -6280,36 +6466,47 @@ function registerProjectRoutes(app, { hosts, fetch }) {
6280
6466
  const { driver } = hosts.get(hostId);
6281
6467
  if (typeof driver.fetchAgentHistory !== "function") return c.json([]);
6282
6468
  try {
6283
- const res = await driver.fetchAgentHistory({
6284
- filter: { includeArchived: true },
6285
- ...q?.trim() ? { search: q.trim() } : {},
6286
- sort: [{
6287
- key: "updated_at",
6288
- direction: "desc"
6289
- }],
6290
- page: { limit: 100 }
6291
- });
6292
6469
  const seen = /* @__PURE__ */ new Set();
6293
6470
  const out = [];
6294
- for (const entry of res.entries ?? []) {
6295
- const agent = entry.agent;
6296
- if (!agent?.archivedAt) continue;
6297
- const dedupeKey = agent.workspaceId || agent.id;
6298
- if (seen.has(dedupeKey)) continue;
6299
- seen.add(dedupeKey);
6300
- const project = entry.project?.projectName || agent.cwd.replace(/\/+$/, "").split("/").pop() || agent.cwd;
6301
- out.push({
6302
- hostId,
6303
- id: agent.id,
6304
- workspaceId: agent.workspaceId ?? null,
6305
- name: agent.title || project,
6306
- project,
6307
- cwd: agent.cwd,
6308
- branch: null,
6309
- archivedAt: agent.archivedAt,
6310
- provider: agent.provider,
6311
- status: agent.status
6471
+ let cursor;
6472
+ for (let pageIndex = 0; pageIndex < 10 && out.length < 100; pageIndex++) {
6473
+ const res = await driver.fetchAgentHistory({
6474
+ filter: { includeArchived: true },
6475
+ ...q?.trim() ? { search: q.trim() } : {},
6476
+ sort: [{
6477
+ key: "updated_at",
6478
+ direction: "desc"
6479
+ }],
6480
+ page: {
6481
+ limit: 100,
6482
+ ...cursor ? { cursor } : {}
6483
+ }
6312
6484
  });
6485
+ const entries = res.entries ?? [];
6486
+ for (const entry of entries) {
6487
+ const agent = entry.agent;
6488
+ if (!agent?.archivedAt) continue;
6489
+ const dedupeKey = agent.workspaceId || agent.id;
6490
+ if (seen.has(dedupeKey)) continue;
6491
+ seen.add(dedupeKey);
6492
+ const project = entry.project?.projectName || agent.cwd.replace(/\/+$/, "").split("/").pop() || agent.cwd;
6493
+ out.push({
6494
+ hostId,
6495
+ id: agent.id,
6496
+ workspaceId: agent.workspaceId ?? null,
6497
+ name: agent.title || project,
6498
+ project,
6499
+ cwd: agent.cwd,
6500
+ branch: null,
6501
+ archivedAt: agent.archivedAt,
6502
+ provider: agent.provider,
6503
+ status: agent.status
6504
+ });
6505
+ if (out.length >= 100) break;
6506
+ }
6507
+ const pageInfo = res.pageInfo;
6508
+ if (!pageInfo?.hasMore || !pageInfo.nextCursor || pageInfo.nextCursor === cursor) break;
6509
+ cursor = pageInfo.nextCursor;
6313
6510
  }
6314
6511
  return c.json(out);
6315
6512
  } catch (error) {
@@ -6654,11 +6851,14 @@ async function generateNextSuggestion(config, messages, fetchImpl = fetch) {
6654
6851
  var NextSuggestionCache = class {
6655
6852
  results = /* @__PURE__ */ new Map();
6656
6853
  inflight = /* @__PURE__ */ new Map();
6854
+ generation = 0;
6657
6855
  getOrRun(key, fn) {
6658
6856
  if (this.results.has(key)) return Promise.resolve(this.results.get(key));
6659
6857
  const existing = this.inflight.get(key);
6660
6858
  if (existing) return existing;
6859
+ const gen = this.generation;
6661
6860
  const promise = fn().then((text) => {
6861
+ if (gen !== this.generation) return text;
6662
6862
  if (this.results.size >= MAX_CACHE_ENTRIES) {
6663
6863
  const oldest = this.results.keys().next().value;
6664
6864
  if (oldest !== void 0) this.results.delete(oldest);
@@ -6666,13 +6866,15 @@ var NextSuggestionCache = class {
6666
6866
  this.results.set(key, text);
6667
6867
  return text;
6668
6868
  }).finally(() => {
6669
- this.inflight.delete(key);
6869
+ if (gen === this.generation && this.inflight.get(key) === promise) this.inflight.delete(key);
6670
6870
  });
6671
6871
  this.inflight.set(key, promise);
6672
6872
  return promise;
6673
6873
  }
6674
6874
  clear() {
6875
+ this.generation++;
6675
6876
  this.results.clear();
6877
+ this.inflight.clear();
6676
6878
  }
6677
6879
  };
6678
6880
  // src/server/suggestion-routes.ts
@@ -7114,6 +7316,7 @@ function registerWorkspaceRoutes(app, { hosts, store, streamValidity, encodingOf
7114
7316
  return c.json({ error: errorMessage(error, "Directory unavailable") }, 404);
7115
7317
  }
7116
7318
  });
7319
+ const isTooLarge = (error) => /too large|maxBytes|exceeds/i.test(error instanceof Error ? error.message : String(error ?? ""));
7117
7320
  app.get("/api/hosts/:host/fs/read", async (c) => {
7118
7321
  const cwd = hostPath.parse(c.req.query("cwd"));
7119
7322
  const file = hostPath.parse(c.req.query("path"));
@@ -7133,6 +7336,7 @@ function registerWorkspaceRoutes(app, { hosts, store, streamValidity, encodingOf
7133
7336
  } : {}
7134
7337
  });
7135
7338
  } catch (error) {
7339
+ if (isTooLarge(error)) return c.json({ error: "File is too large to preview" }, 413);
7136
7340
  return c.json({ error: errorMessage(error, "File unavailable") }, 404);
7137
7341
  }
7138
7342
  });
@@ -7144,14 +7348,16 @@ function registerWorkspaceRoutes(app, { hosts, store, streamValidity, encodingOf
7144
7348
  const result = await driver.readFile(cwd, file, void 0, 33554433);
7145
7349
  if (result.size > MAX_DOWNLOAD_BYTES) return c.json({ error: "File exceeds 32 MB download limit" }, 413);
7146
7350
  const rawName = (result.path.split("/").pop() || "download").replace(/[\r\n"\\]/g, "_");
7351
+ const asciiName = rawName.replace(/[^\x20-\x7e]/g, "_") || "download";
7147
7352
  const encoded = encodeURIComponent(rawName);
7148
7353
  return c.body(result.bytes, 200, {
7149
7354
  "Content-Type": result.mime || "application/octet-stream",
7150
- "Content-Disposition": `attachment; filename="${rawName}"; filename*=UTF-8''${encoded}`,
7355
+ "Content-Disposition": `attachment; filename="${asciiName}"; filename*=UTF-8''${encoded}`,
7151
7356
  "X-Content-Type-Options": "nosniff",
7152
7357
  "Cache-Control": "private, no-store"
7153
7358
  });
7154
7359
  } catch (error) {
7360
+ if (isTooLarge(error)) return c.json({ error: "File exceeds 32 MB download limit" }, 413);
7155
7361
  return c.json({ error: errorMessage(error, "File unavailable") }, 404);
7156
7362
  }
7157
7363
  });
@@ -7259,20 +7465,28 @@ function registerWorkspaceRoutes(app, { hosts, store, streamValidity, encodingOf
7259
7465
  } else if (event.replay.type === "data") push(event.replay.data);
7260
7466
  }, { restore: {
7261
7467
  mode: "full-snapshot",
7262
- scrollbackLines: 2e3,
7468
+ scrollbackLines: 5e3,
7263
7469
  size: {
7264
7470
  rows,
7265
7471
  cols
7266
7472
  }
7267
7473
  } });
7474
+ let exited = false;
7475
+ const finishExit = () => {
7476
+ if (exited) return;
7477
+ exited = true;
7478
+ clearTimeout(timer);
7479
+ flush();
7480
+ send({ t: "exit" });
7481
+ };
7268
7482
  const stop = subscription.subscribe({
7269
7483
  snapshot: () => {},
7270
7484
  update: (message) => {
7271
- if (message.type === "terminal_stream_exit") send({ t: "exit" });
7485
+ if (message.type === "terminal_stream_exit") finishExit();
7272
7486
  },
7273
- error: () => send({ t: "exit" })
7487
+ error: finishExit
7274
7488
  });
7275
- subscription.ready.catch(() => send({ t: "exit" }));
7489
+ subscription.ready.catch(finishExit);
7276
7490
  return () => {
7277
7491
  clearTimeout(timer);
7278
7492
  stop();
@@ -7451,7 +7665,10 @@ function createApp(store, hosts, token, webRoot, options = {}) {
7451
7665
  c.header("Content-Security-Policy", `default-src 'self'; script-src ${scriptSrc}; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self'; manifest-src 'self'; frame-ancestors 'none'`);
7452
7666
  });
7453
7667
  app.use("/api/*", compressJson(compression));
7454
- app.use("/api/*", (c, next) => bodyLimit({ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path === "/api/dictation/transcribe" ? MAX_DICTATION_BYTES : 1048576 })(c, next));
7668
+ app.use("/api/*", (c, next) => bodyLimit({
7669
+ maxSize: c.req.method !== "POST" ? 1048576 : c.req.path.endsWith("/attachments") ? MAX_FILE_BYTES : c.req.path === "/api/dictation/transcribe" ? MAX_DICTATION_BYTES : 1048576,
7670
+ onError: (ctx) => ctx.json({ error: "Request body too large" }, 413)
7671
+ })(c, next));
7455
7672
  app.use("/api/*", apiAuth(auth));
7456
7673
  app.onError((error, c) => {
7457
7674
  if (error instanceof UnknownHostError) return c.json({ error: "Unknown host" }, 404);
@@ -7460,6 +7677,7 @@ function createApp(store, hosts, token, webRoot, options = {}) {
7460
7677
  detail: error.issues
7461
7678
  }, 400);
7462
7679
  if (error instanceof HttpError) return c.json({ error: error.message }, error.status);
7680
+ if (error instanceof HTTPException) return c.json({ error: error.message || "Request failed" }, error.status);
7463
7681
  const requestId = randomUUID();
7464
7682
  const failure = error;
7465
7683
  const cause = failure.cause instanceof Error ? failure.cause : null;