@vibefield/rosetta-room 0.1.10 → 0.1.12

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 (100) hide show
  1. package/README.md +65 -3
  2. package/dist/components/Transcript.js +6 -2
  3. package/dist/components/file-viewer/FileViewerDialog.js +3 -2
  4. package/dist/components/file-viewer/diff/parse.js +7 -0
  5. package/dist/components/file-viewer/kinds.d.ts +22 -0
  6. package/dist/components/file-viewer/kinds.js +57 -0
  7. package/dist/components/file-viewer/markdown/render.d.ts +7 -1
  8. package/dist/components/file-viewer/markdown/render.js +16 -12
  9. package/dist/components/file-viewer/registry.d.ts +2 -2
  10. package/dist/components/file-viewer/registry.js +20 -59
  11. package/dist/components/file-viewer/views/DiffBody.js +7 -2
  12. package/dist/components/git/CommitViewer.js +3 -2
  13. package/dist/components/transcript/Activity.d.ts +10 -4
  14. package/dist/components/transcript/Activity.js +36 -11
  15. package/dist/components/transcript/Anchor.js +3 -2
  16. package/dist/components/transcript/Compaction.d.ts +9 -0
  17. package/dist/components/transcript/Compaction.js +10 -5
  18. package/dist/components/transcript/Document.js +150 -208
  19. package/dist/components/transcript/PromptJump.js +28 -8
  20. package/dist/components/transcript/Prose.d.ts +5 -1
  21. package/dist/components/transcript/Prose.js +7 -6
  22. package/dist/components/transcript/ReadingBlocks.d.ts +71 -0
  23. package/dist/components/transcript/ReadingBlocks.js +279 -0
  24. package/dist/components/transcript/activity-plan.d.ts +38 -7
  25. package/dist/components/transcript/activity-plan.js +198 -28
  26. package/dist/components/transcript/attachment-file-source.d.ts +1 -2
  27. package/dist/components/transcript/attachment-file-source.js +7 -5
  28. package/dist/components/transcript/disclosure-state.d.ts +2 -0
  29. package/dist/components/transcript/disclosure-state.js +6 -2
  30. package/dist/components/transcript/document-model.js +53 -9
  31. package/dist/components/transcript/document-plan.js +263 -98
  32. package/dist/components/transcript/reading-identity.d.ts +14 -1
  33. package/dist/components/transcript/reading-identity.js +126 -10
  34. package/dist/components/worktree/WorktreeColumn.js +12 -1
  35. package/dist/components/worktree/WorktreeList.d.ts +8 -2
  36. package/dist/components/worktree/WorktreeList.js +200 -5
  37. package/dist/components/worktree/worktree-ledger.d.ts +40 -0
  38. package/dist/components/worktree/worktree-ledger.js +68 -0
  39. package/dist/conversation/ConversationGallery.d.ts +11 -0
  40. package/dist/conversation/ConversationGallery.js +14 -0
  41. package/dist/conversation/ConversationMedia.d.ts +44 -0
  42. package/dist/conversation/ConversationMedia.js +210 -0
  43. package/dist/conversation/ConversationProse.d.ts +13 -0
  44. package/dist/conversation/ConversationProse.js +6 -0
  45. package/dist/conversation/ConversationRunRows.d.ts +57 -0
  46. package/dist/conversation/ConversationRunRows.js +84 -0
  47. package/dist/conversation/ConversationTurnView.d.ts +64 -0
  48. package/dist/conversation/ConversationTurnView.js +169 -0
  49. package/dist/conversation/ConversationView.d.ts +3 -0
  50. package/dist/conversation/ConversationView.js +257 -0
  51. package/dist/conversation/feed-reads.d.ts +36 -0
  52. package/dist/conversation/feed-reads.js +155 -0
  53. package/dist/conversation/feed.d.ts +106 -0
  54. package/dist/conversation/feed.js +884 -0
  55. package/dist/conversation/index.d.ts +11 -0
  56. package/dist/conversation/index.js +25 -0
  57. package/dist/conversation/model.d.ts +108 -0
  58. package/dist/conversation/model.js +257 -0
  59. package/dist/conversation/ports.d.ts +194 -0
  60. package/dist/conversation/ports.js +9 -0
  61. package/dist/conversation/rosetta-client.d.ts +8 -0
  62. package/dist/conversation/rosetta-client.js +1 -0
  63. package/dist/conversation/use-conversation-feed.d.ts +16 -0
  64. package/dist/conversation/use-conversation-feed.js +41 -0
  65. package/dist/conversation/use-conversation-window.d.ts +50 -0
  66. package/dist/conversation/use-conversation-window.js +336 -0
  67. package/dist/conversation/words.d.ts +51 -0
  68. package/dist/conversation/words.js +79 -0
  69. package/dist/fixtures/conversation.d.ts +34 -0
  70. package/dist/fixtures/conversation.js +723 -0
  71. package/dist/fixtures/index.d.ts +2 -0
  72. package/dist/fixtures/index.js +1 -0
  73. package/dist/index.d.ts +1 -1
  74. package/dist/lib/hooks.js +6 -1
  75. package/dist/lib/session-leases.d.ts +11 -8
  76. package/dist/lib/transcript/collaboration.js +53 -19
  77. package/dist/lib/transcript/head-of-document.js +9 -3
  78. package/dist/lib/transcript/index.d.ts +1 -1
  79. package/dist/lib/transcript/index.js +1 -1
  80. package/dist/lib/transcript/prompt-jump.d.ts +2 -0
  81. package/dist/lib/transcript/prompt-jump.js +5 -1
  82. package/dist/lib/transcript/sittings.d.ts +2 -1
  83. package/dist/lib/transcript/sittings.js +72 -10
  84. package/dist/lib/transcript/tail-state.d.ts +9 -0
  85. package/dist/lib/transcript/tail-state.js +25 -1
  86. package/dist/lib/transcript/turns.d.ts +5 -0
  87. package/dist/lib/transcript/turns.js +221 -57
  88. package/dist/lib/transcript/use-transcript-tail.js +17 -3
  89. package/dist/lib/transcript/vocabulary.d.ts +2 -1
  90. package/dist/lib/transcript/vocabulary.js +11 -1
  91. package/dist/parts-context.d.ts +25 -0
  92. package/dist/parts-context.js +32 -0
  93. package/dist/ports.d.ts +36 -0
  94. package/dist/room-context.d.ts +1 -2
  95. package/dist/room-context.js +11 -9
  96. package/dist/styles/conversation-turn.css +147 -0
  97. package/dist/styles/conversation.css +45 -0
  98. package/dist/styles/room.css +102 -12
  99. package/dist/styles/transcript.css +11 -2
  100. package/package.json +9 -4
@@ -0,0 +1,884 @@
1
+ import { attempt, codeOf, hasTurnReads, isAbort, isRefusedCredential, latestOf, markOfTurn, messageOf, replyBytesOf, sameLatest, sameStructure, } from "./feed-reads.js";
2
+ import { isTurnsUnsupported } from "./ports.js";
3
+ /** The feed's bounds and pace. */
4
+ export const CONVERSATION_FEED_LIMITS = Object.freeze({
5
+ /** Turns per read, and per snapshot. */
6
+ page: 20,
7
+ /** Turns read on either side of the ones in view. */
8
+ around: 20,
9
+ bodies: 400,
10
+ replyBytes: 8 * 1024 * 1024,
11
+ /** Sessions open at once: the newest and the two nearest the view. */
12
+ sessions: 3,
13
+ /** The chain's newest turns, never let go. */
14
+ newest: 20,
15
+ retryFirstMs: 1_000,
16
+ retryMostMs: 30_000,
17
+ });
18
+ const LIMITS = CONVERSATION_FEED_LIMITS;
19
+ const DEFAULT_TIMERS = {
20
+ set: (run, ms) => setTimeout(run, ms),
21
+ clear: (handle) => clearTimeout(handle),
22
+ };
23
+ function newSession(id) {
24
+ return {
25
+ id, outline: null, marks: [], heard: new Map(), index: new Map(), bodies: new Map(), readUnder: new Map(),
26
+ bytes: new Map(), inflight: new Set(), reads: new Set(), outlineRead: null, probe: null, watermark: null, needOutline: false,
27
+ catchingUp: false, connected: false, missing: false, withheld: false, unavailable: null, lastError: null, mismatches: 0,
28
+ lease: null, client: null, subscription: null, token: null, retry: null,
29
+ backoff: LIMITS.retryFirstMs, view: null,
30
+ };
31
+ }
32
+ const keyOf = (sessionId, turnKey) => `${sessionId}\u0000${turnKey}`;
33
+ /* ── the feed ────────────────────────────────────────────────────────────── */
34
+ export function createConversationFeed(options) {
35
+ const leases = options.sessions;
36
+ const timers = options.timers ?? DEFAULT_TIMERS;
37
+ const listeners = new Set();
38
+ const records = new Map();
39
+ const kept = new Map();
40
+ const waiters = new Set();
41
+ let chain = [];
42
+ /** The index in the chain of the earliest session the reader reached. */
43
+ let reach = 0;
44
+ let viewport = null;
45
+ let focus = null;
46
+ let disposed = false;
47
+ let pumping = false;
48
+ let again = false;
49
+ let dirty = true;
50
+ let version = 0;
51
+ let totalBodies = 0;
52
+ let totalBytes = 0;
53
+ let current = Object.freeze({
54
+ phase: "reading", unavailable: null, sessions: Object.freeze([]), latest: null, atTop: false, version: 0,
55
+ });
56
+ const changed = () => {
57
+ dirty = true;
58
+ };
59
+ const last = () => {
60
+ const id = chain[chain.length - 1];
61
+ return id === undefined ? null : records.get(id) ?? null;
62
+ };
63
+ const reached = () => chain.slice(reach).map((id) => records.get(id));
64
+ const settled = (rec) => rec.marks.length > 0 || rec.outline !== null || rec.missing || rec.withheld || rec.unavailable !== null;
65
+ const leased = () => [...records.values()].filter((rec) => rec.lease !== null);
66
+ const busy = (rec) => rec.reads.size > 0 || rec.outlineRead !== null;
67
+ /* bodies */
68
+ function store(rec, turn, watermark) {
69
+ const had = rec.bodies.has(turn.key);
70
+ if (had)
71
+ totalBytes -= rec.bytes.get(turn.key) ?? 0;
72
+ else
73
+ totalBodies += 1;
74
+ const bytes = replyBytesOf(turn);
75
+ rec.bodies.set(turn.key, turn);
76
+ rec.bytes.set(turn.key, bytes);
77
+ if (watermark === null)
78
+ rec.readUnder.delete(turn.key);
79
+ else
80
+ rec.readUnder.set(turn.key, watermark);
81
+ totalBytes += bytes;
82
+ changed();
83
+ }
84
+ function drop(rec, turnKey) {
85
+ if (!rec.bodies.has(turnKey))
86
+ return;
87
+ totalBodies -= 1;
88
+ totalBytes -= rec.bytes.get(turnKey) ?? 0;
89
+ rec.bodies.delete(turnKey);
90
+ rec.bytes.delete(turnKey);
91
+ rec.readUnder.delete(turnKey);
92
+ changed();
93
+ }
94
+ /** A turn's range and state as last heard: live, else the outline's, else
95
+ * the mark the rows were made from. */
96
+ const rangeOf = (rec, i) => {
97
+ const mark = rec.marks[i];
98
+ const outlined = rec.outline?.turns[i];
99
+ return rec.heard.get(mark.key) ?? (outlined?.key === mark.key ? outlined : mark);
100
+ };
101
+ const fresh = (rec, turnKey) => rec.bodies.has(turnKey) && rec.outline !== null && rec.readUnder.get(turnKey) === rec.outline.watermark;
102
+ /* marks */
103
+ function setMarks(rec, marks) {
104
+ rec.marks = marks;
105
+ rec.index = new Map(marks.map((mark, i) => [mark.key, i]));
106
+ for (const key of [...rec.bodies.keys()])
107
+ if (!rec.index.has(key))
108
+ drop(rec, key);
109
+ changed();
110
+ }
111
+ /** A turn heard live: its mark is grown into the list when its key is new. */
112
+ function hear(rec, turn) {
113
+ const mark = markOfTurn(turn);
114
+ const at = rec.index.get(turn.key);
115
+ if (at === undefined) {
116
+ const marks = [...rec.marks];
117
+ let i = marks.length;
118
+ while (i > 0 && marks[i - 1].first_ordinal > mark.first_ordinal)
119
+ i -= 1;
120
+ marks.splice(i, 0, mark);
121
+ if (i < rec.marks.length) {
122
+ setMarks(rec, marks);
123
+ return;
124
+ }
125
+ // At the end, as a turn arrives: no key moves and none goes, so the
126
+ // index grows by the one key instead of being made again over every turn.
127
+ rec.marks = marks;
128
+ rec.index.set(mark.key, i);
129
+ changed();
130
+ return;
131
+ }
132
+ if (rec.marks[at].first_at !== mark.first_at) {
133
+ const marks = [...rec.marks];
134
+ marks[at] = mark;
135
+ setMarks(rec, marks);
136
+ return;
137
+ }
138
+ rec.heard.set(turn.key, mark);
139
+ }
140
+ function applyOutline(rec, outline) {
141
+ rec.needOutline = false;
142
+ rec.missing = false;
143
+ if (outline.withheld && outline.turns.length === 0) {
144
+ rec.withheld = true;
145
+ if (rec.outline === null)
146
+ rec.outline = outline;
147
+ scheduleRetry(rec);
148
+ changed();
149
+ return;
150
+ }
151
+ rec.withheld = false;
152
+ rec.outline = outline;
153
+ rec.heard.clear();
154
+ rec.catchingUp = false;
155
+ rec.backoff = LIMITS.retryFirstMs;
156
+ rec.lastError = null;
157
+ // The same turns keep the array the rows were made from; a turn's range
158
+ // and state now are the outline's (`rangeOf`).
159
+ if (!sameStructure(rec.marks, outline.turns))
160
+ setMarks(rec, outline.turns);
161
+ changed();
162
+ }
163
+ /* sessions: leases, the subscription, retries */
164
+ function release(rec) {
165
+ const lease = rec.lease;
166
+ rec.lease = null;
167
+ rec.client = null;
168
+ lease?.release();
169
+ }
170
+ function unsubscribe(rec) {
171
+ rec.token = null;
172
+ const subscription = rec.subscription;
173
+ rec.subscription = null;
174
+ subscription?.close();
175
+ }
176
+ function abortReads(rec) {
177
+ for (const controller of rec.reads)
178
+ controller.abort();
179
+ rec.reads.clear();
180
+ rec.inflight.clear();
181
+ rec.outlineRead?.abort();
182
+ rec.outlineRead = null;
183
+ rec.probe?.abort();
184
+ rec.probe = null;
185
+ }
186
+ function closeSession(rec) {
187
+ unsubscribe(rec);
188
+ abortReads(rec);
189
+ if (rec.retry !== null)
190
+ timers.clear(rec.retry);
191
+ rec.retry = null;
192
+ release(rec);
193
+ for (const key of [...rec.bodies.keys()])
194
+ drop(rec, key);
195
+ }
196
+ function makeUnavailable(rec, reason) {
197
+ rec.unavailable = reason;
198
+ unsubscribe(rec);
199
+ abortReads(rec);
200
+ if (rec.retry !== null)
201
+ timers.clear(rec.retry);
202
+ rec.retry = null;
203
+ release(rec);
204
+ changed();
205
+ }
206
+ /** A credential the daemon refused: close the session, keep what is held,
207
+ * and open it again through the port (a host answers with a fresh one). Its
208
+ * reads wait for the backoff, so a port that keeps answering a refused one
209
+ * is asked again only that often. */
210
+ function reopen(rec) {
211
+ unsubscribe(rec);
212
+ abortReads(rec);
213
+ release(rec);
214
+ rec.connected = false;
215
+ if (rec.marks.length > 0 || rec.outline !== null)
216
+ rec.catchingUp = true;
217
+ scheduleRetry(rec);
218
+ changed();
219
+ }
220
+ /** The subscription said an error it reads on after. A refused credential is
221
+ * one it says only by its words, so the session's own read asks. */
222
+ function probe(rec) {
223
+ const client = rec.client;
224
+ if (client === null || rec.probe !== null)
225
+ return;
226
+ const controller = new AbortController();
227
+ rec.probe = controller;
228
+ attempt(() => client.turnOutline(rec.id, controller.signal)).then(() => {
229
+ if (rec.probe === controller)
230
+ rec.probe = null;
231
+ }, (error) => {
232
+ if (rec.probe !== controller || disposed)
233
+ return;
234
+ rec.probe = null;
235
+ if (!isRefusedCredential(error))
236
+ return;
237
+ reopen(rec);
238
+ pump();
239
+ });
240
+ }
241
+ function scheduleRetry(rec) {
242
+ if (rec.retry !== null || disposed)
243
+ return;
244
+ const delay = rec.backoff;
245
+ rec.backoff = Math.min(LIMITS.retryMostMs, rec.backoff * 2);
246
+ rec.retry = timers.set(() => {
247
+ rec.retry = null;
248
+ if (disposed || records.get(rec.id) !== rec)
249
+ return;
250
+ retryNow(rec);
251
+ pump();
252
+ }, delay);
253
+ }
254
+ /** Ask a session again: its subscription anew when it is the chain's last
255
+ * and answered not_found, its outline otherwise. */
256
+ function retryNow(rec) {
257
+ if (rec.retry !== null)
258
+ timers.clear(rec.retry);
259
+ rec.retry = null;
260
+ rec.mismatches = 0;
261
+ if (rec === last() && rec.missing) {
262
+ unsubscribe(rec);
263
+ return;
264
+ }
265
+ if (rec !== last() || rec.outline !== null || rec.withheld)
266
+ rec.needOutline = true;
267
+ }
268
+ /** A read went wrong: what it says decides what follows. */
269
+ function failed(rec, error) {
270
+ if (isAbort(error))
271
+ return;
272
+ if (isTurnsUnsupported(error)) {
273
+ makeUnavailable(rec, { kind: "unsupported" });
274
+ return;
275
+ }
276
+ if (isRefusedCredential(error)) {
277
+ rec.lastError = messageOf(error);
278
+ reopen(rec);
279
+ return;
280
+ }
281
+ const code = codeOf(error);
282
+ if (code === "cursor_expired") {
283
+ rec.mismatches += 1;
284
+ rec.needOutline = true;
285
+ changed();
286
+ return;
287
+ }
288
+ if (code === "not_found") {
289
+ rec.missing = true;
290
+ if (rec === last())
291
+ unsubscribe(rec);
292
+ }
293
+ else
294
+ rec.lastError = messageOf(error);
295
+ scheduleRetry(rec);
296
+ changed();
297
+ }
298
+ /** The session's lease, taken when the bound allows; true once its client
299
+ * answered. */
300
+ function leaseOf(rec, may) {
301
+ if (rec.unavailable !== null)
302
+ return false;
303
+ if (rec.lease === null) {
304
+ if (!may || leased().length >= LIMITS.sessions)
305
+ return false;
306
+ const lease = leases.acquire(rec.id);
307
+ rec.lease = lease;
308
+ const adopt = (client) => {
309
+ if (hasTurnReads(client))
310
+ rec.client = client;
311
+ else
312
+ makeUnavailable(rec, { kind: "unsupported" });
313
+ };
314
+ if (lease.client !== null)
315
+ adopt(lease.client);
316
+ else {
317
+ lease.ready.then((client) => {
318
+ if (disposed || rec.lease !== lease)
319
+ return;
320
+ adopt(client);
321
+ changed();
322
+ pump();
323
+ }, (error) => {
324
+ if (disposed || rec.lease !== lease)
325
+ return;
326
+ makeUnavailable(rec, isTurnsUnsupported(error) ? { kind: "unsupported" } : { kind: "refused", message: messageOf(error) });
327
+ pump();
328
+ });
329
+ }
330
+ }
331
+ return rec.client !== null;
332
+ }
333
+ function subscribe(rec) {
334
+ const client = rec.client;
335
+ if (client === null || rec.subscription !== null || rec.retry !== null || rec.unavailable !== null)
336
+ return;
337
+ const token = {};
338
+ rec.token = token;
339
+ const live = () => rec.token === token && !disposed;
340
+ const handlers = {
341
+ onSnapshot(s) {
342
+ if (!live())
343
+ return;
344
+ snapshotted(rec, s);
345
+ pump();
346
+ },
347
+ onTurn(turn) {
348
+ if (!live() || (rec.marks.length === 0 && rec.outline === null))
349
+ return;
350
+ hear(rec, turn);
351
+ store(rec, turn, rec.watermark);
352
+ pump();
353
+ },
354
+ onReset() {
355
+ if (!live())
356
+ return;
357
+ rec.catchingUp = true;
358
+ changed();
359
+ pump();
360
+ },
361
+ onStatus(status) {
362
+ if (!live())
363
+ return;
364
+ statused(rec, status);
365
+ pump();
366
+ },
367
+ onError(error) {
368
+ if (!live())
369
+ return;
370
+ if (isTurnsUnsupported(error))
371
+ makeUnavailable(rec, { kind: "unsupported" });
372
+ else if (codeOf(error) === "not_found")
373
+ failed(rec, error);
374
+ else {
375
+ rec.lastError = messageOf(error);
376
+ if (codeOf(error) === "internal")
377
+ probe(rec);
378
+ }
379
+ changed();
380
+ pump();
381
+ },
382
+ };
383
+ try {
384
+ const subscription = client.subscribeTurns(rec.id, handlers, { limit: LIMITS.page, outline: true });
385
+ if (rec.token === token)
386
+ rec.subscription = subscription;
387
+ else
388
+ subscription.close();
389
+ }
390
+ catch (error) {
391
+ rec.token = null;
392
+ failed(rec, error);
393
+ }
394
+ }
395
+ function snapshotted(rec, s) {
396
+ rec.watermark = s.watermark;
397
+ rec.missing = false;
398
+ rec.connected = true;
399
+ if (s.outline !== null)
400
+ applyOutline(rec, s.outline);
401
+ else {
402
+ if (rec.outline === null || rec.outline.watermark !== s.watermark)
403
+ rec.needOutline = true;
404
+ // Nothing read yet: the snapshot's turns stand for the outline, so the
405
+ // view opens at the end before the outline lands.
406
+ if (rec.outline === null && rec.marks.length === 0)
407
+ setMarks(rec, s.turns.map(markOfTurn));
408
+ }
409
+ for (const turn of s.turns) {
410
+ if (!rec.index.has(turn.key))
411
+ hear(rec, turn);
412
+ store(rec, turn, s.watermark);
413
+ }
414
+ rec.backoff = LIMITS.retryFirstMs;
415
+ changed();
416
+ }
417
+ function statused(rec, status) {
418
+ if (status === "live") {
419
+ rec.connected = true;
420
+ return;
421
+ }
422
+ if (status === "closed") {
423
+ makeUnavailable(rec, { kind: "closed", message: rec.lastError ?? "The session's turns stopped" });
424
+ return;
425
+ }
426
+ if (rec.connected) {
427
+ // The socket dropped, or the session is read again: keep everything,
428
+ // and read the outline again once it is back (unless a snapshot brings it).
429
+ rec.connected = false;
430
+ rec.catchingUp = true;
431
+ rec.needOutline = true;
432
+ changed();
433
+ }
434
+ }
435
+ function readOutline(rec) {
436
+ const client = rec.client;
437
+ if (client === null || rec.outlineRead !== null || rec.retry !== null)
438
+ return;
439
+ const controller = new AbortController();
440
+ rec.outlineRead = controller;
441
+ rec.needOutline = false;
442
+ attempt(() => client.turnOutline(rec.id, controller.signal)).then((outline) => {
443
+ if (rec.outlineRead !== controller || disposed)
444
+ return;
445
+ rec.outlineRead = null;
446
+ applyOutline(rec, outline);
447
+ pump();
448
+ }, (error) => {
449
+ if (rec.outlineRead !== controller || disposed)
450
+ return;
451
+ rec.outlineRead = null;
452
+ failed(rec, error);
453
+ pump();
454
+ });
455
+ changed();
456
+ }
457
+ /** One page: the 20 turns at and below `high`, under the outline's watermark. */
458
+ function readPage(rec, high) {
459
+ const client = rec.client;
460
+ const outline = rec.outline;
461
+ if (client === null || outline === null)
462
+ return;
463
+ const watermark = outline.watermark;
464
+ const before = rec.marks[high + 1]?.first_ordinal;
465
+ const keys = rec.marks.slice(Math.max(0, high - LIMITS.page + 1), high + 1).map((mark) => mark.key);
466
+ for (const key of keys)
467
+ rec.inflight.add(key);
468
+ const controller = new AbortController();
469
+ rec.reads.add(controller);
470
+ const ask = before === undefined ? { limit: LIMITS.page, watermark } : { limit: LIMITS.page, before, watermark };
471
+ const settle = () => {
472
+ if (!rec.reads.delete(controller))
473
+ return false;
474
+ for (const key of keys)
475
+ rec.inflight.delete(key);
476
+ return !disposed && records.get(rec.id) === rec;
477
+ };
478
+ attempt(() => client.turns(rec.id, ask, controller.signal)).then((page) => {
479
+ if (!settle())
480
+ return;
481
+ if (page.watermark !== watermark || rec.outline?.watermark !== watermark) {
482
+ // Read under another generation than the outline's: drop the page
483
+ // and read the outline again (it is behind, or the page is).
484
+ if (page.watermark !== watermark && rec.outline?.watermark === watermark) {
485
+ rec.mismatches += 1;
486
+ rec.needOutline = true;
487
+ }
488
+ changed();
489
+ pump();
490
+ return;
491
+ }
492
+ rec.mismatches = 0;
493
+ for (const turn of page.turns)
494
+ if (rec.index.has(turn.key) && !fresh(rec, turn.key))
495
+ store(rec, turn, watermark);
496
+ pump();
497
+ }, (error) => {
498
+ if (!settle())
499
+ return;
500
+ // A page asked under a watermark the outline has since left is simply
501
+ // asked again under the new one.
502
+ if (codeOf(error) !== "cursor_expired" || rec.outline?.watermark === watermark)
503
+ failed(rec, error);
504
+ pump();
505
+ });
506
+ }
507
+ function windowOf() {
508
+ const offsets = new Map();
509
+ let total = 0;
510
+ for (const rec of reached()) {
511
+ offsets.set(rec.id, total);
512
+ total += rec.marks.length;
513
+ }
514
+ const position = (at) => {
515
+ if (at === null)
516
+ return null;
517
+ const offset = offsets.get(at.sessionId);
518
+ const index = records.get(at.sessionId)?.index.get(at.turnKey);
519
+ return offset === undefined || index === undefined ? null : offset + index;
520
+ };
521
+ const firstAt = position(focus ?? viewport?.first ?? null);
522
+ const lastAt = position(focus ?? viewport?.last ?? null);
523
+ // Before the view says what it shows, the newest page alone: the first
524
+ // snapshot holds it, and nothing more is read until the reader is seen.
525
+ if (viewport === null && focus === null)
526
+ return { lo: Math.max(0, total - LIMITS.page), hi: total - 1, total, first: null, offsets };
527
+ let lo = firstAt ?? lastAt;
528
+ let hi = lastAt ?? firstAt;
529
+ if (lo === null || hi === null) {
530
+ // No turn in the rows: the reader is at the top of what is held.
531
+ lo = 0;
532
+ hi = Math.min(total - 1, LIMITS.page - 1);
533
+ }
534
+ if (hi < lo)
535
+ [lo, hi] = [hi, lo];
536
+ return { lo: Math.max(0, lo - LIMITS.around), hi: Math.min(total - 1, hi + LIMITS.around), total, first: firstAt, offsets };
537
+ }
538
+ /** How far a session lies from the window, in turns: 0 when it overlaps. */
539
+ function distance(rec, w) {
540
+ const start = w.offsets.get(rec.id);
541
+ if (start === undefined)
542
+ return Number.POSITIVE_INFINITY;
543
+ const end = start + Math.max(0, rec.marks.length - 1);
544
+ if (end < w.lo)
545
+ return w.lo - end;
546
+ if (start > w.hi)
547
+ return start - w.hi;
548
+ return 0;
549
+ }
550
+ function maybeReach() {
551
+ if (reach === 0 || (viewport === null && focus === null))
552
+ return;
553
+ for (const rec of reached())
554
+ if (!settled(rec) && rec.unavailable === null)
555
+ return;
556
+ // Near the top of what is held: within a page of its first turn, or no
557
+ // turn held at all.
558
+ const first = windowOf().first;
559
+ if (first !== null && first >= LIMITS.page)
560
+ return;
561
+ reach -= 1;
562
+ again = true;
563
+ changed();
564
+ }
565
+ function evict(w) {
566
+ if (totalBodies <= LIMITS.bodies && totalBytes <= LIMITS.replyBytes)
567
+ return;
568
+ const candidates = [];
569
+ for (const rec of records.values()) {
570
+ const offset = w.offsets.get(rec.id);
571
+ for (const [key, body] of rec.bodies) {
572
+ const index = rec.index.get(key);
573
+ const position = offset === undefined || index === undefined ? null : offset + index;
574
+ if (position !== null && position >= w.total - LIMITS.newest)
575
+ continue;
576
+ if ((kept.get(keyOf(rec.id, key)) ?? 0) > 0)
577
+ continue;
578
+ if (body.outcome.state === "open" || body.running > 0)
579
+ continue;
580
+ const far = position === null ? Number.POSITIVE_INFINITY : position < w.lo ? w.lo - position : position > w.hi ? position - w.hi : 0;
581
+ // In reach: the next step would read it again and let another go, so a
582
+ // still reader would see reads without end.
583
+ if (far === 0)
584
+ continue;
585
+ candidates.push({ rec, key, far });
586
+ }
587
+ }
588
+ candidates.sort((a, b) => b.far - a.far);
589
+ for (const { rec, key } of candidates) {
590
+ if (totalBodies <= LIMITS.bodies && totalBytes <= LIMITS.replyBytes)
591
+ break;
592
+ drop(rec, key);
593
+ }
594
+ }
595
+ /** Read what the window needs, within the bounds. */
596
+ function step() {
597
+ const newest = last();
598
+ if (newest === null)
599
+ return;
600
+ maybeReach();
601
+ const w = windowOf();
602
+ // Who may hold a session open: the newest, and the two nearest the view.
603
+ const earlier = reached()
604
+ .filter((rec) => rec !== newest && rec.unavailable === null)
605
+ .sort((a, b) => distance(a, w) - distance(b, w));
606
+ const allowed = new Set([newest.id, ...earlier.slice(0, LIMITS.sessions - 1).map((rec) => rec.id)]);
607
+ for (const rec of leased())
608
+ if (!allowed.has(rec.id) && !busy(rec) && rec.subscription === null)
609
+ release(rec);
610
+ if (leaseOf(newest, true)) {
611
+ subscribe(newest);
612
+ if (newest.needOutline && newest.subscription !== null && newest.connected)
613
+ readOutline(newest);
614
+ }
615
+ for (const rec of earlier) {
616
+ if (rec.retry !== null || !(rec.outline === null || rec.needOutline))
617
+ continue;
618
+ if (leaseOf(rec, allowed.has(rec.id)))
619
+ readOutline(rec);
620
+ }
621
+ for (const rec of [newest, ...earlier]) {
622
+ if (rec.unavailable !== null || rec.outline === null || rec.needOutline || rec.outlineRead !== null)
623
+ continue;
624
+ if (rec.retry !== null || rec.mismatches >= 3 || rec.marks.length === 0)
625
+ continue;
626
+ const offset = w.offsets.get(rec.id);
627
+ if (offset === undefined)
628
+ continue;
629
+ const from = Math.max(0, w.lo - offset);
630
+ const to = Math.min(rec.marks.length - 1, w.hi - offset);
631
+ for (let i = to; i >= from;) {
632
+ const key = rec.marks[i].key;
633
+ if (fresh(rec, key) || rec.inflight.has(key)) {
634
+ i -= 1;
635
+ continue;
636
+ }
637
+ if (!leaseOf(rec, allowed.has(rec.id)))
638
+ break;
639
+ // The page reaches up over the unread turns just above it, so it
640
+ // ends where the held ones begin and reads none of them again.
641
+ let high = i;
642
+ while (high + 1 < rec.marks.length && high + 1 < i + LIMITS.page) {
643
+ const above = rec.marks[high + 1].key;
644
+ if (fresh(rec, above) || rec.inflight.has(above))
645
+ break;
646
+ high += 1;
647
+ }
648
+ readPage(rec, high);
649
+ i = high - LIMITS.page;
650
+ }
651
+ }
652
+ evict(w);
653
+ }
654
+ function pump() {
655
+ if (disposed)
656
+ return;
657
+ if (pumping) {
658
+ again = true;
659
+ return;
660
+ }
661
+ pumping = true;
662
+ try {
663
+ do {
664
+ again = false;
665
+ step();
666
+ } while (again && !disposed);
667
+ }
668
+ finally {
669
+ pumping = false;
670
+ }
671
+ emit();
672
+ }
673
+ /* what the view reads */
674
+ function sessionView(rec) {
675
+ const held = rec.outline !== null || rec.marks.length > 0;
676
+ const status = rec.unavailable !== null ? "unavailable"
677
+ : rec.missing ? "missing"
678
+ : rec.withheld ? "withheld"
679
+ : rec.catchingUp ? "catching-up"
680
+ : held ? "ready" : "reading";
681
+ const view = rec.view;
682
+ if (view !== null && view.turns === rec.marks && view.held === held && view.status === status && view.unavailable === rec.unavailable) {
683
+ return view;
684
+ }
685
+ rec.view = Object.freeze({ sessionId: rec.id, turns: rec.marks, held, status, unavailable: rec.unavailable });
686
+ return rec.view;
687
+ }
688
+ function phaseOf(rec) {
689
+ if (rec === null)
690
+ return "ready";
691
+ if (rec.unavailable !== null)
692
+ return "unavailable";
693
+ const held = rec.marks.length > 0 || rec.outline !== null;
694
+ if (rec.missing)
695
+ return "catching-up";
696
+ if (rec.catchingUp || rec.withheld)
697
+ return held && !(rec.withheld && rec.marks.length === 0) ? "catching-up" : "reading";
698
+ return held ? "ready" : "reading";
699
+ }
700
+ function latestNow() {
701
+ const sessions = reached();
702
+ for (let s = sessions.length - 1; s >= 0; s -= 1) {
703
+ const rec = sessions[s];
704
+ const mark = rec.marks[rec.marks.length - 1];
705
+ if (mark === undefined) {
706
+ if (!settled(rec) || rec.missing)
707
+ return null;
708
+ continue;
709
+ }
710
+ const body = rec.bodies.get(mark.key);
711
+ return body === undefined ? null : latestOf(rec.id, body);
712
+ }
713
+ return null;
714
+ }
715
+ function emit() {
716
+ if (!dirty || disposed)
717
+ return;
718
+ dirty = false;
719
+ const newest = last();
720
+ const views = reached().map(sessionView);
721
+ const sessions = views.length === current.sessions.length && views.every((view, i) => view === current.sessions[i])
722
+ ? current.sessions
723
+ : Object.freeze(views);
724
+ const latest = latestNow();
725
+ const atTop = reach === 0 && reached().every((rec) => settled(rec));
726
+ version += 1;
727
+ current = Object.freeze({
728
+ phase: phaseOf(newest),
729
+ unavailable: newest?.unavailable ?? null,
730
+ sessions,
731
+ latest: sameLatest(latest, current.latest) ? current.latest : latest,
732
+ atTop,
733
+ version,
734
+ });
735
+ for (const waiter of [...waiters])
736
+ if (waiter())
737
+ waiters.delete(waiter);
738
+ for (const listener of [...listeners])
739
+ listener();
740
+ }
741
+ return {
742
+ state: () => current,
743
+ subscribe(listener) {
744
+ listeners.add(listener);
745
+ return () => {
746
+ listeners.delete(listener);
747
+ };
748
+ },
749
+ body(sessionId, turnKey) {
750
+ return records.get(sessionId)?.bodies.get(turnKey) ?? null;
751
+ },
752
+ setChain(next) {
753
+ if (disposed)
754
+ return;
755
+ const ids = [...new Set(next)];
756
+ if (ids.length === chain.length && ids.every((id, i) => id === chain[i]))
757
+ return;
758
+ const before = chain;
759
+ const reachedId = before[reach];
760
+ const previousLast = before[before.length - 1];
761
+ chain = ids;
762
+ for (const [id, rec] of [...records]) {
763
+ if (ids.includes(id))
764
+ continue;
765
+ closeSession(rec);
766
+ records.delete(id);
767
+ }
768
+ for (const id of ids)
769
+ if (!records.has(id))
770
+ records.set(id, newSession(id));
771
+ const newestId = ids[ids.length - 1];
772
+ if (previousLast !== undefined && previousLast !== newestId) {
773
+ const rec = records.get(previousLast);
774
+ if (rec !== undefined) {
775
+ // It is read now, never subscribed: what it was catching up on
776
+ // comes from its outline.
777
+ unsubscribe(rec);
778
+ rec.connected = false;
779
+ rec.missing = false;
780
+ if (rec.catchingUp || rec.watermark !== rec.outline?.watermark)
781
+ rec.needOutline = true;
782
+ }
783
+ }
784
+ const at = reachedId === undefined ? -1 : ids.indexOf(reachedId);
785
+ const held = ids.findIndex((id) => settled(records.get(id)));
786
+ reach = ids.length === 0 ? 0 : at >= 0 ? at : held >= 0 ? held : ids.length - 1;
787
+ // A session that answered not_found, or held nothing public, is asked
788
+ // again at once: the chain changed.
789
+ for (const rec of records.values()) {
790
+ if (!rec.missing && !rec.withheld)
791
+ continue;
792
+ rec.backoff = LIMITS.retryFirstMs;
793
+ retryNow(rec);
794
+ }
795
+ changed();
796
+ pump();
797
+ },
798
+ setViewport(next) {
799
+ if (disposed)
800
+ return;
801
+ viewport = next;
802
+ focus = null;
803
+ for (const rec of records.values())
804
+ if (rec.mismatches >= 3)
805
+ rec.mismatches = 0;
806
+ pump();
807
+ },
808
+ keep(sessionId, turnKey) {
809
+ const key = keyOf(sessionId, turnKey);
810
+ kept.set(key, (kept.get(key) ?? 0) + 1);
811
+ let released = false;
812
+ return () => {
813
+ if (released)
814
+ return;
815
+ released = true;
816
+ const holders = (kept.get(key) ?? 1) - 1;
817
+ if (holders <= 0)
818
+ kept.delete(key);
819
+ else
820
+ kept.set(key, holders);
821
+ };
822
+ },
823
+ locate(target) {
824
+ const s = chain.indexOf(target.sessionId);
825
+ if (disposed || s < 0)
826
+ return Promise.resolve(null);
827
+ const rec = records.get(target.sessionId);
828
+ const find = () => {
829
+ if ("turnKey" in target)
830
+ return rec.index.has(target.turnKey) ? { sessionId: rec.id, turnKey: target.turnKey } : null;
831
+ let found = null;
832
+ for (const [i, mark] of rec.marks.entries()) {
833
+ const range = rangeOf(rec, i);
834
+ if (range.first_ordinal > target.ordinal)
835
+ break;
836
+ found = mark;
837
+ if (target.ordinal <= range.last_ordinal)
838
+ break;
839
+ }
840
+ return found === null ? null : { sessionId: rec.id, turnKey: found.key };
841
+ };
842
+ if (s < reach) {
843
+ reach = s;
844
+ changed();
845
+ }
846
+ return new Promise((resolve) => {
847
+ const check = () => {
848
+ if (disposed || records.get(rec.id) !== rec) {
849
+ resolve(null);
850
+ return true;
851
+ }
852
+ if (!settled(rec) && rec.unavailable === null)
853
+ return false;
854
+ const at = find();
855
+ if (at !== null) {
856
+ // Read the bodies around it next; this check may run as the feed
857
+ // tells its listeners, so the read waits for that to end.
858
+ focus = at;
859
+ changed();
860
+ queueMicrotask(pump);
861
+ }
862
+ resolve(at);
863
+ return true;
864
+ };
865
+ if (!check())
866
+ waiters.add(check);
867
+ pump();
868
+ });
869
+ },
870
+ held: () => ({ bodies: totalBodies, replyBytes: totalBytes, open: leased().map((rec) => rec.id) }),
871
+ dispose() {
872
+ if (disposed)
873
+ return;
874
+ for (const rec of records.values())
875
+ closeSession(rec);
876
+ disposed = true;
877
+ records.clear();
878
+ listeners.clear();
879
+ for (const waiter of [...waiters])
880
+ waiter();
881
+ waiters.clear();
882
+ },
883
+ };
884
+ }