@moberg_hr/work-tree 2.0.11 → 2.0.13

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 (113) hide show
  1. package/dist/{answer-6UVHVEGQ.js → answer-IL5AQHRO.js} +4 -4
  2. package/dist/{attach-6Q6HGPCM.js → attach-MFU4KN47.js} +7 -7
  3. package/dist/bin.js +2 -2
  4. package/dist/{block-46DPS75I.js → block-OXGEQ2PZ.js} +4 -4
  5. package/dist/{broadcast-OGOEQX4Z.js → broadcast-UJURJNEK.js} +2 -2
  6. package/dist/{catchup-TTAC3GMX.js → catchup-HN4VL5XK.js} +4 -4
  7. package/dist/chunk-4KNBN2OF.js +9 -0
  8. package/dist/{chunk-4PP27RI7.js → chunk-7GQCPGKQ.js} +4 -4
  9. package/dist/{chunk-UAAH334K.js → chunk-7JPCVEOY.js} +35 -4
  10. package/dist/chunk-7JPCVEOY.js.map +1 -0
  11. package/dist/{chunk-Y6VPABC3.js → chunk-BSFL3WDR.js} +32 -31
  12. package/dist/chunk-BSFL3WDR.js.map +1 -0
  13. package/dist/{chunk-7HGABVGR.js → chunk-E3Y4ZACK.js} +18 -1
  14. package/dist/chunk-E3Y4ZACK.js.map +1 -0
  15. package/dist/{chunk-WG3BMHKU.js → chunk-EU3BS5A6.js} +2 -2
  16. package/dist/{chunk-AFV5S6UV.js → chunk-F375JY4M.js} +3 -3
  17. package/dist/{chunk-D4FUDMMX.js → chunk-FX4IA5U4.js} +3 -3
  18. package/dist/{chunk-HBXDIRM4.js → chunk-KSIXTTO6.js} +3 -3
  19. package/dist/{chunk-RMICESXA.js → chunk-KUWFGPGW.js} +6 -6
  20. package/dist/{chunk-ACXPSQJR.js → chunk-MI3PS2SH.js} +18 -1
  21. package/dist/{chunk-ACXPSQJR.js.map → chunk-MI3PS2SH.js.map} +1 -1
  22. package/dist/{chunk-AVRDRZ4D.js → chunk-OZIR2255.js} +62 -8
  23. package/dist/chunk-OZIR2255.js.map +1 -0
  24. package/dist/{chunk-RG63ACAK.js → chunk-PVN5IGDZ.js} +11 -10
  25. package/dist/chunk-PVN5IGDZ.js.map +1 -0
  26. package/dist/chunk-TNJF7T33.js +17 -0
  27. package/dist/chunk-TNJF7T33.js.map +1 -0
  28. package/dist/{chunk-SRIYY5HL.js → chunk-U4UB4LG6.js} +2 -2
  29. package/dist/{cleanup-OO3DCPGC.js → cleanup-LRT6J36R.js} +10 -10
  30. package/dist/{cli-I6N4U4GN.js → cli-VGUJI5WG.js} +3 -3
  31. package/dist/{fork-WTNAUILU.js → fork-RJ3ZPPWT.js} +8 -8
  32. package/dist/{hook-OTPVWY52.js → hook-CA5X3VKU.js} +3 -3
  33. package/dist/{move-CE5NIZKL.js → move-OLXCDNA3.js} +2 -2
  34. package/dist/{note-2JHWK6CV.js → note-JOR53JP4.js} +4 -4
  35. package/dist/{pin-UOW5VW42.js → pin-DAWKCVB2.js} +4 -4
  36. package/dist/{pr-74X5MOPX.js → pr-RKOVRSHC.js} +3 -3
  37. package/dist/{prune-L3VXZUIE.js → prune-UYCQOEUF.js} +9 -9
  38. package/dist/{pty-host-5Z3GYXTW.js → pty-host-X3QK2LSK.js} +115 -14
  39. package/dist/pty-host-X3QK2LSK.js.map +1 -0
  40. package/dist/{read-G7CVQRH6.js → read-IKDSIDJD.js} +4 -4
  41. package/dist/{remove-NVQ2JNMA.js → remove-6XACPXUU.js} +8 -8
  42. package/dist/restart-6ZAFDRBO.js +70 -0
  43. package/dist/restart-6ZAFDRBO.js.map +1 -0
  44. package/dist/{screen-XSBZHJNW.js → screen-KUXSDDLB.js} +4 -4
  45. package/dist/{section-BWZW3E2I.js → section-QLUIAYAV.js} +4 -4
  46. package/dist/{send-4E7CD6PL.js → send-V6LL6YR6.js} +4 -4
  47. package/dist/{sessions-4LFKWTBZ.js → sessions-MKXREA2M.js} +7 -7
  48. package/dist/{snooze-SSSA656T.js → snooze-JXI7VZJ4.js} +4 -4
  49. package/dist/{start-5LODG4WG.js → start-5XFUYT6I.js} +4 -4
  50. package/dist/{stop-OFQFHRXD.js → stop-PFI7J2CS.js} +4 -4
  51. package/dist/{sync-FDXM5EFD.js → sync-MSU7QJWN.js} +9 -9
  52. package/dist/{time-IIAXBSE7.js → time-VDRCEIYQ.js} +4 -4
  53. package/dist/{tree-7S4DUZRZ.js → tree-MOIO4GQL.js} +5 -5
  54. package/dist/{update-7ZE4CG7T.js → update-DXIY6BEX.js} +4 -4
  55. package/dist/{wait-TGQLNTE7.js → wait-KPH5BQUD.js} +4 -4
  56. package/dist/wd-bin.js +2 -2
  57. package/dist/web/assets/{PtyView-CAaXDb9_.js → PtyView-D1TEpjVE.js} +2 -2
  58. package/dist/web/assets/{PtyView-CAaXDb9_.js.map → PtyView-D1TEpjVE.js.map} +1 -1
  59. package/dist/web/assets/index-BVeughC2.css +1 -0
  60. package/dist/web/assets/index-DoMf82kx.js +118 -0
  61. package/dist/web/assets/index-DoMf82kx.js.map +1 -0
  62. package/dist/web/index.html +2 -2
  63. package/dist/{web-NFKTIH4M.js → web-6AOR3MIE.js} +490 -144
  64. package/dist/web-6AOR3MIE.js.map +1 -0
  65. package/npm-shrinkwrap.json +2 -2
  66. package/package.json +1 -1
  67. package/dist/chunk-7HGABVGR.js.map +0 -1
  68. package/dist/chunk-AVRDRZ4D.js.map +0 -1
  69. package/dist/chunk-RG63ACAK.js.map +0 -1
  70. package/dist/chunk-UAAH334K.js.map +0 -1
  71. package/dist/chunk-W5B4NLBI.js +0 -9
  72. package/dist/chunk-Y6VPABC3.js.map +0 -1
  73. package/dist/pty-host-5Z3GYXTW.js.map +0 -1
  74. package/dist/web/assets/index-3r-glBYq.js +0 -118
  75. package/dist/web/assets/index-3r-glBYq.js.map +0 -1
  76. package/dist/web/assets/index-Dk0Q1Qib.css +0 -1
  77. package/dist/web-NFKTIH4M.js.map +0 -1
  78. /package/dist/{answer-6UVHVEGQ.js.map → answer-IL5AQHRO.js.map} +0 -0
  79. /package/dist/{attach-6Q6HGPCM.js.map → attach-MFU4KN47.js.map} +0 -0
  80. /package/dist/{block-46DPS75I.js.map → block-OXGEQ2PZ.js.map} +0 -0
  81. /package/dist/{broadcast-OGOEQX4Z.js.map → broadcast-UJURJNEK.js.map} +0 -0
  82. /package/dist/{catchup-TTAC3GMX.js.map → catchup-HN4VL5XK.js.map} +0 -0
  83. /package/dist/{chunk-W5B4NLBI.js.map → chunk-4KNBN2OF.js.map} +0 -0
  84. /package/dist/{chunk-4PP27RI7.js.map → chunk-7GQCPGKQ.js.map} +0 -0
  85. /package/dist/{chunk-WG3BMHKU.js.map → chunk-EU3BS5A6.js.map} +0 -0
  86. /package/dist/{chunk-AFV5S6UV.js.map → chunk-F375JY4M.js.map} +0 -0
  87. /package/dist/{chunk-D4FUDMMX.js.map → chunk-FX4IA5U4.js.map} +0 -0
  88. /package/dist/{chunk-HBXDIRM4.js.map → chunk-KSIXTTO6.js.map} +0 -0
  89. /package/dist/{chunk-RMICESXA.js.map → chunk-KUWFGPGW.js.map} +0 -0
  90. /package/dist/{chunk-SRIYY5HL.js.map → chunk-U4UB4LG6.js.map} +0 -0
  91. /package/dist/{cleanup-OO3DCPGC.js.map → cleanup-LRT6J36R.js.map} +0 -0
  92. /package/dist/{cli-I6N4U4GN.js.map → cli-VGUJI5WG.js.map} +0 -0
  93. /package/dist/{fork-WTNAUILU.js.map → fork-RJ3ZPPWT.js.map} +0 -0
  94. /package/dist/{hook-OTPVWY52.js.map → hook-CA5X3VKU.js.map} +0 -0
  95. /package/dist/{move-CE5NIZKL.js.map → move-OLXCDNA3.js.map} +0 -0
  96. /package/dist/{note-2JHWK6CV.js.map → note-JOR53JP4.js.map} +0 -0
  97. /package/dist/{pin-UOW5VW42.js.map → pin-DAWKCVB2.js.map} +0 -0
  98. /package/dist/{pr-74X5MOPX.js.map → pr-RKOVRSHC.js.map} +0 -0
  99. /package/dist/{prune-L3VXZUIE.js.map → prune-UYCQOEUF.js.map} +0 -0
  100. /package/dist/{read-G7CVQRH6.js.map → read-IKDSIDJD.js.map} +0 -0
  101. /package/dist/{remove-NVQ2JNMA.js.map → remove-6XACPXUU.js.map} +0 -0
  102. /package/dist/{screen-XSBZHJNW.js.map → screen-KUXSDDLB.js.map} +0 -0
  103. /package/dist/{section-BWZW3E2I.js.map → section-QLUIAYAV.js.map} +0 -0
  104. /package/dist/{send-4E7CD6PL.js.map → send-V6LL6YR6.js.map} +0 -0
  105. /package/dist/{sessions-4LFKWTBZ.js.map → sessions-MKXREA2M.js.map} +0 -0
  106. /package/dist/{snooze-SSSA656T.js.map → snooze-JXI7VZJ4.js.map} +0 -0
  107. /package/dist/{start-5LODG4WG.js.map → start-5XFUYT6I.js.map} +0 -0
  108. /package/dist/{stop-OFQFHRXD.js.map → stop-PFI7J2CS.js.map} +0 -0
  109. /package/dist/{sync-FDXM5EFD.js.map → sync-MSU7QJWN.js.map} +0 -0
  110. /package/dist/{time-IIAXBSE7.js.map → time-VDRCEIYQ.js.map} +0 -0
  111. /package/dist/{tree-7S4DUZRZ.js.map → tree-MOIO4GQL.js.map} +0 -0
  112. /package/dist/{update-7ZE4CG7T.js.map → update-DXIY6BEX.js.map} +0 -0
  113. /package/dist/{wait-TGQLNTE7.js.map → wait-KPH5BQUD.js.map} +0 -0
@@ -20,6 +20,20 @@ import {
20
20
  sessionBaseForPath,
21
21
  submitReviewSchema
22
22
  } from "./chunk-B2RCWZUW.js";
23
+ import {
24
+ announceChange,
25
+ createArchivedRows,
26
+ linkedComments,
27
+ linkedSession,
28
+ prStageWire,
29
+ readContextUsage,
30
+ reviewThreadsOf,
31
+ scopeLinkedStoreIds,
32
+ sessionLinkedStoreIds,
33
+ sessionWire,
34
+ stageSeenKey,
35
+ storeHolding
36
+ } from "./chunk-OZIR2255.js";
23
37
  import {
24
38
  createDigestSource
25
39
  } from "./chunk-PUYXTZ32.js";
@@ -31,7 +45,12 @@ import {
31
45
  deleteMergedBranches,
32
46
  findMergedBranches,
33
47
  summarizeAgents
34
- } from "./chunk-D4FUDMMX.js";
48
+ } from "./chunk-FX4IA5U4.js";
49
+ import {
50
+ DiffStatCache,
51
+ findOverlaps,
52
+ wantsDiffStat
53
+ } from "./chunk-YJVZ5H3I.js";
35
54
  import {
36
55
  defaultTimeDeps,
37
56
  fetchIssueDetail,
@@ -47,20 +66,11 @@ import {
47
66
  } from "./chunk-M7AUWYOP.js";
48
67
  import {
49
68
  defaultCleanupDeps
50
- } from "./chunk-AFV5S6UV.js";
51
- import {
52
- createArchivedRows,
53
- prStageWire,
54
- readContextUsage,
55
- reviewThreadsOf,
56
- sessionWire,
57
- stageSeenKey
58
- } from "./chunk-AVRDRZ4D.js";
69
+ } from "./chunk-F375JY4M.js";
59
70
  import {
60
- DiffStatCache,
61
- findOverlaps,
62
- wantsDiffStat
63
- } from "./chunk-YJVZ5H3I.js";
71
+ LATER_TEXT,
72
+ restartCountsText
73
+ } from "./chunk-TNJF7T33.js";
64
74
  import {
65
75
  MAX_NOTE_CHARS,
66
76
  readNote,
@@ -112,7 +122,11 @@ import {
112
122
  archiveMergedSession,
113
123
  archiveWaiting,
114
124
  defaultArchiveDeps
115
- } from "./chunk-RMICESXA.js";
125
+ } from "./chunk-KUWFGPGW.js";
126
+ import {
127
+ cleanupVerdict,
128
+ createCleanupJob
129
+ } from "./chunk-AKMPF72Y.js";
116
130
  import {
117
131
  MAX_REPLY_CHARS,
118
132
  THREAD_ID,
@@ -124,15 +138,11 @@ import {
124
138
  rememberSent,
125
139
  saveDraft
126
140
  } from "./chunk-26IZBYVL.js";
127
- import {
128
- cleanupVerdict,
129
- createCleanupJob
130
- } from "./chunk-AKMPF72Y.js";
131
141
  import {
132
142
  defaultForkDeps,
133
143
  forkSession,
134
144
  startSessionWithPrompt
135
- } from "./chunk-4PP27RI7.js";
145
+ } from "./chunk-7GQCPGKQ.js";
136
146
  import {
137
147
  createInChild,
138
148
  createInProcess,
@@ -163,18 +173,21 @@ import {
163
173
  listHostPtys,
164
174
  outputStatus,
165
175
  peekPty,
176
+ ptyLastOutputMs,
177
+ ptyPid,
166
178
  ptyPids,
167
179
  readPtyScreen,
180
+ restartPty,
168
181
  resumePersistedSessions,
169
182
  spawnSpecFor,
170
183
  subscribeSession,
171
184
  syncPtyPool,
172
185
  writeToPty
173
- } from "./chunk-UAAH334K.js";
186
+ } from "./chunk-7JPCVEOY.js";
174
187
  import {
175
188
  dbPtySessions
176
- } from "./chunk-SRIYY5HL.js";
177
- import "./chunk-ACXPSQJR.js";
189
+ } from "./chunk-U4UB4LG6.js";
190
+ import "./chunk-MI3PS2SH.js";
178
191
  import {
179
192
  BehindCache,
180
193
  behindMain,
@@ -226,7 +239,7 @@ import {
226
239
  } from "./chunk-LNHSBM4L.js";
227
240
  import {
228
241
  VERSION
229
- } from "./chunk-W5B4NLBI.js";
242
+ } from "./chunk-4KNBN2OF.js";
230
243
  import {
231
244
  resolveProjectTarget
232
245
  } from "./chunk-JTHILJFB.js";
@@ -272,12 +285,13 @@ import {
272
285
  import {
273
286
  NOTE_NUDGE,
274
287
  findSessionForCwd,
275
- readPendingForSession
276
- } from "./chunk-RG63ACAK.js";
288
+ readPendingForSession,
289
+ readPendingForWorktree
290
+ } from "./chunk-PVN5IGDZ.js";
277
291
  import "./chunk-ZSHWP2VS.js";
278
292
  import {
279
293
  getCommentFileStore
280
- } from "./chunk-7HGABVGR.js";
294
+ } from "./chunk-E3Y4ZACK.js";
281
295
  import {
282
296
  createCommentStore
283
297
  } from "./chunk-HUXS3VAI.js";
@@ -417,7 +431,7 @@ import {
417
431
  import chalk from "chalk";
418
432
 
419
433
  // src/server/web-server.ts
420
- import fs10 from "fs";
434
+ import fs12 from "fs";
421
435
 
422
436
  // src/server/routes/session-control-routes.ts
423
437
  function realDeps(app) {
@@ -801,22 +815,71 @@ function mountNoteRoutes(app, opts) {
801
815
  });
802
816
  }
803
817
 
804
- // src/core/diff/diff-seen.ts
805
- function isSeen(v) {
818
+ // src/core/diff/diff-looks.ts
819
+ var LOOK_JOIN_MS = 15 * 6e4;
820
+ var MAX_LOOKS = 20;
821
+ var isTime = (v) => typeof v === "string" && Number.isFinite(Date.parse(v));
822
+ var isTurn = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
823
+ function isLook(v) {
824
+ const o = v;
825
+ return !!o && typeof o === "object" && isTurn(o.from) && isTurn(o.to) && o.to > o.from && isTime(o.startedAt) && isTime(o.at) && (o.fromTs === void 0 || isTime(o.fromTs)) && (o.toTs === void 0 || isTime(o.toTs));
826
+ }
827
+ function cleanSeen(v) {
806
828
  const o = v;
807
- return !!o && typeof o === "object" && typeof o.checkpointId === "number" && typeof o.at === "string";
829
+ if (!o || typeof o !== "object" || !isTurn(o.checkpointId) || !isTime(o.at)) return null;
830
+ const looks = Array.isArray(o.looks) ? o.looks.filter(isLook) : [];
831
+ return {
832
+ checkpointId: o.checkpointId,
833
+ at: o.at,
834
+ ...isTime(o.ts) ? { ts: o.ts } : {},
835
+ ...looks.length ? { looks } : {}
836
+ };
808
837
  }
838
+ function rebaselined(old, checkpointId, ts, marked) {
839
+ if (marked && old.ts && marked.checkpointId === old.checkpointId && marked.ts !== old.ts) return true;
840
+ return checkpointId <= old.checkpointId && !!ts && !!old.ts && Date.parse(ts) > Date.parse(old.ts);
841
+ }
842
+ function markedTurn(v) {
843
+ const o = v;
844
+ if (!o || typeof o !== "object" || !isTurn(o.checkpointId)) return void 0;
845
+ if (o.ts !== null && !isTime(o.ts)) return void 0;
846
+ return { checkpointId: o.checkpointId, ts: o.ts };
847
+ }
848
+ function nextSeen(old, checkpointId, now, ts, marked) {
849
+ const fresh = !!old && rebaselined(old, checkpointId, ts, marked);
850
+ if (old && old.checkpointId >= checkpointId && !fresh) return old;
851
+ if (old?.ts && ts && Date.parse(ts) < Date.parse(old.ts)) return old;
852
+ const at = now.toISOString();
853
+ const looks = (old?.looks ?? []).filter(isLook);
854
+ if (old && !fresh) {
855
+ const last = looks.at(-1);
856
+ if (last && last.to === old.checkpointId && last.toTs === old.ts && now.getTime() - Date.parse(last.at) < LOOK_JOIN_MS) {
857
+ looks[looks.length - 1] = { ...last, to: checkpointId, ...ts ? { toTs: ts } : {}, at };
858
+ } else {
859
+ looks.push({
860
+ from: old.checkpointId,
861
+ to: checkpointId,
862
+ ...old.ts ? { fromTs: old.ts } : {},
863
+ ...ts ? { toTs: ts } : {},
864
+ startedAt: at,
865
+ at
866
+ });
867
+ }
868
+ }
869
+ return { checkpointId, at, ...ts ? { ts } : {}, ...looks.length ? { looks: looks.slice(-MAX_LOOKS) } : {} };
870
+ }
871
+
872
+ // src/core/diff/diff-seen.ts
809
873
  function readDiffSeen(sessionId) {
810
874
  const row = withDb((d) => d.prepare("SELECT data FROM diff_seen WHERE session_id = ?").get(sessionId));
811
- const v = row ? json.parse(row.data) : null;
812
- return isSeen(v) ? v : null;
875
+ return row ? cleanSeen(json.parse(row.data)) : null;
813
876
  }
814
- function markDiffSeen(sessionId, checkpointId, now = /* @__PURE__ */ new Date()) {
877
+ function markDiffSeen(sessionId, checkpointId, now = /* @__PURE__ */ new Date(), ts, marked) {
815
878
  return tx((d) => {
816
879
  const row = d.prepare("SELECT data FROM diff_seen WHERE session_id = ?").get(sessionId);
817
- const old = row ? json.parse(row.data) : null;
818
- if (isSeen(old) && old.checkpointId >= checkpointId) return old;
819
- const seen = { checkpointId, at: now.toISOString() };
880
+ const old = row ? cleanSeen(json.parse(row.data)) : null;
881
+ const seen = nextSeen(old, checkpointId, now, ts, marked);
882
+ if (seen === old) return old;
820
883
  d.prepare("INSERT OR REPLACE INTO diff_seen (session_id, data) VALUES (?, ?)").run(sessionId, JSON.stringify(seen));
821
884
  return seen;
822
885
  });
@@ -835,7 +898,9 @@ function mountDiffSeenRoutes(app) {
835
898
  const body = await c.req.json().catch(() => null);
836
899
  const cp = body?.checkpointId;
837
900
  if (typeof cp !== "number" || !Number.isInteger(cp) || cp < 0) return c.json({ error: "expected {checkpointId}" }, 400);
838
- return c.json({ seen: markDiffSeen(id, cp) });
901
+ const ts = typeof body?.ts === "string" && Number.isFinite(Date.parse(body.ts)) ? body.ts : void 0;
902
+ const marked = markedTurn(body?.marked);
903
+ return c.json({ seen: markDiffSeen(id, cp, /* @__PURE__ */ new Date(), ts, marked) });
839
904
  });
840
905
  }
841
906
 
@@ -1707,7 +1772,7 @@ function describeStall(s) {
1707
1772
  }
1708
1773
 
1709
1774
  // src/server/web-server.ts
1710
- import path13 from "path";
1775
+ import path14 from "path";
1711
1776
  import { Hono } from "hono";
1712
1777
  import { streamSSE as streamSSE2 } from "hono/streaming";
1713
1778
 
@@ -1717,65 +1782,76 @@ function mountSessionCommentRoutes(app, opts) {
1717
1782
  function requireSession(id) {
1718
1783
  return findSession2(id);
1719
1784
  }
1785
+ function context(id) {
1786
+ const session = requireSession(id);
1787
+ if (!session) return null;
1788
+ const self = { id, paths: session.paths };
1789
+ return { session, self, ids: sessionLinkedStoreIds(self) };
1790
+ }
1791
+ const listFor = (ctx) => linkedComments(ctx.ids);
1792
+ const tell = {
1793
+ session: (_sessionId, data) => opts.broadcast("comments-changed", data),
1794
+ scope: (_scopeHash, data) => opts.notifyScope?.(data)
1795
+ };
1796
+ const changed = (ctx, storeId, data) => announceChange(storeId, storeId === ctx.self.id ? [ctx.self] : [ctx.self, ...loadHistory().map(linkedSession)], tell, data);
1720
1797
  app.get("/api/sessions/:id/comments", (c) => {
1721
- const id = c.req.param("id");
1722
- if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
1723
- const store = getCommentFileStore(id);
1724
- return c.json({ comments: store.snapshot() });
1798
+ const ctx = context(c.req.param("id"));
1799
+ if (!ctx) return c.json({ error: "unknown session" }, 404);
1800
+ return c.json({ comments: listFor(ctx) });
1725
1801
  });
1726
1802
  app.post("/api/sessions/:id/comments", zValidator2("json", commentInputSchema), (c) => {
1727
1803
  const id = c.req.param("id");
1728
- if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
1729
- const store = getCommentFileStore(id);
1804
+ const ctx = context(id);
1805
+ if (!ctx) return c.json({ error: "unknown session" }, 404);
1806
+ const input = c.req.valid("json");
1807
+ const home = input.parentId ? storeHolding(ctx.ids, input.parentId) ?? id : id;
1808
+ const store = getCommentFileStore(home);
1730
1809
  try {
1731
- const comment2 = store.post(c.req.valid("json"));
1732
- opts.broadcast("comments-changed", { sessionId: id, id: comment2.id });
1810
+ const comment2 = store.post(home === id ? input : { ...input, status: "published" });
1811
+ changed(ctx, home, { id: comment2.id });
1733
1812
  const delivery = comment2.status === "published" ? ownedPtyDelivery(id, comment2.author) : null;
1734
1813
  if (delivery === "typed") void typeAndSubmit(id, NOTE_NUDGE).catch(() => false);
1735
- return c.json({ comment: comment2, comments: store.snapshot(), delivery });
1814
+ return c.json({ comment: comment2, comments: listFor(ctx), delivery });
1736
1815
  } catch (err) {
1737
1816
  return c.json({ error: err.message }, 400);
1738
1817
  }
1739
1818
  });
1740
1819
  app.delete("/api/sessions/:id/comments/:cid", (c) => {
1741
- const id = c.req.param("id");
1742
1820
  const cid = c.req.param("cid");
1743
- if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
1744
- const store = getCommentFileStore(id);
1745
- const removed = store.remove(cid);
1746
- if (removed) opts.broadcast("comments-changed", { sessionId: id, deleted: cid });
1747
- return c.json({ comments: store.snapshot() });
1821
+ const ctx = context(c.req.param("id"));
1822
+ if (!ctx) return c.json({ error: "unknown session" }, 404);
1823
+ const home = storeHolding(ctx.ids, cid);
1824
+ if (home && getCommentFileStore(home).remove(cid)) changed(ctx, home, { deleted: cid });
1825
+ return c.json({ comments: listFor(ctx) });
1748
1826
  });
1749
1827
  app.post("/api/sessions/:id/comments/:cid/resolve", zValidator2("json", resolveSchema), (c) => {
1750
- const id = c.req.param("id");
1751
- if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
1752
- const store = getCommentFileStore(id);
1753
- const updated = store.setResolved(c.req.param("cid"), c.req.valid("json").resolved);
1754
- if (updated) opts.broadcast("comments-changed", { sessionId: id, id: updated.id });
1755
- return c.json({ comments: store.snapshot() });
1828
+ const cid = c.req.param("cid");
1829
+ const ctx = context(c.req.param("id"));
1830
+ if (!ctx) return c.json({ error: "unknown session" }, 404);
1831
+ const home = storeHolding(ctx.ids, cid);
1832
+ const updated = home ? getCommentFileStore(home).setResolved(cid, c.req.valid("json").resolved) : null;
1833
+ if (home && updated) changed(ctx, home, { id: updated.id });
1834
+ return c.json({ comments: listFor(ctx) });
1756
1835
  });
1757
1836
  app.post("/api/sessions/:id/submit-review", zValidator2("json", submitReviewSchema), (c) => {
1758
1837
  const id = c.req.param("id");
1759
- if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
1760
- const store = getCommentFileStore(id);
1761
- const result = store.submit(c.req.valid("json").summary);
1762
- opts.broadcast("comments-changed", {
1763
- sessionId: id,
1764
- submittedCount: result.drafts.length
1765
- });
1838
+ const ctx = context(id);
1839
+ if (!ctx) return c.json({ error: "unknown session" }, 404);
1840
+ const result = getCommentFileStore(id).submit(c.req.valid("json").summary);
1841
+ changed(ctx, id, { submittedCount: result.drafts.length });
1766
1842
  if (result.drafts.length > 0) void deliverViaOwnedPty(id, "user");
1767
1843
  return c.json({
1768
1844
  count: result.drafts.length,
1769
- comments: store.snapshot()
1845
+ comments: listFor(ctx)
1770
1846
  });
1771
1847
  });
1772
1848
  app.post("/api/sessions/:id/discard-review", (c) => {
1773
1849
  const id = c.req.param("id");
1774
- if (!requireSession(id)) return c.json({ error: "unknown session" }, 404);
1775
- const store = getCommentFileStore(id);
1776
- const discarded = store.discardDrafts();
1777
- if (discarded > 0) opts.broadcast("comments-changed", { sessionId: id });
1778
- return c.json({ discarded, comments: store.snapshot() });
1850
+ const ctx = context(id);
1851
+ if (!ctx) return c.json({ error: "unknown session" }, 404);
1852
+ const discarded = getCommentFileStore(id).discardDrafts();
1853
+ if (discarded > 0) changed(ctx, id, {});
1854
+ return c.json({ discarded, comments: listFor(ctx) });
1779
1855
  });
1780
1856
  }
1781
1857
  async function deliverViaOwnedPty(sessionId, author) {
@@ -1785,7 +1861,8 @@ async function deliverViaOwnedPty(sessionId, author) {
1785
1861
  function ownedPtyDelivery(sessionId, author) {
1786
1862
  if (author !== "user") return null;
1787
1863
  if (!peekPty(sessionId)) return null;
1788
- if (readPendingForSession(sessionId).length === 0) return null;
1864
+ const session = findSession2(sessionId);
1865
+ if ((session ? readPendingForWorktree(session, sessionId) : readPendingForSession(sessionId)).length === 0) return null;
1789
1866
  return readStatus(sessionId)?.state === "working" ? "next-turn" : "typed";
1790
1867
  }
1791
1868
  async function typeAndSubmit(sessionId, text, write = writeToPty, wait) {
@@ -2531,25 +2608,36 @@ function mountScopeRoutes(app, opts) {
2531
2608
  function commentStore(hash) {
2532
2609
  return getCommentFileStore(commentStoreIdForScope(hash));
2533
2610
  }
2611
+ function context(hash) {
2612
+ const sessions = loadHistory().map(linkedSession);
2613
+ return { own: commentStoreIdForScope(hash), sessions, ids: scopeLinkedStoreIds(hash, sessions) };
2614
+ }
2615
+ const listFor = (ctx) => linkedComments(ctx.ids);
2616
+ const tell = {
2617
+ scope: (_hash, data) => emitCommentsChanged(data),
2618
+ session: (_id, data) => opts.broadcast("comments-changed", data)
2619
+ };
2620
+ const storeChanged = (ctx, storeId, data) => announceChange(storeId, ctx.sessions, tell, data);
2534
2621
  app.get("/api/scopes/:hash/comments", (c) => {
2535
2622
  const scope = getScope(c.req.param("hash"));
2536
2623
  if (!scope) return c.json({ error: "unknown scope" }, 404);
2537
2624
  return c.json({
2538
- comments: commentStore(scope.hash).snapshot(),
2625
+ comments: c.req.query("linked") === "1" ? listFor(context(scope.hash)) : commentStore(scope.hash).snapshot(),
2539
2626
  ended: scope.ended
2540
2627
  });
2541
2628
  });
2542
2629
  app.post("/api/scopes/:hash/comments", zValidator5("json", commentInputSchema), (c) => {
2543
2630
  const scope = getScope(c.req.param("hash"));
2544
2631
  if (!scope) return c.json({ error: "unknown scope" }, 404);
2545
- const store = commentStore(scope.hash);
2632
+ const ctx = context(scope.hash);
2633
+ const input = c.req.valid("json");
2634
+ const home = input.parentId ? storeHolding(ctx.ids, input.parentId) ?? ctx.own : ctx.own;
2635
+ const store = getCommentFileStore(home);
2546
2636
  try {
2547
- const comment2 = store.post(c.req.valid("json"));
2548
- emitCommentsChanged({
2549
- scopeHash: scope.hash,
2550
- id: comment2.id
2551
- });
2552
- return c.json({ comment: comment2, comments: store.snapshot() });
2637
+ const comment2 = store.post(home === ctx.own ? input : { ...input, status: "published" });
2638
+ storeChanged(ctx, home, { id: comment2.id });
2639
+ if (home !== ctx.own) void deliverViaOwnedPty(home, comment2.author);
2640
+ return c.json({ comment: comment2, comments: listFor(ctx) });
2553
2641
  } catch (err) {
2554
2642
  return c.json({ error: err.message }, 400);
2555
2643
  }
@@ -2557,52 +2645,40 @@ function mountScopeRoutes(app, opts) {
2557
2645
  app.delete("/api/scopes/:hash/comments/:cid", (c) => {
2558
2646
  const scope = getScope(c.req.param("hash"));
2559
2647
  if (!scope) return c.json({ error: "unknown scope" }, 404);
2560
- const store = commentStore(scope.hash);
2561
- const removed = store.remove(c.req.param("cid"));
2562
- if (removed) {
2563
- emitCommentsChanged({
2564
- scopeHash: scope.hash,
2565
- deleted: c.req.param("cid")
2566
- });
2567
- }
2568
- return c.json({ comments: store.snapshot() });
2648
+ const ctx = context(scope.hash);
2649
+ const cid = c.req.param("cid");
2650
+ const home = storeHolding(ctx.ids, cid);
2651
+ if (home && getCommentFileStore(home).remove(cid)) storeChanged(ctx, home, { deleted: cid });
2652
+ return c.json({ comments: listFor(ctx) });
2569
2653
  });
2570
2654
  app.post("/api/scopes/:hash/comments/:cid/resolve", zValidator5("json", resolveSchema), (c) => {
2571
2655
  const scope = getScope(c.req.param("hash"));
2572
2656
  if (!scope) return c.json({ error: "unknown scope" }, 404);
2573
- const store = commentStore(scope.hash);
2574
- const updated = store.setResolved(c.req.param("cid"), c.req.valid("json").resolved);
2575
- if (updated) {
2576
- emitCommentsChanged({
2577
- scopeHash: scope.hash,
2578
- id: updated.id
2579
- });
2580
- }
2581
- return c.json({ comments: store.snapshot() });
2657
+ const ctx = context(scope.hash);
2658
+ const cid = c.req.param("cid");
2659
+ const home = storeHolding(ctx.ids, cid);
2660
+ const updated = home ? getCommentFileStore(home).setResolved(cid, c.req.valid("json").resolved) : null;
2661
+ if (home && updated) storeChanged(ctx, home, { id: updated.id });
2662
+ return c.json({ comments: listFor(ctx) });
2582
2663
  });
2583
2664
  app.post("/api/scopes/:hash/submit-review", zValidator5("json", submitReviewSchema), (c) => {
2584
2665
  const scope = getScope(c.req.param("hash"));
2585
2666
  if (!scope) return c.json({ error: "unknown scope" }, 404);
2586
- const store = commentStore(scope.hash);
2587
- const result = store.submit(c.req.valid("json").summary);
2588
- emitCommentsChanged({
2589
- scopeHash: scope.hash,
2590
- submittedCount: result.drafts.length
2591
- });
2667
+ const ctx = context(scope.hash);
2668
+ const result = commentStore(scope.hash).submit(c.req.valid("json").summary);
2669
+ storeChanged(ctx, ctx.own, { submittedCount: result.drafts.length });
2592
2670
  return c.json({
2593
2671
  count: result.drafts.length,
2594
- comments: store.snapshot()
2672
+ comments: listFor(ctx)
2595
2673
  });
2596
2674
  });
2597
2675
  app.post("/api/scopes/:hash/discard-review", (c) => {
2598
2676
  const scope = getScope(c.req.param("hash"));
2599
2677
  if (!scope) return c.json({ error: "unknown scope" }, 404);
2600
- const store = commentStore(scope.hash);
2601
- const discarded = store.discardDrafts();
2602
- if (discarded > 0) {
2603
- emitCommentsChanged({ scopeHash: scope.hash });
2604
- }
2605
- return c.json({ discarded, comments: store.snapshot() });
2678
+ const ctx = context(scope.hash);
2679
+ const discarded = commentStore(scope.hash).discardDrafts();
2680
+ if (discarded > 0) storeChanged(ctx, ctx.own, {});
2681
+ return c.json({ discarded, comments: listFor(ctx) });
2606
2682
  });
2607
2683
  app.post("/api/scopes/:hash/done", (c) => {
2608
2684
  const scope = getScope(c.req.param("hash"));
@@ -2670,7 +2746,7 @@ function mountScopeRoutes(app, opts) {
2670
2746
  return existing ?? ensureScope(paths, label);
2671
2747
  }
2672
2748
  const releaseSessionScope = (paths, clearRefs) => dropScope(scopeHashForPaths(paths), { clearRefs });
2673
- return { ensureScope, sessionScope, releaseSessionScope };
2749
+ return { ensureScope, sessionScope, releaseSessionScope, emitCommentsChanged };
2674
2750
  }
2675
2751
 
2676
2752
  // src/server/routes/terminal-routes.ts
@@ -3351,7 +3427,7 @@ function createActivityLog(opts = {}) {
3351
3427
  changed();
3352
3428
  return {
3353
3429
  next(atMs) {
3354
- s.nextAt = iso(atMs);
3430
+ s.nextAt = atMs === null ? null : iso(atMs);
3355
3431
  changed();
3356
3432
  },
3357
3433
  pause(untilMs, why) {
@@ -4728,6 +4804,220 @@ async function bridgeToHost(ws, sessionId, pending) {
4728
4804
  });
4729
4805
  }
4730
4806
 
4807
+ // src/core/pty/agent-restart.ts
4808
+ import fs11 from "fs";
4809
+
4810
+ // src/core/platform/find-on-path.ts
4811
+ import fs10 from "fs";
4812
+ import path13 from "path";
4813
+ function findOnPath(cmd, env = process.env, platform = process.platform) {
4814
+ const win = platform === "win32";
4815
+ const isFile = (p) => {
4816
+ try {
4817
+ const st = fs10.statSync(p);
4818
+ return st.isFile() && (win || (st.mode & 73) !== 0);
4819
+ } catch {
4820
+ return false;
4821
+ }
4822
+ };
4823
+ const pathExt = (env.PATHEXT ?? env.Pathext ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((e) => e.toLowerCase());
4824
+ const hasExt = pathExt.includes(path13.extname(cmd).toLowerCase());
4825
+ const candidates = (base) => !win || hasExt ? [base] : pathExt.map((e) => base + e);
4826
+ if (cmd.includes("/") || win && cmd.includes("\\")) return candidates(cmd).find(isFile) ?? null;
4827
+ const dirs = (env.PATH ?? env.Path ?? "").split(win ? ";" : path13.delimiter).filter(Boolean);
4828
+ for (const dir of dirs) {
4829
+ const hit = candidates(path13.join(dir, cmd)).find(isFile);
4830
+ if (hit) return hit;
4831
+ }
4832
+ return null;
4833
+ }
4834
+
4835
+ // src/core/pty/agent-restart.ts
4836
+ var PACKED_MTIME_BEFORE = Date.parse("1990-01-01T00:00:00Z");
4837
+ function installedAt(cmd, find = findOnPath) {
4838
+ const file = find(cmd);
4839
+ if (!file) return null;
4840
+ try {
4841
+ return installTime(fs11.statSync(fs11.realpathSync(file)));
4842
+ } catch {
4843
+ return null;
4844
+ }
4845
+ }
4846
+ function installTime(st) {
4847
+ const real = (ms) => ms >= PACKED_MTIME_BEFORE ? ms : null;
4848
+ const known = [real(st.mtimeMs), real(st.birthtimeMs)].filter((x) => x !== null);
4849
+ return known.length ? Math.max(...known) : st.ctimeMs;
4850
+ }
4851
+ function installedAtCache(ttlMs = 6e4, look = installedAt, now = Date.now) {
4852
+ const cache = /* @__PURE__ */ new Map();
4853
+ return (cmd) => {
4854
+ const hit = cache.get(cmd);
4855
+ if (hit && now() - hit.read < ttlMs) return hit.at;
4856
+ const at = look(cmd);
4857
+ cache.set(cmd, { at, read: now() });
4858
+ return at;
4859
+ };
4860
+ }
4861
+ function outdatedPtys(ptys, toolInstalledAt) {
4862
+ return ptys.filter((p) => {
4863
+ if (p.exited || !p.tool) return false;
4864
+ const at = toolInstalledAt(p.tool);
4865
+ const started = Date.parse(p.startedAt);
4866
+ return at !== null && Number.isFinite(started) && started < at;
4867
+ });
4868
+ }
4869
+ var PRINTING_MS = 1e4;
4870
+ function busyForRestart(state, lastOutputMs, now = Date.now(), live = null) {
4871
+ if (live === "busy" || live === "waiting") return true;
4872
+ if (state === "working" || state === "needs_input") return true;
4873
+ return lastOutputMs !== null && now - lastOutputMs < PRINTING_MS;
4874
+ }
4875
+ function restartPlan(ids, busy) {
4876
+ const now = [];
4877
+ const later = [];
4878
+ for (const id of new Set(ids)) (busy(id) ? later : now).push(id);
4879
+ return { now, later };
4880
+ }
4881
+ var RESTART_AT_ONCE = 3;
4882
+ function restartNotesSummary(notes) {
4883
+ const n = (level) => notes.filter((x) => x.level === level).length;
4884
+ return restartCountsText({ restarted: n("action"), later: n("info"), failed: n("warn") });
4885
+ }
4886
+ var QUEUE_RECHECK_MS = 15e3;
4887
+ var TURN_END_GRACE_MS = 1e4;
4888
+ function createRestarter(deps) {
4889
+ const queued = /* @__PURE__ */ new Set();
4890
+ const inFlight = /* @__PURE__ */ new Map();
4891
+ const later = deps.later ?? ((fn, ms) => void setTimeout(fn, ms).unref?.());
4892
+ const one = (id) => {
4893
+ const running = inFlight.get(id);
4894
+ if (running) return running;
4895
+ queued.delete(id);
4896
+ const p = deps.restart(id).then(
4897
+ (how) => ({ ok: true, how: how || "restarted its agent (its conversation goes on)" }),
4898
+ (err) => ({ ok: false, error: err.message })
4899
+ );
4900
+ inFlight.set(id, p);
4901
+ void p.finally(() => inFlight.delete(id));
4902
+ return p;
4903
+ };
4904
+ const run = async (ids, notes) => {
4905
+ const failed = [];
4906
+ const ok = /* @__PURE__ */ new Set();
4907
+ const queue = [...ids];
4908
+ const worker = async () => {
4909
+ for (let id = queue.shift(); id !== void 0; id = queue.shift()) {
4910
+ const r = await one(id);
4911
+ if (r.ok) {
4912
+ ok.add(id);
4913
+ notes.push({ id, text: r.how, level: "action" });
4914
+ } else {
4915
+ failed.push({ id, error: r.error });
4916
+ notes.push({ id, text: `couldn't restart its agent: ${r.error}`, level: "warn" });
4917
+ }
4918
+ }
4919
+ };
4920
+ await Promise.all(Array.from({ length: Math.min(RESTART_AT_ONCE, queue.length) }, worker));
4921
+ return { done: ids.filter((id) => ok.has(id)), failed };
4922
+ };
4923
+ const finish = (notes) => {
4924
+ if (!notes.length) return;
4925
+ deps.report?.(notes);
4926
+ deps.changed?.();
4927
+ };
4928
+ const request = async (ids) => {
4929
+ const plan = restartPlan(ids, (id) => deps.busy(id));
4930
+ const notes = [];
4931
+ for (const id of plan.later) {
4932
+ queued.add(id);
4933
+ notes.push({ id, text: `${LATER_TEXT} (it is working or waiting on you)`, level: "info" });
4934
+ }
4935
+ const { done, failed } = await run(plan.now, notes);
4936
+ finish(notes);
4937
+ tick();
4938
+ return { now: done, later: plan.later, failed };
4939
+ };
4940
+ let ticking = false;
4941
+ const tick = () => {
4942
+ if (ticking) return;
4943
+ if (queued.size === 0) {
4944
+ deps.scheduled?.(null);
4945
+ return;
4946
+ }
4947
+ ticking = true;
4948
+ deps.scheduled?.(Date.now() + QUEUE_RECHECK_MS);
4949
+ later(() => {
4950
+ ticking = false;
4951
+ void retry().catch(() => {
4952
+ }).finally(tick);
4953
+ }, QUEUE_RECHECK_MS);
4954
+ };
4955
+ const retry = async (only, opts) => {
4956
+ const notes = [];
4957
+ const ready = [];
4958
+ for (const id of [...queued]) {
4959
+ if (only !== void 0 && id !== only) continue;
4960
+ if (!deps.running(id)) {
4961
+ queued.delete(id);
4962
+ notes.push({ id, text: "no longer waits to restart: it was stopped meanwhile (it starts on the new version)", level: "info" });
4963
+ continue;
4964
+ }
4965
+ if (!deps.busy(id, opts)) ready.push(id);
4966
+ }
4967
+ await run(ready, notes);
4968
+ finish(notes);
4969
+ };
4970
+ return {
4971
+ request,
4972
+ retry: () => retry(),
4973
+ /** A session's turn ended: restart it if it was waiting for that — and if it still reads as busy, look again shortly. */
4974
+ turnEnded: (id) => {
4975
+ if (!queued.has(id)) return;
4976
+ later(() => void retry(id, { turnEnded: true }).catch(() => {
4977
+ }), TURN_END_GRACE_MS);
4978
+ },
4979
+ queued: () => [...queued],
4980
+ /** Being restarted now (the host lists them as exited meanwhile: still this session's). */
4981
+ restarting: () => [...inFlight.keys()]
4982
+ };
4983
+ }
4984
+
4985
+ // src/server/routes/agent-restart-routes.ts
4986
+ function agentsWire(ptys, deps) {
4987
+ const times = /* @__PURE__ */ new Map();
4988
+ const at = (tool) => {
4989
+ if (!times.has(tool)) times.set(tool, deps.installedAt(tool));
4990
+ return times.get(tool);
4991
+ };
4992
+ const outdated = outdatedPtys(ptys, at);
4993
+ const newest = Math.max(...[...new Set(ptys.map((p) => p.tool).filter((t) => !!t))].map((t) => at(t) ?? -Infinity));
4994
+ return {
4995
+ installedAt: Number.isFinite(newest) ? new Date(newest).toISOString() : null,
4996
+ outdated: outdated.map((p) => ({ id: p.id, tool: p.tool, startedAt: p.startedAt, busy: deps.busy(p.id) })),
4997
+ queued: deps.restarter.queued()
4998
+ };
4999
+ }
5000
+ function mountAgentRestartRoutes(app, opts) {
5001
+ const { deps } = opts;
5002
+ app.get("/api/agents", async (c) => c.json(agentsWire(await deps.list().catch(() => []), deps)));
5003
+ app.post("/api/agents/restart", async (c) => {
5004
+ if (opts.lookOnly) return c.json({ error: opts.lookOnly }, 409);
5005
+ const body = await c.req.json().catch(() => null) ?? {};
5006
+ const live = (await deps.list().catch(() => [])).filter((p) => !p.exited);
5007
+ let ids;
5008
+ if (body.all === true) ids = live.map((p) => p.id);
5009
+ else if (body.outdated === true) ids = outdatedPtys(live, deps.installedAt).map((p) => p.id);
5010
+ else if (Array.isArray(body.ids) && body.ids.length > 0 && body.ids.every((i) => typeof i === "string")) {
5011
+ ids = body.ids;
5012
+ const running = /* @__PURE__ */ new Set([...live.map((p) => p.id), ...deps.restarter.restarting()]);
5013
+ const notRunning = ids.filter((id) => !running.has(id));
5014
+ if (notRunning.length === ids.length) return c.json({ error: "its agent is not running in the PTY host" }, 409);
5015
+ ids = ids.filter((id) => running.has(id));
5016
+ } else return c.json({ error: "say which: ids, outdated or all" }, 400);
5017
+ return c.json(await deps.restarter.request(ids));
5018
+ });
5019
+ }
5020
+
4731
5021
  // src/core/pty/host-health.ts
4732
5022
  var UNRESPONSIVE_MS = 11e3;
4733
5023
  var SLOW_MS = 1500;
@@ -4758,7 +5048,7 @@ function sleepCandidates(ptys, now, afterMs, busy, keep = /* @__PURE__ */ new Se
4758
5048
  function computeSessionDiff(s, base) {
4759
5049
  const resolved = s.paths.map((p) => resolveRepoDiff(p, base, s.baseBranches?.[p] ?? s.baseBranch));
4760
5050
  const repos = s.paths.map((p, i) => ({
4761
- name: path13.basename(p),
5051
+ name: path14.basename(p),
4762
5052
  root: p,
4763
5053
  resolvedBase: resolved[i].resolvedBase,
4764
5054
  files: computeDiff({ root: p, diffArg: resolved[i].diffArg })
@@ -4809,7 +5099,7 @@ async function startWebServer(opts = {}) {
4809
5099
  let activityWatcher = null;
4810
5100
  if (!lean) {
4811
5101
  try {
4812
- const roots = activityRoots().filter((r) => fs10.existsSync(r));
5102
+ const roots = activityRoots().filter((r) => fs12.existsSync(r));
4813
5103
  if (roots.length > 0) {
4814
5104
  activityWatcher = createFsWatcher({
4815
5105
  roots,
@@ -4860,7 +5150,7 @@ async function startWebServer(opts = {}) {
4860
5150
  }, 500);
4861
5151
  }
4862
5152
  });
4863
- const repoNames = (s) => s.isGroup ? s.paths.map((p) => path13.basename(p)) : [s.target];
5153
+ const repoNames = (s) => s.isGroup ? s.paths.map((p) => path14.basename(p)) : [s.target];
4864
5154
  const diffStatFor = (id, s, hasStatus) => wantsDiffStat(s, hasStatus) ? diffStats.get(id, s.paths, repoNames(s)) : null;
4865
5155
  const archivedRow = createArchivedRows();
4866
5156
  app.get("/api/sessions", (c) => {
@@ -4973,7 +5263,7 @@ async function startWebServer(opts = {}) {
4973
5263
  return c.json({ error: err.message }, 500);
4974
5264
  }
4975
5265
  });
4976
- mountSessionCommentRoutes(app, { broadcast });
5266
+ mountSessionCommentRoutes(app, { broadcast, notifyScope: (data) => scopeApi?.emitCommentsChanged(data) });
4977
5267
  mountSessionControlRoutes(app, { broadcast });
4978
5268
  mountRevertRoutes(app, { uncommitted: (s) => computeSessionDiff(s, "uncommitted").repos });
4979
5269
  mountDevRoutes(app, { broadcast });
@@ -5007,18 +5297,50 @@ async function startWebServer(opts = {}) {
5007
5297
  const stopPrWatch = lean ? null : prWatch.start(dev ? 10 * 6e4 : 18e4);
5008
5298
  const SLEEP_EVERY_MS = 5 * 6e4;
5009
5299
  const sleepSchedule = !jobs ? null : activity.schedule("idle-sleep", "Idle Claude check", SLEEP_EVERY_MS);
5300
+ const agentBusy = (id) => {
5301
+ const st = readStatus(id)?.state;
5302
+ return st === "working" || st === "needs_input";
5303
+ };
5304
+ const restartBusy = (id, opts2) => {
5305
+ const session = findSession2(id);
5306
+ const pid = ptyPid(id);
5307
+ const live = pid === null ? null : liveAgents().find((a) => a.pid === pid)?.state ?? null;
5308
+ return busyForRestart(session ? shownState(session) : null, opts2?.turnEnded ? null : ptyLastOutputMs(id), Date.now(), live);
5309
+ };
5310
+ const restartSchedule = dev ? null : activity.schedule("agents", "Agents waiting to restart", QUEUE_RECHECK_MS);
5311
+ const restarter = createRestarter({
5312
+ restart: restartPty,
5313
+ busy: restartBusy,
5314
+ running: peekPty,
5315
+ report: (notes) => {
5316
+ const run = activity.start("agents", "Restarting agents");
5317
+ for (const { id, text, level } of notes) {
5318
+ const s = findSession2(id);
5319
+ run.note(`${s ? `${s.target} ${s.branch}` : id}: ${text}`, { level, sessionId: s ? id : void 0 });
5320
+ }
5321
+ run.done(restartNotesSummary(notes));
5322
+ },
5323
+ changed: () => {
5324
+ broadcast("agents-changed", { ts: Date.now() });
5325
+ broadcast("sessions-changed", { ts: Date.now() });
5326
+ },
5327
+ scheduled: (nextAt) => restartSchedule?.next(nextAt)
5328
+ });
5329
+ mountAgentRestartRoutes(app, {
5330
+ deps: { list: listHostPtys, installedAt: installedAtCache(), busy: restartBusy, restarter },
5331
+ // The dev server shares the real PTY host and acts on nothing: the real work web restarts.
5332
+ lookOnly: dev ? "the dev server restarts nothing: use the real work web (the app, or `work restart`)" : void 0
5333
+ });
5010
5334
  const sleepIdle = async () => {
5011
5335
  sleepSchedule?.next(Date.now() + SLEEP_EVERY_MS);
5336
+ await restarter.retry().catch(() => {
5337
+ });
5012
5338
  const minutes = loadConfig()?.sleepIdleAfterMinutes ?? DEFAULT_SLEEP_AFTER_MINUTES;
5013
5339
  if (sleepAfterMs(minutes) === 0)
5014
5340
  return activity.skip("idle-sleep", "Looking for idle Claudes", "turned off (sleepIdleAfterMinutes: 0)");
5015
5341
  const run = activity.start("idle-sleep", "Looking for idle Claudes");
5016
5342
  const ptys = await listHostPtys().catch(() => []);
5017
- const busy = (id) => {
5018
- const st = readStatus(id)?.state;
5019
- return st === "working" || st === "needs_input";
5020
- };
5021
- const ids = sleepCandidates(ptys, Date.now(), sleepAfterMs(minutes), busy);
5343
+ const ids = sleepCandidates(ptys, Date.now(), sleepAfterMs(minutes), agentBusy);
5022
5344
  for (const id of ids) {
5023
5345
  report("detail", `[sleep] ${id}: idle ${minutes} min with nothing attached; stopping its Claude (opening the session resumes it)`);
5024
5346
  const s = findSession2(id);
@@ -5254,6 +5576,7 @@ async function startWebServer(opts = {}) {
5254
5576
  } : {},
5255
5577
  onStatusChanged: (id) => {
5256
5578
  diffStats.invalidate(id);
5579
+ restarter.turnEnded(id);
5257
5580
  timeKeeper?.soon();
5258
5581
  if (jobs) void syncStacksAfter(id);
5259
5582
  const session = findSession2(id);
@@ -5296,7 +5619,7 @@ async function startWebServer(opts = {}) {
5296
5619
  updatesTimer?.unref?.();
5297
5620
  const desktopFile = desktopUpdatePath();
5298
5621
  const onDesktopUpdate = () => broadcast("updates-changed", { ts: Date.now() });
5299
- if (jobs) fs10.watchFile(desktopFile, { interval: 3e3 }, onDesktopUpdate);
5622
+ if (jobs) fs12.watchFile(desktopFile, { interval: 3e3 }, onDesktopUpdate);
5300
5623
  app.get("/api/pty-host/health", (c) => c.json(hostHealth(hostBeat())));
5301
5624
  let lastHostState = hostHealth(hostBeat()).state;
5302
5625
  const hostTick = lean ? null : setInterval(() => {
@@ -5361,7 +5684,7 @@ async function startWebServer(opts = {}) {
5361
5684
  if (timeFirst) clearTimeout(timeFirst);
5362
5685
  if (timeTimer) clearInterval(timeTimer);
5363
5686
  timeKeeper?.stop();
5364
- fs10.unwatchFile(desktopFile, onDesktopUpdate);
5687
+ fs12.unwatchFile(desktopFile, onDesktopUpdate);
5365
5688
  for (const t of conversationSyncs.values()) clearTimeout(t);
5366
5689
  clearTimeout(sweepTimer);
5367
5690
  activityWatcher?.stop();
@@ -5384,11 +5707,11 @@ async function startWebServer(opts = {}) {
5384
5707
  }
5385
5708
 
5386
5709
  // src/core/platform/autostart.ts
5387
- import fs11 from "fs";
5388
- import path14 from "path";
5710
+ import fs13 from "fs";
5711
+ import path15 from "path";
5389
5712
  function startupScriptPath() {
5390
5713
  if (process.platform !== "win32" || !process.env.APPDATA) return null;
5391
- return path14.join(process.env.APPDATA, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "work-web.vbs");
5714
+ return path15.join(process.env.APPDATA, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "work-web.vbs");
5392
5715
  }
5393
5716
  function vbsQuote(s) {
5394
5717
  return '"' + s.replace(/"/g, '""') + '"';
@@ -5406,11 +5729,11 @@ function setAutostart(enabled, workBin) {
5406
5729
  const file = startupScriptPath();
5407
5730
  if (!file) throw new Error("Autostart is only supported on Windows so far.");
5408
5731
  if (enabled) {
5409
- fs11.mkdirSync(path14.dirname(file), { recursive: true });
5410
- fs11.writeFileSync(file, buildStartupScript(process.execPath, workBin), "utf-8");
5732
+ fs13.mkdirSync(path15.dirname(file), { recursive: true });
5733
+ fs13.writeFileSync(file, buildStartupScript(process.execPath, workBin), "utf-8");
5411
5734
  } else {
5412
5735
  try {
5413
- fs11.unlinkSync(file);
5736
+ fs13.unlinkSync(file);
5414
5737
  } catch {
5415
5738
  }
5416
5739
  }
@@ -5454,7 +5777,7 @@ function createDemoRepos(liveTargets) {
5454
5777
  /** GET /api/projects: what New worktree offers, as the real one reads config. */
5455
5778
  projects() {
5456
5779
  return {
5457
- singles: Object.entries(repos).map(([name, path15]) => ({ name, kind: "single", path: path15 })),
5780
+ singles: Object.entries(repos).map(([name, path16]) => ({ name, kind: "single", path: path16 })),
5458
5781
  groups: Object.entries(groups).map(([name, members]) => ({ name, kind: "group", members }))
5459
5782
  };
5460
5783
  },
@@ -5496,12 +5819,12 @@ function createDemoRepos(liveTargets) {
5496
5819
  }));
5497
5820
  return { roots: [root], repos: rows, groups: groupRows };
5498
5821
  },
5499
- enroll(alias, path15) {
5500
- if (!found.some((f) => f.path === path15)) throw new DemoRepoError(`${path15} is not the top folder of a git repository`);
5501
- const problem = enrollProblem(alias, path15, config());
5822
+ enroll(alias, path16) {
5823
+ if (!found.some((f) => f.path === path16)) throw new DemoRepoError(`${path16} is not the top folder of a git repository`);
5824
+ const problem = enrollProblem(alias, path16, config());
5502
5825
  if (problem) throw new DemoRepoError(problem);
5503
- repos[alias] = path15;
5504
- ignored.delete(path15);
5826
+ repos[alias] = path16;
5827
+ ignored.delete(path16);
5505
5828
  },
5506
5829
  remove(alias, force) {
5507
5830
  if (!(alias in repos)) throw new DemoRepoError(`no repo \u201C${alias}\u201D`);
@@ -5510,9 +5833,9 @@ function createDemoRepos(liveTargets) {
5510
5833
  delete repos[alias];
5511
5834
  for (const g of Object.keys(groups)) groups[g] = groups[g].filter((m) => m !== alias);
5512
5835
  },
5513
- ignore(path15, on) {
5514
- if (on) ignored.add(path15);
5515
- else ignored.delete(path15);
5836
+ ignore(path16, on) {
5837
+ if (on) ignored.add(path16);
5838
+ else ignored.delete(path16);
5516
5839
  },
5517
5840
  saveGroup(name, members, creating) {
5518
5841
  const problem = groupProblem(name, members, config(), { creating });
@@ -7116,6 +7439,28 @@ async function startDemoServer(opts) {
7116
7439
  broadcast({ event: "sessions-changed", data: { ts: Date.now() } });
7117
7440
  return c.json({ ok: true });
7118
7441
  });
7442
+ const claudeUpdatedAt = new Date(Date.now() - 60 * 6e4).toISOString();
7443
+ const outdated = /* @__PURE__ */ new Set();
7444
+ app.get(
7445
+ "/api/agents",
7446
+ (c) => c.json({
7447
+ installedAt: claudeUpdatedAt,
7448
+ outdated: [...outdated].map((id) => ({
7449
+ id,
7450
+ tool: "claude",
7451
+ startedAt: new Date(Date.now() - 3 * 36e5).toISOString(),
7452
+ busy: false
7453
+ })),
7454
+ queued: []
7455
+ })
7456
+ );
7457
+ app.post("/api/agents/restart", async (c) => {
7458
+ const body = await c.req.json().catch(() => null) ?? {};
7459
+ const ids = Array.isArray(body.ids) ? body.ids.filter((i) => typeof i === "string") : [...outdated];
7460
+ for (const id of ids) outdated.delete(id);
7461
+ broadcast({ event: "agents-changed", data: { ts: Date.now() } });
7462
+ return c.json({ now: ids, later: [], failed: [] });
7463
+ });
7119
7464
  app.get("/api/pty-host/health", (c) => c.json({ state: "ok", latencyMs: 4, quietMs: 1e3, error: null }));
7120
7465
  const worklogs = /* @__PURE__ */ new Map();
7121
7466
  app.get("/api/sessions/:id/worklog", (c) => {
@@ -7242,8 +7587,9 @@ async function startDemoServer(opts) {
7242
7587
  const body = await c.req.json().catch(() => null);
7243
7588
  const cp = body?.checkpointId;
7244
7589
  if (typeof cp !== "number" || !Number.isInteger(cp) || cp < 0) return c.json({ error: "expected {checkpointId}" }, 400);
7245
- const old = diffSeen.get(id);
7246
- if (!old || old.checkpointId < cp) diffSeen.set(id, { checkpointId: cp, at: (/* @__PURE__ */ new Date()).toISOString() });
7590
+ const ts = typeof body?.ts === "string" && Number.isFinite(Date.parse(body.ts)) ? body.ts : void 0;
7591
+ const marked = markedTurn(body?.marked);
7592
+ diffSeen.set(id, nextSeen(diffSeen.get(id) ?? null, cp, /* @__PURE__ */ new Date(), ts, marked));
7247
7593
  return c.json({ seen: diffSeen.get(id) });
7248
7594
  });
7249
7595
  app.get("/api/sessions/:id/diff", (c) => {
@@ -8191,4 +8537,4 @@ export {
8191
8537
  stopExisting,
8192
8538
  webCommand
8193
8539
  };
8194
- //# sourceMappingURL=web-NFKTIH4M.js.map
8540
+ //# sourceMappingURL=web-6AOR3MIE.js.map