zidane-ui 9.2.3 → 9.3.1

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 (151) hide show
  1. package/dist/adapters/live.d.ts +6 -0
  2. package/dist/adapters/live.js +16 -8
  3. package/dist/adapters/server-composer-host.js +22 -9
  4. package/dist/adapters/server-host.js +143 -18
  5. package/dist/adapters/server-media.d.ts +9 -1
  6. package/dist/adapters/server-media.js +14 -1
  7. package/dist/chat/HostTranscript.d.ts +0 -12
  8. package/dist/chat/HostTranscript.js +6 -1
  9. package/dist/chat/SessionStreamsProvider.d.ts +8 -0
  10. package/dist/chat/SessionStreamsProvider.js +11 -2
  11. package/dist/chat/Transcript.d.ts +20 -11
  12. package/dist/chat/Transcript.js +326 -160
  13. package/dist/chat/composer/ComposerEditor.js +1 -1
  14. package/dist/chat/headless/host.d.ts +43 -7
  15. package/dist/chat/headless/index.d.ts +7 -6
  16. package/dist/chat/headless/index.js +10 -9
  17. package/dist/chat/headless/labels.d.ts +17 -0
  18. package/dist/chat/headless/labels.js +17 -0
  19. package/dist/chat/headless/markdown-chunks.d.ts +2 -1
  20. package/dist/chat/headless/markdown-chunks.js +12 -20
  21. package/dist/chat/headless/markdown-scan.d.ts +66 -0
  22. package/dist/chat/headless/markdown-scan.js +124 -0
  23. package/dist/chat/headless/markdown-stream.d.ts +64 -0
  24. package/dist/chat/headless/markdown-stream.js +143 -0
  25. package/dist/chat/headless/output-pager.d.ts +68 -0
  26. package/dist/chat/headless/output-pager.js +113 -0
  27. package/dist/chat/headless/session-list.d.ts +10 -0
  28. package/dist/chat/headless/sidebar/activity.d.ts +14 -0
  29. package/dist/chat/headless/sidebar/activity.js +32 -0
  30. package/dist/chat/headless/sidebar/directory.d.ts +9 -1
  31. package/dist/chat/headless/sidebar/directory.js +10 -50
  32. package/dist/chat/headless/sidebar/labels.d.ts +11 -1
  33. package/dist/chat/headless/sidebar/prewarm.d.ts +68 -0
  34. package/dist/chat/headless/sidebar/prewarm.js +114 -0
  35. package/dist/chat/headless/streams/actions.d.ts +2 -0
  36. package/dist/chat/headless/streams/actions.js +1 -0
  37. package/dist/chat/headless/streams/event-bytes.d.ts +6 -0
  38. package/dist/chat/headless/streams/event-bytes.js +34 -0
  39. package/dist/chat/headless/streams/live-events.d.ts +25 -1
  40. package/dist/chat/headless/streams/live-events.js +53 -2
  41. package/dist/chat/headless/streams/selectors.d.ts +3 -0
  42. package/dist/chat/headless/streams/selectors.js +8 -1
  43. package/dist/chat/headless/streams/session-streams.d.ts +15 -3
  44. package/dist/chat/headless/streams/session-streams.js +31 -3
  45. package/dist/chat/headless/streams/store.d.ts +24 -1
  46. package/dist/chat/headless/streams/store.js +51 -26
  47. package/dist/chat/headless/streams/transcript-map.d.ts +57 -0
  48. package/dist/chat/headless/streams/transcript-map.js +88 -0
  49. package/dist/chat/headless/streams/transcript.d.ts +4 -2
  50. package/dist/chat/headless/streams/transcript.js +19 -7
  51. package/dist/chat/headless/transcript/batch.js +5 -1
  52. package/dist/chat/headless/transcript/blob-media.d.ts +15 -0
  53. package/dist/chat/headless/transcript/blob-media.js +23 -0
  54. package/dist/chat/headless/transcript/collapse.d.ts +10 -0
  55. package/dist/chat/headless/transcript/collapse.js +32 -6
  56. package/dist/chat/headless/transcript/derive.d.ts +98 -0
  57. package/dist/chat/headless/transcript/derive.js +89 -0
  58. package/dist/chat/headless/transcript/exchange-media.d.ts +3 -1
  59. package/dist/chat/headless/transcript/exchange-media.js +8 -5
  60. package/dist/chat/headless/transcript/fold-attachments.d.ts +2 -0
  61. package/dist/chat/headless/transcript/fold-attachments.js +3 -2
  62. package/dist/chat/headless/transcript/fold.d.ts +2 -1
  63. package/dist/chat/headless/transcript/fold.js +16 -6
  64. package/dist/chat/headless/transcript/incremental.d.ts +53 -0
  65. package/dist/chat/headless/transcript/incremental.js +181 -0
  66. package/dist/chat/headless/transcript/index.d.ts +2 -2
  67. package/dist/chat/headless/transcript/index.js +2 -2
  68. package/dist/chat/headless/transcript/nesting.js +2 -1
  69. package/dist/chat/headless/transcript/rail.d.ts +50 -1
  70. package/dist/chat/headless/transcript/rail.js +165 -23
  71. package/dist/chat/headless/transcript/rows.d.ts +5 -1
  72. package/dist/chat/headless/transcript/run-failures.js +2 -1
  73. package/dist/chat/headless/transcript/seams.d.ts +78 -0
  74. package/dist/chat/headless/transcript/seams.js +116 -0
  75. package/dist/chat/headless/transcript/tool-media.d.ts +6 -7
  76. package/dist/chat/headless/transcript/tool-media.js +27 -9
  77. package/dist/chat/index.d.ts +8 -7
  78. package/dist/chat/index.js +17 -16
  79. package/dist/chat/sidebar/SidebarFooter.d.ts +8 -5
  80. package/dist/chat/sidebar/SidebarFooter.js +6 -6
  81. package/dist/chat/testing/contract.d.ts +5 -3
  82. package/dist/chat/testing/contract.js +66 -1
  83. package/dist/chat/transcript/DiffLines.d.ts +6 -1
  84. package/dist/chat/transcript/DiffLines.js +35 -20
  85. package/dist/chat/transcript/EditDiffBlock.d.ts +5 -1
  86. package/dist/chat/transcript/EditDiffBlock.js +89 -30
  87. package/dist/chat/transcript/LazyRow.d.ts +40 -40
  88. package/dist/chat/transcript/LazyRow.js +101 -149
  89. package/dist/chat/transcript/MermaidDiagram.js +2 -1
  90. package/dist/chat/transcript/SubagentBlock.js +3 -2
  91. package/dist/chat/transcript/TranscriptRail.d.ts +25 -2
  92. package/dist/chat/transcript/TranscriptRail.js +175 -17
  93. package/dist/chat/transcript/TranscriptRow.d.ts +4 -7
  94. package/dist/chat/transcript/TranscriptRow.js +4 -3
  95. package/dist/chat/transcript/actions.d.ts +37 -1
  96. package/dist/chat/transcript/actions.js +27 -1
  97. package/dist/chat/transcript/clipped-output.d.ts +58 -0
  98. package/dist/chat/transcript/clipped-output.js +131 -0
  99. package/dist/chat/transcript/fold-attachments.js +10 -5
  100. package/dist/chat/transcript/fold-worker.js +3 -2
  101. package/dist/chat/transcript/fold.js +2 -1
  102. package/dist/chat/transcript/index.d.ts +10 -9
  103. package/dist/chat/transcript/index.js +9 -8
  104. package/dist/chat/transcript/markdown-cache.d.ts +7 -1
  105. package/dist/chat/transcript/markdown-cache.js +12 -1
  106. package/dist/chat/transcript/markdown.js +116 -54
  107. package/dist/chat/transcript/media-gallery.d.ts +3 -2
  108. package/dist/chat/transcript/media-gallery.js +10 -7
  109. package/dist/chat/transcript/notices.js +2 -1
  110. package/dist/chat/transcript/prompt.js +6 -4
  111. package/dist/chat/transcript/prose.js +2 -1
  112. package/dist/chat/transcript/root-items.d.ts +96 -0
  113. package/dist/chat/transcript/root-items.js +180 -0
  114. package/dist/chat/transcript/row-mount.d.ts +165 -0
  115. package/dist/chat/transcript/row-mount.js +498 -0
  116. package/dist/chat/transcript/row-parking.d.ts +125 -0
  117. package/dist/chat/transcript/row-parking.js +135 -0
  118. package/dist/chat/transcript/row-ui-state.d.ts +37 -0
  119. package/dist/chat/transcript/row-ui-state.js +53 -0
  120. package/dist/chat/transcript/run-rows.js +3 -2
  121. package/dist/chat/transcript/script-input.d.ts +1 -1
  122. package/dist/chat/transcript/tasks.js +3 -2
  123. package/dist/chat/transcript/tool-media.d.ts +4 -2
  124. package/dist/chat/transcript/tool-media.js +15 -7
  125. package/dist/chat/transcript/tool-parts.d.ts +27 -4
  126. package/dist/chat/transcript/tool-parts.js +31 -5
  127. package/dist/chat/transcript/tool-payload.js +26 -11
  128. package/dist/chat/transcript/tool-row.d.ts +2 -1
  129. package/dist/chat/transcript/tool-row.js +38 -19
  130. package/dist/chat/transcript/use-transcript-rows.d.ts +24 -7
  131. package/dist/chat/transcript/use-transcript-rows.js +28 -46
  132. package/dist/chat/transcript/useStickToBottom.js +2 -3
  133. package/dist/chat/transcript/useTranscriptSearch.js +30 -14
  134. package/dist/chat/transcript/view-scope.d.ts +26 -6
  135. package/dist/chat/transcript/view-scope.js +106 -20
  136. package/dist/dist/{index-E1Z0aPmi.d.ts → index-C6-t1SS9.d.ts} +2 -1
  137. package/dist/dist/index.d.ts +1 -1
  138. package/dist/session/SessionHeader.js +1 -0
  139. package/dist/settings/headless/fixture-performance.js +4 -2
  140. package/dist/settings/headless/performance.d.ts +4 -0
  141. package/dist/settings/headless/search.d.ts +1 -1
  142. package/dist/settings/sections/performance/PerformanceSection.js +8 -1
  143. package/dist/settings/sections/performance/labels.d.ts +2 -0
  144. package/dist/settings/sections/performance/labels.js +2 -0
  145. package/dist/styles.css +33 -2
  146. package/dist/views/headless/answers.d.ts +8 -2
  147. package/dist/views/headless/answers.js +58 -1
  148. package/dist/views/headless/placement.d.ts +78 -0
  149. package/dist/views/headless/placement.js +154 -44
  150. package/package.json +2 -2
  151. package/src/styles/transcript.css +33 -2
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Prewarm: the transcripts around the open session load in idle time, so
3
+ * opening the next one shows it at once.
4
+ *
5
+ * A load is a tail page (`loadEvents`, the page an open shows), but on a
6
+ * host's cache miss it costs a replay of the whole session. So the window
7
+ * reads ahead only when what it would read changes:
8
+ *
9
+ * - Only the open session and the order of the sessions around it count.
10
+ * A row's other fields (a title, a status, a count: every
11
+ * `sessions:changed`) leave the window as it is and read nothing.
12
+ * - A change waits {@link PREWARM_DELAY_MS} for the next: a burst of
13
+ * reorders or a run of selections reads once, for where it ended.
14
+ * - A load in flight is never asked again: a later window takes its page
15
+ * when it lands.
16
+ *
17
+ * What the window holds is bounded by bytes, not by sessions: nearest first,
18
+ * the prewarmed transcripts are kept while their rows fit in `maxBytes`
19
+ * (`eventBytes`), and the reading stops when one no longer fits. The open
20
+ * session and the pinned ones are always kept and never counted.
21
+ */
22
+ /** The stream store as prewarm reads and fills it. */
23
+ export interface PrewarmStreams<K extends string, P> {
24
+ /** The session's transcript is cached. */
25
+ hasEvents: (sessionId: K) => boolean;
26
+ /** Cache a loaded transcript page. */
27
+ setEventsPage: (sessionId: K, page: P) => void;
28
+ /** Drop every cached transcript except these. */
29
+ evictExcept: (keep: ReadonlySet<K>) => void;
30
+ /** About how many bytes the session's cached rows hold. Absent: the window is bounded by its sessions only. */
31
+ eventBytes?: (sessionId: K) => number;
32
+ }
33
+ export interface PrewarmOptions<K extends string, P> {
34
+ streams: PrewarmStreams<K, P>;
35
+ /** Load a session's tail page, as a read ahead of the user. */
36
+ loadEvents: (sessionId: K, options: {
37
+ prewarm: true;
38
+ }) => Promise<P>;
39
+ /** Schedules one read in idle time. */
40
+ idle: {
41
+ request: (run: () => void) => number;
42
+ cancel: (handle: number) => void;
43
+ };
44
+ /** Sessions kept besides the window (side chats on screen). */
45
+ pinned?: () => Iterable<K>;
46
+ /** Wait for a change to settle before reading. Default {@link PREWARM_DELAY_MS}. */
47
+ delayMs?: number;
48
+ /** Bytes of prewarmed rows kept. Default {@link PREWARM_MAX_BYTES}. */
49
+ maxBytes?: number;
50
+ }
51
+ export interface Prewarmer<K extends string> {
52
+ /** The sessions as listed and the open one, after any change: reads ahead when the window moved. */
53
+ update: (sessions: readonly {
54
+ id: K;
55
+ }[], activeSessionId: K | null) => void;
56
+ stop: () => void;
57
+ }
58
+ /** Every session is in the window up to this many. */
59
+ export declare const PREWARM_FULL_THRESHOLD = 12;
60
+ /** Past it, this many on each side of the open session. */
61
+ export declare const PREWARM_WINDOW_RADIUS = 6;
62
+ export declare const PREWARM_DELAY_MS = 200;
63
+ export declare const PREWARM_MAX_BYTES: number;
64
+ /** The sessions around the open one (the first when none is open), nearest first, the one below before the one above. */
65
+ export declare function prewarmWindow<K extends string>(sessions: readonly {
66
+ id: K;
67
+ }[], activeSessionId: K | null): K[];
68
+ export declare function createPrewarmer<K extends string, P>(options: PrewarmOptions<K, P>): Prewarmer<K>;
@@ -0,0 +1,114 @@
1
+ // src/chat/headless/sidebar/prewarm.ts
2
+ /** Every session is in the window up to this many. */
3
+ const PREWARM_FULL_THRESHOLD = 12;
4
+ /** Past it, this many on each side of the open session. */
5
+ const PREWARM_WINDOW_RADIUS = 6;
6
+ const PREWARM_DELAY_MS = 200;
7
+ const PREWARM_MAX_BYTES = 25165824;
8
+ /** The sessions around the open one (the first when none is open), nearest first, the one below before the one above. */
9
+ function prewarmWindow(sessions, activeSessionId) {
10
+ const anchor = activeSessionId ? sessions.findIndex((s) => s.id === activeSessionId) : -1;
11
+ const center = anchor === -1 ? 0 : anchor;
12
+ const radius = sessions.length <= 12 ? sessions.length : 6;
13
+ const out = [];
14
+ for (let d = 0; d <= radius; d++) {
15
+ const below = sessions[center + d];
16
+ if (below) out.push(below.id);
17
+ const above = d > 0 ? sessions[center - d] : void 0;
18
+ if (above) out.push(above.id);
19
+ }
20
+ return out;
21
+ }
22
+ function createPrewarmer(options) {
23
+ const { streams, idle } = options;
24
+ const delayMs = options.delayMs ?? 200;
25
+ const maxBytes = options.maxBytes ?? 25165824;
26
+ let windowKey = null;
27
+ let candidates = [];
28
+ let active = null;
29
+ let timer;
30
+ let stopPump = null;
31
+ /** What the last fit kept: a load landing after the window moved is taken only if it is still in. */
32
+ let kept = /* @__PURE__ */ new Set();
33
+ const inFlight = /* @__PURE__ */ new Set();
34
+ /** Keep the open and pinned sessions, then the window nearest first while its loaded rows fit; evict the rest. */
35
+ const fit = () => {
36
+ const keep = new Set(options.pinned?.() ?? []);
37
+ if (active) keep.add(active);
38
+ const toLoad = [];
39
+ let used = 0;
40
+ for (const id of candidates) {
41
+ if (!streams.hasEvents(id)) {
42
+ keep.add(id);
43
+ toLoad.push(id);
44
+ continue;
45
+ }
46
+ if (keep.has(id)) continue;
47
+ used += streams.eventBytes?.(id) ?? 0;
48
+ if (used > maxBytes) break;
49
+ keep.add(id);
50
+ }
51
+ kept = keep;
52
+ streams.evictExcept(keep);
53
+ return toLoad;
54
+ };
55
+ const run = () => {
56
+ stopPump?.();
57
+ stopPump = null;
58
+ if (candidates.length === 0) return;
59
+ const targets = fit();
60
+ let cancelled = false;
61
+ let handle;
62
+ const pump = (index) => {
63
+ if (cancelled || index >= targets.length) return;
64
+ handle = idle.request(() => {
65
+ if (cancelled) return;
66
+ const id = targets[index];
67
+ if (streams.hasEvents(id) || inFlight.has(id) || !kept.has(id)) {
68
+ pump(index + 1);
69
+ return;
70
+ }
71
+ inFlight.add(id);
72
+ options.loadEvents(id, { prewarm: true }).then((page) => {
73
+ if (!kept.has(id) || streams.hasEvents(id)) return;
74
+ streams.setEventsPage(id, page);
75
+ fit();
76
+ if (!kept.has(id)) cancelled = true;
77
+ }).catch(() => {}).finally(() => {
78
+ inFlight.delete(id);
79
+ pump(index + 1);
80
+ });
81
+ });
82
+ };
83
+ pump(0);
84
+ stopPump = () => {
85
+ cancelled = true;
86
+ if (handle !== void 0) idle.cancel(handle);
87
+ };
88
+ };
89
+ return {
90
+ update(sessions, activeSessionId) {
91
+ const next = prewarmWindow(sessions, activeSessionId);
92
+ const key = `${activeSessionId ?? ""}\n${next.join("\n")}`;
93
+ if (key === windowKey) return;
94
+ windowKey = key;
95
+ candidates = next;
96
+ active = activeSessionId;
97
+ stopPump?.();
98
+ stopPump = null;
99
+ if (timer !== void 0) clearTimeout(timer);
100
+ timer = setTimeout(() => {
101
+ timer = void 0;
102
+ run();
103
+ }, delayMs);
104
+ },
105
+ stop() {
106
+ if (timer !== void 0) clearTimeout(timer);
107
+ timer = void 0;
108
+ stopPump?.();
109
+ stopPump = null;
110
+ windowKey = null;
111
+ }
112
+ };
113
+ }
114
+ export { PREWARM_DELAY_MS, PREWARM_FULL_THRESHOLD, PREWARM_MAX_BYTES, PREWARM_WINDOW_RADIUS, createPrewarmer, prewarmWindow };
@@ -29,6 +29,8 @@ export interface SessionStreamActions<K extends string = string> {
29
29
  appendErrorEvent: (sessionId: K, text: string) => void;
30
30
  /** Whether the store holds any record for the session (no subscription). */
31
31
  hasEvents: (sessionId: K) => boolean;
32
+ /** About how many bytes the session's rows hold (no subscription). */
33
+ eventBytes: (sessionId: K) => number;
32
34
  /** Seeds a run seen only through the session list. */
33
35
  markRunning: (sessionId: K) => void;
34
36
  /** Confirms the session is idle (a run that ended while nobody listened). */
@@ -22,6 +22,7 @@ function createSessionStreamActions(streams) {
22
22
  renamePromptPreviews: (sessionId, from, to) => store.renamePromptPreviews(sessionId, from, to),
23
23
  appendErrorEvent: (sessionId, text) => store.appendErrorEvent(sessionId, text),
24
24
  hasEvents: (sessionId) => store.hasEvents(sessionId),
25
+ eventBytes: (sessionId) => store.eventBytes(sessionId),
25
26
  markRunning: (sessionId) => store.markRunning(sessionId),
26
27
  confirmIdle: (sessionId) => streams.confirmIdle(sessionId),
27
28
  noteActiveSession: (sessionId) => streams.noteActiveSession(sessionId)
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The approximate size of `events`, measured once per array.
3
+ *
4
+ * @param events - A session's rows.
5
+ */
6
+ export declare function eventsBytes(events: readonly unknown[]): number;
@@ -0,0 +1,34 @@
1
+ // src/chat/headless/streams/event-bytes.ts
2
+ /**
3
+ * About how many bytes a transcript's rows hold, as JSON would spell them:
4
+ * what the prewarm window budgets by (`sidebar/prewarm.ts`). Strings count
5
+ * their length, so it is a size, not an exact one. A rows array is never
6
+ * changed in place (the store replaces it), so its size is kept per array.
7
+ */
8
+ const sizes = /* @__PURE__ */ new WeakMap();
9
+ function approxBytes(value) {
10
+ if (typeof value === "string") return value.length + 2;
11
+ if (value === null || typeof value !== "object") return typeof value === "undefined" || typeof value === "function" ? 0 : 8;
12
+ if (Array.isArray(value)) {
13
+ let bytes = 2;
14
+ for (const item of value) bytes += approxBytes(item) + 1;
15
+ return bytes;
16
+ }
17
+ let bytes = 2;
18
+ for (const key in value) bytes += key.length + 4 + approxBytes(value[key]);
19
+ return bytes;
20
+ }
21
+ /**
22
+ * The approximate size of `events`, measured once per array.
23
+ *
24
+ * @param events - A session's rows.
25
+ */
26
+ function eventsBytes(events) {
27
+ let bytes = sizes.get(events);
28
+ if (bytes === void 0) {
29
+ bytes = approxBytes(events);
30
+ sizes.set(events, bytes);
31
+ }
32
+ return bytes;
33
+ }
34
+ export { eventsBytes };
@@ -15,7 +15,7 @@
15
15
  * the run's end closes every lane still open.
16
16
  */
17
17
  import { ChatEvent } from "../host.js";
18
- import { MarkdownDeltaOptions } from "zidane/chat/pure";
18
+ import { MarkdownDeltaOptions, TranscriptEvents } from "zidane/chat/pure";
19
19
  import { Owner, StreamEvent } from "zidane/chat";
20
20
  /** A live transcript event with the live timings (`ChatEvent`'s, the desktop app's `GuiStreamEvent`'s). */
21
21
  type TimedEvent = Omit<StreamEvent, 'attachments'> & Pick<ChatEvent, 'thinkingStartedAt' | 'thinkingMs' | 'receivedAt'>;
@@ -49,4 +49,28 @@ export declare function applyLiveEvent<E extends TimedEvent = ChatEvent>(events:
49
49
  * @param now - Epoch milliseconds the open lanes close at. Defaults to the current time.
50
50
  */
51
51
  export declare function finishLive<E extends TimedEvent = ChatEvent>(events: readonly E[], now?: number): E[];
52
+ /**
53
+ * {@link applyLiveEvent} on a transcript store: a delta costs the open exchange, not the session.
54
+ *
55
+ * @param transcript - The transcript so far.
56
+ * @param event - The live event to fold in.
57
+ * @param now - Epoch milliseconds stamped on tool rows and thinking lanes. Defaults to the current time.
58
+ * @param markdown - How streamed markdown merges.
59
+ */
60
+ export declare function applyLiveEventToTranscript<E extends TimedEvent = ChatEvent>(transcript: TranscriptEvents<E>, event: E, now?: number, markdown?: MarkdownDeltaOptions): TranscriptEvents<E>;
61
+ /**
62
+ * A turn of `owner` ended (`turn:end`): its thinking lane closes and its streaming markdown is final.
63
+ *
64
+ * @param transcript - The transcript so far.
65
+ * @param owner - The owner whose turn ended.
66
+ * @param now - Epoch milliseconds the lane closes at. Defaults to the current time.
67
+ */
68
+ export declare function endTurnInTranscript<E extends TimedEvent = ChatEvent>(transcript: TranscriptEvents<E>, owner: Owner, now?: number): TranscriptEvents<E>;
69
+ /**
70
+ * {@link finishLive} on a transcript store: only the exchanges still live are visited.
71
+ *
72
+ * @param transcript - The transcript so far.
73
+ * @param now - Epoch milliseconds the open lanes close at. Defaults to the current time.
74
+ */
75
+ export declare function finishLiveTranscript<E extends TimedEvent = ChatEvent>(transcript: TranscriptEvents<E>, now?: number): TranscriptEvents<E>;
52
76
  export {};
@@ -1,4 +1,4 @@
1
- import { appendMarkdownDelta, appendThinkingLines, finalizeStreamingMarkdown, mergeTargetIndex, ownerOf, readEnvironmentSetup, upsertEnvironmentSetup, upsertToolProgress } from "zidane/chat/pure";
1
+ import { appendMarkdownDelta, appendThinkingLines, appendTranscriptEvent, chunkFact, finalizeStreamingMarkdown, mapTranscript, mergeTargetIndex, ownerOf, readEnvironmentSetup, transcriptFinalizeStreamingMarkdownForOwner, transcriptMarkdownDelta, transcriptThinkingLines, transcriptUpsertEnvironmentSetup, transcriptUpsertToolProgress, upsertEnvironmentSetup, upsertToolProgress, withTranscriptTail } from "zidane/chat/pure";
2
2
  // src/chat/headless/streams/live-events.ts
3
3
  const rows = (events) => events;
4
4
  const timed = (events) => events;
@@ -75,4 +75,55 @@ function finishLive(events, now = Date.now()) {
75
75
  const settled = events.some((e) => e.thinkingStartedAt !== void 0 && e.thinkingMs === void 0) ? events.map((e) => e.thinkingStartedAt !== void 0 && e.thinkingMs === void 0 ? closed(e, e.thinkingStartedAt, now) : e) : events;
76
76
  return timed(finalizeStreamingMarkdown(rows(settled)));
77
77
  }
78
- export { applyLiveEvent, closeThinkingSegment, finishLive };
78
+ const asStream = (transcript) => transcript;
79
+ const asTimed = (transcript) => transcript;
80
+ /**
81
+ * {@link applyLiveEvent} on a transcript store: a delta costs the open exchange, not the session.
82
+ *
83
+ * @param transcript - The transcript so far.
84
+ * @param event - The live event to fold in.
85
+ * @param now - Epoch milliseconds stamped on tool rows and thinking lanes. Defaults to the current time.
86
+ * @param markdown - How streamed markdown merges.
87
+ */
88
+ function applyLiveEventToTranscript(transcript, event, now = Date.now(), markdown) {
89
+ const stream = asStream(transcript);
90
+ const plain = event;
91
+ if (event.kind === "tool-progress") return asTimed(transcriptUpsertToolProgress(stream, plain));
92
+ if (readEnvironmentSetup(event)) return asTimed(transcriptUpsertEnvironmentSetup(stream, plain));
93
+ const owner = ownerOf(plain);
94
+ if (event.kind === "thinking") return asTimed(transcriptThinkingLines(stream, event.text, owner, event.depth, event.turnId, { onLaneOpen: (row) => ({
95
+ ...row,
96
+ thinkingStartedAt: now
97
+ }) }));
98
+ const open = withTranscriptTail(transcript, closeThinkingSegment(transcript.tail, owner, now));
99
+ if (event.kind === "markdown" && event.streaming) return asTimed(transcriptMarkdownDelta(asStream(open), event.text, owner, event.depth, event.turnId, markdown));
100
+ if ((event.kind === "tool" || event.kind === "tool-result") && !event.receivedAt) return appendTranscriptEvent(open, {
101
+ ...event,
102
+ receivedAt: now
103
+ });
104
+ return appendTranscriptEvent(open, event);
105
+ }
106
+ /**
107
+ * A turn of `owner` ended (`turn:end`): its thinking lane closes and its streaming markdown is final.
108
+ *
109
+ * @param transcript - The transcript so far.
110
+ * @param owner - The owner whose turn ended.
111
+ * @param now - Epoch milliseconds the lane closes at. Defaults to the current time.
112
+ */
113
+ function endTurnInTranscript(transcript, owner, now = Date.now()) {
114
+ const closed = withTranscriptTail(transcript, closeThinkingSegment(transcript.tail, owner, now));
115
+ return asTimed(transcriptFinalizeStreamingMarkdownForOwner(asStream(closed), owner));
116
+ }
117
+ function isLive(events) {
118
+ return events.some((e) => e.thinkingStartedAt !== void 0 && e.thinkingMs === void 0 || e.kind === "markdown" && e.streaming === true);
119
+ }
120
+ /**
121
+ * {@link finishLive} on a transcript store: only the exchanges still live are visited.
122
+ *
123
+ * @param transcript - The transcript so far.
124
+ * @param now - Epoch milliseconds the open lanes close at. Defaults to the current time.
125
+ */
126
+ function finishLiveTranscript(transcript, now = Date.now()) {
127
+ return mapTranscript(transcript, (events) => finishLive(events, now), (chunk) => chunkFact(chunk, "live", isLive));
128
+ }
129
+ export { applyLiveEvent, applyLiveEventToTranscript, closeThinkingSegment, endTurnInTranscript, finishLive, finishLiveTranscript };
@@ -8,11 +8,14 @@
8
8
  import { ChatEvent } from "../host.js";
9
9
  import { SessionStreamStore } from "./store.js";
10
10
  import { SessionFallbackModel, SessionPageState, SessionRetryState } from "./types.js";
11
+ import { TranscriptEvents } from "zidane/chat/pure";
11
12
  import { SystemMdFile } from "zidane/chat";
12
13
  /** One session's read of the store. Module-level reads keep the subscription stable. */
13
14
  export type SessionStreamRead<T, K extends string = string> = (store: SessionStreamStore<K>, sessionId: K | null) => T;
14
15
  /** The session's events. */
15
16
  export declare function readSessionEvents<K extends string>(store: SessionStreamStore<K>, id: K | null): readonly ChatEvent[];
17
+ /** The session's events as the store holds them (settled exchanges and the open one): no array is made. */
18
+ export declare function readSessionTranscript<K extends string>(store: SessionStreamStore<K>, id: K | null): TranscriptEvents<ChatEvent>;
16
19
  /** The session's scrollback state. */
17
20
  export declare function readSessionPage<K extends string>(store: SessionStreamStore<K>, id: K | null): SessionPageState;
18
21
  /** Whether a run is in flight. */
@@ -1,8 +1,15 @@
1
+ import { emptyTranscript } from "zidane/chat/pure";
1
2
  // src/chat/headless/streams/selectors.ts
2
3
  /** The session's events. */
3
4
  function readSessionEvents(store, id) {
4
5
  return store.getEventsSnapshot(id);
5
6
  }
7
+ /** A session the store holds nothing for: one transcript, so a reader's memo holds. */
8
+ const NO_TRANSCRIPT = emptyTranscript();
9
+ /** The session's events as the store holds them (settled exchanges and the open one): no array is made. */
10
+ function readSessionTranscript(store, id) {
11
+ return (id ? store.getTranscriptSnapshot(id) : void 0) ?? NO_TRANSCRIPT;
12
+ }
6
13
  /** The session's scrollback state. */
7
14
  function readSessionPage(store, id) {
8
15
  return store.getPageSnapshot(id);
@@ -49,4 +56,4 @@ function stableSelection(select) {
49
56
  return next;
50
57
  };
51
58
  }
52
- export { readSessionEvents, readSessionFallback, readSessionPage, readSessionRetry, readSessionRunning, readSessionSystemMd, selectEditEvents, stableSelection };
59
+ export { readSessionEvents, readSessionFallback, readSessionPage, readSessionRetry, readSessionRunning, readSessionSystemMd, readSessionTranscript, selectEditEvents, stableSelection };
@@ -10,7 +10,7 @@ import { ChatEvent, Transcript } from "../host.js";
10
10
  import { FrameScheduler } from "./scheduler.js";
11
11
  import { OtherStreamSignal, SessionStreamPage, SessionStreamSignal } from "./types.js";
12
12
  import { SessionStreamStore } from "./store.js";
13
- import { HistoryChange, HistorySince, MarkdownDeltaOptions } from "zidane/chat/pure";
13
+ import { HistoryChange, HistorySince, MarkdownDeltaOptions, PromptOutline } from "zidane/chat/pure";
14
14
  /** Options for {@link createSessionStreams}. */
15
15
  export interface SessionStreamsOptions<K extends string = string> {
16
16
  /** Pace streamed markdown at a steady speed. A function is read on every signal, so a setting can flip it live (call {@link SessionStreams.drainSmoothing} when it turns off). Default: `false`. */
@@ -21,8 +21,10 @@ export interface SessionStreamsOptions<K extends string = string> {
21
21
  markdown?: MarkdownDeltaOptions;
22
22
  /** Loads a session's persisted tail page. Run-end compaction and a history rewrite's fetch need it; without it neither happens. */
23
23
  loadTail?: (sessionId: K) => Promise<SessionStreamPage>;
24
- /** Loads the page before `beforeSeq`. {@link SessionStreams.loadEarlier} needs it. */
25
- loadBefore?: (sessionId: K, beforeSeq: number) => Promise<SessionStreamPage>;
24
+ /** Loads the page before `beforeSeq`, `limit` turns when given. {@link SessionStreams.loadEarlier} needs it. */
25
+ loadBefore?: (sessionId: K, beforeSeq: number, limit?: number) => Promise<SessionStreamPage>;
26
+ /** Reads the session's prompt outline (`Transcript.outline`). Absent: transcripts offer none. */
27
+ loadOutline?: (sessionId: K) => Promise<PromptOutline | null>;
26
28
  /**
27
29
  * The reconnect ladder's second step (`sessions.historySince`). Reads the rows
28
30
  * of the turns appended after `afterPos` of numbering `historyId`. Returns
@@ -37,7 +39,11 @@ export interface SessionStreamsOptions<K extends string = string> {
37
39
  export interface LoadEarlierOptions {
38
40
  /** Called once the fetch settles: `true` when the older page was spliced in. */
39
41
  onSettled?: (prepended: boolean) => void;
42
+ /** Turns in the page; default the host's page size. */
43
+ limit?: number;
40
44
  }
45
+ /** The most turns {@link SessionStreams.loadThrough} asks for in one page: a host's page ceiling. */
46
+ export declare const LOAD_THROUGH_MAX_TURNS = 1000;
41
47
  /** The session stream store with pacing, scrollback and compaction. Created by {@link createSessionStreams}. */
42
48
  export interface SessionStreams<K extends string = string> {
43
49
  /** The store: per-session snapshots (`get…Snapshot`), per-session subscriptions and the direct writes. */
@@ -85,6 +91,12 @@ export interface SessionStreams<K extends string = string> {
85
91
  * (reset, re-hydration) is dropped and reported as `onSettled(false)`.
86
92
  */
87
93
  loadEarlier: (sessionId: K, options?: LoadEarlierOptions) => boolean;
94
+ /**
95
+ * Loads the earlier pages up to turn position `index`, the gap at once (a page of at most
96
+ * {@link LOAD_THROUGH_MAX_TURNS}, again while it is not in). Resolves `true` once the window starts at or
97
+ * before it, `false` when it can't get there (no more history, a rewrite, a failed read).
98
+ */
99
+ loadThrough: (sessionId: K, index: number) => Promise<boolean>;
88
100
  /** The session the user is looking at: run-end compaction skips it and catches up once it is backgrounded. */
89
101
  noteActiveSession: (sessionId: K | null) => void;
90
102
  /** Reveals every waiting smoothed delta at once and stops the ticker (smoothing was turned off). */
@@ -13,6 +13,8 @@ import { climbReconnectLadder, cursorValid } from "zidane/chat/pure";
13
13
  * walk starts eating the frame budget.
14
14
  */
15
15
  const EVENT_WINDOW_COMPACT_THRESHOLD = 2e3;
16
+ /** The most turns {@link SessionStreams.loadThrough} asks for in one page: a host's page ceiling. */
17
+ const LOAD_THROUGH_MAX_TURNS = 1e3;
16
18
  /**
17
19
  * Creates the session stream store with smooth streaming, lazy scrollback and
18
20
  * run-end compaction. Feed it a client's live signals with `apply`.
@@ -184,7 +186,10 @@ function createSessionStreams(options = {}) {
184
186
  transcript(sessionId) {
185
187
  let transcript = transcripts.get(sessionId);
186
188
  if (!transcript) {
187
- transcript = storeTranscript(store, sessionId, options.loadBefore ? () => void streams.loadEarlier(sessionId) : void 0);
189
+ transcript = storeTranscript(store, sessionId, options.loadBefore ? () => void streams.loadEarlier(sessionId) : void 0, {
190
+ ...options.loadBefore ? { loadThrough: (index) => streams.loadThrough(sessionId, index) } : {},
191
+ ...options.loadOutline ? { outline: () => options.loadOutline(sessionId) } : {}
192
+ });
188
193
  transcripts.set(sessionId, transcript);
189
194
  }
190
195
  return transcript;
@@ -228,7 +233,7 @@ function createSessionStreams(options = {}) {
228
233
  store.setLoadingEarlier(sessionId, true);
229
234
  const issued = store.getPageSnapshot(sessionId);
230
235
  const current = () => store.getPageSnapshot(sessionId) === issued;
231
- loadBefore(sessionId, page.firstSeq).then((older) => {
236
+ (opts?.limit !== void 0 ? loadBefore(sessionId, page.firstSeq, opts.limit) : loadBefore(sessionId, page.firstSeq)).then((older) => {
232
237
  if (!current()) {
233
238
  opts?.onSettled?.(false);
234
239
  return;
@@ -247,6 +252,29 @@ function createSessionStreams(options = {}) {
247
252
  });
248
253
  return true;
249
254
  },
255
+ loadThrough(sessionId, index) {
256
+ return new Promise((resolve) => {
257
+ const step = () => {
258
+ const page = store.getPageSnapshot(sessionId);
259
+ if (store.isHydrated(sessionId) && page.firstSeq <= index) return resolve(true);
260
+ if (!page.hasMore || page.firstSeq <= 0) return resolve(false);
261
+ if (page.loadingEarlier) {
262
+ const off = store.subscribeSession(sessionId, () => {
263
+ if (store.getPageSnapshot(sessionId).loadingEarlier) return;
264
+ off();
265
+ step();
266
+ });
267
+ return;
268
+ }
269
+ const limit = Math.min(Math.max(page.firstSeq - index, 1), LOAD_THROUGH_MAX_TURNS);
270
+ if (!streams.loadEarlier(sessionId, {
271
+ limit,
272
+ onSettled: (ok) => ok ? step() : resolve(false)
273
+ })) resolve(false);
274
+ };
275
+ step();
276
+ });
277
+ },
250
278
  noteActiveSession(sessionId) {
251
279
  activeSession = sessionId;
252
280
  for (const deferred of [...deferredCompact]) {
@@ -268,4 +296,4 @@ function createSessionStreams(options = {}) {
268
296
  };
269
297
  return streams;
270
298
  }
271
- export { createSessionStreams };
299
+ export { LOAD_THROUGH_MAX_TURNS, createSessionStreams };
@@ -15,7 +15,7 @@ import { ChatAttachment, ChatEvent } from "../host.js";
15
15
  import { DrainPlan } from "./pacer.js";
16
16
  import { FrameScheduler } from "./scheduler.js";
17
17
  import { OtherStreamSignal, SessionFallbackModel, SessionPageState, SessionRetryState, SessionStreamPage, SessionStreamSignal } from "./types.js";
18
- import { HistoryChange, HistorySince, MarkdownDeltaOptions, PromptSegmentRef } from "zidane/chat/pure";
18
+ import { HistoryChange, HistorySince, MarkdownDeltaOptions, PromptSegmentRef, TranscriptEvents } from "zidane/chat/pure";
19
19
  import { SystemMdFile } from "zidane/chat";
20
20
  /** A prompt this client appended optimistically, awaiting its host echo (`SessionStreamStore.pendingEchoes`). */
21
21
  export interface PendingEcho {
@@ -39,6 +39,8 @@ export interface SessionStreamStoreOptions {
39
39
  export interface SessionStreamWrite {
40
40
  /** Replaces the events. */
41
41
  events?: readonly ChatEvent[];
42
+ /** Replaces the events with a transcript store (one a reducer made from the current one keeps its settled chunks). Wins over `events`. */
43
+ transcript?: TranscriptEvents<ChatEvent>;
42
44
  /** Sets the run flag. */
43
45
  running?: boolean;
44
46
  /** Sets the page state (and so marks the window hydrated); `null` drops it. */
@@ -59,6 +61,7 @@ export interface SessionStreamWrite {
59
61
  * @typeParam K - The session key type (the desktop app's branded `SessionKey`). Default: `string`.
60
62
  */
61
63
  export declare class SessionStreamStore<K extends string = string> {
64
+ /** Each session's events as a transcript store: a streamed delta copies only the open exchange (`TranscriptMap`). */
62
65
  private _events;
63
66
  private _running;
64
67
  private readonly _scheduler;
@@ -166,6 +169,14 @@ export declare class SessionStreamStore<K extends string = string> {
166
169
  * @param sessionId - The session, or `null` for none.
167
170
  */
168
171
  getEventsSnapshot(sessionId: K | null): readonly ChatEvent[];
172
+ /**
173
+ * A session's events as a transcript store (settled exchanges and the open
174
+ * one), for a consumer that derives per exchange. `getEventsSnapshot` is
175
+ * its array (`transcriptOfArray` maps one to the other).
176
+ *
177
+ * @param sessionId - The session.
178
+ */
179
+ getTranscriptSnapshot(sessionId: K): TranscriptEvents<ChatEvent> | undefined;
169
180
  /**
170
181
  * Whether a run is in flight for the session.
171
182
  *
@@ -231,6 +242,12 @@ export declare class SessionStreamStore<K extends string = string> {
231
242
  * @param sessionId - The session, or `null` for none.
232
243
  */
233
244
  hasEvents(sessionId: K | null): boolean;
245
+ /**
246
+ * About how many bytes the session's rows hold (`eventsBytes`): what the prewarm window budgets by.
247
+ *
248
+ * @param sessionId - The session.
249
+ */
250
+ eventBytes(sessionId: K): number;
234
251
  /**
235
252
  * Whether the session's window was hydrated from DISK (`setEventsPage`),
236
253
  * as opposed to merely having a record. `markRunning` and every live
@@ -243,6 +260,12 @@ export declare class SessionStreamStore<K extends string = string> {
243
260
  * @param sessionId - The session, or `null` for none.
244
261
  */
245
262
  isHydrated(sessionId: K | null): boolean;
263
+ /**
264
+ * The sessions whose window was hydrated from disk (see `isHydrated`). An
265
+ * app keeps their live signals coming (`sessions.subscribe`): a window
266
+ * that stops getting them goes stale. `subscribeHas` fires when this changes.
267
+ */
268
+ hydratedSessions(): K[];
246
269
  /**
247
270
  * The session's scrollback bookkeeping (a shared empty state when it was never hydrated). Stable identity until a page write.
248
271
  *