@vibefield/rosetta-room 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +64 -2
  2. package/dist/components/Transcript.js +6 -2
  3. package/dist/components/file-viewer/kinds.d.ts +22 -0
  4. package/dist/components/file-viewer/kinds.js +57 -0
  5. package/dist/components/file-viewer/markdown/render.d.ts +7 -1
  6. package/dist/components/file-viewer/markdown/render.js +16 -12
  7. package/dist/components/file-viewer/registry.d.ts +2 -2
  8. package/dist/components/file-viewer/registry.js +20 -59
  9. package/dist/components/transcript/Activity.d.ts +10 -4
  10. package/dist/components/transcript/Activity.js +36 -11
  11. package/dist/components/transcript/Compaction.d.ts +9 -0
  12. package/dist/components/transcript/Compaction.js +8 -4
  13. package/dist/components/transcript/Document.js +150 -208
  14. package/dist/components/transcript/PromptJump.js +28 -8
  15. package/dist/components/transcript/Prose.d.ts +5 -1
  16. package/dist/components/transcript/Prose.js +3 -3
  17. package/dist/components/transcript/ReadingBlocks.d.ts +71 -0
  18. package/dist/components/transcript/ReadingBlocks.js +279 -0
  19. package/dist/components/transcript/activity-plan.d.ts +38 -7
  20. package/dist/components/transcript/activity-plan.js +198 -28
  21. package/dist/components/transcript/attachment-file-source.d.ts +1 -2
  22. package/dist/components/transcript/attachment-file-source.js +7 -5
  23. package/dist/components/transcript/disclosure-state.d.ts +2 -0
  24. package/dist/components/transcript/disclosure-state.js +6 -2
  25. package/dist/components/transcript/document-model.js +53 -9
  26. package/dist/components/transcript/document-plan.js +263 -98
  27. package/dist/components/transcript/reading-identity.d.ts +14 -1
  28. package/dist/components/transcript/reading-identity.js +126 -10
  29. package/dist/conversation/ConversationGallery.d.ts +11 -0
  30. package/dist/conversation/ConversationGallery.js +14 -0
  31. package/dist/conversation/ConversationMedia.d.ts +44 -0
  32. package/dist/conversation/ConversationMedia.js +210 -0
  33. package/dist/conversation/ConversationProse.d.ts +13 -0
  34. package/dist/conversation/ConversationProse.js +6 -0
  35. package/dist/conversation/ConversationRunRows.d.ts +57 -0
  36. package/dist/conversation/ConversationRunRows.js +84 -0
  37. package/dist/conversation/ConversationTurnView.d.ts +64 -0
  38. package/dist/conversation/ConversationTurnView.js +169 -0
  39. package/dist/conversation/ConversationView.d.ts +3 -0
  40. package/dist/conversation/ConversationView.js +257 -0
  41. package/dist/conversation/feed-reads.d.ts +36 -0
  42. package/dist/conversation/feed-reads.js +155 -0
  43. package/dist/conversation/feed.d.ts +106 -0
  44. package/dist/conversation/feed.js +884 -0
  45. package/dist/conversation/index.d.ts +11 -0
  46. package/dist/conversation/index.js +25 -0
  47. package/dist/conversation/model.d.ts +108 -0
  48. package/dist/conversation/model.js +257 -0
  49. package/dist/conversation/ports.d.ts +194 -0
  50. package/dist/conversation/ports.js +9 -0
  51. package/dist/conversation/rosetta-client.d.ts +8 -0
  52. package/dist/conversation/rosetta-client.js +1 -0
  53. package/dist/conversation/use-conversation-feed.d.ts +16 -0
  54. package/dist/conversation/use-conversation-feed.js +41 -0
  55. package/dist/conversation/use-conversation-window.d.ts +50 -0
  56. package/dist/conversation/use-conversation-window.js +336 -0
  57. package/dist/conversation/words.d.ts +51 -0
  58. package/dist/conversation/words.js +79 -0
  59. package/dist/fixtures/conversation.d.ts +34 -0
  60. package/dist/fixtures/conversation.js +723 -0
  61. package/dist/fixtures/index.d.ts +2 -0
  62. package/dist/fixtures/index.js +1 -0
  63. package/dist/lib/session-leases.d.ts +11 -8
  64. package/dist/lib/transcript/collaboration.js +53 -19
  65. package/dist/lib/transcript/head-of-document.js +9 -3
  66. package/dist/lib/transcript/index.d.ts +1 -1
  67. package/dist/lib/transcript/index.js +1 -1
  68. package/dist/lib/transcript/prompt-jump.d.ts +2 -0
  69. package/dist/lib/transcript/prompt-jump.js +5 -1
  70. package/dist/lib/transcript/sittings.d.ts +2 -1
  71. package/dist/lib/transcript/sittings.js +72 -10
  72. package/dist/lib/transcript/tail-state.d.ts +9 -0
  73. package/dist/lib/transcript/tail-state.js +25 -1
  74. package/dist/lib/transcript/turns.d.ts +5 -0
  75. package/dist/lib/transcript/turns.js +221 -57
  76. package/dist/lib/transcript/use-transcript-tail.js +17 -3
  77. package/dist/lib/transcript/vocabulary.d.ts +2 -1
  78. package/dist/lib/transcript/vocabulary.js +11 -1
  79. package/dist/parts-context.d.ts +25 -0
  80. package/dist/parts-context.js +32 -0
  81. package/dist/ports.d.ts +3 -0
  82. package/dist/room-context.d.ts +1 -7
  83. package/dist/room-context.js +12 -18
  84. package/dist/styles/conversation-turn.css +147 -0
  85. package/dist/styles/conversation.css +45 -0
  86. package/dist/styles/transcript.css +11 -2
  87. package/package.json +9 -4
@@ -0,0 +1,41 @@
1
+ // The conversation view's feed, held by a component: made when the component
2
+ // mounts over a lease set and let go when it unmounts (or the lease set
3
+ // changes), told each new chain, and read as one external store, so every
4
+ // change the feed makes is one render of the view.
5
+ //
6
+ // The feed is made in an effect, never during render: a server render, or a
7
+ // render React throws away, opens no session.
8
+ import { useEffect, useRef, useState, useSyncExternalStore } from "react";
9
+ import { createConversationFeed } from "./feed.js";
10
+ /** What the view draws before its feed is made: nothing held yet. */
11
+ export const READING_FEED_STATE = Object.freeze({
12
+ phase: "reading", unavailable: null, sessions: Object.freeze([]), latest: null, atTop: false, version: 0,
13
+ });
14
+ const noStore = () => () => { };
15
+ const readingState = () => READING_FEED_STATE;
16
+ /**
17
+ * The feed over `sessions` for `chain`. A chain with the same ids (a new
18
+ * array, the same sessions) changes nothing; a new lease set makes a new feed
19
+ * and lets the old one go.
20
+ */
21
+ export function useConversationFeed(sessions, chain, timers) {
22
+ const [feed, setFeed] = useState(null);
23
+ const chainNow = useRef(chain);
24
+ chainNow.current = chain;
25
+ const timersNow = useRef(timers);
26
+ timersNow.current = timers;
27
+ useEffect(() => {
28
+ const made = createConversationFeed(timersNow.current === undefined ? { sessions } : { sessions, timers: timersNow.current });
29
+ made.setChain(chainNow.current);
30
+ setFeed(made);
31
+ return () => made.dispose();
32
+ }, [sessions]);
33
+ // The chain's ids, not its array: a host that passes a new array of the
34
+ // same sessions on every render asks for nothing.
35
+ const chainKey = chain.join("\u0000");
36
+ useEffect(() => {
37
+ feed?.setChain(chainNow.current);
38
+ }, [feed, chainKey]);
39
+ const state = useSyncExternalStore(feed?.subscribe ?? noStore, feed?.state ?? readingState, readingState);
40
+ return { feed, state };
41
+ }
@@ -0,0 +1,50 @@
1
+ import type { Virtualizer, VirtualItem } from "@tanstack/react-virtual";
2
+ import type { RefObject } from "react";
3
+ import type { ConversationRowRef } from "./model.js";
4
+ /** Rows mounted beyond the viewport, on either side. */
5
+ export declare const WINDOW_OVERSCAN = 6;
6
+ /** Within this many px of the foot, the reader is at it. */
7
+ export declare const FOOT_SLACK_PX = 4;
8
+ /** A width change larger than this re-measures every row. */
9
+ export declare const WIDTH_SLACK_PX = 1;
10
+ /** The host's box around the rows: `--tr-conv-pad` (1 to 4 lengths, as CSS
11
+ * padding) and `--tr-conv-gap`. */
12
+ export interface WindowBox {
13
+ readonly top: number;
14
+ readonly right: number;
15
+ readonly bottom: number;
16
+ readonly left: number;
17
+ readonly gap: number;
18
+ }
19
+ export declare const DEFAULT_WINDOW_BOX: WindowBox;
20
+ /** `6px 28px 26px` as CSS reads padding; a value that is not px lengths is the default. */
21
+ export declare function windowBoxOf(pad: string, gap: string): WindowBox;
22
+ export interface ConversationWindowOptions {
23
+ readonly rows: readonly ConversationRowRef[];
24
+ /** A row's height before it is measured, given the row and its place in
25
+ * `rows`: the one remembered for its key wins over this. */
26
+ readonly estimate: (row: ConversationRowRef, index: number) => number;
27
+ /** False while a row draws only its placeholder: its height is not kept. */
28
+ readonly measured: (row: ConversationRowRef) => boolean;
29
+ readonly scroller: RefObject<HTMLDivElement | null>;
30
+ readonly root: RefObject<HTMLDivElement | null>;
31
+ /** The view has its first rows to show: it opens at the end once. */
32
+ readonly ready: boolean;
33
+ /** The rows in view changed: first and last index. Told once the window
34
+ * has opened; when the scroll stands where no row is drawn (a pad), the row
35
+ * nearest it stands for both. */
36
+ readonly onRange?: ((first: number, last: number) => void) | undefined;
37
+ readonly onAway?: ((away: boolean, unseen: number) => void) | undefined;
38
+ }
39
+ export interface ConversationWindow {
40
+ readonly virtualizer: Virtualizer<HTMLDivElement, HTMLDivElement>;
41
+ readonly items: readonly VirtualItem[];
42
+ readonly totalSize: number;
43
+ readonly box: WindowBox;
44
+ readonly measure: (element: HTMLDivElement | null) => void;
45
+ scrollToLatest(): void;
46
+ /** Scroll the row with this key to the top; true once it is placed there,
47
+ * or as near as the list's end allows. */
48
+ scrollToKey(key: string): Promise<boolean>;
49
+ }
50
+ export declare function useConversationWindow(o: ConversationWindowOptions): ConversationWindow;
@@ -0,0 +1,336 @@
1
+ // The conversation view's window: only the rows near the viewport are
2
+ // mounted, each measured as it draws, its height remembered by its key.
3
+ //
4
+ // - It opens at the end, and follows the foot while the reader is there
5
+ // (within 4 px): a new row, or the last row growing, keeps the foot in view.
6
+ // Away from the foot nothing moves, and the host hears how many turns
7
+ // arrived since the reader left (`onAway`).
8
+ // - It holds the reader's place when rows land above. The first row in view
9
+ // and its offset are the anchor, taken whenever the reader scrolls; after
10
+ // every commit that moved it (an older session's rows prepended, bodies read
11
+ // in place of placeholders above, a row above growing), the scroll is set so
12
+ // the anchor stands where it stood. The virtualizer's own end anchor and
13
+ // size adjustments do most of it at once; the commit's check makes it exact.
14
+ // Its own writes and the virtualizer's are not the reader's: they move no
15
+ // anchor.
16
+ // - A jump scrolls a row to the top and answers once it is placed.
17
+ // - A column whose width changes by more than 1 px is measured again.
18
+ // - The rows in view are told from the scroll as it stands, over every row's
19
+ // place, on every scroll and after every commit, and never before the window
20
+ // has opened: the first rows told are the ones the reader opens on.
21
+ //
22
+ // The host's `--tr-conv-pad` and `--tr-conv-gap` are read from the root once
23
+ // it mounts, so the window's own sums are the host's.
24
+ import { elementScroll, useVirtualizer } from "@tanstack/react-virtual";
25
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
26
+ /** Rows mounted beyond the viewport, on either side. */
27
+ export const WINDOW_OVERSCAN = 6;
28
+ /** Within this many px of the foot, the reader is at it. */
29
+ export const FOOT_SLACK_PX = 4;
30
+ /** A width change larger than this re-measures every row. */
31
+ export const WIDTH_SLACK_PX = 1;
32
+ export const DEFAULT_WINDOW_BOX = Object.freeze({ top: 6, right: 28, bottom: 26, left: 28, gap: 14 });
33
+ /** `6px 28px 26px` as CSS reads padding; a value that is not px lengths is the default. */
34
+ export function windowBoxOf(pad, gap) {
35
+ const lengths = pad.trim() === "" ? [] : pad.trim().split(/\s+/).map((each) => (/^-?\d+(\.\d+)?px$/.test(each) ? Number.parseFloat(each) : Number.NaN));
36
+ const spacing = /^\d+(\.\d+)?px$/.test(gap.trim()) ? Number.parseFloat(gap) : DEFAULT_WINDOW_BOX.gap;
37
+ if (lengths.length === 0 || lengths.length > 4 || lengths.some((each) => !Number.isFinite(each))) {
38
+ return { ...DEFAULT_WINDOW_BOX, gap: spacing };
39
+ }
40
+ const [top, right = top, bottom = top, left = right] = lengths;
41
+ return { top, right, bottom, left, gap: spacing };
42
+ }
43
+ const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()));
44
+ export function useConversationWindow(o) {
45
+ const { rows, scroller, root } = o;
46
+ const rowsNow = useRef(rows);
47
+ rowsNow.current = rows;
48
+ const heights = useRef(new Map());
49
+ const [box, setBox] = useState(DEFAULT_WINDOW_BOX);
50
+ const estimate = useRef(o.estimate);
51
+ estimate.current = o.estimate;
52
+ const measured = useRef(o.measured);
53
+ measured.current = o.measured;
54
+ // The last scroll written by the window or its virtualizer: a scroll event
55
+ // that lands there is not the reader's.
56
+ const written = useRef(null);
57
+ // The same function while the rows are the same: the virtualizer places
58
+ // every row again whenever it changes, so a new one on every render would
59
+ // place every row on every render, not once when the rows change.
60
+ const itemKey = useCallback((index) => rows[index]?.key ?? index, [rows]);
61
+ const virtualizer = useVirtualizer({
62
+ count: rows.length,
63
+ scrollToFn: (offset, options, instance) => {
64
+ written.current = offset + (options.adjustments ?? 0);
65
+ elementScroll(offset, options, instance);
66
+ },
67
+ getScrollElement: () => scroller.current,
68
+ getItemKey: itemKey,
69
+ estimateSize: (index) => {
70
+ const row = rowsNow.current[index];
71
+ if (row === undefined)
72
+ return 0;
73
+ return heights.current.get(row.key) ?? estimate.current(row, index);
74
+ },
75
+ measureElement: (element, entry, instance) => {
76
+ const size = entry?.borderBoxSize?.[0]?.blockSize ?? element.getBoundingClientRect().height;
77
+ const index = instance.indexFromElement(element);
78
+ const row = rowsNow.current[index];
79
+ if (row !== undefined && measured.current(row))
80
+ heights.current.set(row.key, size);
81
+ return size;
82
+ },
83
+ overscan: WINDOW_OVERSCAN,
84
+ paddingStart: box.top,
85
+ paddingEnd: box.bottom,
86
+ gap: box.gap,
87
+ // Rows prepended or inserted keep the first visible row in place, by key.
88
+ anchorTo: "end",
89
+ scrollEndThreshold: FOOT_SLACK_PX,
90
+ // Measured in the next frame, so a row's new height never lands in the
91
+ // same layout pass that changed it.
92
+ useAnimationFrameWithResizeObserver: true,
93
+ });
94
+ // A row entirely above the viewport that grows or shrinks moves the scroll
95
+ // by as much, whichever way the reader was going: the place holds.
96
+ virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => item.start + item.size <= (instance.scrollOffset ?? 0);
97
+ // The host's box, once the root mounts.
98
+ useLayoutEffect(() => {
99
+ const element = root.current;
100
+ if (element === null)
101
+ return;
102
+ const style = getComputedStyle(element);
103
+ const next = windowBoxOf(style.getPropertyValue("--tr-conv-pad"), style.getPropertyValue("--tr-conv-gap"));
104
+ setBox((now) => (now.top === next.top && now.right === next.right && now.bottom === next.bottom && now.left === next.left &&
105
+ now.gap === next.gap ? now : next));
106
+ }, [root]);
107
+ // At the foot: from the scroll position, read on every scroll.
108
+ const stuck = useRef(true);
109
+ /** The first row in view and how far the scroll stands below its top. */
110
+ const anchor = useRef(null);
111
+ const jumping = useRef(false);
112
+ const capture = useCallback(() => {
113
+ const element = scroller.current;
114
+ if (element === null)
115
+ return;
116
+ const top = element.scrollTop;
117
+ const item = virtualizer.getVirtualItems().find((each) => each.end > top);
118
+ const row = item === undefined ? undefined : rowsNow.current[item.index];
119
+ anchor.current = item === undefined || row === undefined ? null : { key: row.key, offset: top - item.start };
120
+ }, [scroller, virtualizer]);
121
+ const awayFrom = useRef(null);
122
+ const onAway = useRef(o.onAway);
123
+ onAway.current = o.onAway;
124
+ const turns = useMemo(() => rows.reduce((sum, row) => sum + (row.kind === "turn" ? 1 : 0), 0), [rows]);
125
+ const turnsNow = useRef(turns);
126
+ turnsNow.current = turns;
127
+ const told = useRef({ away: false, unseen: 0 });
128
+ const tell = useCallback(() => {
129
+ const away = !stuck.current;
130
+ const unseen = away && awayFrom.current !== null ? Math.max(0, turnsNow.current - awayFrom.current) : 0;
131
+ if (told.current.away === away && told.current.unseen === unseen)
132
+ return;
133
+ told.current = { away, unseen };
134
+ onAway.current?.(away, unseen);
135
+ }, []);
136
+ // What the scroll position says, read on every scroll event and again at the
137
+ // start of every commit's check: the virtualizer re-renders from its own
138
+ // scroll listener, which can run before this one hears the same scroll.
139
+ // The reader leaves the foot by scrolling up; a scroll that moves down short
140
+ // of the foot, or one the window or its virtualizer wrote, leaves the reader
141
+ // where they were.
142
+ const lastTop = useRef(null);
143
+ const opened = useRef(false);
144
+ // The rows in view, told when they change. Read from the scroll as it
145
+ // stands, after this commit's own writes (the foot at open, an anchor held),
146
+ // over every row's place: never from the render's items, which describe the
147
+ // scroll before those writes, so a view opened at its foot would tell the
148
+ // rows at its top, or none.
149
+ const onRange = useRef(o.onRange);
150
+ onRange.current = o.onRange;
151
+ const lastRange = useRef("");
152
+ const tellRange = useCallback(() => {
153
+ const element = scroller.current;
154
+ if (element === null || !opened.current)
155
+ return;
156
+ virtualizer.getVirtualItems();
157
+ const places = virtualizer.measurementsCache;
158
+ if (places.length === 0)
159
+ return;
160
+ const top = element.scrollTop;
161
+ const bottom = top + element.clientHeight;
162
+ // The first row that ends below the top, by halving: the rows' places
163
+ // never go back, and a walk from the first row would cost every row above.
164
+ let low = 0;
165
+ let high = places.length;
166
+ while (low < high) {
167
+ const mid = (low + high) >>> 1;
168
+ if (places[mid].end <= top)
169
+ low = mid + 1;
170
+ else
171
+ high = mid;
172
+ }
173
+ let first = -1;
174
+ let last = -1;
175
+ for (let i = low; i < places.length; i += 1) {
176
+ const item = places[i];
177
+ if (item.start >= bottom)
178
+ break;
179
+ if (first < 0)
180
+ first = item.index;
181
+ last = item.index;
182
+ }
183
+ if (first < 0) {
184
+ // The scroll stands in a pad, where no row is drawn: the row nearest it.
185
+ first = low < places.length ? low : places.length - 1;
186
+ last = first;
187
+ }
188
+ const key = `${first}:${last}:${rowsNow.current[first]?.key ?? ""}:${rowsNow.current[last]?.key ?? ""}`;
189
+ if (key === lastRange.current)
190
+ return;
191
+ lastRange.current = key;
192
+ onRange.current?.(first, last);
193
+ }, [scroller, virtualizer]);
194
+ const observe = useCallback(() => {
195
+ const element = scroller.current;
196
+ if (element === null)
197
+ return;
198
+ const top = element.scrollTop;
199
+ const before = lastTop.current;
200
+ lastTop.current = top;
201
+ const atFoot = element.scrollHeight - top - element.clientHeight <= FOOT_SLACK_PX;
202
+ if (atFoot && !stuck.current) {
203
+ stuck.current = true;
204
+ awayFrom.current = null;
205
+ }
206
+ if (before !== null && Math.abs(top - before) < 0.5)
207
+ return;
208
+ const ours = written.current !== null && Math.abs(top - written.current) < 1.5;
209
+ written.current = null;
210
+ if (ours)
211
+ return;
212
+ if (!atFoot && before !== null && top < before - 1 && stuck.current) {
213
+ stuck.current = false;
214
+ awayFrom.current = turnsNow.current;
215
+ }
216
+ if (!jumping.current)
217
+ capture();
218
+ }, [scroller, capture]);
219
+ useEffect(() => {
220
+ const element = scroller.current;
221
+ if (element === null)
222
+ return;
223
+ const read = () => {
224
+ observe();
225
+ tell();
226
+ tellRange();
227
+ };
228
+ element.addEventListener("scroll", read, { passive: true });
229
+ return () => element.removeEventListener("scroll", read);
230
+ }, [scroller, tell, observe, tellRange]);
231
+ // The foot: the list's own end, its bottom pad included (the last row's end
232
+ // alone stops short of it by the pad).
233
+ const toFoot = useCallback(() => {
234
+ if (typeof virtualizer.scrollToEnd === "function")
235
+ virtualizer.scrollToEnd();
236
+ else
237
+ virtualizer.scrollToOffset(Math.max(0, virtualizer.getTotalSize() - (scroller.current?.clientHeight ?? 0)));
238
+ }, [virtualizer, scroller]);
239
+ // Open at the end, once there is something to show.
240
+ useLayoutEffect(() => {
241
+ if (!o.ready || opened.current || rows.length === 0)
242
+ return;
243
+ opened.current = true;
244
+ stuck.current = true;
245
+ toFoot();
246
+ }, [o.ready, rows.length, toFoot]);
247
+ // After every commit: at the foot, keep the foot in view (a row added or
248
+ // grown while the reader was there); away, keep the anchor where it stood.
249
+ const total = virtualizer.getTotalSize();
250
+ useLayoutEffect(() => {
251
+ const element = scroller.current;
252
+ if (!opened.current || element === null)
253
+ return;
254
+ observe();
255
+ if (stuck.current) {
256
+ if (element.scrollHeight - element.scrollTop - element.clientHeight > FOOT_SLACK_PX)
257
+ toFoot();
258
+ }
259
+ else if (!jumping.current) {
260
+ const held = anchor.current;
261
+ const index = held === null ? -1 : rowsNow.current.findIndex((row) => row.key === held.key);
262
+ virtualizer.getVirtualItems();
263
+ const item = index < 0 ? undefined : virtualizer.measurementsCache[index];
264
+ if (held === null || item === undefined)
265
+ capture();
266
+ else {
267
+ const target = Math.max(0, item.start + held.offset);
268
+ if (Math.abs(element.scrollTop - target) > 0.5) {
269
+ written.current = target;
270
+ element.scrollTop = target;
271
+ lastTop.current = element.scrollTop;
272
+ }
273
+ }
274
+ }
275
+ tell();
276
+ });
277
+ // A new width re-measures every row.
278
+ useEffect(() => {
279
+ const element = scroller.current;
280
+ if (element === null)
281
+ return;
282
+ let width = element.clientWidth;
283
+ const observer = new ResizeObserver(() => {
284
+ const next = element.clientWidth;
285
+ if (Math.abs(next - width) <= WIDTH_SLACK_PX)
286
+ return;
287
+ width = next;
288
+ heights.current.clear();
289
+ virtualizer.measure();
290
+ });
291
+ observer.observe(element);
292
+ return () => observer.disconnect();
293
+ }, [scroller, virtualizer]);
294
+ // After every commit (its layout effects have written the scroll): the rows
295
+ // in view, if they changed.
296
+ const items = virtualizer.getVirtualItems();
297
+ useEffect(() => {
298
+ tellRange();
299
+ });
300
+ const scrollToLatest = useCallback(() => {
301
+ stuck.current = true;
302
+ awayFrom.current = null;
303
+ toFoot();
304
+ tell();
305
+ }, [toFoot, tell]);
306
+ const scrollToKey = useCallback(async (key) => {
307
+ const index = rowsNow.current.findIndex((row) => row.key === key);
308
+ const element = scroller.current;
309
+ if (index < 0 || element === null)
310
+ return false;
311
+ stuck.current = false;
312
+ awayFrom.current = turnsNow.current;
313
+ jumping.current = true;
314
+ try {
315
+ virtualizer.scrollToIndex(index, { align: "start" });
316
+ for (let frame = 0; frame < 60; frame += 1) {
317
+ await nextFrame();
318
+ const row = element.querySelector(`[data-key="${CSS.escape(key)}"]`);
319
+ if (row === null)
320
+ continue;
321
+ const delta = row.getBoundingClientRect().top - element.getBoundingClientRect().top;
322
+ const atEnd = element.scrollHeight - element.scrollTop - element.clientHeight <= 1;
323
+ if (Math.abs(delta) <= 1 || (atEnd && delta > 0))
324
+ return true;
325
+ }
326
+ // Never placed in time: a row merely mounted is not at the top.
327
+ return false;
328
+ }
329
+ finally {
330
+ // The place the jump reached is the reader's from now on.
331
+ jumping.current = false;
332
+ capture();
333
+ }
334
+ }, [scroller, virtualizer, capture]);
335
+ return { virtualizer, items, totalSize: total, box, measure: virtualizer.measureElement, scrollToLatest, scrollToKey };
336
+ }
@@ -0,0 +1,51 @@
1
+ import type { TimelineEntry, TurnOutcome, TurnRun } from "@vibefield/rosetta-protocol";
2
+ /** Every default the view's words slots fall back to, by slot. */
3
+ export interface ConversationWords {
4
+ /** `label`: the view's accessible name. */
5
+ readonly label: string;
6
+ /** `reading`: nothing is held yet and the first read is out. */
7
+ readonly reading: string;
8
+ /** `empty`: the chain holds no turn. */
9
+ readonly empty: string;
10
+ /** `catchingUp`: the view keeps what it holds while it reads the session again. */
11
+ readonly catchingUp: string;
12
+ /** `unavailable`, by reason. A refused or closed session's own message is
13
+ * drawn beside these words. */
14
+ readonly unavailable: {
15
+ readonly unsupported: string;
16
+ readonly refused: string;
17
+ readonly closed: string;
18
+ };
19
+ /** `outcomeWords`, by state: the line after a turn that did not finish. A
20
+ * finished, open or unknown turn draws no line. */
21
+ readonly outcome: {
22
+ readonly failed: string;
23
+ readonly stopped: string;
24
+ readonly cut_off: string;
25
+ };
26
+ /** `compactionWords`: the line a compaction draws, opening to its summary. */
27
+ readonly compaction: string;
28
+ /** `requestWords`, by what the agent asked: a question with no words of its
29
+ * own, or a permission. */
30
+ readonly request: {
31
+ readonly question: string;
32
+ readonly permission: string;
33
+ };
34
+ }
35
+ export declare const CONVERSATION_WORDS: ConversationWords;
36
+ /**
37
+ * A run's line as the room says a run: its tool rows by the room's nouns,
38
+ * acts before looks, a larger count first within a class and ties in the
39
+ * run's own order, joined with ` · ` — `2 edits · 5 commands · 3 reads`. Then
40
+ * ` · 1 failed` when something in it failed. A run with no tool says its
41
+ * thoughts (`2 thoughts`); a run with nothing to say is null, and its line
42
+ * hides. Every tool counts: which calls a host leaves out of its own words is
43
+ * the host's, through `runWords`.
44
+ */
45
+ export declare function defaultRunWords(run: TurnRun): string | null;
46
+ /** The line after a turn: a failed turn with its reason when it gave one, a
47
+ * stopped or a cut-off turn plainly; any other state draws none. */
48
+ export declare function defaultOutcomeWords(outcome: TurnOutcome): string | null;
49
+ /** A request's line: a question by its own first line, a permission with what
50
+ * it was asked for. A row that is neither draws none. */
51
+ export declare function defaultRequestWords(row: TimelineEntry): string | null;
@@ -0,0 +1,79 @@
1
+ import { canonicalText, FAMILY_CLASS, familyNoun, firstLine } from "../lib/transcript/vocabulary.js";
2
+ export const CONVERSATION_WORDS = Object.freeze({
3
+ label: "Conversation",
4
+ reading: "Loading messages…",
5
+ empty: "Nothing readable yet",
6
+ catchingUp: "Catching up…",
7
+ unavailable: Object.freeze({
8
+ unsupported: "Conversations need a newer index",
9
+ refused: "Could not open this conversation",
10
+ closed: "This conversation was closed",
11
+ }),
12
+ outcome: Object.freeze({ failed: "The turn failed", stopped: "Stopped", cut_off: "Cut off" }),
13
+ compaction: "Context compacted",
14
+ request: Object.freeze({ question: "Asked a question", permission: "Permission requested" }),
15
+ });
16
+ /** A kind this build does not know reads as `unknown`, whose noun is `call`. */
17
+ function familyOf(kind) {
18
+ return Object.hasOwn(FAMILY_CLASS, kind) ? kind : "unknown";
19
+ }
20
+ /**
21
+ * A run's line as the room says a run: its tool rows by the room's nouns,
22
+ * acts before looks, a larger count first within a class and ties in the
23
+ * run's own order, joined with ` · ` — `2 edits · 5 commands · 3 reads`. Then
24
+ * ` · 1 failed` when something in it failed. A run with no tool says its
25
+ * thoughts (`2 thoughts`); a run with nothing to say is null, and its line
26
+ * hides. Every tool counts: which calls a host leaves out of its own words is
27
+ * the host's, through `runWords`.
28
+ */
29
+ export function defaultRunWords(run) {
30
+ const order = [];
31
+ const counts = new Map();
32
+ for (const { kind, count } of run.kinds) {
33
+ if (!(count > 0))
34
+ continue;
35
+ const family = familyOf(kind);
36
+ if (!counts.has(family))
37
+ order.push(family);
38
+ counts.set(family, (counts.get(family) ?? 0) + count);
39
+ }
40
+ const byClass = (cls) => order
41
+ .filter((family) => FAMILY_CLASS[family] === cls)
42
+ .sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0) || order.indexOf(a) - order.indexOf(b));
43
+ const words = [...byClass("act"), ...byClass("look")].map((family) => familyNoun(family, counts.get(family) ?? 0));
44
+ if (words.length === 0 && run.thoughts > 0)
45
+ words.push(`${run.thoughts} ${run.thoughts === 1 ? "thought" : "thoughts"}`);
46
+ if (run.failed > 0)
47
+ words.push(`${run.failed} failed`);
48
+ return words.length === 0 ? null : words.join(" · ");
49
+ }
50
+ /** The line after a turn: a failed turn with its reason when it gave one, a
51
+ * stopped or a cut-off turn plainly; any other state draws none. */
52
+ export function defaultOutcomeWords(outcome) {
53
+ switch (outcome.state) {
54
+ case "failed": {
55
+ const reason = outcome.reason?.trim() ?? "";
56
+ return reason === "" ? CONVERSATION_WORDS.outcome.failed : `${CONVERSATION_WORDS.outcome.failed} · ${firstLine(reason)}`;
57
+ }
58
+ case "stopped":
59
+ return CONVERSATION_WORDS.outcome.stopped;
60
+ case "cut_off":
61
+ return CONVERSATION_WORDS.outcome.cut_off;
62
+ default:
63
+ return null;
64
+ }
65
+ }
66
+ /** A request's line: a question by its own first line, a permission with what
67
+ * it was asked for. A row that is neither draws none. */
68
+ export function defaultRequestWords(row) {
69
+ const body = row.body;
70
+ if (body.type === "notice" && body.notice.type === "permission_requested") {
71
+ const scope = body.notice.scope?.trim() ?? "";
72
+ return scope === "" ? CONVERSATION_WORDS.request.permission : `${CONVERSATION_WORDS.request.permission} · ${scope}`;
73
+ }
74
+ if (body.type === "tool_use" && body.tool.action.type === "question") {
75
+ const asked = body.tool.action.questions.map((question) => firstLine(canonicalText(question.prompt))).find((line) => line !== "");
76
+ return asked ?? CONVERSATION_WORDS.request.question;
77
+ }
78
+ return null;
79
+ }
@@ -0,0 +1,34 @@
1
+ import type { ConversationSessionPort } from "../conversation/ports.js";
2
+ import type { AssetSource } from "../ports.js";
3
+ export interface ConversationDemoOptions {
4
+ /** Turns in the whole chain, shared out over its sessions. Default 12. */
5
+ readonly turns?: number;
6
+ /** Sessions in the chain, oldest first. Default 1. */
7
+ readonly sessions?: number;
8
+ /** Pictures on some runs: one on some, several on others. Default false. */
9
+ readonly media?: boolean;
10
+ /** The chain's newest turn is still at work: open, with a tool running and
11
+ * no reply yet, and each `append` leaves its new turn open. Default false. */
12
+ readonly live?: boolean;
13
+ /** The generator's seed. Default 1. */
14
+ readonly seed?: number;
15
+ /** When the chain's newest turn began, in ms. Default a fixed instant, so
16
+ * nothing in the demo depends on the clock. */
17
+ readonly now?: number;
18
+ }
19
+ export interface ConversationDemo {
20
+ readonly sessionPort: ConversationSessionPort;
21
+ readonly assets: AssetSource;
22
+ /** The chain's session ids, oldest first. */
23
+ readonly chain: readonly string[];
24
+ /** A new turn of `text` and a reply in the chain's last session, told to
25
+ * every open subscription of it with the turn before it. */
26
+ append(text: string): void;
27
+ /** The sessions are read again: each open subscription hears `onReset`,
28
+ * then a fresh snapshot under a new watermark, which expires the old one. */
29
+ reset(): void;
30
+ /** Every LATER `open` answers a client with no turn reads at all, as a host
31
+ * over a daemon that has none would. */
32
+ unsupported(): void;
33
+ }
34
+ export declare function createConversationDemo(o?: ConversationDemoOptions): ConversationDemo;