{"version":3,"file":"threadStore.cjs","names":["createPagedTranscript","applySessionFrame","watchHubThread"],"sources":["../../../src/web/stores/threadStore.ts"],"sourcesContent":["import type { SessionServiceState, TranscriptPage, TranscriptPageRequest } from '@agimon-ai/po-core/sessionProtocol';\nimport type { Context } from '@earendil-works/chord/context';\n\nimport type { BrowserPerformanceEvent } from '../lib/browserTelemetry';\nimport { watchHubThread } from '../lib/transport';\nimport { createPagedTranscript } from './pagedTranscriptStore';\nimport { applySessionFrame, dropSessionStore } from './sessionStore';\n\n/** A session id is a registry id and never starts with this, so a thread's fold cannot shadow a session's. */\nconst THREAD_KEY_PREFIX = 'thread:';\n\ninterface ThreadHold {\n  sessionId: string;\n  threadId: string;\n  refs: number;\n  unwatch?: () => void;\n  transcript?: ReturnType<typeof createPagedTranscript>;\n  pendingState?: SessionServiceState;\n  ready?: boolean;\n}\n\n/**\n * The page's holds on threads, counted per thread so two views of one thread\n * share one server reference. The reference survives reconnects; a newly bound\n * socket picks up holds taken before it.\n */\nconst holds = new Map<string, ThreadHold>();\n/** What a thread fold reads its pages through: the parent session's protocol binding. */\nexport interface ThreadTranscriptReader {\n  readTranscriptPage(request: TranscriptPageRequest, context: Context): Promise<TranscriptPage>;\n}\n\nconst readers = new Map<\n  string,\n  { service: ThreadTranscriptReader; context: Context; record: (event: BrowserPerformanceEvent) => void }\n>();\n\nfunction startTranscript(held: ThreadHold): void {\n  if (held.transcript || !held.ready) return;\n  const reader = readers.get(held.sessionId);\n  if (!reader) return;\n  const key = threadStoreKey(held.sessionId, held.threadId);\n  const transcript = createPagedTranscript(\n    key,\n    {\n      readTranscriptPage: (request, context) =>\n        reader.service.readTranscriptPage({ ...request, threadId: held.threadId }, context),\n    },\n    (id, frame, replay) => applySessionFrame(id, frame, { replay }),\n    reader.context,\n    reader.record,\n  );\n  held.transcript = transcript;\n  if (held.pendingState) transcript.publish(held.pendingState);\n  void transcript.initialize().catch((error: unknown) => {\n    if (held.transcript === transcript) applySessionFrame(key, { type: 'error', message: String(error) });\n  });\n}\n\nexport function bindThreadReader(\n  sessionId: string,\n  service: ThreadTranscriptReader,\n  context: Context,\n  record: (event: BrowserPerformanceEvent) => void = () => {},\n): () => void {\n  const reader = { service, context, record };\n  readers.set(sessionId, reader);\n  for (const held of holds.values()) if (held.sessionId === sessionId) startTranscript(held);\n  return () => {\n    if (readers.get(sessionId) !== reader) return;\n    readers.delete(sessionId);\n    for (const held of holds.values())\n      if (held.sessionId === sessionId) {\n        held.transcript?.dispose();\n        held.transcript = undefined;\n      }\n  };\n}\n\n/** SQLite children use the same cursor window and delta reducer as their parent. */\nexport function applyThreadTranscriptFrame(\n  sessionId: string,\n  threadId: string,\n  frame: Record<string, unknown>,\n): boolean {\n  if (frame.type !== 'transcript_state' && frame.type !== 'transcript_ready') return false;\n  const held = holds.get(threadStoreKey(sessionId, threadId));\n  if (!held) return true;\n  held.ready = true;\n  if (frame.type === 'transcript_state') held.pendingState = frame.state as SessionServiceState;\n  startTranscript(held);\n  if (held.pendingState) held.transcript?.publish(held.pendingState);\n  return true;\n}\n\n/** Where a thread's fold lives in the session store map. */\nexport function threadStoreKey(sessionId: string, threadId: string): string {\n  return `${THREAD_KEY_PREFIX}${sessionId}:${threadId}`;\n}\n\nexport function subscribeThread(sessionId: string, threadId: string): void {\n  const key = threadStoreKey(sessionId, threadId);\n  const held = holds.get(key);\n  if (held !== undefined) {\n    held.refs += 1;\n    return;\n  }\n  holds.set(key, { sessionId, threadId, refs: 1, unwatch: watchHubThread(sessionId, threadId) });\n}\n\nexport function unsubscribeThread(sessionId: string, threadId: string): void {\n  const key = threadStoreKey(sessionId, threadId);\n  const held = holds.get(key);\n  if (held === undefined) return;\n  held.refs -= 1;\n  if (held.refs > 0) return;\n  holds.delete(key);\n  held.transcript?.dispose();\n  held.unwatch?.();\n}\n\n/** Holds taken before a socket was bound start following their thread now. */\nexport function resubscribeThreads(): void {\n  for (const held of holds.values()) held.unwatch ??= watchHubThread(held.sessionId, held.threadId);\n}\n\n/** A session that left takes its threads' folds and holds with it. */\nexport function dropThreads(sessionId: string): void {\n  for (const [key, held] of holds) {\n    if (held.sessionId !== sessionId) continue;\n    holds.delete(key);\n    held.transcript?.dispose();\n    held.unwatch?.();\n    dropSessionStore(key);\n  }\n}\n\n/** The threads currently held, for tests and diagnostics. */\nexport function heldThreads(): Array<{ sessionId: string; threadId: string; refs: number }> {\n  return [...holds.values()].map((held) => ({ ...held }));\n}\n\nexport function resetThreads(): void {\n  for (const held of holds.values()) {\n    held.transcript?.dispose();\n    held.unwatch?.();\n  }\n  holds.clear();\n  readers.clear();\n}\n"],"mappings":";;;;;AASA,MAAM,oBAAoB;;;;;;AAiB1B,MAAM,wBAAQ,IAAI,IAAwB;AAM1C,MAAM,0BAAU,IAAI,IAGlB;AAEF,SAAS,gBAAgB,MAAwB;CAC/C,IAAI,KAAK,cAAc,CAAC,KAAK,OAAO;CACpC,MAAM,SAAS,QAAQ,IAAI,KAAK,SAAS;CACzC,IAAI,CAAC,QAAQ;CACb,MAAM,MAAM,eAAe,KAAK,WAAW,KAAK,QAAQ;CACxD,MAAM,aAAaA,6BAAAA,sBACjB,KACA,EACE,qBAAqB,SAAS,YAC5B,OAAO,QAAQ,mBAAmB;EAAE,GAAG;EAAS,UAAU,KAAK;CAAS,GAAG,OAAO,EACtF,IACC,IAAI,OAAO,WAAWC,qBAAAA,kBAAkB,IAAI,OAAO,EAAE,OAAO,CAAC,GAC9D,OAAO,SACP,OAAO,MACT;CACA,KAAK,aAAa;CAClB,IAAI,KAAK,cAAc,WAAW,QAAQ,KAAK,YAAY;CAC3D,WAAgB,WAAW,CAAC,CAAC,OAAO,UAAmB;EACrD,IAAI,KAAK,eAAe,YAAY,qBAAA,kBAAkB,KAAK;GAAE,MAAM;GAAS,SAAS,OAAO,KAAK;EAAE,CAAC;CACtG,CAAC;AACH;AAEA,SAAgB,iBACd,WACA,SACA,SACA,eAAyD,CAAC,GAC9C;CACZ,MAAM,SAAS;EAAE;EAAS;EAAS;CAAO;CA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