| 1 | import { app } from "./bridge"; |
| 2 | import { readNativeTranscriptOutline } from "./nativeTranscriptHistory"; |
| 3 | import { readBoundHistoryOutline } from "./historyReadBinding"; |
| 4 | import { observeOutline } from "./transcriptOutlineSignals"; |
| 5 | import type { HistoryOutlineEntry, HistoryOutlinePage, HistoryOutlineRequest } from "../generated/desktopContract.generated"; |
| 6 | |
| 7 | export type OutlineRead = (tabId: string, request: HistoryOutlineRequest) => Promise<HistoryOutlinePage>; |
| 8 | export type TranscriptOutlineView = { |
| 9 | mode: "loading" | "ready" | "error" | "unsupported"; |
| 10 | generation: string; snapshotSequence?: number; totalTurns: number; |
| 11 | entries: ReadonlyMap<number, HistoryOutlineEntry>; errors: ReadonlyMap<number, string>; |
| 12 | }; |
| 13 | const EMPTY: TranscriptOutlineView = Object.freeze({ mode: "loading", generation: "", totalTurns: 0, entries: new Map(), errors: new Map() }); |
| 14 | export const OUTLINE_PAGE_SIZE = 128; |
| 15 | const MAX_PAGES = 6; |
| 16 | const MAX_BYTES = 8 << 20; |
| 17 | type Page = { entries: HistoryOutlineEntry[]; bytes: number; touched: number }; |
| 18 | type Binding = { |
| 19 | identity: string; read: OutlineRead; active: number; epoch: number; dirty: boolean; |
| 20 | view: TranscriptOutlineView; pages: Map<number, Page>; pending: Map<number, Promise<void>>; |
| 21 | timer?: ReturnType<typeof setTimeout>; lastRead: number; |
| 22 | refresh?: Promise<void>; |
| 23 | releaseSignal?: () => void; |
| 24 | range?: [number, number]; |
| 25 | }; |
| 26 | |
| 27 | /** Sparse, fixed-cut directory. Body residency never determines the rail size. */ |
| 28 | export class TranscriptOutlineStore { |
| 29 | private bindings = new Map<string, Binding>(); |
| 30 | private listeners = new Map<string, Set<() => void>>(); |
| 31 | private clock = 0; |
| 32 | constructor(private now = () => Date.now()) {} |
| 33 | getView(tab: string): TranscriptOutlineView { return this.bindings.get(tab)?.view ?? EMPTY; } |
| 34 | subscribe(tab: string, listener: () => void): () => void { |
| 35 | const set = this.listeners.get(tab) ?? new Set(); |
| 36 | this.listeners.set(tab, set); set.add(listener); |
| 37 | return () => { set.delete(listener); if (!set.size) this.listeners.delete(tab); }; |
| 38 | } |
| 39 | private publish(tab: string, b: Binding): void { |
| 40 | const entries = new Map<number, HistoryOutlineEntry>(); |
| 41 | for (const page of b.pages.values()) for (const entry of page.entries) entries.set(entry.turn, entry); |
| 42 | b.view = { ...b.view, entries }; |
| 43 | for (const listener of [...(this.listeners.get(tab) ?? [])]) listener(); |
| 44 | } |
| 45 | activate(tab: string, identity: string, read: OutlineRead, knownTurns: number): () => void { |
| 46 | let b = this.bindings.get(tab); |
| 47 | if (!b || b.identity !== identity) { |
| 48 | this.release(tab); |
| 49 | b = { identity, read, active: 0, epoch: 0, dirty: true, view: { ...EMPTY, totalTurns: knownTurns }, pages: new Map(), pending: new Map(), lastRead: -Infinity }; |
| 50 | this.bindings.set(tab, b); |
| 51 | b.releaseSignal = observeOutline(tab, signal => signal === "suspend" ? this.suspend(tab) : this.dirty(tab)); |
| 52 | } |
| 53 | b.active++; b.read = read; |
| 54 | if (b.dirty) this.schedule(tab, b); |
| 55 | const owner = b; |
| 56 | return () => { |
| 57 | if (this.bindings.get(tab) !== owner) return; |
| 58 | owner.active = Math.max(0, owner.active - 1); |
| 59 | if (!owner.active) this.release(tab); |
| 60 | }; |
| 61 | } |
| 62 | release(tab: string): void { |
| 63 | const b = this.bindings.get(tab); |
| 64 | if (b) { b.epoch++; clearTimeout(b.timer); b.releaseSignal?.(); } |
| 65 | this.bindings.delete(tab); |
| 66 | } |
| 67 | suspend(tab: string): void { |
| 68 | const b = this.bindings.get(tab); |
| 69 | if (!b) return; |
| 70 | b.epoch++; b.pending.clear(); b.refresh = undefined; clearTimeout(b.timer); b.timer = undefined; b.dirty = true; |
| 71 | } |
| 72 | dirty(tab: string): void { |
| 73 | const b = this.bindings.get(tab); |
| 74 | if (!b) return; |
| 75 | b.dirty = true; |
| 76 | if (b.active) this.schedule(tab, b); |
| 77 | } |
| 78 | private schedule(tab: string, b: Binding): void { |
| 79 | if (b.timer !== undefined || b.refresh) return; |
| 80 | b.timer = setTimeout(() => { |
| 81 | b.timer = undefined; |
| 82 | if (b.active && this.bindings.get(tab) === b) void this.refresh(tab); |
| 83 | }, Math.max(0, 250 - (this.now() - b.lastRead))); |
| 84 | } |
| 85 | async refresh(tab: string): Promise<void> { |
| 86 | const b = this.bindings.get(tab); |
| 87 | if (!b) return; |
| 88 | if (b.refresh) return b.refresh; |
| 89 | clearTimeout(b.timer); b.timer = undefined; |
| 90 | b.epoch++; b.pending.clear(); b.dirty = false; b.lastRead = this.now(); |
| 91 | // Keep the previous directory visible until the new cut has arrived. |
| 92 | const run = this.readPage(tab, b, 1, true).finally(() => { |
| 93 | if (this.bindings.get(tab) !== b || b.refresh !== run) return; |
| 94 | b.refresh = undefined; |
| 95 | if (b.dirty && b.active) this.schedule(tab, b); |
| 96 | }); |
| 97 | b.refresh = run; |
| 98 | await run; |
| 99 | } |
| 100 | async retry(tab: string): Promise<void> { |
| 101 | const b = this.bindings.get(tab); |
| 102 | if (!b) return; |
| 103 | const failed = [...b.view.errors.keys()]; |
| 104 | await this.refresh(tab); |
| 105 | if (this.bindings.get(tab) !== b || b.view.snapshotSequence === undefined || b.view.mode === "unsupported") return; |
| 106 | await Promise.all(failed.filter(start => start > 1 && start <= b.view.totalTurns).map(start => this.readPage(tab, b, start))); |
| 107 | if (b.range) await this.ensure(tab, ...b.range); |
| 108 | } |
| 109 | async ensure(tab: string, first: number, last = first): Promise<void> { |
| 110 | const b = this.bindings.get(tab); |
| 111 | if (!b || b.view.mode === "unsupported") return; |
| 112 | b.range = [first, last]; |
| 113 | await b.refresh; |
| 114 | if (this.bindings.get(tab) !== b) return; |
| 115 | if (b.view.snapshotSequence === undefined) { |
| 116 | await (b.pending.get(1) ?? this.readPage(tab, b, 1, true)); |
| 117 | if (b.view.snapshotSequence === undefined) return; |
| 118 | } |
| 119 | const starts = new Set<number>(); |
| 120 | for (let turn = Math.max(1, first); turn <= Math.min(last, b.view.totalTurns);) { |
| 121 | const start = Math.floor((turn - 1) / OUTLINE_PAGE_SIZE) * OUTLINE_PAGE_SIZE + 1; |
| 122 | starts.add(start); turn = start + OUTLINE_PAGE_SIZE; |
| 123 | } |
| 124 | await Promise.all([...starts].map(start => { |
| 125 | const page = b.pages.get(start); |
| 126 | if (page) { page.touched = ++this.clock; return; } |
| 127 | return this.readPage(tab, b, start); |
| 128 | })); |
| 129 | } |
| 130 | async entry(tab: string, turn: number): Promise<HistoryOutlineEntry | undefined> { |
| 131 | await this.ensure(tab, turn); return this.getView(tab).entries.get(turn); |
| 132 | } |
| 133 | private readPage(tab: string, b: Binding, start: number, fresh = false): Promise<void> { |
| 134 | const pending = b.pending.get(start); |
| 135 | if (pending) return pending; |
| 136 | const epoch = b.epoch; |
| 137 | const current = () => this.bindings.get(tab) === b && b.epoch === epoch; |
| 138 | const request: HistoryOutlineRequest = { startTurn: start, limit: OUTLINE_PAGE_SIZE, |
| 139 | ...(fresh ? {} : { generation: b.view.generation, snapshotSequence: b.view.snapshotSequence }) }; |
| 140 | const run = Promise.resolve().then(async () => { |
| 141 | try { |
| 142 | const page = await b.read(tab, request); |
| 143 | if (!current()) return; |
| 144 | if (page.status === "preparing") { b.dirty = true; this.schedule(tab, b); return; } |
| 145 | if (page.status === "unsupported") { b.pages.clear(); b.view = { ...EMPTY, mode: "unsupported" }; this.publish(tab, b); return; } |
| 146 | if (page.status !== "ready") throw new Error(page.status); |
| 147 | if (!Number.isSafeInteger(page.totalTurns) || page.totalTurns < 0 || !Array.isArray(page.entries) |
| 148 | || (!fresh && (page.generation !== b.view.generation || page.snapshotSequence !== b.view.snapshotSequence))) throw new Error("invalid outline cut"); |
| 149 | const changedCut = fresh && (page.generation !== b.view.generation || page.snapshotSequence !== b.view.snapshotSequence); |
| 150 | if (changedCut) b.pages.clear(); |
| 151 | const entries = page.entries.filter(entry => Number.isSafeInteger(entry.turn) && entry.turn >= start && entry.turn < start + OUTLINE_PAGE_SIZE && Boolean(entry.messageId)); |
| 152 | b.pages.set(start, { entries, bytes: JSON.stringify(entries).length * 2, touched: ++this.clock }); |
| 153 | const errors = new Map(changedCut ? [] : b.view.errors); errors.delete(start); |
| 154 | b.view = { ...b.view, mode: errors.size ? "error" : "ready", generation: page.generation, snapshotSequence: page.snapshotSequence, totalTurns: page.totalTurns, errors }; |
| 155 | this.trim(); this.publish(tab, b); |
| 156 | if (changedCut && b.range && b.range[0] > OUTLINE_PAGE_SIZE) void this.ensure(tab, ...b.range); |
| 157 | } catch (error) { |
| 158 | if (!current()) return; |
| 159 | const errors = new Map(b.view.errors); errors.set(start, String(error)); |
| 160 | b.view = { ...b.view, mode: "error", errors }; this.publish(tab, b); |
| 161 | } finally { if (current() && b.pending.get(start) === run) b.pending.delete(start); } |
| 162 | }); |
| 163 | b.pending.set(start, run); return run; |
| 164 | } |
| 165 | private trim(): void { |
| 166 | let bytes = 0; |
| 167 | const pages: { tab: string; b: Binding; start: number; page: Page }[] = []; |
| 168 | for (const [tab, b] of this.bindings) for (const [start, page] of b.pages) { bytes += page.bytes; pages.push({ tab, b, start, page }); } |
| 169 | pages.sort((a, b) => a.page.touched - b.page.touched); |
| 170 | for (const item of pages) { |
| 171 | if (item.b.pages.size <= MAX_PAGES && bytes <= MAX_BYTES) continue; |
| 172 | item.b.pages.delete(item.start); bytes -= item.page.bytes; this.publish(item.tab, item.b); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | let singleton: TranscriptOutlineStore | undefined; |
| 177 | export function getTranscriptOutlineStore(): TranscriptOutlineStore { return singleton ??= new TranscriptOutlineStore(); } |
| 178 | const unsupported = (): HistoryOutlinePage => ({ status: "unsupported", entries: [], totalTurns: 0, generation: "", snapshotSequence: 0, coverageSequence: 0, nextTurn: 1, done: true }); |
| 179 | export const localOutlineRead: OutlineRead = async (tab, request) => (await readNativeTranscriptOutline(tab, request)) ?? (await readBoundHistoryOutline(tab, request)) ?? (typeof app.SessionHistoryOutlineForTab === "function" |
| 180 | ? app.SessionHistoryOutlineForTab(tab, request) : unsupported()); |
| 181 | export const remoteOutlineRead: OutlineRead = async (tab, request) => (await readNativeTranscriptOutline(tab, request)) ?? (typeof app.RemoteSessionHistoryOutlineForTab === "function" |
| 182 | ? app.RemoteSessionHistoryOutlineForTab(tab, request) : unsupported()); |
| 183 |