@dexhq/canvas 0.14.0 → 0.15.0

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 (229) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +5 -3
  3. package/app/canvas/activity.tsx +8 -15
  4. package/app/canvas/anchoring.ts +3 -5
  5. package/app/canvas/canvas-input.ts +151 -14
  6. package/app/canvas/canvas-keys.ts +9 -0
  7. package/app/canvas/canvas-model.ts +5 -42
  8. package/app/canvas/canvas-panels.ts +1 -17
  9. package/app/canvas/canvas-scene.ts +7 -3
  10. package/app/canvas/canvas-ui.ts +2 -1
  11. package/app/canvas/canvas.css +61 -26
  12. package/app/canvas/change-notice.tsx +10 -1
  13. package/app/canvas/comment-layer.tsx +2 -1
  14. package/app/canvas/comments.tsx +204 -82
  15. package/app/canvas/element-picker.ts +200 -27
  16. package/app/canvas/engine/canvas-gestures.ts +72 -17
  17. package/app/canvas/engine/canvas-store.ts +17 -1
  18. package/app/canvas/engine/engine.css +6 -3
  19. package/app/canvas/find-bar.tsx +817 -0
  20. package/app/canvas/find-model.ts +135 -0
  21. package/app/canvas/flow-canvas.tsx +18 -2
  22. package/app/canvas/follow-pin.ts +26 -6
  23. package/app/canvas/frame-node.tsx +9 -9
  24. package/app/canvas/imported-reviews.tsx +12 -22
  25. package/app/canvas/layout.ts +27 -0
  26. package/app/canvas/live-page.ts +142 -19
  27. package/app/canvas/page-find.ts +220 -0
  28. package/app/canvas/page-style.ts +23 -0
  29. package/app/canvas/section-node.tsx +2 -0
  30. package/app/canvas/spec-threads.ts +24 -23
  31. package/app/canvas/thread-focus.tsx +14 -12
  32. package/app/canvas/use-activity.ts +0 -8
  33. package/app/canvas/use-agent-changes.tsx +34 -40
  34. package/app/canvas/use-canvas-clipboard.tsx +11 -14
  35. package/app/canvas/xray.ts +3 -12
  36. package/app/frame.tsx +5 -0
  37. package/app/i18n/locales/en/messages.po +88 -8
  38. package/app/i18n/locales/en/messages.ts +1 -1
  39. package/app/i18n/locales/pseudo/messages.po +88 -8
  40. package/app/i18n/locales/pseudo/messages.ts +1 -1
  41. package/app/icons/glyphs.tsx +4 -0
  42. package/app/main.tsx +3 -0
  43. package/app/pages/canvas.tsx +27 -8
  44. package/app/pages/commands-settings.tsx +16 -2
  45. package/app/shell/feedback-form.tsx +10 -21
  46. package/app/shell/feedback-link.tsx +2 -1
  47. package/app/shell/scaled-frame.tsx +21 -9
  48. package/app/types.ts +21 -205
  49. package/app/ui/file-drop.ts +128 -0
  50. package/app/ui/shadcn/input-group.tsx +2 -2
  51. package/dist/cli/banner.d.mts +4 -2
  52. package/dist/cli/banner.mjs +34 -11
  53. package/dist/cli/commands/app.mjs +19 -11
  54. package/dist/cli/commands/hook.mjs +2 -1
  55. package/dist/config/project-files.d.mts +6 -0
  56. package/dist/config/project-files.mjs +14 -2
  57. package/dist/config/renamed.d.mts +0 -2
  58. package/dist/config/renamed.mjs +1 -3
  59. package/dist/content/capture.d.mts +2 -2
  60. package/dist/content/capture.mjs +2 -2
  61. package/dist/content/content.d.mts +3 -141
  62. package/dist/content/content.mjs +7 -62
  63. package/dist/content/flow-specs.mjs +1 -1
  64. package/dist/content/prototype-summary.d.mts +3 -39
  65. package/dist/content/prototype-summary.mjs +2 -3
  66. package/dist/content/prototypes.mjs +1 -1
  67. package/dist/content/text-replace.d.mts +30 -0
  68. package/dist/content/text-replace.mjs +309 -0
  69. package/dist/content/thread-module.mjs +1 -1
  70. package/dist/content/threads.mjs +1 -1
  71. package/dist/paste/paste.mjs +1 -1
  72. package/dist/paths.d.mts +0 -2
  73. package/dist/paths.mjs +1 -3
  74. package/dist/server/agent-env.d.mts +5 -1
  75. package/dist/server/agent-env.mjs +7 -2
  76. package/dist/server/agent-session.d.mts +14 -1
  77. package/dist/server/agent-session.mjs +84 -19
  78. package/dist/server/build-pictures.mjs +1 -1
  79. package/dist/server/channel.d.mts +13 -24
  80. package/dist/server/channel.mjs +55 -37
  81. package/dist/server/claimed-presence.d.mts +3 -2
  82. package/dist/server/claimed-presence.mjs +15 -7
  83. package/dist/server/close-check.mjs +2 -2
  84. package/dist/server/comments/actions.d.mts +153 -0
  85. package/dist/server/comments/actions.mjs +154 -0
  86. package/dist/server/comments/routes.d.mts +25 -0
  87. package/dist/server/comments/routes.mjs +88 -0
  88. package/dist/server/comments/tools.d.mts +6 -0
  89. package/dist/server/comments/tools.mjs +154 -0
  90. package/dist/server/dev-server.mjs +27 -13
  91. package/dist/server/file-lock.d.mts +2 -2
  92. package/dist/server/file-lock.mjs +130 -36
  93. package/dist/server/mcp.d.mts +0 -2
  94. package/dist/server/mcp.mjs +7 -8
  95. package/dist/server/me.d.mts +1 -1
  96. package/dist/server/open-page.d.mts +22 -0
  97. package/dist/server/open-page.mjs +20 -2
  98. package/dist/server/outcome.d.mts +22 -0
  99. package/dist/server/outcome.mjs +8 -0
  100. package/dist/server/own-copies.mjs +2 -2
  101. package/dist/server/people.d.mts +1 -1
  102. package/dist/server/port.d.mts +12 -0
  103. package/dist/server/port.mjs +66 -14
  104. package/dist/server/presence.d.mts +4 -1
  105. package/dist/server/presence.mjs +2 -2
  106. package/dist/server/requests.d.mts +5 -1
  107. package/dist/server/requests.mjs +33 -48
  108. package/dist/server/studio-for.d.mts +5 -0
  109. package/dist/server/studio-for.mjs +17 -3
  110. package/dist/server/sync-install.d.mts +8 -12
  111. package/dist/server/sync-install.mjs +12 -30
  112. package/dist/server/thread-source.mjs +2 -2
  113. package/dist/server/tools/describe.d.mts +1 -1
  114. package/dist/server/tools/describe.mjs +1 -1
  115. package/dist/server/tools/feedback.d.mts +1 -1
  116. package/dist/server/tools/reading.mjs +13 -4
  117. package/dist/server/tools/show.d.mts +1 -1
  118. package/dist/server/tools/snapshot.d.mts +1 -1
  119. package/dist/server/tools/thread-list.mjs +1 -1
  120. package/dist/server/tools/watch.mjs +5 -3
  121. package/dist/server/vite.mjs +2 -2
  122. package/dist/server/web-app.mjs +4 -7
  123. package/dist/server/work-groups.mjs +1 -1
  124. package/dist/setup/create.d.mts +4 -2
  125. package/dist/setup/create.mjs +67 -17
  126. package/dist/setup/design-system-checks.mjs +3 -12
  127. package/dist/setup/desktop-app-script.mjs +4 -3
  128. package/dist/setup/desktop-app-start.d.mts +8 -2
  129. package/dist/setup/desktop-app-start.mjs +64 -29
  130. package/dist/setup/desktop-app.d.mts +8 -0
  131. package/dist/setup/desktop-app.mjs +19 -3
  132. package/dist/setup/detect.d.mts +0 -2
  133. package/dist/setup/detect.mjs +1 -3
  134. package/dist/setup/doctor.mjs +1 -1
  135. package/dist/setup/migrate/row-titles.mjs +1 -1
  136. package/dist/setup/project.d.mts +6 -1
  137. package/dist/setup/project.mjs +9 -9
  138. package/dist/setup/starters.d.mts +2 -0
  139. package/dist/setup/starters.mjs +7 -1
  140. package/dist/shared/annotations-core.mjs +1 -1
  141. package/dist/shared/canvas-core.mjs +1 -1
  142. package/dist/shared/canvas-file.d.mts +201 -0
  143. package/dist/shared/canvas-file.mjs +1 -0
  144. package/dist/shared/comments/routes.d.mts +53 -0
  145. package/dist/shared/comments/routes.mjs +37 -0
  146. package/dist/shared/feedback.d.mts +8 -0
  147. package/dist/shared/feedback.mjs +10 -2
  148. package/dist/shared/page-review.d.mts +2 -11
  149. package/dist/shared/page-review.mjs +4 -13
  150. package/dist/shared/presence-core.d.mts +11 -0
  151. package/dist/shared/presence-core.mjs +11 -2
  152. package/dist/shared/review-file.d.mts +5 -0
  153. package/dist/shared/review-file.mjs +23 -13
  154. package/dist/shared/server-page.mjs +1 -1
  155. package/dist/shared/signup.d.mts +2 -5
  156. package/dist/shared/signup.mjs +2 -35
  157. package/dist/shared/studio-events.d.mts +0 -6
  158. package/dist/shared/studio-events.mjs +1 -5
  159. package/dist/shared/studio-files.d.mts +12 -0
  160. package/dist/shared/studio-files.mjs +6 -1
  161. package/dist/shared/studio-routes.d.mts +16 -62
  162. package/dist/shared/studio-routes.mjs +1 -69
  163. package/dist/shared/threads-core.d.mts +2 -2
  164. package/dist/shared/threads-core.mjs +1 -1
  165. package/extension/dist/feedback.js +148 -138
  166. package/extension/dist/manifest.json +1 -1
  167. package/extension/dist/picker.js +146 -136
  168. package/package.json +2 -2
  169. package/src/cli/banner.ts +45 -11
  170. package/src/cli/commands/app.ts +23 -8
  171. package/src/cli/commands/hook.ts +4 -1
  172. package/src/config/project-files.ts +21 -6
  173. package/src/config/renamed.ts +0 -3
  174. package/src/content/capture.ts +6 -12
  175. package/src/content/content.ts +7 -241
  176. package/src/content/flow-specs.ts +2 -1
  177. package/src/content/prototype-summary.ts +4 -44
  178. package/src/content/review-pages.ts +2 -1
  179. package/src/content/text-replace.ts +449 -0
  180. package/src/paths.ts +0 -8
  181. package/src/server/agent-env.ts +12 -2
  182. package/src/server/agent-session.ts +124 -34
  183. package/src/server/channel.ts +94 -52
  184. package/src/server/claimed-presence.ts +26 -10
  185. package/src/server/comments/actions.ts +352 -0
  186. package/src/server/comments/routes.ts +176 -0
  187. package/src/server/comments/tools.ts +317 -0
  188. package/src/server/dev-server.ts +36 -15
  189. package/src/server/file-lock.ts +205 -54
  190. package/src/server/mcp.ts +13 -14
  191. package/src/server/me.ts +2 -5
  192. package/src/server/open-page.ts +54 -4
  193. package/src/server/outcome.ts +26 -0
  194. package/src/server/people.ts +2 -1
  195. package/src/server/port.ts +94 -20
  196. package/src/server/presence.ts +11 -3
  197. package/src/server/requests.ts +60 -70
  198. package/src/server/studio-for.ts +26 -2
  199. package/src/server/sync-install.ts +35 -26
  200. package/src/server/thread-place.ts +2 -4
  201. package/src/server/tools/reading.ts +16 -3
  202. package/src/server/tools/watch.ts +7 -7
  203. package/src/server/web-app.ts +11 -9
  204. package/src/setup/create.ts +91 -17
  205. package/src/setup/design-system-checks.ts +7 -15
  206. package/src/setup/desktop-app-script.ts +4 -3
  207. package/src/setup/desktop-app-start.ts +94 -26
  208. package/src/setup/desktop-app.ts +23 -2
  209. package/src/setup/detect.ts +0 -4
  210. package/src/setup/project.ts +9 -8
  211. package/src/setup/starters.ts +8 -1
  212. package/src/shared/canvas-file.ts +205 -0
  213. package/src/shared/comments/routes.ts +79 -0
  214. package/src/shared/feedback.ts +14 -4
  215. package/src/shared/page-review.ts +11 -16
  216. package/src/shared/presence-core.ts +16 -2
  217. package/src/shared/review-file.ts +28 -12
  218. package/src/shared/server-page.ts +2 -1
  219. package/src/shared/signup.ts +4 -28
  220. package/src/shared/studio-events.ts +0 -13
  221. package/src/shared/studio-files.ts +14 -0
  222. package/src/shared/studio-routes.ts +21 -64
  223. package/src/shared/threads-core.ts +2 -2
  224. package/dist/server/tools/close-reply.d.mts +0 -6
  225. package/dist/server/tools/close-reply.mjs +0 -138
  226. package/dist/server/tools/comment.d.mts +0 -6
  227. package/dist/server/tools/comment.mjs +0 -49
  228. package/src/server/tools/close-reply.ts +0 -271
  229. package/src/server/tools/comment.ts +0 -96
@@ -4,15 +4,20 @@
4
4
  // and another session cannot take it: the thread's 👀 says it was picked
5
5
  // up. Claiming marks no view as being edited: the agent's edits do that
6
6
  // (`dex hook`, presence.ts), so the canvas shows work only once there is
7
- // some. Resolving or dismissing a thread clears this session's marks on it,
8
- // and a session that ends lets go of the threads it had not finished.
7
+ // some. The dev server marks under the session's id, Claude Code's hook
8
+ // under the id of the Claude session it serves, and both are the session's
9
+ // marks. They end with its work, as the heads-up's "working" ends with its
10
+ // claims: a thread it lets go clears its view, unless it holds another
11
+ // there; holding none clears every mark, and so does going back to `watch`
12
+ // with none. A session that ends lets go of the threads it had not finished.
9
13
 
10
14
  import { randomUUID } from "node:crypto";
11
15
  import type { ThreadAnswer, ThreadModule } from "../content/thread-module.ts";
12
16
  import type { PresenceTarget } from "../shared/presence-core.ts";
13
- import type {
14
- AgentAction,
15
- ThreadWithPrototype,
17
+ import {
18
+ type AgentAction,
19
+ claimOf,
20
+ type ThreadWithPrototype,
16
21
  } from "../shared/threads-core.ts";
17
22
  import { openPresence } from "./presence.ts";
18
23
 
@@ -70,30 +75,32 @@ export function openAgentSession(
70
75
  threads: ThreadModule,
71
76
  {
72
77
  agent,
78
+ claudeSession,
73
79
  id = newSessionId(),
74
80
  presence = openPresence(root),
75
81
  }: {
76
82
  agent: () => string;
83
+ /**
84
+ * The Claude Code session it serves, when it does: Claude's hook marks
85
+ * that agent's edits under its id.
86
+ */
87
+ claudeSession?: string;
77
88
  id?: string;
78
89
  presence?: SessionPresence;
79
90
  }
80
91
  ) {
81
- /** Once the thread is resolved or dismissed, clear this session's marks on its view. */
82
- const clearOnClose = async (
83
- action: UnsignedAction,
84
- thread: ThreadWithPrototype
85
- ) => {
86
- const where = presenceTargetOf(thread);
87
- if (!where) {
88
- return;
89
- }
90
- try {
91
- if (action.action === "resolve" || action.action === "dismiss") {
92
- await presence.clear({ ...where, session: id });
93
- }
94
- } catch {
95
- // Presence only shows the work; the thread has changed all the same.
96
- }
92
+ /** Whom its marks are under: itself, and the Claude Code session it serves. */
93
+ const marksUnder =
94
+ claudeSession && claudeSession !== id ? [id, claudeSession] : [id];
95
+ /**
96
+ * Clear its marks, its sub-agents' too, on one view or doc or everywhere.
97
+ * Presence only shows the work: a clear that fails changes nothing, and
98
+ * marks expire.
99
+ */
100
+ const clearMarks = async (where?: PresenceTarget): Promise<void> => {
101
+ await Promise.allSettled(
102
+ marksUnder.map((within) => presence.clear({ ...where, within }))
103
+ );
97
104
  };
98
105
 
99
106
  /** Threads this session claimed and has not yet closed or answered. */
@@ -113,6 +120,80 @@ export function openAgentSession(
113
120
  /** Given to another server (mcp-handover.ts): this one lets go of nothing. */
114
121
  let handedOver = false;
115
122
 
123
+ /** Where each thread it holds is on the canvas, once it has looked. */
124
+ const places = new Map<string, PresenceTarget | undefined>();
125
+ const placeOf = async (
126
+ threadId: string
127
+ ): Promise<PresenceTarget | undefined> => {
128
+ if (!places.has(threadId)) {
129
+ const thread = await threads.find(threadId);
130
+ places.set(threadId, thread && presenceTargetOf(thread));
131
+ }
132
+ return places.get(threadId);
133
+ };
134
+
135
+ /**
136
+ * Let go of the threads it holds that a person closed or answered since
137
+ * it claimed them, which are no longer its own. One claimed meanwhile
138
+ * stays held.
139
+ */
140
+ const letGoOfClosed = async (): Promise<void> => {
141
+ const ids = [...held];
142
+ if (ids.length === 0) {
143
+ return;
144
+ }
145
+ const own = new Set(
146
+ (await threads.list({ status: "acknowledged" }))
147
+ .filter((thread) => claimOf(thread)?.session === id)
148
+ .map((thread) => thread.id)
149
+ );
150
+ const closed = ids.filter((each) => !own.has(each));
151
+ if (closed.length > 0) {
152
+ holdingChange(() => {
153
+ for (const each of closed) {
154
+ held.delete(each);
155
+ places.delete(each);
156
+ }
157
+ });
158
+ }
159
+ };
160
+
161
+ /** Whether it holds a thread on `where`, as far as it knows. */
162
+ const holdsOn = async (where: PresenceTarget): Promise<boolean> =>
163
+ (await Promise.all([...held].map(placeOf))).some(
164
+ (on) => on?.slug === where.slug && on.target === where.target
165
+ );
166
+
167
+ /**
168
+ * Its work on `thread` (or on nothing, waiting) is over: the thread's view
169
+ * shows nobody at work for it, unless it holds another there, and once
170
+ * it holds nothing, nothing it marked does (the file's shared code, other
171
+ * views it changed on the way). What it holds is looked at again first
172
+ * with `recheck`, or when another it holds would keep the view's marks,
173
+ * as a person may have closed it meanwhile. Handed over, its marks are
174
+ * the next server's.
175
+ */
176
+ const workEnded = async (
177
+ thread: ThreadWithPrototype | undefined,
178
+ recheck: boolean
179
+ ): Promise<void> => {
180
+ if (handedOver) {
181
+ return;
182
+ }
183
+ const where = thread && presenceTargetOf(thread);
184
+ if (recheck || (where && (await holdsOn(where)))) {
185
+ // Without the look, it ends what it knows to have ended.
186
+ await letGoOfClosed().catch(() => undefined);
187
+ }
188
+ if (held.size === 0) {
189
+ await clearMarks();
190
+ return;
191
+ }
192
+ if (where && !(await holdsOn(where))) {
193
+ await clearMarks(where);
194
+ }
195
+ };
196
+
116
197
  /**
117
198
  * An action on a thread, signed by this session: the thread after it, the
118
199
  * problems that stopped it, or undefined when there is no such thread.
@@ -126,22 +207,26 @@ export function openAgentSession(
126
207
  author: agent(),
127
208
  session: id,
128
209
  } as AgentAction);
129
- if (answer?.thread) {
130
- await clearOnClose(action, answer.thread);
131
- }
132
210
  // Closed, answered or let go, it is no longer this session's to release;
133
211
  // nor is one a refused release names (a person answered first).
134
- if (
212
+ const letGo =
135
213
  action.action === "release" ||
136
- (answer?.thread && LETS_GO.has(action.action))
137
- ) {
214
+ Boolean(answer?.thread && LETS_GO.has(action.action));
215
+ if (letGo) {
216
+ // Done with one it held: the rest are looked at again. One it never
217
+ // held (closed straight from a list) changes nothing it holds.
218
+ const finished = held.has(threadId);
138
219
  holdingChange(() => held.delete(threadId));
220
+ places.delete(threadId);
221
+ // Presence only shows the work: the thread has changed all the same.
222
+ await workEnded(answer?.thread, finished).catch(() => undefined);
139
223
  }
140
224
  return answer;
141
225
  };
142
226
 
143
227
  return {
144
228
  id,
229
+ marksUnder,
145
230
  act,
146
231
  /**
147
232
  * Claim a thread for this session: it is acknowledged (👀), and the
@@ -151,6 +236,7 @@ export function openAgentSession(
151
236
  claim: async (threadId: string) => {
152
237
  const answer = await act(threadId, { action: "acknowledge" });
153
238
  if (answer?.thread) {
239
+ places.set(threadId, presenceTargetOf(answer.thread));
154
240
  holdingChange(() => held.add(threadId));
155
241
  }
156
242
  return answer;
@@ -168,6 +254,14 @@ export function openAgentSession(
168
254
  },
169
255
  /** The threads the session holds now, for the server after this one. */
170
256
  holding: (): string[] => [...held],
257
+ /**
258
+ * The agent waits for work (`watch`): holding none, it is at work
259
+ * nowhere, as when its turn ends, so nothing it marked shows. Holding
260
+ * some, its marks stay with them. A comment a person closed or answered
261
+ * while it held it is no longer its own, and counts for none.
262
+ */
263
+ waits: (): Promise<void> =>
264
+ workEnded(undefined, true).catch(() => undefined),
171
265
  /** Hear how many threads the session holds, each time that changes. */
172
266
  onHoldingChange: (listener: (count: number) => void): void => {
173
267
  holdingListeners.add(listener);
@@ -182,6 +276,7 @@ export function openAgentSession(
182
276
  holdingChange(() => {
183
277
  for (const threadId of given) {
184
278
  held.delete(threadId);
279
+ places.delete(threadId);
185
280
  }
186
281
  });
187
282
  },
@@ -196,13 +291,8 @@ export function openAgentSession(
196
291
  await Promise.allSettled(
197
292
  unfinished.map((threadId) => act(threadId, { action: "release" }))
198
293
  );
199
- if (handedOver) {
200
- return;
201
- }
202
- try {
203
- await presence.clear({ session: id });
204
- } catch {
205
- // Marks expire on their own.
294
+ if (!handedOver) {
295
+ await clearMarks();
206
296
  }
207
297
  },
208
298
  };
@@ -38,7 +38,9 @@ import {
38
38
  } from "../shared/threads-core.ts";
39
39
  import type { AgentSession } from "./agent-session.ts";
40
40
  import { readCloudConfig } from "./cloud.ts";
41
+ import { claimComment } from "./comments/actions.ts";
41
42
  import { yoursGroups } from "./own-copies.ts";
43
+ import { openPresence } from "./presence.ts";
42
44
  import { firstOf, RESPONSE_BUDGETS } from "./response-budget.ts";
43
45
  import { prepareState, studioState } from "./state.ts";
44
46
  import { FOR_WORK, type Form, SHORT, shaped } from "./thread-forms.ts";
@@ -224,35 +226,55 @@ export function openReceipt({
224
226
  /** A session's heartbeat file: who it is, and when it last beat. */
225
227
  interface Heartbeat extends ConnectedAgent {
226
228
  at: number;
229
+ /** The Claude Code session it serves, whose hook marks presence under it. */
230
+ claudeSession?: string;
227
231
  /** The agent session's id, which signs its claims; missing from older ones. */
228
232
  session?: string;
229
233
  /** The Dex version the session runs; missing from older ones. */
230
234
  version?: string;
231
235
  }
232
236
 
233
- /** What hears of a session whose heartbeat stopped without its saying so. */
234
- type OnGone = (beat: Heartbeat) => Promise<void>;
237
+ /** What lets go of a gone session's threads: the studio's thread module. */
238
+ type SessionThreads = Pick<ThreadModule, "act" | "list">;
239
+
240
+ /** The ids a heartbeat's session works under: its own, and its Claude session's. */
241
+ const idsOf = ({ claudeSession, session }: Heartbeat): string[] =>
242
+ [session, claudeSession].filter((each): each is string => each !== undefined);
235
243
 
236
244
  /**
237
- * Let go of the threads a session that is gone still holds, so they wait
238
- * for an agent again instead of showing its 👀 for good: a session that
239
- * crashed or was killed never let go of them itself (agent-session.ts).
245
+ * End the work of a session whose heartbeat stopped without its saying so,
246
+ * as a session that crashed or was killed never did (agent-session.ts):
247
+ * clear its marks and its Claude session's, so the canvas shows it at work
248
+ * nowhere, and, given `threads`, let go of the threads it still holds, so
249
+ * they wait for an agent again instead of showing its 👀 for good. Ids
250
+ * still `beating` are left alone: a session moved to another server
251
+ * (mcp-handover.ts) beats there under the same ids.
240
252
  */
241
- export const releaseGone =
242
- (threads: Pick<ThreadModule, "act" | "list">): OnGone =>
243
- async ({ agent, session }) => {
244
- if (!session) {
245
- return;
246
- }
247
- const held = (await threads.list({ status: "acknowledged" })).filter(
248
- (thread) => claimOf(thread)?.session === session
249
- );
250
- await Promise.allSettled(
251
- held.map((thread) =>
252
- threads.act(thread.id, { action: "release", author: agent, session })
253
- )
254
- );
255
- };
253
+ const endGone = async (
254
+ root: string,
255
+ beat: Heartbeat,
256
+ beating: ReadonlySet<string>,
257
+ threads?: SessionThreads
258
+ ): Promise<void> => {
259
+ const { agent, session } = beat;
260
+ if (!session || beating.has(session)) {
261
+ return;
262
+ }
263
+ const releases = threads
264
+ ? (await threads.list({ status: "acknowledged" }))
265
+ .filter((thread) => claimOf(thread)?.session === session)
266
+ .map((thread) =>
267
+ threads.act(thread.id, { action: "release", author: agent, session })
268
+ )
269
+ : [];
270
+ const presence = openPresence(root);
271
+ await Promise.allSettled([
272
+ ...releases,
273
+ ...idsOf(beat)
274
+ .filter((each) => !beating.has(each))
275
+ .map((within) => presence.clear({ within })),
276
+ ]);
277
+ };
256
278
 
257
279
  /**
258
280
  * Let go of the threads held by sessions that are no longer connected, so a
@@ -266,7 +288,7 @@ export const releaseGone =
266
288
  */
267
289
  export async function releaseAbandoned(
268
290
  root: string,
269
- threads: Pick<ThreadModule, "act" | "list">,
291
+ threads: SessionThreads,
270
292
  own: string,
271
293
  {
272
294
  now = Date.now(),
@@ -342,15 +364,20 @@ export async function setWatching(root: string, on: boolean): Promise<void> {
342
364
  * The agents connected to the studio over MCP, from their heartbeats: each
343
365
  * one's name and whether it is a channel (feedback reaches it by itself).
344
366
  * Heartbeats left by sessions that ended without saying so are cleared once
345
- * they are `listeningMs` old at `now`, and `onGone` hears of each first.
367
+ * they are `listeningMs` old at `now`, each session's work ended first
368
+ * (endGone), its threads let go given `threads`.
346
369
  */
347
370
  export async function connectedAgents(
348
371
  root: string,
349
372
  {
350
373
  now = Date.now(),
351
374
  listeningMs = LISTENING_MS,
352
- onGone,
353
- }: { listeningMs?: number; now?: number; onGone?: OnGone } = {}
375
+ threads,
376
+ }: {
377
+ listeningMs?: number;
378
+ now?: number;
379
+ threads?: SessionThreads;
380
+ } = {}
354
381
  ): Promise<ConnectedAgent[]> {
355
382
  const dir = studioState(root).agents;
356
383
  let names: string[] = [];
@@ -359,30 +386,41 @@ export async function connectedAgents(
359
386
  } catch {
360
387
  return [];
361
388
  }
362
- const agents: ConnectedAgent[] = [];
389
+ const beats: { beat: Heartbeat; file: string; name: string }[] = [];
363
390
  for (const name of names) {
364
391
  const file = join(dir, name);
365
392
  try {
366
- const beat: Heartbeat = JSON.parse(await readFile(file, "utf8"));
367
- if (now - beat.at < listeningMs) {
368
- // Sessions from before versions were written run an older one.
369
- agents.push({
370
- agent: beat.agent,
371
- channel: Boolean(beat.channel),
372
- ...pidOf(name),
373
- ...(beat.unproven && !beat.channel ? { unproven: true } : {}),
374
- ...(beat.watching ? { watching: true } : {}),
375
- ...(beat.holding ? { holding: beat.holding } : {}),
376
- ...outdatedOf(beat.version),
377
- });
378
- } else {
379
- await onGone?.(beat).catch(() => undefined);
380
- await rm(file, { force: true });
381
- }
393
+ beats.push({
394
+ beat: JSON.parse(await readFile(file, "utf8")),
395
+ file,
396
+ name,
397
+ });
382
398
  } catch {
383
399
  // A heartbeat mid-write: it will be whole next time.
384
400
  }
385
401
  }
402
+ const isFresh = (beat: Heartbeat) => now - beat.at < listeningMs;
403
+ const beating = new Set(
404
+ beats.flatMap(({ beat }) => (isFresh(beat) ? idsOf(beat) : []))
405
+ );
406
+ const agents: ConnectedAgent[] = [];
407
+ for (const { beat, file, name } of beats) {
408
+ if (isFresh(beat)) {
409
+ // Sessions from before versions were written run an older one.
410
+ agents.push({
411
+ agent: beat.agent,
412
+ channel: Boolean(beat.channel),
413
+ ...pidOf(name),
414
+ ...(beat.unproven && !beat.channel ? { unproven: true } : {}),
415
+ ...(beat.watching ? { watching: true } : {}),
416
+ ...(beat.holding ? { holding: beat.holding } : {}),
417
+ ...outdatedOf(beat.version),
418
+ });
419
+ } else {
420
+ await endGone(root, beat, beating, threads).catch(() => undefined);
421
+ await rm(file, { force: true });
422
+ }
423
+ }
386
424
  return agents;
387
425
  }
388
426
 
@@ -466,9 +504,10 @@ const commandOf = (pid: number): Promise<string | undefined> =>
466
504
  */
467
505
  export async function stopAgentServer(
468
506
  root: string,
469
- pid: number
507
+ pid: number,
508
+ threads?: SessionThreads
470
509
  ): Promise<void> {
471
- const agent = (await connectedAgents(root)).find(
510
+ const agent = (await connectedAgents(root, { threads })).find(
472
511
  (each) => each.pid === pid && each.outdated?.restartOnce
473
512
  );
474
513
  if (!agent) {
@@ -515,7 +554,7 @@ const everyTick: Tick = (check) => {
515
554
  * when it changes: an agent connects, or its heartbeat stops and passes the
516
555
  * listening window. A page hears the list as it is when it starts listening.
517
556
  * Nothing is checked while no page listens. Given `threads`, the threads a
518
- * gone session held are let go (releaseGone). `now` and `tick` are for tests.
557
+ * gone session held are let go (endGone). `now` and `tick` are for tests.
519
558
  */
520
559
  export function trackAgents(
521
560
  root: string,
@@ -525,11 +564,10 @@ export function trackAgents(
525
564
  threads,
526
565
  }: {
527
566
  now?: () => number;
528
- threads?: Pick<ThreadModule, "act" | "list">;
567
+ threads?: SessionThreads;
529
568
  tick?: Tick;
530
569
  } = {}
531
570
  ) {
532
- const onGone = threads ? releaseGone(threads) : undefined;
533
571
  const pages = new Set<(agents: ConnectedAgent[]) => void>();
534
572
  // The list as the pages last heard it; undefined until the first check.
535
573
  let agents: ConnectedAgent[] | undefined;
@@ -537,7 +575,7 @@ export function trackAgents(
537
575
  let stopTicking: (() => void) | undefined;
538
576
 
539
577
  const check = () => {
540
- checking ??= connectedAgents(root, { now: now(), onGone })
578
+ checking ??= connectedAgents(root, { now: now(), threads })
541
579
  .then((found) => {
542
580
  if (JSON.stringify(found) !== JSON.stringify(agents)) {
543
581
  agents = found;
@@ -618,11 +656,14 @@ export function startHeartbeat(
618
656
  describe: () => ConnectedAgent,
619
657
  {
620
658
  beatMs = BEAT_MS,
659
+ claudeSession,
621
660
  onEnd,
622
661
  session,
623
662
  write = writeWhole,
624
663
  }: {
625
664
  beatMs?: number;
665
+ /** The Claude Code session it serves, when it does. */
666
+ claudeSession?: string;
626
667
  onEnd?: () => Promise<void>;
627
668
  session?: string;
628
669
  /** How a beat is written (for tests): whole, or not at all. */
@@ -648,6 +689,7 @@ export function startHeartbeat(
648
689
  ...describe(),
649
690
  at: Date.now(),
650
691
  ...(session ? { session } : {}),
692
+ ...(claudeSession ? { claudeSession } : {}),
651
693
  version: runningVersion,
652
694
  })
653
695
  );
@@ -1017,17 +1059,17 @@ export async function startChannel(
1017
1059
  }
1018
1060
  const claimed: ThreadWithPrototype[] = [];
1019
1061
  for (const thread of [...held.values()]) {
1020
- let answer: Awaited<ReturnType<AgentSession["claim"]>>;
1062
+ let answer: Awaited<ReturnType<typeof claimComment>>;
1021
1063
  try {
1022
- answer = await session.claim(thread.id);
1064
+ answer = await claimComment({ session }, thread.id);
1023
1065
  } catch {
1024
1066
  continue;
1025
1067
  }
1026
1068
  held.delete(thread.id);
1027
1069
  sent.add(stamp(thread));
1028
- if (answer?.thread) {
1029
- sent.add(stamp(answer.thread));
1030
- claimed.push(answer.thread);
1070
+ if (answer.value) {
1071
+ sent.add(stamp(answer.value));
1072
+ claimed.push(answer.value);
1031
1073
  }
1032
1074
  }
1033
1075
  if (claimed.length === 0) {
@@ -4,14 +4,16 @@
4
4
  // hook, so the dev server, which sees every file in a prototype change, marks
5
5
  // the session on this machine holding a claimed thread there. The mark is the
6
6
  // thread's own target, so closing the thread clears it (agent-session.ts);
7
- // otherwise it expires as a hook's does.
7
+ // otherwise it expires as a hook's does. A thread closed while its mark is
8
+ // written would leave it behind, so the claims are looked at again after.
8
9
 
9
10
  import { relative } from "node:path";
10
11
  import type { ThreadModule } from "../content/thread-module.ts";
11
12
  import { targetForPath } from "../shared/live-presence.ts";
13
+ import type { PresenceTarget } from "../shared/presence-core.ts";
12
14
  import { claimOf } from "../shared/threads-core.ts";
13
15
  import { presenceTargetOf } from "./agent-session.ts";
14
- import type { PresenceMark } from "./presence.ts";
16
+ import type { PresenceMark, PresenceMatch } from "./presence.ts";
15
17
 
16
18
  /** How often one claim's session is marked again while it edits. */
17
19
  const REMARK_MS = 10_000;
@@ -23,12 +25,14 @@ const REMARK_MS = 10_000;
23
25
  * a teammate's claim, synced from the workspace, is never marked here.
24
26
  */
25
27
  export function claimedPresence({
28
+ clear,
26
29
  content,
27
30
  mark,
28
31
  sessions,
29
32
  threads,
30
33
  now = Date.now,
31
34
  }: {
35
+ clear: (match: PresenceMatch) => Promise<void>;
32
36
  content: string;
33
37
  mark: (entry: PresenceMark) => Promise<void>;
34
38
  sessions: () => Promise<Set<string>>;
@@ -36,25 +40,24 @@ export function claimedPresence({
36
40
  now?: () => number;
37
41
  }) {
38
42
  const marked = new Map<string, number>();
43
+ /** The claimed threads on the view or doc edited. */
44
+ const claimsOn = async (edited: PresenceTarget) =>
45
+ (
46
+ await threads.list({ prototype: edited.slug, status: "acknowledged" })
47
+ ).filter((thread) => presenceTargetOf(thread)?.target === edited.target);
39
48
  return async (file: string): Promise<void> => {
40
49
  const edited = targetForPath(relative(content, file).replaceAll("\\", "/"));
41
50
  if (!edited || edited.target === "prototype") {
42
51
  return;
43
52
  }
44
- const claimed = await threads.list({
45
- prototype: edited.slug,
46
- status: "acknowledged",
47
- });
53
+ const claimed = await claimsOn(edited);
48
54
  const time = now();
49
55
  const marks: PresenceMark[] = [];
50
56
  let local: Set<string> | undefined;
51
57
  for (const thread of claimed) {
52
58
  const claim = claimOf(thread);
53
59
  const session = claim?.session;
54
- if (
55
- !(claim && session) ||
56
- presenceTargetOf(thread)?.target !== edited.target
57
- ) {
60
+ if (!(claim && session)) {
58
61
  continue;
59
62
  }
60
63
  // Each claim's first edit marks at once, even just after another
@@ -72,6 +75,19 @@ export function claimedPresence({
72
75
  marked.set(key, time);
73
76
  marks.push({ ...edited, agent: claim.by, session });
74
77
  }
78
+ if (marks.length === 0) {
79
+ return;
80
+ }
75
81
  await Promise.all(marks.map(mark));
82
+ // A claim closed since it was looked up has cleared its marks already,
83
+ // maybe before this one landed: clear the mark of a claim no longer held.
84
+ const holding = new Set(
85
+ (await claimsOn(edited)).map((thread) => claimOf(thread)?.session)
86
+ );
87
+ await Promise.all(
88
+ marks
89
+ .filter(({ session }) => !holding.has(session))
90
+ .map(({ session }) => clear({ ...edited, session }))
91
+ );
76
92
  };
77
93
  }