返回 DeepSeek-Reasonix
transcriptStore.ts
根目录 / desktop / frontend / src / lib / transcriptStore.ts
1 import type { HistoryPreparationWait } from "./historyPreparation";
2 // Bounded transcript records with stable ids, lazy content, generation-aware paging, and weighted LRU eviction.
3 import { asArray } from "./array";
4 import { canonicalHistoryContent, canonicalHistorySlice } from "./canonicalTranscriptBackend";
5 import { fetchPreparedHistorySlice } from "./transcriptHistoryFetch";
6 import { prepareTranscriptInstall } from "./transcriptStoreInstall";
7 import { registerTranscriptCacheDiagnostics } from "./sessionDiagnostics";
8 import { TranscriptMarkdownCache, type ParsedMarkdownValue } from "./transcriptMarkdownCache";
9 export type { ParsedMarkdownValue } from "./transcriptMarkdownCache";
10 import type { Item, State } from "./useController";
11 import { resolveTranscriptEntryAlias, TranscriptContentResolverRegistry } from "./transcriptContentResolver";
12 import { convertRecord, entryToRecord, type RecordConversion, type TranscriptRecord } from "./transcriptRecordProjection";
13 import { readTranscriptContent } from "./transcriptContentRead";
14 import { appendLivePageEntries, type TranscriptWindowPage } from "./transcriptLiveWindow";
15 import { RESOURCE_BUDGETS } from "./resourceBudgets";
16 import { bindTranscriptSession, boundSessionKey, detachTranscriptTab, type TranscriptTabBinding } from "./transcriptSessionBinding";
17 import type {
18 HistoryEntry,
19 HistorySlice,
20 HistorySliceRequest,
21 } from "./types";
22
23 import type { TranscriptBackend, TranscriptStoreOptions, TranscriptProjection, PreparedTranscriptInstall, LoadOlderResult, LoadNewerResult, AppendEntriesResult, TranscriptContentChange, SessionTranscript, HistoryReadOptions } from "./transcriptStoreTypes";
24 export type { TranscriptBackend, TranscriptStoreOptions, TranscriptProjection, PreparedTranscriptInstall, LoadOlderResult, LoadNewerResult, AppendEntriesResult, TranscriptContentChange, SessionTranscript, HistoryReadOptions } from "./transcriptStoreTypes";
25
26 const DEFAULT_MAX_RESIDENT_SESSIONS = 3;
27 const DEFAULT_HISTORY_BODY_BUDGET = RESOURCE_BUDGETS.historyBodyBytes;
28 const DEFAULT_MARKDOWN_BUDGET = 16 << 20;
29 const DEFAULT_WINDOW_MAX_PAGES = RESOURCE_BUDGETS.historyWindowPages;
30 const DEFAULT_WINDOW_PAGE_ENTRIES = RESOURCE_BUDGETS.historyPageEntries;
31
32 function sliceRevisionKnown(slice: Pick<HistorySlice, "revision" | "revisionKnown">): boolean {
33 // Compatibility with the first HistorySlice contract: positive revisions
34 // were already canonical, but revisionKnown was not exposed yet.
35 return slice.revisionKnown ?? (slice.revision ?? 0) > 0;
36 }
37
38 function compareRecords(a: Pick<TranscriptRecord, "order" | "entryId">, b: Pick<TranscriptRecord, "order" | "entryId">): number {
39 if (a.order !== b.order) return a.order - b.order;
40 return a.entryId < b.entryId ? -1 : a.entryId > b.entryId ? 1 : 0;
41 }
42
43 export class TranscriptStore {
44 readonly states = new Map<string, State>();
45 private readonly stateListeners = new Map<string, Set<() => void>>();
46
47 subscribeState(tabId: string, listener: () => void): () => void {
48 let listeners = this.stateListeners.get(tabId);
49 if (!listeners) this.stateListeners.set(tabId, listeners = new Set());
50 listeners.add(listener);
51 return () => { listeners.delete(listener); if (!listeners.size) this.stateListeners.delete(tabId); };
52 }
53
54 setState(tabId: string, state: State): void {
55 if (this.states.get(tabId) === state) return;
56 this.states.set(tabId, state);
57 for (const listener of this.stateListeners.get(tabId) ?? []) listener();
58 }
59
60 /** Install the page that belongs to a Follow cut, without another read. */
61 installSlice(tabId: string, sessionPath: string, slice: HistorySlice): TranscriptProjection {
62 const prepared = this.prepareInstallSlice(tabId, sessionPath, slice);
63 prepared.commit();
64 return prepared.projection;
65 }
66
67 /** Build a complete replacement without exposing it to readers. The caller
68 * commits only after the reducer has accepted the matching snapshot. */
69 prepareInstallSlice(tabId: string, sessionPath: string, slice: HistorySlice): PreparedTranscriptInstall {
70 const key = this.sessionKeyFor(tabId, sessionPath);
71 const previous = this.sessions.get(key);
72 const session = this.newSession(key, tabId, sessionPath);
73 return prepareTranscriptInstall(previous, session, slice, this.windowPageEntries,
74 (candidate, entries) => this.replaceRecords(candidate, entries), candidate => this.projectionOf(candidate), installed => {
75 this.sessions.set(key, installed);
76 this.touch(installed);
77 this.enforceBudgets();
78 });
79 }
80 private readonly contentResolvers = new TranscriptContentResolverRegistry();
81 registerContentResolver(tabId: string, resolve: (entryId: string, field: string) => Promise<string | undefined>, enabled: () => boolean = () => true): () => void {
82 return this.contentResolvers.register(tabId, resolve, enabled);
83 }
84 private readonly backend: TranscriptBackend;
85 private readonly preparationWait?: HistoryPreparationWait;
86 private readonly maxResidentSessions: number;
87 private readonly historyBodyBudgetBytes: number;
88 private readonly windowMaxPages: number;
89 private readonly windowPageEntries: number;
90 /** Insertion-ordered (oldest first); touch re-inserts at the end. */
91 private readonly sessions = new Map<string, SessionTranscript>();
92 /** Ephemeral UI tab bindings; canonical resident ownership is session-based. */
93 private readonly tabBindings = new Map<string, TranscriptTabBinding>();
94 private readonly tabPins = new Map<string, { live: boolean; active: boolean }>();
95 private readonly listeners = new Map<string, Set<(change: TranscriptContentChange) => void>>();
96 private readonly markdown: TranscriptMarkdownCache;
97 private historyEvictions = 0;
98
99 constructor(backend: TranscriptBackend, options: TranscriptStoreOptions = {}) {
100 this.backend = backend;
101 this.preparationWait = options.preparationWait;
102 this.maxResidentSessions = Math.max(1, options.maxResidentSessions ?? DEFAULT_MAX_RESIDENT_SESSIONS);
103 this.historyBodyBudgetBytes = Math.max(0, options.historyBodyBudgetBytes ?? DEFAULT_HISTORY_BODY_BUDGET);
104 this.windowMaxPages = Math.max(1, options.windowMaxPages ?? DEFAULT_WINDOW_MAX_PAGES);
105 this.windowPageEntries = Math.max(1, options.windowPageEntries ?? DEFAULT_WINDOW_PAGE_ENTRIES);
106 this.markdown = new TranscriptMarkdownCache(Math.max(0, options.markdownBudgetBytes ?? DEFAULT_MARKDOWN_BUDGET));
107 }
108
109 // ── session identity / LRU ────────────────────────────────────────────────
110
111 private sessionKeyFor(tabId: string, sessionPath: string): string {
112 return boundSessionKey(this.tabBindings, tabId, sessionPath);
113 }
114
115 /** Atomically bind an ephemeral tab to a stable canonical session owner. */
116 noteSessionBinding(tabId: string, sessionPath: string, bindingKey: string): boolean {
117 return bindTranscriptSession(
118 this.tabBindings, this.sessions, tabId, sessionPath, bindingKey,
119 key => this.newSession(key, tabId, sessionPath),
120 session => this.evictSession(session),
121 session => this.touch(session),
122 );
123 }
124
125 private newSession(key: string, tabId: string, sessionPath: string): SessionTranscript {
126 return {
127 key,
128 tabId,
129 sessionPath,
130 records: [],
131 byId: new Map(),
132 toolResultOwners: new Map(),
133 contributions: new Map(),
134 consumed: new Set(),
135 consumedBy: new Map(),
136 unresolvedCalls: new Map(),
137 pendingPositional: new Map(),
138 matchTables: new Map(),
139 itemsCache: null,
140 nextCursor: "",
141 hasOlder: false,
142 pages: [],
143 newerCursor: "",
144 hasNewer: false,
145 reclaimedOlder: 0,
146 reclaimedNewer: 0,
147 totalTurns: 0,
148 startTurn: 0,
149 endTurn: 0,
150 revision: 0,
151 revisionKnown: false,
152 digest: "",
153 generation: 0,
154 bodyBytes: 0,
155 olderInFlight: false,
156 newerInFlight: false,
157 pendingContent: new Map(),
158 };
159 }
160
161 private touch(session: SessionTranscript): void {
162 this.sessions.delete(session.key);
163 this.sessions.set(session.key, session);
164 }
165
166 private isPinned(session: SessionTranscript): boolean {
167 return this.tabIsPinned(session.tabId);
168 }
169
170 tabIsPinned(tabId: string): boolean {
171 const pins = this.tabPins.get(tabId);
172 return Boolean(pins?.live || pins?.active);
173 }
174
175 /** Pin/unpin a tab with live or in-flight turn state out of the LRU. */
176 setPinned(tabId: string, pinned: boolean): void {
177 const pins = this.tabPins.get(tabId) ?? { live: false, active: false };
178 if (pins.live === pinned) return;
179 this.tabPins.set(tabId, { ...pins, live: pinned });
180 }
181
182 /**
183 * The visible tab changed: pin the new active tab out of eviction and drop
184 * the previous tab's active pin. Generations are NOT bumped here — a
185 * background tab's in-flight load still completes into its own state (and
186 * the store); generations move on session switch (fresh loadLatest), evict,
187 * and unload only.
188 */
189 noteActiveTab(tabId: string | undefined, previousTabId?: string): void {
190 if (previousTabId && previousTabId !== tabId) {
191 const pins = this.tabPins.get(previousTabId) ?? { live: false, active: false };
192 if (pins.active) this.tabPins.set(previousTabId, { ...pins, active: false });
193 }
194 if (tabId) {
195 const pins = this.tabPins.get(tabId) ?? { live: false, active: false };
196 if (!pins.active) this.tabPins.set(tabId, { ...pins, active: true });
197 }
198 }
199
200 /** Detach a tab. Canonical sessions remain LRU-resident across tab IDs. */
201 evictTab(tabId: string): void {
202 detachTranscriptTab(this.tabBindings, this.sessions, tabId, session => this.evictSession(session));
203 this.tabPins.delete(tabId);
204 }
205
206 private evictSession(session: SessionTranscript): void {
207 session.generation += 1; // in-flight responses discard against a missing/stale session
208 this.sessions.delete(session.key);
209 this.historyEvictions += 1;
210 }
211
212 private enforceBudgets(): void {
213 // The page budget applies to every session, pinned ones included: a live
214 // session keeps its tail streaming but no longer holds its whole history.
215 for (const session of this.sessions.values()) {
216 if (session.pages.length > this.windowMaxPages) this.trimWindow(session, "newer");
217 }
218 const evictable = (): SessionTranscript[] =>
219 Array.from(this.sessions.values()).filter((s) => s.records.length > 0 && !this.isPinned(s));
220 let candidates = evictable();
221 let resident = candidates.length;
222 while (resident > this.maxResidentSessions && candidates.length > 0) {
223 const victim = candidates.shift();
224 if (!victim) break;
225 this.evictSession(victim);
226 resident -= 1;
227 }
228 let total = 0;
229 for (const session of this.sessions.values()) total += session.bodyBytes;
230 candidates = evictable();
231 while (total > this.historyBodyBudgetBytes && candidates.length > 0) {
232 const victim = candidates.shift();
233 if (!victim) break;
234 total -= victim.bodyBytes;
235 this.evictSession(victim);
236 }
237 }
238
239 // ── projection ────────────────────────────────────────────────────────────
240
241 private rebuildProjection(session: SessionTranscript): Item[] {
242 const items: Item[] = [];
243 for (const rec of session.records) {
244 const contribution = session.contributions.get(rec.entryId);
245 if (contribution) items.push(...contribution);
246 }
247 session.itemsCache = items;
248 return items;
249 }
250
251 exportObservation(tabId: string, sessionPath: string) {
252 const session = this.sessions.get(this.sessionKeyFor(tabId, sessionPath));
253 return session ? { capturedAt: new Date().toISOString(), tabId, sessionPath, generation: session.generation, appliedSequence: session.revision, hasOlder: session.hasOlder, hasNewer: session.hasNewer, residentRecords: session.records.length } : { capturedAt: new Date().toISOString(), tabId, sessionPath, unavailable: "No resident transcript binding" };
254 }
255
256 private projectionOf(session: SessionTranscript): TranscriptProjection {
257 return {
258 items: session.itemsCache ?? this.rebuildProjection(session),
259 startTurn: session.startTurn,
260 endTurn: session.endTurn,
261 totalTurns: session.totalTurns,
262 hasOlder: session.hasOlder,
263 hasNewer: session.hasNewer,
264 revision: session.revision,
265 revisionKnown: session.revisionKnown,
266 digest: session.digest,
267 };
268 }
269
270 /** Synchronous projection for an LRU-resident session; undefined on a miss
271 * or when the caller's authoritative fingerprint cannot prove the resident
272 * cut belongs to the selected session generation. */
273 peek(
274 tabId: string,
275 sessionPath: string,
276 expected?: { revision?: number; digest?: string },
277 ): TranscriptProjection | undefined {
278 const session = this.sessions.get(this.sessionKeyFor(tabId, sessionPath));
279 if (!session || session.records.length === 0
280 || (expected !== undefined && !this.matchesExpectedFingerprint(session, expected.revision, expected.digest))) return undefined;
281 this.touch(session);
282 return this.projectionOf(session);
283 }
284
285 /** Test/diagnostic introspection. */
286 isResident(tabId: string, sessionPath: string): boolean {
287 const session = this.sessions.get(this.sessionKeyFor(tabId, sessionPath));
288 return Boolean(session && session.records.length > 0);
289 }
290
291 residentSessionCount(): number {
292 let count = 0;
293 for (const session of this.sessions.values()) if (session.records.length > 0) count += 1;
294 return count;
295 }
296
297 totalBodyBytes(): number {
298 let total = 0;
299 for (const session of this.sessions.values()) total += session.bodyBytes;
300 return total;
301 }
302
303 private reclaimedPages(): number {
304 let total = 0;
305 for (const session of this.sessions.values()) total += session.reclaimedOlder + session.reclaimedNewer;
306 return total;
307 }
308
309 /** Messages held across every resident window; the bounded reading cost. */
310 residentWindowEntries(): number {
311 let total = 0;
312 for (const session of this.sessions.values()) total += session.records.length;
313 return total;
314 }
315
316 /** Cache-weight snapshot for diagnostics (sessionDiagnostics/crash context). */
317 stats() {
318 return {
319 residentSessions: this.residentSessionCount(),
320 maxResidentSessions: this.maxResidentSessions,
321 bodyBytes: this.totalBodyBytes(),
322 bodyBudgetBytes: this.historyBodyBudgetBytes,
323 markdownBytes: this.markdown.bytes,
324 markdownBudgetBytes: this.markdown.budgetBytes,
325 historyEvictions: this.historyEvictions,
326 markdownEvictions: this.markdown.evictions,
327 windowMaxPages: this.windowMaxPages,
328 reclaimedPages: this.reclaimedPages(),
329 residentWindowEntries: this.residentWindowEntries(),
330 };
331 }
332
333 // fetchSlice times one backend page request and records the content-free
334 // page stats (entries, inline bytes, duration, stale, read-path source).
335 private async fetchSlice(tabId: string, req: HistorySliceRequest, current: () => boolean): Promise<HistorySlice | undefined> {
336 return fetchPreparedHistorySlice(() => this.backend.HistorySliceForTab(tabId, req), current, this.preparationWait);
337 }
338
339 generationOf(tabId: string, sessionPath: string): number | undefined {
340 return this.sessions.get(this.sessionKeyFor(tabId, sessionPath))?.generation;
341 }
342
343 // ── record merge ops ──────────────────────────────────────────────────────
344
345 private viewOf(records: TranscriptRecord[]): {
346 records: TranscriptRecord[];
347 indexOf: Map<string, number>;
348 toolResultOwners: Map<string, string>;
349 } {
350 const indexOf = new Map<string, number>();
351 const toolResultOwners = new Map<string, string>();
352 records.forEach((rec, index) => {
353 indexOf.set(rec.entryId, index);
354 const toolCallId = rec.message.role === "tool" ? rec.message.toolCallId : undefined;
355 if (toolCallId && !toolResultOwners.has(toolCallId)) toolResultOwners.set(toolCallId, rec.entryId);
356 });
357 return { records, indexOf, toolResultOwners };
358 }
359
360 private trackConversion(session: SessionTranscript, rec: TranscriptRecord, conversion: RecordConversion): void {
361 session.contributions.set(rec.entryId, conversion.items);
362 session.matchTables.set(rec.entryId, conversion.matches);
363 for (const claimed of conversion.claims) session.consumedBy.set(claimed, rec.entryId);
364 for (const toolCallId of conversion.unresolvedIds) session.unresolvedCalls.set(toolCallId, rec.entryId);
365 if (conversion.pendingPositional.length > 0) session.pendingPositional.set(rec.entryId, conversion.pendingPositional);
366 else session.pendingPositional.delete(rec.entryId);
367 }
368
369 private replaceRecords(session: SessionTranscript, entries: HistoryEntry[]): void {
370 const records = entries.map(entryToRecord);
371 const view = this.viewOf(records);
372 const consumed = new Set<string>();
373 session.records = records;
374 session.byId = new Map(records.map((rec) => [rec.entryId, rec]));
375 session.toolResultOwners = view.toolResultOwners;
376 session.contributions = new Map();
377 session.consumed = consumed;
378 session.consumedBy = new Map();
379 session.unresolvedCalls = new Map();
380 session.pendingPositional = new Map();
381 session.matchTables = new Map();
382 session.bodyBytes = 0;
383 for (const rec of records) {
384 session.bodyBytes += rec.bytes;
385 const conversion = convertRecord(rec, view, consumed);
386 this.trackConversion(session, rec, conversion);
387 }
388 session.itemsCache = null;
389 this.rebuildProjection(session);
390 }
391
392 /**
393 * Prepend an older page. Returns the page's contributed items plus the ids
394 * of existing standalone tool items now folded into a call from this page.
395 */
396 private prependRecords(session: SessionTranscript, entries: HistoryEntry[]): { items: Item[]; removeIds: string[] } {
397 const fresh: TranscriptRecord[] = [];
398 for (const entry of entries) {
399 if (session.byId.has(entry.entryId)) continue; // contract guard: never duplicate
400 fresh.push(entryToRecord(entry));
401 }
402 if (fresh.length === 0) return { items: [], removeIds: [] };
403 const combined = [...fresh, ...session.records];
404 if (session.records.length > 0 && compareRecords(fresh[fresh.length - 1], session.records[0]) > 0) {
405 // Backend contract violation (pages must be contiguous prefixes): fall
406 // back to one full sort rather than corrupting the order.
407 combined.sort(compareRecords);
408 }
409 const view = this.viewOf(combined);
410 const consumed = new Set(session.consumed);
411 const removeIds: string[] = [];
412 const prependItems: Item[] = [];
413 for (const rec of fresh) {
414 const before = new Set(consumed);
415 const conversion = convertRecord(rec, view, consumed);
416 for (const claimed of conversion.claims) {
417 if (before.has(claimed)) continue;
418 const existing = session.contributions.get(claimed);
419 if (existing && existing.length > 0) {
420 // An existing standalone tool row is now folded into this call.
421 for (const item of existing) removeIds.push(item.id);
422 session.contributions.set(claimed, []);
423 }
424 }
425 this.trackConversion(session, rec, conversion);
426 prependItems.push(...conversion.items);
427 session.bodyBytes += rec.bytes;
428 }
429 session.records = combined;
430 session.byId = new Map(combined.map((rec) => [rec.entryId, rec]));
431 session.toolResultOwners = view.toolResultOwners;
432 session.consumed = consumed;
433 const removeSet = new Set(removeIds);
434 const base = session.itemsCache ?? this.rebuildProjection(session);
435 session.itemsCache = removeSet.size > 0 ? [...prependItems, ...base.filter((item) => !removeSet.has(item.id))] : [...prependItems, ...base];
436 return { items: prependItems, removeIds };
437 }
438
439 /**
440 * Append a live suffix into entry-bounded pages. Once the page window fills,
441 * old records are reclaimed and their mounted item ids are returned.
442 */
443 appendEntries(tabId: string, sessionPath: string, entries: HistoryEntry[]): AppendEntriesResult | undefined {
444 const session = this.sessions.get(this.sessionKeyFor(tabId, sessionPath));
445 if (!session || session.records.length === 0) return undefined;
446 const fresh = entries.filter((entry) => !session.byId.has(entry.entryId));
447 this.appendRecords(session, fresh);
448 appendLivePageEntries(session.pages, fresh.map((entry) => entry.entryId), this.windowPageEntries);
449 if (fresh.length > 0) {
450 session.hasNewer = false;
451 session.newerCursor = "";
452 session.totalTurns = Math.max(session.totalTurns, ...fresh.map((entry) => entry.turn));
453 session.endTurn = Math.max(session.endTurn, ...fresh.map((entry) => entry.turn));
454 }
455 const removeIds = this.trimWindow(session, "newer");
456 this.enforceBudgets();
457 return this.sessions.get(session.key) === session ? { ...this.projectionOf(session), removeIds } : undefined;
458 }
459
460 upsertEntries(tabId: string, sessionPath: string, entries: HistoryEntry[], commitSeq?: number): AppendEntriesResult | undefined {
461 const session = this.sessions.get(this.sessionKeyFor(tabId, sessionPath));
462 if (!session) return undefined;
463 session.latestSequence = Math.max(session.latestSequence ?? session.revision, commitSeq ?? 0);
464 // The reader owns a contiguous window. A remote tail must not evict it or
465 // create a false adjacency across an unloaded range. Accepted records stay
466 // reachable through canonical pagination; active prefixes live in State.
467 if (session.hasNewer) entries = entries.filter(entry => session.byId.has(entry.entryId));
468 const fresh = entries.filter(entry => !session.byId.has(entry.entryId));
469 const replacements = new Map(entries.map(entry => [entry.entryId, entry]));
470 const combined = session.records.map(record => replacements.get(record.entryId) ?? {
471 entryId: record.entryId, turn: record.turn, order: record.order, message: record.message, refs: record.refs,
472 });
473 combined.push(...fresh);
474 this.replaceRecords(session, combined);
475 appendLivePageEntries(session.pages, fresh.map(entry => entry.entryId), this.windowPageEntries);
476 const removeIds = this.trimWindow(session, "newer");
477 this.enforceBudgets();
478 return { ...this.projectionOf(session), removeIds };
479 }
480
481 isReadingHistory(tabId: string, sessionPath: string): boolean {
482 return Boolean(this.sessions.get(this.sessionKeyFor(tabId, sessionPath))?.hasNewer);
483 }
484
485 /** Append newer entries (live tail / fresh suffix). */
486 private appendRecords(session: SessionTranscript, entries: HistoryEntry[]): Item[] {
487 const fresh: TranscriptRecord[] = [];
488 for (const entry of entries) {
489 if (session.byId.has(entry.entryId)) continue;
490 fresh.push(entryToRecord(entry));
491 }
492 if (fresh.length === 0) return [];
493 const combined = [...session.records, ...fresh];
494 if (session.records.length > 0 && compareRecords(session.records[session.records.length - 1], fresh[0]) > 0) {
495 combined.sort(compareRecords);
496 }
497 const view = this.viewOf(combined);
498 const consumed = new Set(session.consumed);
499 const appendedItems: Item[] = [];
500 let dirty = false;
501
502 session.records = combined;
503 session.byId = new Map(combined.map((rec) => [rec.entryId, rec]));
504 session.toolResultOwners = view.toolResultOwners;
505
506 // Resolve existing calls whose results only arrive now (a page cut between
507 // a call and its result, or a live tail landing after the call).
508 for (const rec of fresh) {
509 const toolCallId = rec.message.role === "tool" ? rec.message.toolCallId : undefined;
510 if (!toolCallId) continue;
511 const owner = session.unresolvedCalls.get(toolCallId);
512 if (!owner) continue;
513 const ownerRec = session.byId.get(owner);
514 if (!ownerRec) continue;
515 session.unresolvedCalls.delete(toolCallId);
516 const reconverted = convertRecord(ownerRec, view, consumed, session.matchTables.get(owner));
517 this.trackConversion(session, ownerRec, reconverted);
518 dirty = true;
519 }
520 for (const rec of fresh) {
521 const conversion = convertRecord(rec, view, consumed);
522 this.trackConversion(session, rec, conversion);
523 appendedItems.push(...conversion.items);
524 session.bodyBytes += rec.bytes;
525 }
526 session.consumed = consumed;
527 if (dirty || session.itemsCache === null) {
528 this.rebuildProjection(session);
529 } else {
530 session.itemsCache = [...session.itemsCache, ...appendedItems];
531 }
532 return appendedItems;
533 }
534
535 // ── bounded window ────────────────────────────────────────────────────────
536
537 /** Replay every identity-keyed map over exactly the surviving records.
538 * Reclaiming changes tool-call ownership, so the maps cannot be spliced.
539 */
540 private rebuildFromRecords(session: SessionTranscript, records: TranscriptRecord[]): void {
541 const view = this.viewOf(records);
542 session.records = records;
543 session.byId = new Map(records.map((rec) => [rec.entryId, rec]));
544 session.toolResultOwners = view.toolResultOwners;
545 session.contributions = new Map();
546 session.consumed = new Set();
547 session.consumedBy = new Map();
548 session.unresolvedCalls = new Map();
549 session.pendingPositional = new Map();
550 session.matchTables = new Map();
551 session.bodyBytes = 0;
552 for (const rec of records) {
553 session.bodyBytes += rec.bytes;
554 this.trackConversion(session, rec, convertRecord(rec, view, session.consumed));
555 }
556 session.itemsCache = null;
557 this.rebuildProjection(session);
558 }
559
560 /** The page a freshly loaded batch of entries belongs to. */
561 private pageFor(entries: HistoryEntry[], olderCursor: string, newerCursor: string): TranscriptWindowPage {
562 return { entryIds: entries.map((entry) => entry.entryId), olderCursor, newerCursor };
563 }
564
565 private updateWindowTurnBounds(session: SessionTranscript): void {
566 const turns = session.records.map((record) => record.turn).filter((turn) => turn > 0);
567 session.startTurn = turns.length > 0 ? Math.min(...turns) : 0;
568 session.endTurn = turns.length > 0 ? Math.max(...turns) : 0;
569 }
570
571 /** Reclaim one page from the given end; undefined when only one page is
572 * left. Widens the page so a result is never stranded from its call.
573 */
574 private reclaimPage(session: SessionTranscript, end: "oldest" | "newest"): string[] | undefined {
575 if (session.pages.length <= 1) return undefined;
576 const page = end === "oldest" ? session.pages[0] : session.pages[session.pages.length - 1];
577 const dropped = new Set(page.entryIds);
578 if (end === "oldest") {
579 // A result whose call is being reclaimed has to go with it, or the
580 // reader is left with an output row that names a call they can no
581 // longer see. Which calls survive is decided by the retained records
582 // alone: collecting it from the reclaimed page would keep the calls
583 // that are leaving and strand exactly the rows this guards.
584 const survivingCalls = new Set<string>();
585 for (const record of session.records) {
586 if (dropped.has(record.entryId) || record.message.role !== "assistant") continue;
587 for (const call of record.message.toolCalls ?? []) survivingCalls.add(call.id);
588 }
589 for (const record of session.records) {
590 if (dropped.has(record.entryId)) continue;
591 const callId = record.message.role === "tool" ? record.message.toolCallId : undefined;
592 if (!callId || survivingCalls.has(callId)) break;
593 dropped.add(record.entryId);
594 }
595 }
596 const retained = session.records.filter((record) => !dropped.has(record.entryId));
597 if (end === "oldest") {
598 session.pages.shift();
599 // The reclaimed page's own older cursor is now the window's head, so the
600 // reader can page straight back into the range that was just dropped.
601 const anchor = [...session.records].reverse().find(record => dropped.has(record.entryId) && record.message.messageId);
602 session.nextCursor = session.pages[0]?.olderCursor || (anchor ? `reasonix:message:${encodeURIComponent(anchor.message.messageId!)}:${session.latestSequence ?? session.revision}:${encodeURIComponent(session.digest)}:older` : page.olderCursor);
603 session.hasOlder = true;
604 session.reclaimedOlder += 1;
605 } else {
606 session.pages.pop();
607 const anchor = session.records.find(record => dropped.has(record.entryId) && record.message.messageId);
608 session.newerCursor = session.pages[session.pages.length - 1]?.newerCursor || (anchor ? `reasonix:message:${encodeURIComponent(anchor.message.messageId!)}:${session.latestSequence ?? session.revision}:${encodeURIComponent(session.digest)}:newer` : page.newerCursor);
609 session.hasNewer = true;
610 session.reclaimedNewer += 1;
611 }
612 const before = new Set((session.itemsCache ?? []).map((item) => item.id));
613 this.rebuildFromRecords(session, retained);
614 this.updateWindowTurnBounds(session);
615 // Reclaiming can also fold a retained result into a call that survived, so
616 // the caller is told which ids it must drop rather than assuming the
617 // difference is exactly the reclaimed page.
618 const after = new Set((session.itemsCache ?? []).map((item) => item.id));
619 return [...before].filter((id) => !after.has(id));
620 }
621
622 /** Reclaim from the end opposite the one being paged, returning the item
623 * ids the caller must drop from its own list.
624 */
625 private trimWindow(session: SessionTranscript, growing: "older" | "newer"): string[] {
626 if (session.pages.length === 0) return [];
627 const give = growing === "older" ? "newest" : "oldest";
628 const removed: string[] = [];
629 while (session.pages.length > this.windowMaxPages) {
630 const dropped = this.reclaimPage(session, give);
631 if (dropped === undefined) break;
632 removed.push(...dropped);
633 }
634 return removed;
635 }
636
637 // ── paging API ────────────────────────────────────────────────────────────
638
639 /**
640 * Load the newest page. preferResident serves an LRU-resident session
641 * synchronously-equivalent projection without a backend round trip.
642 * Returns undefined when the load was superseded/evicted mid-flight.
643 */
644 async loadLatest(
645 tabId: string,
646 sessionPath: string,
647 options: HistoryReadOptions & { preferResident?: boolean; expectedRevision?: number; expectedDigest?: string } = {},
648 ): Promise<TranscriptProjection | undefined> {
649 const key = this.sessionKeyFor(tabId, sessionPath);
650 const existing = this.sessions.get(key);
651 if (options.preferResident && existing && existing.records.length > 0 &&
652 this.matchesExpectedFingerprint(existing, options.expectedRevision, options.expectedDigest)) {
653 this.touch(existing);
654 return this.projectionOf(existing);
655 }
656 const session = existing ?? this.newSession(key, tabId, sessionPath);
657 session.tabId = tabId;
658 session.sessionPath = sessionPath;
659 // A fresh load supersedes every in-flight request of the previous load.
660 session.generation += 1;
661 const generation = session.generation;
662 let settleGeneration!: () => void;
663 const generationSettled = new Promise<void>((resolve) => { settleGeneration = resolve; });
664 session.generationSettlement = { generation, promise: generationSettled };
665 this.sessions.set(key, session);
666 this.touch(session);
667
668 try {
669 const { turns, entries, bytes } = options;
670 const current = () => this.sessions.get(key) === session && session.generation === generation && (options.current?.() ?? true);
671 let slice = await this.fetchSlice(tabId, { cursor: "", turns, entries, bytes }, current);
672 if (!slice || !current()) return undefined;
673 if (slice.stale) {
674 // cursor "" cannot bind a stale identity, but a concurrent rewrite may
675 // still report one — retry once against the settled revision.
676 slice = await this.fetchSlice(tabId, { cursor: "", turns, entries, bytes }, current);
677 if (!slice || !current()) return undefined;
678 }
679 const newestEntries = asArray<HistoryEntry>(slice.entries);
680 this.replaceRecords(session, newestEntries);
681 session.pages = [this.pageFor(newestEntries, slice.nextCursor ?? "", slice.newerCursor ?? "")];
682 session.reclaimedOlder = 0;
683 session.reclaimedNewer = 0;
684 session.nextCursor = slice.nextCursor ?? "";
685 session.hasOlder = Boolean(slice.hasOlder);
686 session.newerCursor = slice.newerCursor ?? "";
687 session.hasNewer = Boolean(slice.hasNewer);
688 session.totalTurns = slice.totalTurns ?? 0;
689 session.startTurn = slice.startTurn ?? 0;
690 session.endTurn = slice.endTurn ?? 0;
691 session.revision = slice.revision ?? 0;
692 session.revisionKnown = sliceRevisionKnown(slice);
693 session.digest = slice.digest ?? "";
694 this.enforceBudgets();
695 if (this.sessions.get(key) !== session) return undefined; // evicted by the budget
696 return this.projectionOf(session);
697 } finally {
698 settleGeneration();
699 if (session.generationSettlement?.generation === generation) {
700 session.generationSettlement = undefined;
701 }
702 }
703 }
704
705 /**
706 * Page toward older history. On a stale cursor the records are dropped and
707 * the latest page is reloaded (kind "reload": callers replace, not prepend).
708 */
709 async loadOlder(
710 tabId: string,
711 sessionPath: string,
712 options: HistoryReadOptions = {},
713 ): Promise<LoadOlderResult | undefined> {
714 const key = this.sessionKeyFor(tabId, sessionPath);
715 const session = this.sessions.get(key);
716 if (!session || session.records.length === 0) {
717 // Evicted or never loaded: re-prime from the newest page; callers must
718 // replace rather than prepend.
719 const projection = await this.loadLatest(tabId, sessionPath, options);
720 return projection ? { ...projection, kind: "reload", prependItems: [], removeIds: [] } : undefined;
721 }
722 if (!session.hasOlder || !session.nextCursor || session.olderInFlight) return undefined;
723 session.olderInFlight = true;
724 const generation = session.generation;
725 const { current: _current, ...budget } = options;
726 try {
727 const slice = await this.fetchSlice(tabId, { cursor: session.nextCursor, ...budget }, () => this.sessions.get(key) === session && session.generation === generation && (options.current?.() ?? true));
728 if (!slice || this.sessions.get(key) !== session || session.generation !== generation) return undefined;
729 if (slice.stale) {
730 if (session.canonicalV2) throw new Error("history snapshot expired");
731 const projection = await this.loadLatest(tabId, sessionPath, options);
732 return projection ? { ...projection, kind: "reload", prependItems: [], removeIds: [] } : undefined;
733 }
734 if (slice.source === "locator-reset") {
735 this.replaceRecords(session, asArray<HistoryEntry>(slice.entries));
736 session.nextCursor = slice.nextCursor ?? "";
737 session.hasOlder = Boolean(slice.hasOlder);
738 session.totalTurns = slice.totalTurns ?? 0;
739 session.startTurn = slice.startTurn ?? 0;
740 session.endTurn = slice.endTurn ?? 0;
741 session.revision = slice.revision ?? 0;
742 session.revisionKnown = sliceRevisionKnown(slice);
743 session.digest = slice.digest ?? "";
744 this.enforceBudgets();
745 if (this.sessions.get(key) !== session) return undefined;
746 return { ...this.projectionOf(session), kind: "reload", prependItems: [], removeIds: [] };
747 }
748 if (!this.sameFingerprint(session, slice)) {
749 if (session.canonicalV2) throw new Error("history identity changed");
750 // A backend that raced a rewrite may return a fresh page instead of a
751 // stale marker. Never prepend rows from a different canonical state.
752 const projection = await this.loadLatest(tabId, sessionPath, options);
753 return projection ? { ...projection, kind: "reload", prependItems: [], removeIds: [] } : undefined;
754 }
755 const pageEntries = asArray<HistoryEntry>(slice.entries);
756 const { items, removeIds } = this.prependRecords(session, pageEntries);
757 session.pages.unshift(this.pageFor(pageEntries, slice.nextCursor ?? "", slice.newerCursor ?? ""));
758 session.nextCursor = slice.nextCursor ?? "";
759 session.hasOlder = Boolean(slice.hasOlder);
760 session.totalTurns = slice.totalTurns ?? session.totalTurns;
761 session.startTurn = slice.startTurn ?? session.startTurn;
762 session.revision = slice.revision ?? session.revision;
763 session.revisionKnown = sliceRevisionKnown(slice);
764 session.digest = slice.digest ?? session.digest;
765 // Reclaiming the far end yields ids the caller must drop alongside the
766 // cross-page merge ids it already handles.
767 const reclaimed = this.trimWindow(session, "older");
768 // Settle the budget before reading the projection: a later trim would
769 // leave the caller holding an item list the store has already released.
770 this.enforceBudgets();
771 const projection = this.projectionOf(session);
772 if (this.sessions.get(key) !== session) return undefined;
773 return { ...projection, kind: "prepend", prependItems: items, removeIds: reclaimed.length > 0 ? [...removeIds, ...reclaimed] : removeIds };
774 } finally {
775 session.olderInFlight = false;
776 }
777 }
778
779 /** Page toward newer history. Needs a binding that reports a newer cursor;
780 * a legacy one leaves the window on its newest page rather than faking it.
781 */
782 async loadNewer(
783 tabId: string,
784 sessionPath: string,
785 options: HistoryReadOptions = {},
786 ): Promise<LoadNewerResult | undefined> {
787 const key = this.sessionKeyFor(tabId, sessionPath);
788 const session = this.sessions.get(key);
789 if (!session || session.records.length === 0) return undefined;
790 if (!session.hasNewer || !session.newerCursor || session.newerInFlight) return undefined;
791 session.newerInFlight = true;
792 const generation = session.generation;
793 const { current: _current, ...budget } = options;
794 try {
795 const slice = await this.fetchSlice(tabId, { cursor: session.newerCursor, newer: true, ...budget }, () => this.sessions.get(key) === session && session.generation === generation && (options.current?.() ?? true));
796 if (!slice || this.sessions.get(key) !== session || session.generation !== generation) return undefined;
797 if (slice.stale || !this.sameFingerprint(session, slice)) {
798 // A newer page from a rebuilt projection cannot be appended to the
799 // window the reader is holding; the window keeps its position and the
800 // caller reports the reload instead of mixing two canonical states.
801 return { ...this.projectionOf(session), kind: "stale", appendItems: [], removeIds: [] };
802 }
803 const pageEntries = asArray<HistoryEntry>(slice.entries);
804 const appendItems = this.appendRecords(session, pageEntries);
805 session.pages.push(this.pageFor(pageEntries, slice.nextCursor ?? "", slice.newerCursor ?? ""));
806 session.newerCursor = slice.newerCursor ?? "";
807 session.hasNewer = Boolean(slice.hasNewer) || session.newerCursor !== "";
808 if (!session.hasNewer && (session.latestSequence ?? 0) > slice.revision && pageEntries.length) {
809 const last = pageEntries[pageEntries.length - 1];
810 if (last.message.messageId) {
811 session.newerCursor = `reasonix:message:${encodeURIComponent(last.message.messageId)}:${session.latestSequence}:${encodeURIComponent(session.digest)}:newer`;
812 session.hasNewer = true;
813 }
814 }
815 session.endTurn = slice.endTurn ?? session.endTurn;
816 session.totalTurns = slice.totalTurns ?? session.totalTurns;
817 const reclaimed = this.trimWindow(session, "newer");
818 this.enforceBudgets();
819 const projection = this.projectionOf(session);
820 if (this.sessions.get(key) !== session) return undefined;
821 return { ...projection, kind: "append", appendItems, removeIds: reclaimed };
822 } finally {
823 session.newerInFlight = false;
824 }
825 }
826
827 private matchesExpectedFingerprint(session: SessionTranscript, expectedRevision?: number, expectedDigest?: string): boolean {
828 const digest = (expectedDigest ?? "").trim();
829 const revisionKnown = typeof expectedRevision === "number" && expectedRevision > 0;
830 if (digest !== "" && session.digest !== digest) return false;
831 if (revisionKnown && (!session.revisionKnown || session.revision !== expectedRevision)) return false;
832 if (!revisionKnown && digest === "") {
833 // Metadata identity temporarily missing cannot prove a known resident
834 // projection is current. A backend round trip is the safe fallback.
835 return !session.revisionKnown && session.digest === "";
836 }
837 return true;
838 }
839
840 private sameFingerprint(session: SessionTranscript, slice: HistorySlice): boolean {
841 if (session.canonicalV2 && session.digest !== "") return session.digest === (slice.digest ?? "");
842 return session.revision === (slice.revision ?? 0) &&
843 session.revisionKnown === sliceRevisionKnown(slice) &&
844 session.digest === (slice.digest ?? "");
845 }
846
847 // ── lazy content ──────────────────────────────────────────────────────────
848
849 private sessionForEntry(tabId: string, entryId: string): SessionTranscript | undefined {
850 for (const session of this.sessions.values()) {
851 if (session.tabId === tabId && session.byId.has(entryId)) return session;
852 }
853 return undefined;
854 }
855
856 /**
857 * Fetch the full value of a ref-replaced field, chunk by chunk, and fold it
858 * into the record. Late (generation-stale) responses are discarded; a stale
859 * chunk marks the ref stale and keeps the inline preview.
860 */
861 hasContentResolver(tabId: string): boolean { return Boolean(this.contentResolvers.active(tabId)); }
862
863 publishToolDetails(tabId: string, item: Extract<Item, { kind: "tool" }>, text: string): void {
864 let value: Record<string, unknown>;
865 try { value = JSON.parse(text); } catch { return; }
866 if (!value || typeof value !== "object" || Array.isArray(value)) return;
867 if (value.execution == null || typeof value.execution !== "object" || Array.isArray(value.execution)) return;
868 const execution = value.execution as NonNullable<typeof item.execution>;
869 if (typeof execution.state !== "string" || (execution.exitCode != null && typeof execution.exitCode !== "number")) return;
870 // The reducer compares the exact requested item version. A newer event,
871 // snapshot or session replacement always wins over this detached read.
872 const patch = { ...item, execution };
873 for (const listener of this.listeners.get(tabId) ?? []) {
874 listener({ tabId, patches: { [item.id]: patch }, expected: { [item.id]: item } });
875 }
876 }
877
878 hasContentReference(tabId: string, entryId: string, field: string): boolean {
879 entryId = resolveTranscriptEntryAlias(this.sessions.values(), tabId, entryId);
880 return Boolean(this.sessionForEntry(tabId, entryId)?.byId.get(entryId)?.refs.some(ref => ref.field === field || ref.field === "canonicalMessage"));
881 }
882
883 /** Detached legacy tool reads use the exact call reference, not a field-only
884 * cache key shared by several calls. Full bodies belong to the drawer. */
885 async requestToolContent(tabId: string, item: Extract<Item, { kind: "tool" }>, value: Record<string, unknown>): Promise<string | undefined> {
886 const source = [...this.sessions.values()].find(session => session.tabId === tabId &&
887 [...session.contributions.values()].some(items => items.some(candidate => candidate.id === item.id)));
888 if (!source) return undefined;
889 const generation = source.generation;
890 const { readTranscriptToolContent } = await import("./transcriptToolContent");
891 if (this.sessions.get(source.key) !== source || source.generation !== generation) throw new Error("Tool reference expired; retry");
892 return readTranscriptToolContent({ sessions: this.sessions, backend: this.backend, requestFullContent: (tab, id, field) => this.requestFullContent(tab, id, field) }, tabId, item, value);
893 }
894
895 async requestFullContent(tabId: string, entryId: string, field: string): Promise<string | undefined> {
896 const resolver = this.contentResolvers.active(tabId);
897 if (resolver) return resolver.resolve(entryId, field);
898 return readTranscriptContent({
899 locate: id => {
900 const resolvedId = resolveTranscriptEntryAlias(this.sessions.values(), tabId, id);
901 const session = this.sessionForEntry(tabId, resolvedId);
902 return session ? { session, entryId: resolvedId } : undefined;
903 },
904 resident: session => this.sessions.get(session.key) === session,
905 read: (ref, index) => this.backend.HistoryContentForTab(tabId, ref, index),
906 publish: (session, record) => {
907 this.reconvertAndNotify(session, record);
908 this.enforceBudgets();
909 },
910 }, entryId, field);
911 }
912
913 private reconvertAndNotify(session: SessionTranscript, rec: TranscriptRecord): void {
914 // A resolved field on a CONSUMED tool-result row shows up in the claiming
915 // call's tool item, so re-convert the claimer instead of the row.
916 const targetId = session.consumedBy.get(rec.entryId) ?? rec.entryId;
917 const target = session.byId.get(targetId);
918 if (!target) return;
919 // Re-convert with the record's established claims so tool results stay put.
920 const view = this.viewOf(session.records);
921 const consumed = new Set(session.consumed);
922 for (const claimed of session.matchTables.get(targetId)?.values() ?? []) consumed.delete(claimed);
923 const conversion = convertRecord(target, view, consumed, session.matchTables.get(targetId));
924 session.consumed = consumed;
925 this.trackConversion(session, target, conversion);
926 session.itemsCache = null;
927 this.rebuildProjection(session);
928 const listeners = this.listeners.get(session.tabId);
929 if (!listeners || listeners.size === 0) return;
930 const patches: Record<string, Item> = {};
931 for (const item of conversion.items) patches[item.id] = item;
932 const change: TranscriptContentChange = { tabId: session.tabId, patches };
933 for (const listener of listeners) listener(change);
934 }
935
936 // ── markdown cache (populated by the rendering/worker phase) ──────────────
937
938 getMarkdown(entryId: string, revision: number): ParsedMarkdownValue | undefined {
939 return this.markdown.get(entryId, revision);
940 }
941
942 setMarkdown(entryId: string, revision: number, value: ParsedMarkdownValue): void {
943 this.markdown.set(entryId, revision, value);
944 }
945
946 pinMarkdown(entryId: string, revision: number): () => void {
947 return this.markdown.pin(entryId, revision);
948 }
949
950 markdownCacheSize(): number {
951 return this.markdown.size();
952 }
953
954 subscribe(tabId: string, listener: (change: TranscriptContentChange) => void): () => void {
955 let set = this.listeners.get(tabId);
956 if (!set) {
957 set = new Set();
958 this.listeners.set(tabId, set);
959 }
960 set.add(listener);
961 return () => {
962 set.delete(listener);
963 if (set.size === 0) this.listeners.delete(tabId);
964 };
965 }
966 }
967
968 // Bridge-backed singleton: resolves the host bindings at call time through
969 // the app proxy, so test/dev mocks install whenever they appear.
970 let singleton: TranscriptStore | undefined;
971
972 export function getTranscriptStore(): TranscriptStore {
973 if (!singleton) {
974 singleton = new TranscriptStore({
975 HistorySliceForTab: (tabID, req) => canonicalHistorySlice(tabID, req),
976 HistoryContentForTab: canonicalHistoryContent,
977 });
978 }
979 return singleton;
980 }
981
982 registerTranscriptCacheDiagnostics(() =>
983 singleton?.stats() ?? {
984 residentSessions: 0,
985 maxResidentSessions: DEFAULT_MAX_RESIDENT_SESSIONS,
986 bodyBytes: 0,
987 bodyBudgetBytes: DEFAULT_HISTORY_BODY_BUDGET,
988 markdownBytes: 0,
989 markdownBudgetBytes: DEFAULT_MARKDOWN_BUDGET,
990 historyEvictions: 0,
991 markdownEvictions: 0,
992 reclaimedPages: 0,
993 residentWindowEntries: 0,
994 windowMaxPages: DEFAULT_WINDOW_MAX_PAGES,
995 },
996 );
997
997 lines TYPESCRIPT