{"version":3,"file":"imageRefStore.mjs","names":[],"sources":["../../../src/web/stores/imageRefStore.ts"],"sourcesContent":["import type { TranscriptImageRef, TranscriptPage } from '@agimon-ai/po-core/sessionProtocol';\nimport { createContext, useContext, useEffect, useMemo, useState } from 'react';\n\ntype ImageRef = TranscriptImageRef['ref'];\ntype EntryReader = (entryId: string) => Promise<TranscriptPage>;\n\n/** Images read lately, kept so a row scrolled back into view does not read its entry again. */\nconst MAX_CACHED_IMAGES = 24;\n/** How deep a value is searched for references, as deep as the server looks for images under a message. */\nconst MAX_REF_DEPTH = 34;\nconst readers = new Map<string, EntryReader>();\nconst cache = new Map<string, Promise<string>>();\n/** Entry reads in flight, so images in one entry, such as a tool result's content and its details, share one read. */\nconst entryReads = new Map<string, Promise<TranscriptPage>>();\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction refKey(ref: ImageRef): string {\n  return `${ref.entryId}\\n${'path' in ref ? JSON.stringify(ref.path) : String(ref.part)}`;\n}\n\n/** Lets images in the fold under `storeKey` read their saved entry. The transcript paging that fold binds it. */\nexport function bindImageReader(storeKey: string, read: EntryReader): () => void {\n  readers.set(storeKey, read);\n  return () => {\n    if (readers.get(storeKey) !== read) return;\n    readers.delete(storeKey);\n    for (const key of cache.keys()) if (key.startsWith(`${storeKey}\\n`)) cache.delete(key);\n  };\n}\n\n/** The base64 data of an image a transcript sent by reference, read from the saved entry that holds it. */\nexport function loadImageRef(storeKey: string, ref: ImageRef): Promise<string> {\n  const key = `${storeKey}\\n${refKey(ref)}`;\n  const cached = cache.get(key);\n  if (cached) {\n    cache.delete(key);\n    cache.set(key, cached);\n    return cached;\n  }\n  const read = readers.get(storeKey);\n  if (!read) return Promise.reject(new Error('No transcript reader is bound for this image.'));\n  const entryKey = `${storeKey}\\n${ref.entryId}`;\n  let reading = entryReads.get(entryKey);\n  if (!reading) {\n    const started = read(ref.entryId);\n    // Only the images are kept once the read settles, never the whole entry.\n    const forget = () => {\n      if (entryReads.get(entryKey) === started) entryReads.delete(entryKey);\n    };\n    started.then(forget, forget);\n    entryReads.set(entryKey, started);\n    reading = started;\n  }\n  const loading = reading.then((page) => {\n    const entry = page.entries[0];\n    const message = isRecord(entry) ? entry.message : undefined;\n    const path = 'path' in ref ? ref.path : ['content', ref.part];\n    const block = path.reduce<unknown>(\n      (value, step) => (isRecord(value) || Array.isArray(value) ? (value as Record<string, unknown>)[step] : undefined),\n      message,\n    );\n    if (!isRecord(block) || typeof block.data !== 'string') throw new Error('The referenced image was not found.');\n    return block.data;\n  });\n  cache.set(key, loading);\n  // A failed read is not remembered, so the image is asked for again the next time it is shown.\n  loading.catch(() => {\n    if (cache.get(key) === loading) cache.delete(key);\n  });\n  if (cache.size > MAX_CACHED_IMAGES) cache.delete(cache.keys().next().value!);\n  return loading;\n}\n\n/** The fold whose saved entries an image reference points into: the store key its transcript pages under. */\nexport const ImageRefScope = createContext<string | null>(null);\n\nfunction unreadRef(block: unknown): ImageRef | undefined {\n  if (!isRecord(block) || typeof block.data === 'string' || !isRecord(block.ref)) return undefined;\n  const { entryId, part, path } = block.ref;\n  if (typeof entryId !== 'string') return undefined;\n  if (typeof part === 'number') return { entryId, part };\n  return Array.isArray(path) && path.every((step) => typeof step === 'string' || typeof step === 'number')\n    ? { entryId, path }\n    : undefined;\n}\n\n/** Every unread reference in `value`, however deep, such as an image in a tool result's details. */\nfunction unreadRefs(value: unknown, depth = 0, found: ImageRef[] = []): ImageRef[] {\n  const ref = unreadRef(value);\n  if (ref) found.push(ref);\n  else if (depth < MAX_REF_DEPTH && (isRecord(value) || Array.isArray(value)))\n    for (const item of Object.values(value)) unreadRefs(item, depth + 1, found);\n  return found;\n}\n\n/** `value` with each reference read so far given its data, copying only the containers on the way to one. */\nfunction withData(value: unknown, loaded: Readonly<Record<string, string>>, depth = 0): unknown {\n  const ref = unreadRef(value);\n  if (ref) {\n    const data = loaded[refKey(ref)];\n    return data ? { ...(value as object), data } : value;\n  }\n  if (depth >= MAX_REF_DEPTH || !(isRecord(value) || Array.isArray(value))) return value;\n  let copy: Record<string, unknown> | unknown[] | undefined;\n  for (const [key, item] of Object.entries(value)) {\n    const next = withData(item, loaded, depth + 1);\n    if (next === item) continue;\n    copy ??= Array.isArray(value) ? [...value] : { ...value };\n    (copy as Record<string, unknown>)[key] = next;\n  }\n  return copy ?? value;\n}\n\n/**\n * `value` with each image a transcript sent by reference given its `data` once read, however deep it sits, for\n * renderers written against inline images. The same value while there is nothing to fill in, so memoized rows stay put.\n */\nexport function useImageRefs<T>(value: T): T {\n  const storeKey = useContext(ImageRefScope);\n  const [loaded, setLoaded] = useState<Readonly<Record<string, string>>>({});\n  const wanted = useMemo(() => JSON.stringify(unreadRefs(value)), [value]);\n  useEffect(() => {\n    if (storeKey === null || wanted === '[]') return;\n    let live = true;\n    for (const ref of JSON.parse(wanted) as ImageRef[]) {\n      loadImageRef(storeKey, ref).then(\n        (data) => {\n          if (live) setLoaded((current) => ({ ...current, [refKey(ref)]: data }));\n        },\n        // The image stays unshown, as an unsupported one would; the row is still readable.\n        (error: unknown) => console.warn('A referenced transcript image could not be read', error),\n      );\n    }\n    return () => {\n      live = false;\n    };\n  }, [storeKey, wanted]);\n  return useMemo(() => (wanted === '[]' ? value : (withData(value, loaded) as T)), [value, wanted, loaded]);\n}\n"],"mappings":";;;AAOA,MAAM,oBAAoB;;AAE1B,MAAM,gBAAgB;AACtB,MAAM,0BAAU,IAAI,IAAyB;AAC7C,MAAM,wBAAQ,IAAI,IAA6B;;AAE/C,MAAM,6BAAa,IAAI,IAAqC;AAE5D,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,OAAO,KAAuB;CACrC,OAAO,GAAG,IAAI,QAAQ,IAAI,UAAU,MAAM,KAAK,UAAU,IAAI,IAAI,IAAI,OAAO,IAAI,IAAI;AACtF;;AAGA,SAAgB,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