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