/** * AdaptiveChatTrail — the "bubble-up" message column that sits above the * chat bar in the canvas lid. * * Messages appear immediately above the chat bar and drift upward as * newer ones arrive. Each stack position carries an opacity + blur * falloff so older messages read as fading from the page. Beyond a * `visibleCount` cap (default 3) the trail collapses into an "N more · * expand" affordance — clicking emits `trail-expand`. * * Shadow DOM (default Lit open root) so chip styles, markdown reset * rules, and animation @keyframes are scoped to this element's tree. * Theme CSS variables (--sc-tile-text-color, --sc-content-bubble-*, * etc.) inherit through the shadow boundary, so canvas-level theming * still reaches the chips. The earlier light-DOM render-root override * silently broke @keyframes lookup once the trail was hosted inside * any shadow root (sc-mount, velvet-mobile, etc.) — keyframes injected * into `document.head` aren't visible from another tree scope. * * See PRD §4.3 (chat trail) for the canonical motion + falloff spec. */ import { LitElement } from 'lit'; export interface TrailToolCall { id: string; name: string; status: 'args-streaming' | 'pending' | 'running' | 'done' | 'error'; /** * Parsed tool-call arguments, when available. Threaded through from * the AG-UI `ToolCall.args` so the trail can render argument-derived * affordances WITHOUT a new transport: an activity receipt for a * `primary_response_action` mount (derives type + label from * `template_id` / `content.title`) and inline reply chips for a * `suggest_replies` call (reads the `replies` array). Undefined while * args are still streaming or for tools whose args we don't surface. */ args?: Record; } export interface TrailMessage { /** Stable identity for keyed rendering (must be unique within the trail). */ id: number | string; role: 'user' | 'assistant' | 'system'; text: string; /** Streaming → assistant text still arriving from backend. Complete → final. Error → fatal during stream. */ status?: 'streaming' | 'complete' | 'error'; /** Tool calls attached to an assistant message (rendered as compact chips). */ toolCalls?: TrailToolCall[]; } export type TileReceipt = { kind: 'tile'; instanceId: string; title: string; dismissed: boolean; turnId?: string; toolCallId?: string; /** Tiny product thumbnail for the chip's leading slot (COI-037). * Absent → the decorative stack glyph renders instead. */ imageUrl?: string; } | { kind: 'alert'; instanceId: string; title: string; turnId?: string; toolCallId?: string; }; /** * A widget the backend wants rendered INLINE IN THE CHAT TRAIL (in the * conversation flow, like a rich message) — currently the reco carousel. * Sourced from `ElementInstanceStore.listInlineWidgets()` (backend * `chat-inline` slot mounts) and forwarded by AdaptiveChatBar. * * The trail mounts `tag` by name via `document.createElement` and assigns * the payload as one `props` object property (`el.props = props`, the * standard tile-widget mount contract) — it never imports the widget package (the * element self-defines when its own bundle loads; on demos both bundles * are present). If `tag` is not a defined custom element, the trail * renders NOTHING for it (no broken box). */ export interface InlineTrailWidget { instanceId: string; /** * The mount identifier for the widget. For self-defining, server-mounted * widgets this IS the custom-element tag (e.g. `syntro-product-reco-carousel`) * and the trail creates it directly. For admin-template widgets it is the * runtime widget-id (e.g. `adaptive-product:card`, `adaptive-faq:accordion`), * which is NOT a valid custom-element tag — those mount through the runtime * widget registry via {@link InlineWidgetMounter}, which resolves the id to * its real element exactly like the deck `SyntroTileCard` path. */ tag: string; props: Record; /** * `mounted_by.turn_id` of the element — the id of the user message that * triggered the mounting turn. Lets the trail restore the widget to its * original transcript position after a reload (see `_anchorFromTurn`). */ turnId?: string; /** * `tool_call_id` of the mount call that created the element — pins the * restored widget to the exact transcript message hosting that call * (see `_anchorFromToolCall`); `turnId` is the coarser fallback. */ toolCallId?: string; } /** * Mounts a registry-registered widget (by its runtime widget-id) into * `container` and returns the created element plus an unmount cleanup. * Injected from the chat-bar mountable, bound to `runtime.widgets`. Lets the * trail render inline tiles whose widget-id is not their custom-element tag * (product card, comparison, FAQ accordion) — the registry owns the * id → element resolution. Returns `null` when the id is not registered. */ export type InlineWidgetMounter = (widgetId: string, container: HTMLElement, props: Record) => { element: HTMLElement; cleanup: () => void; } | null; export declare class AdaptiveChatTrail extends LitElement { static styles: import("lit").CSSResult; static properties: { messages: { attribute: boolean; }; visibleCount: { type: NumberConstructor; }; expanded: { type: BooleanConstructor; }; greeting: { type: StringConstructor; }; /** When true: trail renders fully expanded AND the * expand/collapse affordance is hidden. Used by hosts that mount * the chat in a full-screen surface (the mobile panel) where * collapse makes no sense — there's nothing to collapse INTO. */ forceExpanded: { type: BooleanConstructor; }; /** * BUG (found 2026-08-13, reported live as a stray horizontal rule * floating above the transcript with nothing above it): the * expanded/forceExpanded scroll container always paints a * `borderTop` to mark "the panel's top edge". That reads correctly * in `AdaptiveChatBar`, which ALWAYS renders `renderHeader(...)` * immediately above the trail when `forceExpanded` is true (see * `AdaptiveChatBar.ts`'s `${this.forceExpanded ? renderHeader(...) * : nothing}`) — the border separates header from transcript. * `LeaveAMessageLit` mounts this element directly with no header * above it, so the same border renders as an orphaned rule sitting * in blank card padding. Default `false` preserves the existing * `AdaptiveChatBar` look exactly; hosts with no header above the * trail set this `true` to suppress it. */ hideTopBorder: { type: BooleanConstructor; }; /** * Short-thread mode (BUG-1789098964): never engage the turn anchor; * every messages change pins the bottom unless the visitor scrolled up. * The anchor contract exists so a long STREAMED answer reads top-down * from the visitor's message. The human-handoff card shows a 160px * thread whose replies land whole, and there the anchor pinned the * visitor's own chip to the top while the reply sat below the fold * (Parker, live on mainpeptides.com 2026-09-10). Hosts that render a * short thread set this `true`; the concierge leaves it `false`. */ followBottom: { type: BooleanConstructor; }; /** * Mirrors `chatSession.inFlight` — true between `send()` and the * assistant's first `receiveStart`/`receiveDelta`, OR while a * stream is in progress. Drives the "thinking" indicator that * fills the gap between the user's just-sent message and the * first assistant token. Wired through AdaptiveChatBar (it owns * the chatSession subscription and forwards inFlight as a prop). */ inFlight: { type: BooleanConstructor; }; /** * Live reasoning narration streamed from the model via AG-UI * `THINKING_TEXT_MESSAGE_CONTENT`. When non-empty, the thinking * chip renders this in place of the bouncing dots so the visitor * sees what the model is actually doing instead of staring at * silent loading state during a tool-call gap. */ thinkingText: { attribute: boolean; }; personaName: { attribute: boolean; }; personaAvatarSm: { attribute: boolean; }; /** * Pre-conversation suggestion chip. When the visitor opens the * chat and `messages` is empty, the trail renders this as a * button beneath the greeting. Clicking it dispatches a * `trail-intro-suggestion` event with the configured prompt — * the parent (chat-bar) forwards that to chatSession.send(). * Disappears the moment the first message lands. */ introSuggestion: { attribute: boolean; }; /** * Tappable tile-receipt chips rendered once at the end of the * trail. Produced from the store by Task 3 (AdaptiveChatBar). * Each chip emits `tile-receipt-activate` with its instanceId. */ tileReceipts: { attribute: boolean; }; /** * Widgets rendered INLINE in the trail (reco carousel etc.), * anchored to a message position like receipts. Sourced from the * store's `chat-inline` slot mounts via AdaptiveChatBar. */ inlineWidgets: { attribute: boolean; }; /** * Registry-backed mounter for inline widgets whose id is not their * custom-element tag. Injected from the chat-bar mountable. */ mountInlineWidget: { attribute: boolean; }; _messagesBelow: { state: boolean; }; }; messages: TrailMessage[]; tileReceipts: TileReceipt[]; inlineWidgets: InlineTrailWidget[]; mountInlineWidget: InlineWidgetMounter | undefined; visibleCount: number; expanded: boolean; forceExpanded: boolean; hideTopBorder: boolean; followBottom: boolean; inFlight: boolean; thinkingText: string; /** Persona identity (FEAT-1784917430) — name + small avatar for assistant * turn-start chips and the thinking indicator. Empty = legacy rendering. */ personaName: string; personaAvatarSm: string; /** True when `m` opens an assistant run (previous visible message is not * assistant) — the persona byline renders once per turn, not per chip. */ private _isAssistantTurnStart; introSuggestion: { label: string; prompt: string; } | undefined; /** * Pre-conversation phantom assistant message. Rendered only when * `messages` is empty. NOT injected into chatSession state — the * greeting is configuration, not conversation, so it disappears * automatically when the first real message arrives. */ greeting: string | undefined; /** Follow the bottom on content growth. On by default (history * browsing); off from a new user message until the visitor opts back in * (pill tap or a user-gesture scroll that reaches the bottom). */ private _stickToBottom; /** The user message the current turn is anchored to. */ private _anchorMsgId; /** Whether a turn anchor is live (drives expand-mid-turn landing). */ private _anchorActive; /** Keep enforcing chip-at-top on updates (late geometry, mode flips) * until the user scrolls or opts into following. */ private _anchorHold; /** Number of messages whose BOTTOM edge is still below the viewport — * messages the visitor hasn't scrolled past yet. Drives the * "⌄ N messages" pill and stays accurate as they scroll (one long * streaming reply counts as 1 until its end has been read). Reactive. */ private _messagesBelow; /** Timestamp of the last user scroll gesture (wheel/touch): scroll * events outside this window are programmatic (our own pin/anchor) and * must not re-engage following — anchoring the newest message clamps AT * the bottom in any longer conversation. */ private _lastUserScrollIntentTs; private static readonly _AT_BOTTOM_EPSILON_PX; private static readonly _USER_SCROLL_INTENT_WINDOW_MS; private get _scrollable(); private _trailContainer; private _isAtBottom; /** Count chips whose bottom edge hasn't entered the viewport yet. */ private _countMessagesBelow; private _syncContentBelow; private _markUserScrollIntent; private _onTrailScroll; /** Pill tap: jump to the newest content and follow for the rest of the turn. */ private _onScrollToRecent; /** Scroll so the anchored user chip sits at the top of the trail * viewport. Idempotent — safe to re-apply on every update while the * hold is live (content grows BELOW the anchor, so the target is * stable; re-applying also covers late geometry, e.g. expanding * mid-turn from the ambient strip). */ private _applyAnchor; private _pinToBottom; private _onExpand; /** * Approve a pending client tool call. The trail emits a generic * event so the host can decide whether to forward to chatSession * (the common path) or override. Keeps the trail itself free of * direct chatSession coupling — it's a pure view component. */ private _onToolCallClick; private _onCollapse; /** * Whether to render the thinking-dots chip after the last message. * True iff a request is in flight AND the assistant hasn't started * streaming a reply yet — once the first delta lands, the streaming * chip's caret takes over and the thinking indicator hides so the * visitor isn't shown both at once. Also hidden when the last * message is an error/system message, because the request that * "errored" is already over from the user's perspective. */ private _shouldShowThinking; /** * The "assistant is busy" indicator — ONE status line, never a stack. * * Two facts can be live at once here: WHO is answering (`personaName`, a * static sticky pick, fixed for the whole turn) and WHAT is happening * (`thinkingText`, rewritten by `ChatTransport`'s narration cycle every ~4s). * They used to render as two independently-gated sibling rows, so a * persona-enabled workspace showed "Jordan is typing…" stacked directly * above the phase copy — the same claim twice, in two different verbs, and * "Jordan is typing…" above three bouncing dots before any phase arrived. * `thinkingStatusLine()` merges them into one sentence instead, and the * dots remain the sole fallback when neither fact is known. * * The row's own height must NOT change when the phase text rotates, or the * whole trail below it jumps every 4 seconds. `thinkingTextStyles()` pins * that with a fixed `line-height` plus `white-space: nowrap` + * `text-overflow: ellipsis`, so a short and a long phase paint the same box. */ private _renderThinking; /** * instanceId → id of the message that was newest when the receipt first * appeared. This is what makes a receipt read like a chat bubble: it renders * inline right after its anchor message, so newer messages push it up into * history instead of it staying pinned below everything. Assigned once per * instanceId (in willUpdate, the only place that sees both `messages` and * `tileReceipts` at the moment a tile mounts) and never re-homed — a * dismiss/bring-back keeps the chip where it was created. `null` = the tile * mounted before the first chat message (canvas replay); those fall to the * tail strip (see render). */ private readonly _receiptAnchors; /** * instanceId → anchor message id for inline widgets — same mechanism as * `_receiptAnchors`. The inline carousel renders right after the message * that was newest when it mounted, so it reads like a rich reply and * drifts up into history as later messages append. */ private readonly _inlineAnchors; /** * instanceId → the cached inline widget entry (render node + props target + * optional registry cleanup). Cached so a prop patch (same instanceId, new * props) updates the EXISTING element instead of tearing it down and * re-creating it — which would reset the carousel's scroll position + * internal state. Created lazily the first time we see the widget: * `document.createElement(tag)` for a defined tag, or a registry mount for a * widget-id. An unresolvable widget caches `null` so the fail-safe renders * nothing without re-checking the registry. */ private readonly _inlineElements; connectedCallback(): void; disconnectedCallback(): void; /** * The id of the newest message the render will actually PAINT — the only * valid anchor target. Anchoring to the raw last message is wrong-by- * construction for tool-call turns: mid-turn the newest message is often a * whitespace-only assistant shell (some providers emit whitespace text * deltas around tool calls) that the empty-bubble filter drops, so an * anchor recorded on it can never be in the painted set and the receipt * falls to the tail strip forever — resurrecting BUG-1783015943 (seen live * on vela desktop, BUG-1783630187). `isSuggestionHost=false` here: a * message whose ONLY content is reply chips is too ephemeral to anchor on * (the chips clear when the visitor answers), so walk past it too. */ private _newestRenderableMessageId; /** * Server-authoritative anchor for a restored element: `turnId` is the * persisted `mounted_by.turn_id` — the id of the user message that * triggered the mounting turn. The element anchors to the first * content-bearing assistant message of that turn (where it appeared live: * intro text, then the mount, then any follow-up), falling back to the * turn's user message when the assistant hasn't produced renderable text. * Returns null when `turnId` is absent or not in the transcript (nudge * mounts carry a runId) — the caller then uses the legacy * newest-renderable anchor. Without this, a reload assigned every element * to the newest message of the fully restored transcript, dumping all * inline views below the last message (the arrival-timing bug). */ /** * Exact restore anchor: `toolCallId` is the persisted id of the tool call * that mounted the element, and the transcript message hosting that call * carries it in `toolCalls`. Anchor to the host message itself when it * renders content, else walk BACK to the nearest renderable message — a * standalone tool-call message persists with empty content and must not * strand the element. This survives every turn shape (text→mount, * text→text→mount, mount→text); `_anchorFromTurn` is the coarser fallback * for elements persisted before tool_call_id existed. */ private _anchorFromToolCall; private _anchorFromTurn; willUpdate(changed: Map): void; /** * Create (once) or refresh the cached element for an inline widget. * * Two mount paths, both keeping the chat bundle free of any widget-package * import: * - Direct tag (self-defining, server-mounted widgets like the reco * carousel whose declared `widget` IS its custom-element tag): * `document.createElement(tag)`. * - Widget-id (admin-template widgets like `adaptive-product:card` or * `adaptive-faq:accordion`, whose `widget` is a runtime widget-id, NOT a * valid custom-element tag): mount through the runtime widget registry * via {@link mountInlineWidget}, which resolves the id to its real * element exactly like the deck `SyntroTileCard` path. Without this, * `createElement('adaptive-product:card')` yields an inert unknown * element and the tile renders permanently blank (the "inline mode * shows nothing but the reco" bug). * * Fail-safe: an id that resolves to neither a defined tag nor a registered * widget caches `null` and renders nothing (no broken box). */ private _ensureInlineElement; updated(changed: Map): void; private _onTileReceiptClick; private _onAlertReceiptClick; /** Render a set of inline widgets (reco carousel etc.) as * `[data-trail-widget]` blocks, anchored to a message position like * receipts. Each block hosts the cached custom element for that * instanceId — a defined tag mounts inline; an undefined tag renders * nothing (fail-safe). Rendered at every trail site (inline per anchor, * tail, empty-state) so placement can't diverge. */ private _renderInlineWidgetStrip; /** A row of receipt chips, used at every trail render site (inline per * anchor message, the tail fallback, and the empty-state branches) so the * markup + styling can never diverge. Returns `nothing` for an empty list. */ private _renderReceiptStrip; /** One receipt chip — a single, unified, single-line design for both kinds * (nav "alert" + mounted "tile"). Same container/title/action style so they * read as one chip family; the icon + action label carry the kind. No * subtitle: the old "Brought up earlier" line was hardcoded (wrong for * same-turn mounts) and made the chip taller — dropping it is the "shorter" * chip. Rendered at every trail site so the kinds can't diverge. */ private _renderReceiptChip; private _onIntroSuggestionClick; /** * Visitor tapped a `suggest_replies` inline chip. Emit * `trail-suggested-reply` carrying the chip text — the parent * (AdaptiveChatBar) re-dispatches it as `chat-message-sent`, the * SAME channel the input row uses, so the reply rides the existing * send path (mountable → chatSession.send → transport). No fabricated * AG-UI events; this is exactly what typing the text and hitting * Enter would do. The chips clear on their own once the reply lands * and a newer assistant message becomes the latest. */ private _onSuggestedReplyClick; /** * The conversation live region. * * Always rendered, in EVERY branch of `render()` — including the ones that * paint no transcript at all. A live region must already be in the DOM when * its first child arrives; one created in the same mutation as its content * is not reliably announced by NVDA or JAWS (adversarial review I3), and the * content that would be lost is the assistant's first reply of the session. * * `display: contents` means it contributes no box and no layout anywhere it * is mounted, so it is safe to place in an empty-state hero or in the flex * scroll container alike. In the empty states it is rendered LAST so it can * never become the `:first-child` any layout rule targets. */ private _renderConversationLog; render(): import("lit-html").TemplateResult<1>; } /** * Discriminated visual state for a chip. Replaces the older * `(role, { isStreaming, isError })` triple whose interaction order * could produce nonsense combinations (e.g. an assistant chip * accidentally reading as a user bubble because `isStreaming` was * checked before role). Each kind below is a real conversational * state with a single visual identity: * * - `settled` — a complete message; the user-vs-assistant * identity comes from `role` * - `streaming` — the assistant chip currently receiving tokens; * keeps assistant identity (the blinking caret * inside the chip carries "in progress") * - `pending` — the thinking chip shown between the user's * just-sent message and the assistant's first * token; assistant identity (the bouncing dots * inside carry "in progress") * - `error` — a chip whose stream failed mid-flight, OR any * system-role message (system messages render * with the error identity by convention) * * Bug history: an earlier branch-ladder design checked `isStreaming` * before `role`, so the `pending`/thinking chip inherited the user * bubble border. On hosts whose chat panel sits over a light surface * that read as a "white div" pasted into the assistant slot. The * discriminated state prevents that combination from being expressible. */ export type ChipVisualState = { kind: 'settled'; role: 'user' | 'assistant' | 'system'; } | { kind: 'streaming'; } | { kind: 'pending'; } | { kind: 'notice'; role: 'user' | 'assistant' | 'system'; }; /** * A misbehaving model can emit a raw SERIALIZED response payload as plain TEXT * on a spurious trailing turn — e.g. * `(Empty response: {'content': [{'type': 'thinking', …}], 'stop_reason': …})`. * Backstop for model degeneration (Kimi); the prompt (S-14) also asks for one * brief closing, but copy can't be trusted on the very turn that degenerates. * * Detection avoids false positives (which are WORSE than the dump — the visitor * would see nothing): a turn is dropped only if it OPENS with the literal * "(Empty response" marker, OR it carries ≥2 serialization tokens at once. A * single token (a product about a "signature blend", the agent quoting one JSON * key) never trips it; a real response dump carries all of them. */ export declare function looksLikeSerializedModelResponse(text: string): boolean; declare global { interface HTMLElementTagNameMap { 'adaptive-chat-trail': AdaptiveChatTrail; } } //# sourceMappingURL=AdaptiveChatTrail.d.ts.map