/** * Type-neutral store for LLM-authored UI element instances — Phase 6. * * On SDK boot: * 1. Caller fetches `/api/adaptive/mounted_elements` (see `fetcher.ts`). * 2. Calls `store.hydrate(response.mounted_elements)`. * 3. The store iterates each instance, looks up its handler, and * either mounts (stateful) or skips (imperative already-applied). * * During chat turns: * - AGUI `syntro.element.mutation` envelopes arrive via * `AgUiTransport.onA2UIEvent`. The transport caller decodes the * envelope and invokes `store.apply(envelope.mutations)`. * * Concurrency / dedup: * - Per-instance `version` is the dedup key. A mutation whose version * is `<= currentVersion` is treated as already-applied and silently * dropped — handles the SSE-during-boot-fetch race per the design * doc (the live mutation might arrive before the boot snapshot does, * and the snapshot is then a no-op). * - The store is single-threaded by Node/browser convention; no * cross-tab sync in v1. * * The store delegates all DOM work to per-type handlers * (`ElementTypeHandler`). It owns the registry, the in-memory state, * and the dispatch logic. */ import type { ActionEngine } from '../types'; import type { ElementTypeHandler } from './ElementTypeHandler'; import type { ElementMutation, MountedElement } from './types'; /** * Slot name reserved for tiles the backend wants rendered INLINE IN THE * CHAT TRAIL (in the conversation flow, like a rich message) rather than * in the canvas deck. The reco carousel uses this: the deck tile mounts * BEHIND the open chat panel, so the visitor never sees it. The backend * owns the placement decision — `adaptive_agent.py` emits * `SlotPlacement(slot="chat-inline")` for the reco mount. On the chat * side these tiles: * - surface via {@link ElementInstanceStore.listInlineWidgets} so the * trail can mount the widget element inline; and * - are SUPPRESSED from {@link ElementInstanceStore.listTileReceipts} * (a receipt chip would be a redundant, weaker affordance for a * widget already visible in the trail). * Every other slot keeps its existing deck + receipt-chip behavior. */ export declare const CHAT_INLINE_SLOT = "chat-inline"; /** One inline-rendered widget for the chat trail — a `chat-inline` tile. */ export interface InlineWidget { instanceId: string; /** Custom-element tag to mount (e.g. `syntro-product-reco-carousel`). */ tag: string; /** Payload assigned to the mounted element as ONE `props` object property * (`el.props = props` — the standard tile-widget mount contract; never * spread as individual per-key properties). */ props: Record; /** `mounted_by.turn_id` — lets the chat trail restore the widget to its * original transcript position after a reload. */ turnId?: string; /** `tool_call_id` of the mount call — pins the restored widget to the exact * transcript message hosting that call; `turnId` is the coarser fallback. */ toolCallId?: string; } export interface ElementInstanceStoreOptions { actions: ActionEngine; /** Runtime's event bus. ItemHandler publishes * `element.compositional_append` events here so container widgets * (chips strip, FAQ accordion, nav tips) can subscribe and inject * LLM-authored items into their compositional-actions lists. * * When `subscribe` is also provided, the store listens for * `element.compositional_replay_request` events. A container widget * publishes this event with its `tile_id` whenever it subscribes * (e.g. on first mount AND on SPA-navigation remount); the store * responds by re-publishing `element.compositional_append` for every * matching item still in its in-memory map. This is what makes * LLM-authored items persist across navigations within the page * session — the store survives chat-bar unmount/remount, container * widgets re-pull on each fresh mount. */ events?: { publish: (name: string, props?: Record) => void; /** * Overloaded to match the runtime SDK's `EventBus.subscribe`: * pass `{names:[...]}` to filter, or a callback to receive every * event. The store uses the filtered form so it doesn't fan * unrelated traffic (PostHog autocapture, every action lifecycle * event) into a string-compare on each delivery. */ subscribe?: { (filter: { names?: string[]; }, handler: (event: { name: string; props?: Record; }) => void): () => void; (handler: (event: { name: string; props?: Record; }) => void): () => void; }; }; handlers?: ElementTypeHandler[]; /** Override the logger — used by tests to capture log output. */ logger?: Pick; /** * Optional template→widget resolver used by the rehydrate replay. * Without this, replayed tile mounts emit ``widget: template_id``, * which only works when the admin's template ids match the widget * registry (e.g. ``adaptive-faq:accordion``). When an admin uses a * friendly id like ``product-card`` mapping to widget * ``adaptive-product:card``, the rehydrate path needs the resolver * to match the live mount path. * * Same shape as ``TileHandler``'s resolver — pass the same function * to both so live mounts and replays agree on the widget id. */ resolveTileWidget?: (templateId: string) => string | undefined; } export interface ApplyReport { ok: boolean; rejectedInstanceIds: string[]; } export declare class ElementInstanceStore { private readonly _actions; private readonly _events; private readonly _handlers; private readonly _instances; private readonly _logger; private readonly _resolveTileWidget?; /** Active TTL timeout — replaced on each call to `scheduleClientTtl`. */ private _ttlTimer; private _unsubscribeReplay?; private _disposed; private _disposing; /** Instance IDs the client has dismissed. Persists across canvas remounts * so a dismissed tile never silently reappears on replay/broadcast. */ private readonly _dismissedIds; constructor(options: ElementInstanceStoreOptions); /** * Listen for `element.compositional_replay_request` from container * widgets and re-publish `element.compositional_append` for every * matching item still tracked in `_instances`. This keeps LLM-authored * items visible across SPA navigations: the store is a module-level * singleton that survives chat-bar unmount/remount, so when a fresh * chips-strip mounts and subscribes, asking for a replay re-populates * its chip array. */ private _subscribeReplayRequests; private _replayItems; private _replayTiles; registerHandler(handler: ElementTypeHandler): void; isDismissed(instanceId: string): boolean; getDismissedIds(): ReadonlySet; /** Store-driven receipt source for the chat trail (one per active slot-tile). */ listTileReceipts(): Array<{ kind: 'tile'; instanceId: string; title: string; dismissed: boolean; turnId?: string; toolCallId?: string; imageUrl?: string; } | { kind: 'alert'; instanceId: string; title: string; turnId?: string; toolCallId?: string; }>; /** * Store-driven inline-widget source for the chat trail — one entry per * active `chat-inline` slot-tile. The trail mounts each entry's widget * element (by tag name, via `document.createElement`) inline in the * conversation flow. Distinct from {@link listTileReceipts}: those are * chips that recall a deck tile; these ARE the rendered widget. */ listInlineWidgets(): InlineWidget[]; /** Clear a client dismissal and re-publish the tile's mount from retained content. */ recreate(instanceId: string): void; /** * Apply the server-provided boot snapshot. For each instance: * - stateful: validated + mounted via the type handler; * - imperative + already-applied: recorded only (no DOM action); * - any: tracked in the in-memory map for future patches. * * Safe to call once on SDK init. Calling again would re-mount * stateful instances; callers should not. */ hydrate(snapshot: MountedElement[]): Promise; private _hydrateWithReport; /** * Re-publish `element.tile_mounted` / `element.compositional_append` * for every active LLM-authored instance in the store. Idempotent — * receivers key by `instance_id` (tiles) or by widget identity * (items via tile_id filter). */ private _broadcastActive; /** * Apply a batch of mutations, atomically per-batch. Each mutation is * version-checked (mount: must not conflict with existing instance; * patch: resulting_version must be > current; unmount: idempotent). */ apply(mutations: ElementMutation[]): Promise; applyWithReport(mutations: ElementMutation[]): Promise; private _applyWithReport; /** Read-only snapshot of currently-known instances. */ getInstances(): MountedElement[]; getInstance(instance_id: string): MountedElement | undefined; /** Replace a host-provided complete UI snapshot; never replay imperative actions. */ reconcileSnapshot(snapshot: MountedElement[]): Promise; /** Release page-lifetime listeners and timers; queued work becomes inert. */ dispose(unmount?: boolean): void; /** * Schedule a client-side TTL that unmounts every active stateful * instance when the server-side session expires. Replaces any * previously-scheduled TTL. * * Avoids the orphan-window where session-expired tiles linger on the * page until manual refresh — the server forgets at the 24h mark and * the SDK tears down concurrently. Re-schedule on each boot fetch / * mutation event that carries a refreshed `session_expires_at`. * * Pass `null` to clear the existing timer without scheduling a new one. * Pass a past timestamp to trigger cleanup immediately. */ scheduleClientTtl(session_expires_at: string | null): void; private _handleSessionExpiry; private _applyOne; private _mount; private _ctx; } //# sourceMappingURL=ElementInstanceStore.d.ts.map