import type { SDKMessage } from "@letta-ai/letta-agent-sdk/client"; import type { TranscriptItem } from "./model"; /** Apply a visual batch of wire events, then perform one transcript projection. */ export function applyStreamBatch( accumulator: { apply: (message: SDKMessage) => void }, events: readonly SDKMessage[], snapshot: TSnapshot, project: (snapshot: TSnapshot) => TSnapshot, ): TSnapshot { for (const event of events) accumulator.apply(event); return project(snapshot); } /** Preserve item identity when projection produced the same flat render data. */ export function stabilizeTranscriptItems( previousById: ReadonlyMap, projected: readonly TranscriptItem[], ): { items: TranscriptItem[]; byId: Map } { const byId = new Map(); const items = projected.map((item) => { const previous = previousById.get(item.id); const stable = previous && sameTranscriptItem(previous, item) ? previous : item; byId.set(stable.id, stable); return stable; }); return { items, byId }; } function sameTranscriptItem(previous: TranscriptItem, next: TranscriptItem): boolean { if (previous.kind !== next.kind) return false; const previousRecord = previous as unknown as Record; const nextRecord = next as unknown as Record; const keys = Object.keys(nextRecord); if (keys.length !== Object.keys(previousRecord).length) return false; return keys.every((key) => previousRecord[key] === nextRecord[key]); }