@openartifactsai/editor-kit 0.0.0-stage → 0.23.0-rc.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 (120) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +143 -2
  4. package/package.json +67 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +37 -0
  9. package/src/FoldToolbar.d.ts +58 -0
  10. package/src/FoldToolbar.js +438 -0
  11. package/src/PanelEdge.d.ts +20 -0
  12. package/src/PanelEdge.js +74 -0
  13. package/src/VideoShrinkNotice.d.ts +10 -0
  14. package/src/VideoShrinkNotice.js +81 -0
  15. package/src/WheelZoomItem.d.ts +12 -0
  16. package/src/WheelZoomItem.js +18 -0
  17. package/src/agent.d.ts +68 -0
  18. package/src/agent.js +113 -0
  19. package/src/announce.d.ts +21 -0
  20. package/src/announce.js +31 -0
  21. package/src/chrome.d.ts +208 -0
  22. package/src/chrome.js +148 -0
  23. package/src/clipboard.d.ts +19 -0
  24. package/src/clipboard.js +48 -0
  25. package/src/collab/CommentList.d.ts +32 -0
  26. package/src/collab/CommentList.js +165 -0
  27. package/src/collab/CommentViews.d.ts +131 -0
  28. package/src/collab/CommentViews.js +619 -0
  29. package/src/collab/HistoryViews.d.ts +38 -0
  30. package/src/collab/HistoryViews.js +103 -0
  31. package/src/collab/PresenceViews.d.ts +53 -0
  32. package/src/collab/PresenceViews.js +48 -0
  33. package/src/collab/cds/cds.d.ts +151 -0
  34. package/src/collab/cds/cds.js +231 -0
  35. package/src/collab/cds/comment-card.d.ts +113 -0
  36. package/src/collab/cds/comment-card.js +230 -0
  37. package/src/collab/cds/comment-composer.d.ts +35 -0
  38. package/src/collab/cds/comment-composer.js +125 -0
  39. package/src/collab/cds/comments-css.d.ts +2 -0
  40. package/src/collab/cds/comments-css.js +3 -0
  41. package/src/collab/cds/comments.css +504 -0
  42. package/src/collab/cds/edge-piles.d.ts +69 -0
  43. package/src/collab/cds/edge-piles.js +178 -0
  44. package/src/collab/cds/layer.d.ts +41 -0
  45. package/src/collab/cds/layer.js +144 -0
  46. package/src/collab/cds/markdown.d.ts +20 -0
  47. package/src/collab/cds/markdown.js +534 -0
  48. package/src/collab/cds/shield.d.ts +28 -0
  49. package/src/collab/cds/shield.js +114 -0
  50. package/src/collab/cds/time.d.ts +2 -0
  51. package/src/collab/cds/time.js +41 -0
  52. package/src/collab/collab.d.ts +102 -0
  53. package/src/collab/collab.js +121 -0
  54. package/src/collab/comments.d.ts +272 -0
  55. package/src/collab/comments.js +596 -0
  56. package/src/collab/history-wiring.d.ts +32 -0
  57. package/src/collab/history-wiring.js +53 -0
  58. package/src/collab/history.d.ts +59 -0
  59. package/src/collab/history.js +96 -0
  60. package/src/collab/mentions/mention-list.d.ts +63 -0
  61. package/src/collab/mentions/mention-list.js +257 -0
  62. package/src/collab/mentions.d.ts +112 -0
  63. package/src/collab/mentions.js +164 -0
  64. package/src/collab/peer-colors.d.ts +123 -0
  65. package/src/collab/peer-colors.js +273 -0
  66. package/src/collab/pins.d.ts +70 -0
  67. package/src/collab/pins.js +44 -0
  68. package/src/collab/presence.d.ts +92 -0
  69. package/src/collab/presence.js +158 -0
  70. package/src/design-systems.d.ts +46 -0
  71. package/src/design-systems.js +61 -0
  72. package/src/downloads.d.ts +31 -0
  73. package/src/downloads.js +46 -0
  74. package/src/file-drop.d.ts +33 -0
  75. package/src/file-drop.js +36 -0
  76. package/src/find.d.ts +64 -0
  77. package/src/find.js +147 -0
  78. package/src/follow.d.ts +141 -0
  79. package/src/follow.js +389 -0
  80. package/src/index.d.ts +32 -0
  81. package/src/index.js +32 -0
  82. package/src/keys.d.ts +18 -0
  83. package/src/keys.js +42 -0
  84. package/src/menu-fit.d.ts +12 -0
  85. package/src/menu-fit.js +9 -0
  86. package/src/merge.d.ts +23 -0
  87. package/src/merge.js +116 -0
  88. package/src/page-link.d.ts +33 -0
  89. package/src/page-link.js +75 -0
  90. package/src/project-sync.d.ts +161 -0
  91. package/src/project-sync.js +319 -0
  92. package/src/react.d.ts +20 -0
  93. package/src/react.js +20 -0
  94. package/src/read-retries.d.ts +55 -0
  95. package/src/read-retries.js +125 -0
  96. package/src/right-drag-pan.d.ts +128 -0
  97. package/src/right-drag-pan.js +253 -0
  98. package/src/roles.d.ts +39 -0
  99. package/src/roles.js +27 -0
  100. package/src/session.d.ts +56 -0
  101. package/src/session.js +57 -0
  102. package/src/shell.d.ts +60 -0
  103. package/src/shell.js +111 -0
  104. package/src/stash.d.ts +26 -0
  105. package/src/stash.js +69 -0
  106. package/src/styles.css +17 -0
  107. package/src/toolbar-fold.d.ts +106 -0
  108. package/src/toolbar-fold.js +130 -0
  109. package/src/video-shrink/index.d.ts +8 -0
  110. package/src/video-shrink/index.js +7 -0
  111. package/src/video-shrink/plan.d.ts +92 -0
  112. package/src/video-shrink/plan.js +133 -0
  113. package/src/video-shrink/protocol.d.ts +29 -0
  114. package/src/video-shrink/protocol.js +2 -0
  115. package/src/video-shrink/queue.d.ts +69 -0
  116. package/src/video-shrink/queue.js +287 -0
  117. package/src/video-shrink/worker.d.ts +8 -0
  118. package/src/video-shrink/worker.js +223 -0
  119. package/src/wheel-zoom.d.ts +14 -0
  120. package/src/wheel-zoom.js +48 -0
@@ -0,0 +1,596 @@
1
+ /**
2
+ * Comment threads for any editor: the store (threads, comment mode, the
3
+ * open card, the draft, the list), and the thread actions over the
4
+ * `comments` capability.
5
+ *
6
+ * Editor-agnostic: what an anchor is,
7
+ * how it is labelled, where it points the agent and how the editor shows it
8
+ * are the {@link CommentsAdapter}'s. The editor hands the capability to
9
+ * {@link CommentsController.start}.
10
+ */
11
+ import { useCapability } from '@openartifactsai/runtime';
12
+ import { create } from 'zustand';
13
+ import { AGENT_KEY, foldName, MENTION_PEOPLE_LIMIT, mentionLimitText, peopleNamed } from "./mentions.js";
14
+ /**
15
+ * Longest comment, in UTF-8 bytes of the trimmed text: claude.ai's comment boxes take as much. The boxes also set it
16
+ * as their `maxLength` (UTF-16 units), so typing and pasting stop there, and a longer text in bytes (CJK, emoji) is
17
+ * refused when it is sent, with the draft kept.
18
+ */
19
+ export const COMMENT_TEXT_BYTES = 4096;
20
+ /** The stored anchor of a comment on the whole artifact (see {@link CommentsAdapter.wholeArtifact}). */
21
+ export const WHOLE_ARTIFACT = '';
22
+ /** What the default check says when a comment is over {@link COMMENT_TEXT_BYTES}. */
23
+ export const COMMENT_TOO_LONG = 'That comment is too long.';
24
+ /** Longest docs comment, in characters: the docs composer counts toward it. */
25
+ export const COMMENT_TEXT_MAX = 4000;
26
+ const utf8 = new TextEncoder();
27
+ /** The UTF-8 size of `text`, as {@link COMMENT_TEXT_BYTES} counts it. */
28
+ export function commentTextBytes(text) {
29
+ return utf8.encode(text).length;
30
+ }
31
+ /** What a menu says while a status change is on its way. */
32
+ export const WAIT_FOR_STATUS_CHANGE = 'Wait for the current change to finish.';
33
+ /** The threads as shown: the stored ones, with an unconfirmed status change already applied. */
34
+ export function withStatusChange(threads, change) {
35
+ if (!change)
36
+ return threads;
37
+ return threads.map((thread) => (thread.id === change.id ? withStatus(thread, change.status) : thread));
38
+ }
39
+ function withStatus(thread, status, resolvedBy) {
40
+ if (thread.status === status && thread.resolvedBy === resolvedBy)
41
+ return thread;
42
+ const { resolvedBy: _, ...rest } = thread;
43
+ return status === 'resolved' && resolvedBy ? { ...rest, status, resolvedBy } : { ...rest, status };
44
+ }
45
+ /** Under a thread sent to the agent that has not taken it yet; one that is not woken while it idles needs a message. */
46
+ export function queuedNote(agent) {
47
+ return agent.wakesIdle === false ? `${agent.name} gets this on its next turn: send it a message to start one` : 'Waiting for the agent';
48
+ }
49
+ /** The toast after a thread goes to the agent; one that is not woken while it idles needs a message from the person. */
50
+ export function sentNotice(name, wakesIdle) {
51
+ return wakesIdle === false
52
+ ? { title: `Sent to ${name}`, description: `${name} gets it on its next turn. If it is idle, send it a message there to start one.` }
53
+ : { title: `Sent to ${name}` };
54
+ }
55
+ export function openCount(threads) {
56
+ return threads.filter((t) => t.status === 'open').length;
57
+ }
58
+ export function openMessageCount(threads) {
59
+ return threads.reduce((sum, t) => (t.status === 'open' ? sum + t.messages.length : sum), 0);
60
+ }
61
+ /** The default note of a card whose anchor moved away. */
62
+ function defaultStateNote(state) {
63
+ if (state === 'detached')
64
+ return 'What this was on is gone; shown on what held it.';
65
+ if (state === 'orphaned')
66
+ return 'What this was on has been deleted.';
67
+ return null;
68
+ }
69
+ /** Creates an editor's comments controller. */
70
+ export function createComments(adapter) {
71
+ const maxThreads = adapter.maxThreads ?? 500;
72
+ const noun = adapter.noun ?? 'document';
73
+ const notify = (message) => adapter.notify?.(message);
74
+ let capability = null;
75
+ let unfollow;
76
+ /** Bumped by {@link CommentsController.stop}: a list arriving after it is dropped. */
77
+ let generation = 0;
78
+ /** The whole artifact's stored anchor, when the type has one. */
79
+ const wholeKey = () => (adapter.wholeArtifact ? adapter.serialize(adapter.wholeArtifact()) : null);
80
+ /** Whole-artifact threads: only a type that has them reads the empty string (or its own anchor for them) so. */
81
+ const isWholeKey = (key) => Boolean(adapter.wholeArtifact) && (key === WHOLE_ARTIFACT || key === wholeKey());
82
+ const isWhole = (thread) => isWholeKey(thread.anchor);
83
+ const isWholeAnchor = (anchor) => isWholeKey(adapter.serialize(anchor));
84
+ const sameSpot = (a, b) => adapter.serialize(a) === adapter.serialize(b);
85
+ const store = create()((set, get) => ({
86
+ available: false,
87
+ threads: [],
88
+ on: false,
89
+ listOpen: false,
90
+ active: null,
91
+ draft: null,
92
+ showResolved: false,
93
+ sendNew: false,
94
+ draftText: '',
95
+ replies: {},
96
+ parked: null,
97
+ editing: null,
98
+ writing: [],
99
+ known: [],
100
+ self: null,
101
+ statusChange: null,
102
+ setOn(on) {
103
+ set({ on, draft: null });
104
+ adapter.onModeChange?.(on);
105
+ },
106
+ setListOpen(listOpen) {
107
+ set({ listOpen });
108
+ },
109
+ setActive(active) {
110
+ const state = get();
111
+ const panel = state.draft !== null && isWholeAnchor(state.draft);
112
+ if (active !== null && active !== state.active) {
113
+ // Changes being edited in another card, or words in the panel's composer, hold the card where it is.
114
+ if (state.editing?.changed && state.editing.thread !== active)
115
+ return;
116
+ if (panel && state.draftText.trim() !== '')
117
+ return;
118
+ }
119
+ // A comment begun on the page with words in it is set aside for later; the panel's composer, empty, just closes.
120
+ const page = state.draft !== null && !panel ? state.draft : null;
121
+ const parks = Boolean(adapter.parksDrafts) && active !== null && page !== null && state.draftText.trim() !== '';
122
+ set({
123
+ active,
124
+ draft: null,
125
+ ...(state.editing && state.editing.thread !== active ? { editing: null } : {}),
126
+ ...(parks ? { parked: { anchor: page, text: state.draftText, send: state.sendNew } } : {}),
127
+ ...(parks || panel ? { draftText: '', sendNew: false } : {}),
128
+ });
129
+ },
130
+ setDraft(draft) {
131
+ const state = get();
132
+ // Dropped: its text and box go too.
133
+ if (draft === null)
134
+ return set({ draft, active: null, editing: null, draftText: '', sendNew: false });
135
+ const panel = state.draft !== null && isWholeAnchor(state.draft);
136
+ if (isWholeAnchor(draft)) {
137
+ // The panel's composer: a comment begun on the page is set aside when it has words in it.
138
+ const page = state.draft !== null && !panel ? state.draft : null;
139
+ const parks = Boolean(adapter.parksDrafts) && page !== null && state.draftText.trim() !== '';
140
+ // Where nothing would show it set aside, its words go on into the panel's composer.
141
+ const carries = page !== null && !adapter.parksDrafts;
142
+ return set({
143
+ draft,
144
+ active: null,
145
+ editing: null,
146
+ ...(panel || carries ? {} : { draftText: '', sendNew: false }),
147
+ ...(parks ? { parked: { anchor: page, text: state.draftText, send: state.sendNew } } : {}),
148
+ });
149
+ }
150
+ // A spot on the page: not while an edit has changes or the panel's composer has words in it.
151
+ if (state.editing?.changed)
152
+ return;
153
+ if (panel && state.draftText.trim() !== '')
154
+ return;
155
+ const parked = state.parked;
156
+ if (parked) {
157
+ // The comment set aside comes back where it was; until it is sent or dropped, no other spot starts one.
158
+ if (!sameSpot(parked.anchor, draft))
159
+ return;
160
+ return set({ draft: parked.anchor, active: null, editing: null, parked: null, draftText: parked.text, sendNew: parked.send });
161
+ }
162
+ // Moved to another spot: its text and box stay. From the panel's empty composer: a fresh one.
163
+ set({ draft, active: null, editing: null, ...(panel ? { draftText: '', sendNew: false } : {}) });
164
+ },
165
+ setShowResolved(showResolved) {
166
+ set({ showResolved });
167
+ },
168
+ setSendNew(sendNew) {
169
+ set({ sendNew });
170
+ },
171
+ setDraftText(draftText) {
172
+ set({ draftText });
173
+ },
174
+ setReply(id, reply) {
175
+ set((state) => ({ replies: { ...state.replies, [id]: reply } }));
176
+ },
177
+ setEditing(editing) {
178
+ set({ editing });
179
+ },
180
+ }));
181
+ /** Marks a write as on its way to the host until it settles. */
182
+ const writing = async (key, work) => {
183
+ store.setState((state) => ({ writing: [...state.writing, key] }));
184
+ try {
185
+ return await work();
186
+ }
187
+ finally {
188
+ store.setState((state) => {
189
+ const at = state.writing.indexOf(key);
190
+ return { writing: at < 0 ? state.writing : [...state.writing.slice(0, at), ...state.writing.slice(at + 1)] };
191
+ });
192
+ }
193
+ };
194
+ /** Anchors parsed once per stored string. */
195
+ const parsed = new Map();
196
+ const anchorOf = (thread) => {
197
+ let anchor = parsed.get(thread.anchor);
198
+ if (anchor === undefined) {
199
+ anchor = adapter.parse(thread.anchor);
200
+ if (parsed.size > 2000)
201
+ parsed.clear();
202
+ parsed.set(thread.anchor, anchor);
203
+ }
204
+ return anchor;
205
+ };
206
+ /** The threads as the host last told them, without an unconfirmed status change. */
207
+ let stored = [];
208
+ const keep = (threads, also) => {
209
+ stored = threads;
210
+ const statusChange = also && 'statusChange' in also ? (also.statusChange ?? null) : store.getState().statusChange;
211
+ // An edit whose message is gone ends with it.
212
+ const editing = store.getState().editing;
213
+ const gone = editing !== null && !threads.some((t) => t.id === editing.thread && t.messages.some((m) => m.id === editing.message));
214
+ store.setState({ ...also, threads: withStatusChange(threads, statusChange), ...(gone ? { editing: null } : {}) });
215
+ };
216
+ const failed = (error) => {
217
+ notify({ title: 'The comment could not be saved', description: error instanceof Error ? error.message : String(error) });
218
+ };
219
+ const put = (thread) => {
220
+ keep(stored.map((t) => (t.id === thread.id ? thread : t)));
221
+ adapter.heard?.([thread]);
222
+ };
223
+ const checkText = (text) => {
224
+ if (adapter.checkText)
225
+ return adapter.checkText(text);
226
+ const body = text.trim();
227
+ if (!body)
228
+ return undefined;
229
+ if (commentTextBytes(body) > COMMENT_TEXT_BYTES) {
230
+ notify({ title: COMMENT_TOO_LONG });
231
+ return undefined;
232
+ }
233
+ return body;
234
+ };
235
+ const canComment = () => Boolean(capability) && adapter.canComment();
236
+ const canSendToAgent = () => Boolean(capability) && adapter.canSendToAgent();
237
+ const canRemove = () => Boolean(capability) && (adapter.canRemove ? adapter.canRemove() : adapter.canComment());
238
+ /** `to` as the host takes it (none when empty), or `undefined` after saying why a message names too many people. */
239
+ const recipients = (options, verb) => {
240
+ const to = [...new Set(options?.to ?? [])];
241
+ if (peopleNamed(to) > MENTION_PEOPLE_LIMIT) {
242
+ notify({ title: mentionLimitText(verb) });
243
+ return undefined;
244
+ }
245
+ return to.length ? { to } : {};
246
+ };
247
+ let following = false;
248
+ let unfollowPeople;
249
+ const controller = {
250
+ store,
251
+ adapter,
252
+ async start(found, open) {
253
+ if (!found)
254
+ return;
255
+ capability = found;
256
+ const started = generation;
257
+ store.setState({ available: true });
258
+ try {
259
+ const threads = await found.list();
260
+ if (started !== generation)
261
+ return;
262
+ keep(threads);
263
+ adapter.heard?.(threads);
264
+ }
265
+ catch {
266
+ // The list arrives with the first change.
267
+ }
268
+ if (started !== generation)
269
+ return;
270
+ unfollow = found.onChange((threads) => {
271
+ const active = store.getState().active;
272
+ keep(threads, { active: active && threads.some((t) => t.id === active) ? active : null });
273
+ adapter.heard?.(threads);
274
+ });
275
+ const thread = open ? store.getState().threads.find((t) => t.id === open) : undefined;
276
+ if (thread)
277
+ controller.reveal(thread);
278
+ },
279
+ stop() {
280
+ generation += 1;
281
+ unfollow?.();
282
+ unfollow = undefined;
283
+ following = false;
284
+ unfollowPeople?.();
285
+ unfollowPeople = undefined;
286
+ },
287
+ capability: () => capability,
288
+ canComment,
289
+ canSendToAgent,
290
+ canRemove,
291
+ anchorOf,
292
+ wholeArtifact: () => adapter.wholeArtifact?.() ?? null,
293
+ isWhole,
294
+ isWholeAnchor,
295
+ composeWhole() {
296
+ const whole = adapter.wholeArtifact?.();
297
+ if (!whole)
298
+ return null;
299
+ const refusal = controller.composeRefusal();
300
+ if (refusal)
301
+ return refusal;
302
+ store.getState().setDraft(whole);
303
+ return null;
304
+ },
305
+ composeRefusal() {
306
+ const state = store.getState();
307
+ if (state.writing.length > 0 || state.statusChange !== null)
308
+ return 'posting';
309
+ if (!state.editing?.changed)
310
+ return null;
311
+ return state.draft !== null ? 'writing' : 'editing';
312
+ },
313
+ labelOf: (anchor) => adapter.label(anchor),
314
+ stateOf: (anchor) => (isWholeAnchor(anchor) ? 'ok' : (adapter.state?.(anchor) ?? 'ok')),
315
+ stateNote: (state) => (adapter.stateNote ? adapter.stateNote(state ?? 'ok') : defaultStateNote(state)),
316
+ async create(anchor, text, options) {
317
+ if (!capability)
318
+ return false;
319
+ const body = checkText(text);
320
+ if (!body)
321
+ return false;
322
+ const named = recipients(options, 'post');
323
+ if (!named)
324
+ return false;
325
+ if (store.getState().threads.length >= maxThreads) {
326
+ notify({ title: `This ${noun} already has ${maxThreads} comments` });
327
+ return false;
328
+ }
329
+ const cap = capability;
330
+ try {
331
+ const detail = adapter.detail?.(anchor);
332
+ const thread = await writing('new', () => cap.create({
333
+ anchor: adapter.serialize(anchor),
334
+ label: adapter.label(anchor),
335
+ ...(detail !== undefined ? { detail } : {}),
336
+ location: adapter.location?.(anchor) ?? {},
337
+ text: body,
338
+ ...named,
339
+ }));
340
+ const sends = Boolean(options?.send) && canSendToAgent();
341
+ keep(stored.some((t) => t.id === thread.id) ? stored : [...stored, thread], {
342
+ draft: null,
343
+ draftText: '',
344
+ sendNew: false,
345
+ active: adapter.opensCreated?.(sends) === false ? null : thread.id,
346
+ });
347
+ adapter.heard?.([thread]);
348
+ if (sends)
349
+ await controller.sendToAgent(thread.id);
350
+ return true;
351
+ }
352
+ catch (error) {
353
+ failed(error);
354
+ return false;
355
+ }
356
+ },
357
+ async reply(id, text, options) {
358
+ if (!capability)
359
+ return false;
360
+ const body = checkText(text);
361
+ if (!body)
362
+ return false;
363
+ const named = recipients(options, 'post');
364
+ if (!named)
365
+ return false;
366
+ const cap = capability;
367
+ try {
368
+ const thread = await writing(`reply:${id}`, async () => {
369
+ const posted = await (named.to ? cap.reply(id, body, named) : cap.reply(id, body));
370
+ // A reply to a resolved thread reopens it.
371
+ return posted.status === 'resolved' ? cap.setResolved(id, false) : posted;
372
+ });
373
+ put(thread);
374
+ store.setState((state) => {
375
+ const { [id]: _, ...replies } = state.replies;
376
+ return { replies };
377
+ });
378
+ if (options?.send && canSendToAgent())
379
+ await controller.sendToAgent(id);
380
+ return true;
381
+ }
382
+ catch (error) {
383
+ failed(error);
384
+ return false;
385
+ }
386
+ },
387
+ async edit(id, messageId, text, options) {
388
+ if (!capability)
389
+ return false;
390
+ const body = checkText(text);
391
+ if (!body)
392
+ return false;
393
+ const named = recipients(options, 'save');
394
+ if (!named)
395
+ return false;
396
+ const cap = capability;
397
+ try {
398
+ put(await writing(`edit:${messageId}`, () => cap.edit(id, messageId, body, { to: named.to ?? [] })));
399
+ if (options?.send && canSendToAgent())
400
+ await controller.sendToAgent(id);
401
+ return true;
402
+ }
403
+ catch (error) {
404
+ failed(error);
405
+ return false;
406
+ }
407
+ },
408
+ canEdit: (author) => canComment() && author.kind === 'person' && author.name === controller.viewerName(),
409
+ followPeople() {
410
+ if (following)
411
+ return;
412
+ following = true;
413
+ void followRoom(store, () => !following).then((stop) => {
414
+ if (following)
415
+ unfollowPeople = stop;
416
+ else
417
+ stop();
418
+ });
419
+ },
420
+ mentionPeople() {
421
+ const { known, threads } = store.getState();
422
+ const out = [...known, ...(adapter.people?.() ?? [])];
423
+ const named = [];
424
+ for (const thread of threads) {
425
+ for (const message of thread.messages) {
426
+ if (message.author.kind === 'person' && message.author.name)
427
+ out.push({ key: message.author.name, name: message.author.name });
428
+ for (const key of message.to ?? [])
429
+ if (key !== AGENT_KEY)
430
+ named.push({ key, name: key });
431
+ }
432
+ }
433
+ return [...out, ...named];
434
+ },
435
+ async resolve(id, resolved) {
436
+ if (!capability)
437
+ return;
438
+ const state = store.getState();
439
+ const status = resolved ? 'resolved' : 'open';
440
+ const thread = state.threads.find((t) => t.id === id);
441
+ if (!thread || state.statusChange || thread.status === status)
442
+ return;
443
+ const closes = resolved && state.active === id && !state.showResolved;
444
+ keep(stored, { statusChange: { id, status }, ...(closes ? { active: null } : {}) });
445
+ try {
446
+ const answer = await capability.setResolved(id, resolved);
447
+ // Only the status is taken from the answer: a change heard meanwhile may be newer in everything else.
448
+ keep(stored.map((t) => (t.id === id ? withStatus(t, answer.status, answer.resolvedBy) : t)), { statusChange: null });
449
+ adapter.heard?.([answer]);
450
+ }
451
+ catch (error) {
452
+ keep(stored, { statusChange: null });
453
+ failed(error);
454
+ const now = store.getState();
455
+ if (closes && now.active === null && now.draft === null && stored.some((t) => t.id === id))
456
+ store.setState({ active: id });
457
+ }
458
+ },
459
+ async remove(id, messageId) {
460
+ if (!capability || (adapter.canRemove && !adapter.canRemove()))
461
+ return;
462
+ const cap = capability;
463
+ try {
464
+ await writing(`delete:${messageId ?? id}`, () => cap.remove(id, messageId));
465
+ if (!messageId)
466
+ keep(stored.filter((t) => t.id !== id), { active: store.getState().active === id ? null : store.getState().active });
467
+ }
468
+ catch (error) {
469
+ failed(error);
470
+ }
471
+ },
472
+ async move(id, anchor, options) {
473
+ if (!capability)
474
+ return;
475
+ const cap = capability;
476
+ const from = options?.checked ? stored.find((t) => t.id === id)?.anchor : undefined;
477
+ if (options?.checked && from === undefined)
478
+ return;
479
+ try {
480
+ put(await cap.move(id, adapter.serialize(anchor), adapter.location?.(anchor), ...(from === undefined ? [] : [{ from }])));
481
+ }
482
+ catch (error) {
483
+ failed(error);
484
+ if (from !== undefined)
485
+ keep(await cap.list().catch(() => stored));
486
+ }
487
+ },
488
+ async sendToAgent(id, parts) {
489
+ if (!capability || !canSendToAgent())
490
+ return false;
491
+ const thread = adapter.sendToAgent ? store.getState().threads.find((t) => t.id === id) : undefined;
492
+ const send = adapter.sendToAgent;
493
+ if (send)
494
+ return thread ? writing('send', () => send(thread, anchorOf(thread))) : false;
495
+ const cap = capability;
496
+ try {
497
+ put(await writing('send', () => (parts?.userText || parts?.selectionSnapshot ? cap.sendToAgent(id, parts) : cap.sendToAgent(id))));
498
+ notify(sentNotice(adapter.agentName?.() || 'the agent', adapter.agentWakesIdle?.()));
499
+ return true;
500
+ }
501
+ catch (error) {
502
+ failed(error);
503
+ return false;
504
+ }
505
+ },
506
+ async sendAllToAgent() {
507
+ if (!capability || !canSendToAgent())
508
+ return;
509
+ const open = store.getState().threads.filter((t) => controller.canSendThread(t));
510
+ if (!open.length)
511
+ return;
512
+ // All at once: the host merges what reaches it within a short window into one message, so the agent gets
513
+ // every thread in one turn. One after another, each would wait out the window and arrive (or queue) alone.
514
+ const send = adapter.sendToAgent;
515
+ if (send) {
516
+ await writing('send', () => Promise.all(open.map((thread) => send(thread, anchorOf(thread)))));
517
+ return;
518
+ }
519
+ const cap = capability;
520
+ const results = await writing('send', () => Promise.allSettled(open.map((thread) => cap.sendToAgent(thread.id))));
521
+ let sent = 0;
522
+ for (const result of results) {
523
+ if (result.status === 'fulfilled') {
524
+ put(result.value);
525
+ sent++;
526
+ }
527
+ }
528
+ if (sent)
529
+ notify(sentNotice(adapter.agentName?.() || 'the agent', adapter.agentWakesIdle?.()));
530
+ const failure = results.find((result) => result.status === 'rejected');
531
+ if (failure)
532
+ failed(failure.reason);
533
+ },
534
+ canSendThread(thread) {
535
+ if (thread.status !== 'open')
536
+ return false;
537
+ const last = thread.messages.at(-1);
538
+ if (!last || last.author.kind !== 'person')
539
+ return false;
540
+ // Not sent yet, or the agent answered and a person wrote since.
541
+ return !thread.agent || thread.agent.status === 'replied';
542
+ },
543
+ reveal(thread) {
544
+ if (!isWhole(thread))
545
+ adapter.reveal?.(anchorOf(thread));
546
+ store.getState().setActive(thread.id);
547
+ },
548
+ show(thread) {
549
+ const state = store.getState();
550
+ if (!state.on)
551
+ state.setOn(true);
552
+ if (thread.status === 'resolved' && !store.getState().showResolved)
553
+ store.getState().setShowResolved(true);
554
+ controller.reveal(thread);
555
+ },
556
+ viewerName: () => adapter.viewerName?.() || 'You',
557
+ };
558
+ return controller;
559
+ }
560
+ /** A peer is someone the `@` list names when it is a person with a name. */
561
+ const personOf = (peer) => (peer.kind === 'person' && peer.name.trim() ? { key: peer.name, name: peer.name, id: peer.id } : null);
562
+ /**
563
+ * Follows the room: who has the artifact (asked once: its owner first) and who is here now, into the store's `known`;
564
+ * and who the viewer is, into `self`. Resolves a stop function. Without a room there is no one to add.
565
+ */
566
+ async function followRoom(store, stopped) {
567
+ const [room, user] = await Promise.all([useCapability('room'), useCapability('user')]);
568
+ const me = await user?.me().catch(() => null);
569
+ if (me)
570
+ store.setState({ self: { id: me.id, name: me.name } });
571
+ if (!room || stopped())
572
+ return () => { };
573
+ const [selfPeer, members, peers] = await Promise.all([
574
+ room.self().catch(() => ''),
575
+ room.participants ? room.participants().catch(() => []) : Promise.resolve([]),
576
+ room.peers().catch(() => []),
577
+ ]);
578
+ const listed = [...members]
579
+ .sort((a, b) => Number(b.owner === true) - Number(a.owner === true))
580
+ .filter((member) => member.name.trim())
581
+ .map((member) => ({ key: member.name, name: member.name, id: member.id }));
582
+ const update = (present) => {
583
+ const here = present.filter((peer) => peer.id !== selfPeer).map(personOf).filter((person) => person !== null);
584
+ const seen = new Set();
585
+ const known = [...listed, ...here].filter((person) => {
586
+ const key = foldName(person.key);
587
+ if (seen.has(key))
588
+ return false;
589
+ seen.add(key);
590
+ return true;
591
+ });
592
+ store.setState({ known });
593
+ };
594
+ update(peers);
595
+ return room.onPeers(update);
596
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Editor-agnostic version-history plumbing: reporting the history to a
3
+ * Shell, answering its `history` command, following who may restore, and
4
+ * reading a version's files a few at a time.
5
+ *
6
+ * Everything here takes the capability and callbacks as parameters (no
7
+ * editor stores), so any editor can wire its own panel and preview to it.
8
+ */
9
+ import type { ChromeCommand, HistoryCapability } from '@openartifactsai/runtime';
10
+ /** What {@link wireVersionHistory} connects. */
11
+ export interface VersionHistoryWiring {
12
+ history: Pick<HistoryCapability, 'list' | 'onChange'>;
13
+ /** The viewer's role may restore (owner or editor); the host's listing has the last word. */
14
+ roleMayRestore: boolean;
15
+ /** Sets part of the Shell report (`{history: true}` on start, `{history: undefined}` on stop). */
16
+ report(part: {
17
+ history?: boolean;
18
+ }): void;
19
+ /** Adds a Shell command handler; returns its remover. */
20
+ onCommand(handler: (command: ChromeCommand) => void): () => void;
21
+ /** Opens or closes the history panel (the Shell's History button). */
22
+ toggle(): void;
23
+ /** Whether this viewer may restore now. */
24
+ setCanRestore(can: boolean): void;
25
+ }
26
+ /** Connects a history capability to a page and its Shell. Returns a stop function. */
27
+ export declare function wireVersionHistory(wiring: VersionHistoryWiring): () => void;
28
+ /**
29
+ * Reads the paths of version `n` that `wanted` keeps, `workers` at a time,
30
+ * as `[path, text]` pairs (unreadable paths are left out).
31
+ */
32
+ export declare function readVersionFiles(history: Pick<HistoryCapability, 'files' | 'read'>, n: number, wanted: (paths: string[]) => string[], workers?: number): Promise<Array<readonly [string, string]>>;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Editor-agnostic version-history plumbing: reporting the history to a
3
+ * Shell, answering its `history` command, following who may restore, and
4
+ * reading a version's files a few at a time.
5
+ *
6
+ * Everything here takes the capability and callbacks as parameters (no
7
+ * editor stores), so any editor can wire its own panel and preview to it.
8
+ */
9
+ /** Connects a history capability to a page and its Shell. Returns a stop function. */
10
+ export function wireVersionHistory(wiring) {
11
+ let stopped = false;
12
+ wiring.setCanRestore(wiring.roleMayRestore);
13
+ wiring.report({ history: true });
14
+ const refresh = () => {
15
+ wiring.history.list().then((listing) => {
16
+ if (!stopped)
17
+ wiring.setCanRestore(listing.canRestore && wiring.roleMayRestore);
18
+ }, () => undefined);
19
+ };
20
+ refresh();
21
+ const stops = [
22
+ wiring.history.onChange(refresh),
23
+ wiring.onCommand((command) => {
24
+ if (command.cmd === 'history')
25
+ wiring.toggle();
26
+ }),
27
+ ];
28
+ return () => {
29
+ stopped = true;
30
+ for (const stop of stops)
31
+ stop();
32
+ wiring.report({ history: undefined });
33
+ };
34
+ }
35
+ /**
36
+ * Reads the paths of version `n` that `wanted` keeps, `workers` at a time,
37
+ * as `[path, text]` pairs (unreadable paths are left out).
38
+ */
39
+ export async function readVersionFiles(history, n, wanted, workers = 12) {
40
+ const paths = wanted(Object.keys(await history.files(n)));
41
+ const texts = [];
42
+ let next = 0;
43
+ const worker = async () => {
44
+ while (next < paths.length) {
45
+ const path = paths[next++];
46
+ const text = await history.read(n, path).catch(() => null);
47
+ if (text !== null)
48
+ texts.push([path, text]);
49
+ }
50
+ };
51
+ await Promise.all(Array.from({ length: Math.min(workers, paths.length) }, worker));
52
+ return texts;
53
+ }