@flamingo-stack/openframe-frontend-core 0.0.249 → 0.0.251-snapshot.20260610152056

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/{chunk-VAKBNCV6.js → chunk-4AVACC2J.js} +41 -28
  2. package/dist/chunk-4AVACC2J.js.map +1 -0
  3. package/dist/{chunk-PCXI7ZB2.js → chunk-D2BC3NZ2.js} +135 -30
  4. package/dist/chunk-D2BC3NZ2.js.map +1 -0
  5. package/dist/{chunk-5ZVPKTXM.js → chunk-DZJ53RX6.js} +2 -2
  6. package/dist/{chunk-4EED3YEI.cjs → chunk-NCXHTQH2.cjs} +663 -558
  7. package/dist/chunk-NCXHTQH2.cjs.map +1 -0
  8. package/dist/{chunk-3DZ7QYNA.cjs → chunk-PDKBCCCD.cjs} +11 -11
  9. package/dist/{chunk-3DZ7QYNA.cjs.map → chunk-PDKBCCCD.cjs.map} +1 -1
  10. package/dist/{chunk-PVAYXHYF.js → chunk-PSG7H4KG.js} +2 -2
  11. package/dist/{chunk-3VTHSACO.cjs → chunk-UMH4RR2F.cjs} +25 -25
  12. package/dist/{chunk-3VTHSACO.cjs.map → chunk-UMH4RR2F.cjs.map} +1 -1
  13. package/dist/{chunk-LHZYI23D.cjs → chunk-UXDWRC5Y.cjs} +63 -50
  14. package/dist/chunk-UXDWRC5Y.cjs.map +1 -0
  15. package/dist/components/chat/chat-message-list.d.ts.map +1 -1
  16. package/dist/components/chat/index.cjs +12 -2
  17. package/dist/components/chat/index.cjs.map +1 -1
  18. package/dist/components/chat/index.js +11 -1
  19. package/dist/components/chat/utils/history-merge.d.ts +92 -0
  20. package/dist/components/chat/utils/history-merge.d.ts.map +1 -0
  21. package/dist/components/chat/utils/index.d.ts +1 -0
  22. package/dist/components/chat/utils/index.d.ts.map +1 -1
  23. package/dist/components/contact/index.cjs +3 -3
  24. package/dist/components/contact/index.js +2 -2
  25. package/dist/components/features/index.cjs +2 -2
  26. package/dist/components/features/index.js +1 -1
  27. package/dist/components/features/policy-configuration-panel.d.ts.map +1 -1
  28. package/dist/components/index.cjs +59 -49
  29. package/dist/components/index.cjs.map +1 -1
  30. package/dist/components/index.js +13 -3
  31. package/dist/components/index.js.map +1 -1
  32. package/dist/components/navigation/index.cjs +2 -2
  33. package/dist/components/navigation/index.js +1 -1
  34. package/dist/components/related-content/index.cjs +3 -3
  35. package/dist/components/related-content/index.js +2 -2
  36. package/dist/components/related-content/related-content-section.d.ts.map +1 -1
  37. package/dist/components/tickets/index.cjs +55 -55
  38. package/dist/components/tickets/index.js +3 -3
  39. package/dist/components/ui/index.cjs +12 -2
  40. package/dist/components/ui/index.cjs.map +1 -1
  41. package/dist/components/ui/index.js +11 -1
  42. package/dist/index.cjs +12 -2
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.js +11 -1
  45. package/package.json +1 -1
  46. package/src/components/chat/__tests__/chat-message-list.test.tsx +92 -0
  47. package/src/components/chat/chat-message-list.tsx +74 -49
  48. package/src/components/chat/utils/__tests__/history-merge.test.ts +339 -0
  49. package/src/components/chat/utils/history-merge.ts +255 -0
  50. package/src/components/chat/utils/index.ts +12 -0
  51. package/src/components/features/policy-configuration-panel.tsx +1 -0
  52. package/src/components/related-content/related-content-section.tsx +59 -33
  53. package/dist/chunk-4EED3YEI.cjs.map +0 -1
  54. package/dist/chunk-LHZYI23D.cjs.map +0 -1
  55. package/dist/chunk-PCXI7ZB2.js.map +0 -1
  56. package/dist/chunk-VAKBNCV6.js.map +0 -1
  57. /package/dist/{chunk-5ZVPKTXM.js.map → chunk-DZJ53RX6.js.map} +0 -0
  58. /package/dist/{chunk-PVAYXHYF.js.map → chunk-PSG7H4KG.js.map} +0 -0
@@ -21,10 +21,11 @@ import {
21
21
  buildListUrl,
22
22
  buildProductReleaseCardProps,
23
23
  canonicalContentRefType,
24
+ extractItemId,
24
25
  extractItems,
25
26
  getContentRefLabelOrTitleCase,
26
27
  orderContentRefTypes
27
- } from "./chunk-PCXI7ZB2.js";
28
+ } from "./chunk-D2BC3NZ2.js";
28
29
  import {
29
30
  buildSuggestionUrl
30
31
  } from "./chunk-VAUI3CND.js";
@@ -171,7 +172,8 @@ function ContentGroup({
171
172
  resolveHref,
172
173
  LinkProvider,
173
174
  extras,
174
- adminCampaignCard
175
+ adminCampaignCard,
176
+ heading
175
177
  }) {
176
178
  const { items, isLoading } = useGroupItems(type, refs, buildUrl);
177
179
  const config = resolveGroupConfig(type);
@@ -179,10 +181,15 @@ function ContentGroup({
179
181
  const cardSize = config.gridSize;
180
182
  if (isLoading && !items) {
181
183
  const skeletons = refs.map((r) => /* @__PURE__ */ jsx("div", { children: renderSkeletonForType(type, cardSize, adminCampaignCard) }, r.id));
182
- return isListLayout ? /* @__PURE__ */ jsx("div", { className: "space-y-4", children: skeletons }) : /* @__PURE__ */ jsx("div", { className: gridClassFor(columns), children: skeletons });
184
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
185
+ heading,
186
+ isListLayout ? /* @__PURE__ */ jsx("div", { className: "space-y-4", children: skeletons }) : /* @__PURE__ */ jsx("div", { className: gridClassFor(columns), children: skeletons })
187
+ ] });
183
188
  }
184
189
  if (!items || items.length === 0) return null;
185
- const itemById = new Map(items.map((it) => [String(it.id), it]));
190
+ const itemById = new Map(
191
+ items.map((it) => [extractItemId(type, it) ?? String(it?.id), it])
192
+ );
186
193
  const cards = refs.map((contentRef) => {
187
194
  const itemId = String(contentRef.id);
188
195
  const item = itemById.get(itemId);
@@ -195,7 +202,6 @@ function ContentGroup({
195
202
  {
196
203
  type,
197
204
  item,
198
- contentRef,
199
205
  size: cardSize,
200
206
  href,
201
207
  targetPlatform,
@@ -206,7 +212,10 @@ function ContentGroup({
206
212
  ) }) }, itemId);
207
213
  }).filter(Boolean);
208
214
  if (cards.length === 0) return null;
209
- return isListLayout ? /* @__PURE__ */ jsx("div", { className: "space-y-4", children: cards }) : /* @__PURE__ */ jsx("div", { className: gridClassFor(columns), children: cards });
215
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
216
+ heading,
217
+ isListLayout ? /* @__PURE__ */ jsx("div", { className: "space-y-4", children: cards }) : /* @__PURE__ */ jsx("div", { className: gridClassFor(columns), children: cards })
218
+ ] });
210
219
  }
211
220
  function RelatedContentSection({
212
221
  contentRefs,
@@ -226,7 +235,8 @@ function RelatedContentSection({
226
235
  LinkProvider = DefaultLinkPropsProvider,
227
236
  adminCampaignCard
228
237
  }) {
229
- const suggestUrl = contentRefs === void 0 && entityType && entityId !== void 0 && entityId !== null && entityId !== "" && includeTypes?.length !== 0 ? buildSuggestionUrl("/api/related-content", {
238
+ const suggestionsDisabled = includeTypes?.length === 0;
239
+ const suggestUrl = contentRefs === void 0 && entityType && entityId !== void 0 && entityId !== null && entityId !== "" && !suggestionsDisabled ? buildSuggestionUrl("/api/related-content", {
230
240
  apiBaseUrl,
231
241
  entityType,
232
242
  entityId,
@@ -238,8 +248,11 @@ function RelatedContentSection({
238
248
  }
239
249
  }) : null;
240
250
  const initialData = useMemo(
241
- () => initialItems ? { refs: initialItems } : void 0,
242
- [initialItems]
251
+ // An explicitly disabled rail (includeTypes: []) must ignore SSR-hydrated
252
+ // refs too — otherwise useSelfFetch(null, {initialData}) keeps serving
253
+ // initialItems and the "nothing participates" contract silently breaks.
254
+ () => !suggestionsDisabled && initialItems ? { refs: initialItems } : void 0,
255
+ [initialItems, suggestionsDisabled]
243
256
  );
244
257
  const { data } = useSelfFetch(suggestUrl, { initialData });
245
258
  const effectiveBuildListUrl = useMemo(
@@ -257,33 +270,33 @@ function RelatedContentSection({
257
270
  }
258
271
  let orderedTypes = orderContentRefTypes(Object.keys(grouped));
259
272
  if (entityType) {
260
- const sameType = orderedTypes.filter((t) => canonicalContentRefType(t) === entityType);
273
+ const canonicalEntityType = canonicalContentRefType(entityType);
274
+ const sameType = orderedTypes.filter((t) => canonicalContentRefType(t) === canonicalEntityType);
261
275
  if (sameType.length > 0) {
262
- orderedTypes = [...sameType, ...orderedTypes.filter((t) => canonicalContentRefType(t) !== entityType)];
276
+ orderedTypes = [...sameType, ...orderedTypes.filter((t) => canonicalContentRefType(t) !== canonicalEntityType)];
263
277
  }
264
278
  }
265
279
  return /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
266
280
  /* @__PURE__ */ jsx("h2", { className: "text-2xl font-bold text-ods-text-primary", children: title }),
267
- orderedTypes.map((type) => /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
268
- /* @__PURE__ */ jsx("h3", { className: "font-['Azeret_Mono'] text-[14px] font-semibold uppercase text-ods-text-secondary tracking-wider", children: getContentRefLabelOrTitleCase(type) }),
269
- /* @__PURE__ */ jsx(
270
- ContentGroup,
271
- {
272
- type,
273
- refs: grouped[type],
274
- columns,
275
- buildUrl: effectiveBuildListUrl,
276
- resolveHref,
277
- LinkProvider,
278
- extras,
279
- adminCampaignCard
280
- }
281
- )
282
- ] }, type))
281
+ orderedTypes.map((type) => /* @__PURE__ */ jsx(
282
+ ContentGroup,
283
+ {
284
+ type,
285
+ refs: grouped[type],
286
+ columns,
287
+ buildUrl: effectiveBuildListUrl,
288
+ resolveHref,
289
+ LinkProvider,
290
+ extras,
291
+ adminCampaignCard,
292
+ heading: /* @__PURE__ */ jsx("h3", { className: "font-['Azeret_Mono'] text-[14px] font-semibold uppercase text-ods-text-secondary tracking-wider", children: getContentRefLabelOrTitleCase(type) })
293
+ },
294
+ type
295
+ ))
283
296
  ] });
284
297
  }
285
298
 
286
299
  export {
287
300
  RelatedContentSection
288
301
  };
289
- //# sourceMappingURL=chunk-VAKBNCV6.js.map
302
+ //# sourceMappingURL=chunk-4AVACC2J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/related-content/related-content-section.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * RelatedContentSection\n *\n * Renders content references grouped by type using the canonical card\n * components. MOVED from the hub (`components/shared/related-content-card.tsx`)\n * so any consuming app can embed it; the hub keeps a thin wrapper that\n * pre-binds its host-specific injections (nav hook, URL recomposition,\n * program configs, admin campaign card).\n *\n * THREE data modes (precedence top-down):\n * 1. CONTROLLED — `contentRefs` provided (even `[]`): render exactly those\n * refs, no suggestion fetch (the original investor-update behavior).\n * 2. SUGGESTION — `entityType` + `entityId` provided: self-fetch\n * `GET {apiBaseUrl}/api/related-content?entityType&entityId[&count][&excludeTypes]`\n * (the generic 5-tier engine's second web service). `minResults` maps to\n * `count`; absent → param not sent (server default applies). Each ref\n * carries a `reason` (data-only — never rendered, matching the\n * FaqSection/FaqWithReason precedent).\n * 3. SSR-HYDRATED suggestion — also pass `initialItems` (the server page\n * called the engine directly); the first client fetch is skipped per the\n * `useSelfFetch` initialData contract.\n *\n * Group layout (list vs grid) + card size (lg vs default) come from\n * `CONTENT_REF_GROUPS` in `../../utils/content-ref-groups` — single source of\n * truth, no per-type logic in this file. Skeletons come from\n * `renderSkeletonForType` so the placeholder height matches the loaded card\n * exactly (zero layout shift on resolve).\n *\n * One API call per content type via the shared list-URL builder\n * (`buildListUrl` — injectable; defaults to the lib's byte-parity-tested\n * builder prefixed with `apiBaseUrl`). Fetching uses `useSelfFetch` (plain\n * fetch, NO react-query) so third-party embedders need no QueryClientProvider;\n * cards are imported via DEEP module paths (not the chat barrel) so this\n * chunk never reaches `@tanstack/react-query`.\n *\n * LOCKSTEP NOTE: this file's per-type card/skeleton dispatch is the SIZED\n * sibling of the chat-side `CHAT_CARD_REGISTRY` (`../chat/entity-cards/\n * dispatch.tsx`), which renders compact `size='sm'` cards wired to the chat\n * runtime. Two dispatchers by design — when registering a new fetch-mode\n * content type, add it BOTH there and here (cards + skeleton + list URL).\n */\n\nimport React, { useMemo } from 'react';\nimport {\n CONTENT_REF_GROUPS,\n getContentRefLabelOrTitleCase,\n orderContentRefTypes,\n type ContentRefGroupConfig,\n} from '../../utils/content-ref-groups';\nimport type { ContentRef, ContentRefWithReason } from '../../types/content-ref';\nimport { useSelfFetch } from '../../hooks/use-self-fetch';\nimport { extractItems, extractItemId } from '../../utils/extract-items';\nimport { buildListUrl as libBuildListUrl, canonicalContentRefType } from '../../utils/list-url';\nimport { buildSuggestionUrl } from '../../utils/suggestion-url';\nimport { decideNewTab } from '../chat/utils/decide-new-tab';\n// DEEP card imports — NOT the `../chat` barrel (the barrel statically reaches\n// @tanstack/react-query via embeddable-chat + its hooks). Deep paths keep this\n// component's SOURCE graph react-query-free. Note: tsup's shared-chunk\n// splitting may still colocate the cards with chat hooks in one dist chunk\n// (react-query is a required peerDep, so resolution always succeeds) — the\n// guarantee that matters here is the RUNTIME one: nothing on this path ever\n// instantiates a QueryClient, so embedders need NO QueryClientProvider.\nimport { BlogCard, BlogCardSkeleton } from '../chat/entity-cards/blog-card';\nimport { CaseStudyCard, CaseStudyCardSkeleton } from '../chat/entity-cards/case-study-card';\nimport { CustomerInterviewCard, CustomerInterviewCardSkeleton } from '../chat/entity-cards/customer-interview-card';\nimport { ProductReleaseCard, ProductReleaseCardSkeleton } from '../chat/entity-cards/product-release-card';\nimport { buildProductReleaseCardProps } from '../chat/entity-cards/product-release-card-defaults';\nimport { ProgramCard, ProgramCardSkeleton } from '../chat/entity-cards/program-card';\nimport { InvestorUpdateCard, InvestorUpdateCardSkeleton } from '../chat/entity-cards/investor-update-card';\nimport { OnboardingGuideCard, OnboardingGuideCardSkeleton } from '../chat/entity-cards/onboarding-guide-card';\nimport { RoadmapCard, RoadmapCardSkeleton } from '../chat/entity-cards/roadmap-card';\n// Type-only — erased at build, no runtime dependency on the dispatch module.\nimport type { ChatCardDispatchExtras } from '../chat/entity-cards/dispatch';\n\ntype CardSize = 'lg' | 'default' | 'sm';\n\n/** Anchor prop bundle the per-card link surface receives — same shape the\n * hub's `useNavLink` returns and the chat dispatcher's anchor builders\n * produce. `null` = non-anchor mode (no URL). */\nexport interface CardLinkAnchorProps {\n href: string;\n target?: '_blank';\n rel?: 'noopener noreferrer';\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n}\n\n/** Render-prop component injection for the navigation decision — keeps hook\n * calls legal (hooks live INSIDE the injected component; `CardForType`\n * itself calls zero hooks). The hub injects a `useNavLink`-backed provider;\n * the default is hook-free (pure `decideNewTab`). MUST be defined at module\n * scope by hosts — an inline arrow would remount every card each render. */\nexport interface CardLinkProviderProps {\n href: string | null;\n targetPlatform: string | null;\n children: (linkProps: CardLinkAnchorProps | null) => React.ReactElement | null;\n}\nexport type CardLinkProvider = React.ComponentType<CardLinkProviderProps>;\n\n/** Default link provider for standalone embeds: relative/-same-origin hrefs\n * stay same-tab, cross-origin pops a new tab (pure `decideNewTab` with no\n * platform context — `currentSource: ''` falls through to the origin\n * check). No router integration, no hooks. */\nfunction DefaultLinkPropsProvider({ href, targetPlatform, children }: CardLinkProviderProps): React.ReactElement | null {\n if (!href) return children(null);\n const newTab = decideNewTab({ href, targetPlatform, currentSource: '' });\n return children(\n newTab\n ? { href, target: '_blank', rel: 'noopener noreferrer' }\n : { href },\n );\n}\n\n/** Default href resolution: trust the ref's stored url/targetPlatform as the\n * API composed them. The hub overrides this with its `buildContentURL`\n * re-composition so dev gets localhost and prod gets platform domains. */\nfunction defaultResolveHref(ref: ContentRef): { href: string | null; targetPlatform: string | null } {\n return { href: ref.url || null, targetPlatform: ref.targetPlatform ?? null };\n}\n\n/** Host-injected renderer pair for the admin-only `marketing_campaign` type.\n * Absent (every non-hub embed) → the type renders nothing (its list URL\n * hits `/api/admin`, unreachable outside the hub anyway). */\nexport interface AdminCampaignCardSlot {\n Card: React.ComponentType<{ campaign: any }>;\n Skeleton: React.ComponentType<{ size?: 'default' | 'sm' }>;\n}\n\n/**\n * Per-type skeleton dispatch — returns the SAME colocated skeleton the\n * resolved card renders, sized to match (zero layout shift on resolve).\n * The chat-side `CHAT_CARD_REGISTRY` already does this via\n * `entry.skeleton()`; this surface exposes the same discipline to the\n * related-content rail.\n */\nfunction renderSkeletonForType(\n type: string,\n size: CardSize,\n adminCampaignCard?: AdminCampaignCardSlot,\n): React.ReactNode {\n // Most card skeletons accept only `{default, sm}`. `'lg'` collapses to\n // `'default'`. ProductReleaseCardSkeleton uses lg/sm pair.\n const legacySize: 'default' | 'sm' = size === 'sm' ? 'sm' : 'default';\n switch (type) {\n case 'blog_post_existing':\n return <BlogCardSkeleton size={legacySize} />;\n case 'case_study':\n return <CaseStudyCardSkeleton size={legacySize} />;\n case 'customer_interview':\n return <CustomerInterviewCardSkeleton size={legacySize} />;\n case 'product_release':\n return <ProductReleaseCardSkeleton size={size === 'sm' ? 'sm' : 'lg'} />;\n case 'podcast':\n case 'webinar':\n case 'event':\n return <ProgramCardSkeleton size={legacySize} />;\n case 'investor_update':\n return <InvestorUpdateCardSkeleton size={legacySize} />;\n case 'onboarding_guide':\n // The rich catalog variant (hero + author grid, clamped description) —\n // the step-numbered 'default' variant is for the guide detail page's\n // \"More in section\" rail, not this full-width row.\n return <OnboardingGuideCardSkeleton size={size === 'sm' ? 'sm' : 'catalog'} />;\n case 'marketing_campaign':\n return adminCampaignCard ? <adminCampaignCard.Skeleton size={legacySize} /> : null;\n case 'roadmap_item':\n case 'delivery_item':\n case 'internal_task':\n return <RoadmapCardSkeleton size={legacySize} />;\n default:\n return null;\n }\n}\n\n/**\n * Per-type card dispatch — renders the right card with the right size.\n * Sized cards (`'lg'` / `'default'`) are unique to this rail — the chat\n * dispatcher only renders `'sm'`, so we go directly through the per-type\n * cards here.\n *\n * PURE FUNCTION COMPONENT WITH ZERO HOOK CALLS: the placeholder comes from a\n * plain `extras.buildOgPlaceholderUrl` call (the chat `dispatch.tsx`\n * pattern) and the anchor-prop bundle arrives via the `LinkProvider`\n * render-prop from the parent — so per-card hook legality is owned by the\n * injected provider component, not by this switch.\n *\n * `href` comes from the host's `resolveHref(ref)` (hub: live\n * `buildContentURL` recomposition; default: the ref's stored url).\n */\nfunction CardForType({\n type,\n item,\n size,\n href,\n targetPlatform,\n linkProps,\n extras,\n adminCampaignCard,\n}: {\n type: string;\n item: any;\n size: CardSize;\n href: string;\n targetPlatform: string | null;\n linkProps: CardLinkAnchorProps | null;\n extras?: ChatCardDispatchExtras;\n adminCampaignCard?: AdminCampaignCardSlot;\n}): React.ReactNode {\n // Most card variants accept only `{default, sm}`. `'lg'` collapses to\n // `'default'` for those. ProductReleaseCard uses its own lg/sm pair.\n const legacySize: 'default' | 'sm' = size === 'sm' ? 'sm' : 'default';\n // OG placeholder URL — injected into the pure-presentation cards so they\n // render a branded fallback when the row's featured image is null. Plain\n // function call (NOT a hook). Title is the universal field across all card\n // item shapes used here.\n const placeholderUrl =\n extras?.buildOgPlaceholderUrl?.((item?.title as string | undefined) ?? '') ?? undefined;\n\n // Top-level target/rel for cards that take them as separate props\n // (BlogCard, CaseStudyCard, …). ProductReleaseCard takes the bundle as a\n // single `anchorProps={...}` and uses `linkProps` directly. When the host\n // didn't surface a URL, `linkProps` is null and the card stays in\n // non-anchor mode.\n const anchorAttrs: Pick<CardLinkAnchorProps, 'target' | 'rel'> = linkProps\n ? { target: linkProps.target, rel: linkProps.rel }\n : {};\n\n switch (type) {\n case 'blog_post_existing':\n return <BlogCard post={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />;\n case 'case_study':\n return <CaseStudyCard study={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />;\n case 'customer_interview':\n return <CustomerInterviewCard interview={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />;\n case 'product_release': {\n // Anchor-prop pattern: build product-release lg-variant props from the\n // shared `buildProductReleaseCardProps` so this rail and the /releases\n // catalog page render byte-identically. The card wraps in\n // `<a {...anchorProps}>` ONLY when `anchorProps.href` is set — pass\n // `undefined` (not an empty object) when href is empty so the card\n // stays in non-anchor mode without rendering a dead <a> tag.\n const releaseSize = size === 'sm' ? 'sm' : 'lg';\n const buildReleaseProps = extras?.buildProductReleaseCardProps ?? buildProductReleaseCardProps;\n const releaseProps = buildReleaseProps(item);\n return (\n <ProductReleaseCard\n size={releaseSize}\n title={item.title}\n summary={item.summary}\n version={item.version}\n {...releaseProps}\n anchorProps={linkProps ?? undefined}\n />\n );\n }\n case 'podcast':\n return extras?.programConfigs?.podcast\n ? <ProgramCard config={extras.programConfigs.podcast} item={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />\n : null;\n case 'webinar':\n return extras?.programConfigs?.webinar\n ? <ProgramCard config={extras.programConfigs.webinar} item={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />\n : null;\n case 'event':\n return extras?.programConfigs?.event\n ? <ProgramCard config={extras.programConfigs.event} item={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />\n : null;\n case 'investor_update':\n return <InvestorUpdateCard update={item} size={legacySize} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />;\n case 'onboarding_guide':\n // Catalog variant (see skeleton note) — full-width rich card with a\n // line-clamped description instead of the step-numbered rail card.\n return <OnboardingGuideCard guide={item} size={size === 'sm' ? 'sm' : 'catalog'} href={href} targetPlatform={targetPlatform} placeholderUrl={placeholderUrl} {...anchorAttrs} />;\n case 'marketing_campaign':\n return adminCampaignCard ? <adminCampaignCard.Card campaign={item} /> : null;\n case 'roadmap_item':\n case 'delivery_item':\n case 'internal_task':\n return (\n <RoadmapCard\n item={item}\n href={href ?? ''}\n targetPlatform={targetPlatform}\n userVote={null}\n onVote={() => {}}\n size={legacySize}\n cardType={type as 'roadmap_item' | 'delivery_item' | 'internal_task'}\n {...anchorAttrs}\n />\n );\n default:\n return null;\n }\n}\n\n// =============================================================================\n// Fetch all items for a type in ONE server-sorted call, via the injectable\n// list-URL builder. `useSelfFetch` (URL = cache key) replaces the hub's old\n// react-query usage: `enabled` ≙ `url === null`, `!res.ok`/network error ≙\n// `error → items null → group renders nothing`. Accepted deltas vs\n// react-query: no retry/backoff, no focus refetch, no cross-mount cache.\n// =============================================================================\n\nfunction useGroupItems(\n type: string,\n refs: ContentRef[],\n buildUrl: (type: string, ids: string[]) => string | null,\n) {\n const ids = refs.map((r) => r.id);\n const url = ids.length > 0 ? buildUrl(type, ids) : null;\n const { data, isLoading } = useSelfFetch<unknown>(url);\n const items = data != null ? extractItems(data) : null;\n return { items, isLoading };\n}\n\n// =============================================================================\n// Per-group renderer — one API call, server-sorted, then render cards via the\n// dispatcher with per-type skeletons + per-type layout from CONTENT_REF_GROUPS.\n// =============================================================================\n\n/** Map columns prop → tailwind grid class. Only consulted for grid-layout\n * groups; list-layout groups stack vertically. */\nfunction gridClassFor(columns: 2 | 3): string {\n return columns === 3\n ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6'\n : 'grid grid-cols-1 sm:grid-cols-2 gap-6';\n}\n\n/** Resolve the group config for a type, falling back to a grid layout with\n * the default card size for unregistered types so the section still renders\n * rather than silently dropping them. The `label` field on the fallback is\n * intentionally a placeholder — the section heading goes through\n * `getContentRefLabelOrTitleCase(type)` instead so cross-surface labels\n * stay consistent between this rail and the investor-email builder. */\nfunction resolveGroupConfig(type: string): ContentRefGroupConfig {\n return CONTENT_REF_GROUPS[type] ?? {\n label: type,\n order: 999,\n layout: 'grid',\n gridSize: 'default',\n };\n}\n\nfunction ContentGroup({\n type,\n refs,\n columns,\n buildUrl,\n resolveHref,\n LinkProvider,\n extras,\n adminCampaignCard,\n heading,\n}: {\n type: string;\n refs: ContentRef[];\n columns: 2 | 3;\n buildUrl: (type: string, ids: string[]) => string | null;\n resolveHref: (ref: ContentRef) => { href: string | null; targetPlatform: string | null };\n LinkProvider: CardLinkProvider;\n extras?: ChatCardDispatchExtras;\n adminCampaignCard?: AdminCampaignCardSlot;\n /** Group heading, rendered INSIDE the group so a group that resolves to\n * nothing (fetch miss / unsupported type / missing program config) drops\n * its heading too — no orphaned titles. */\n heading: React.ReactNode;\n}) {\n const { items, isLoading } = useGroupItems(type, refs, buildUrl);\n const config = resolveGroupConfig(type);\n const isListLayout = config.layout === 'list';\n const cardSize = config.gridSize;\n\n // Skeleton gate: `isLoading && !items` — SSR HTML and the client's first\n // paint render identical skeletons (useSelfFetch starts isLoading=true on\n // both sides), and once items exist they are never replaced by skeletons.\n if (isLoading && !items) {\n const skeletons = refs.map((r) => (\n <div key={r.id}>{renderSkeletonForType(type, cardSize, adminCampaignCard)}</div>\n ));\n return (\n <div className=\"space-y-4\">\n {heading}\n {isListLayout ? (\n <div className=\"space-y-4\">{skeletons}</div>\n ) : (\n <div className={gridClassFor(columns)}>{skeletons}</div>\n )}\n </div>\n );\n }\n\n if (!items || items.length === 0) return null;\n\n // Index fetched rows by id, then render in REF order — refs carry the\n // intended sequence (suggestion mode: the engine's tier order, so\n // same-platform/tag-matched items lead; controlled mode: the curated\n // display_order). The list APIs return rows date-sorted, which would\n // otherwise scramble that ordering (same-platform items sinking below\n // newer cross-platform ones).\n // Shared extractor (NOT raw `.id`) — some API shapes key items differently\n // (e.g. external_id types); raw access would silently drop valid items.\n const itemById = new Map(\n (items as any[]).map((it) => [extractItemId(type, it) ?? String((it as any)?.id), it]),\n );\n\n const cards = refs\n .map((contentRef) => {\n const itemId = String(contentRef.id);\n const item = itemById.get(itemId);\n if (!item) return null;\n // Re-compose the URL via the host's resolver (hub: buildContentURL so\n // dev gets localhost and prod the right platform domain; default: the\n // ref's stored url as the API composed it).\n const resolved = resolveHref(contentRef);\n const href = resolved.href ?? '';\n const targetPlatform = resolved.targetPlatform ?? contentRef.targetPlatform ?? null;\n return (\n <div key={itemId}>\n <LinkProvider href={href || null} targetPlatform={targetPlatform}>\n {(linkProps) => (\n <CardForType\n type={type}\n item={item}\n size={cardSize}\n href={href}\n targetPlatform={targetPlatform}\n linkProps={linkProps}\n extras={extras}\n adminCampaignCard={adminCampaignCard}\n />\n )}\n </LinkProvider>\n </div>\n );\n })\n .filter(Boolean);\n\n if (cards.length === 0) return null;\n\n return (\n <div className=\"space-y-4\">\n {heading}\n {isListLayout ? (\n <div className=\"space-y-4\">{cards}</div>\n ) : (\n <div className={gridClassFor(columns)}>{cards}</div>\n )}\n </div>\n );\n}\n\n// =============================================================================\n// Main component\n// =============================================================================\n\ninterface RelatedContentResponse {\n refs: ContentRefWithReason[];\n}\n\nexport interface RelatedContentSectionProps {\n /** CONTROLLED mode (the original behavior). When defined — even `[]` — no\n * suggestion fetch runs and exactly these refs render. */\n contentRefs?: ContentRef[];\n /** SUGGESTION mode (with `entityId`): self-fetch suggestions for this host\n * entity from `{apiBaseUrl}/api/related-content`. Ignored when\n * `contentRefs` is provided. */\n entityType?: string;\n entityId?: number | string;\n /** Maps to the suggestion API's `count` param — the PER-TYPE fill target\n * for every candidate type EXCEPT the host's own. Absent → param not sent\n * (server default applies). */\n minResults?: number;\n /** Maps to the suggestion API's `sameTypeCount` param — the budget for the\n * candidate type MATCHING the host's own `entityType` (same-type boost:\n * a blog post's rail leads with more blog posts). Absent → param not\n * sent (host's type uses the server's `count`). */\n sameTypeMinResults?: number;\n /** SSR hydrate for suggestion mode — the server page ran the engine and\n * drills the refs here; the first client fetch is skipped (useSelfFetch\n * initialData contract). */\n initialItems?: ContentRefWithReason[];\n /** Section title (default: \"Related Content\") */\n title?: string;\n /**\n * Grid columns at desktop. 2 = denser cards / wider summary (original\n * investor-update layout); 3 = more cards per row for dashboards.\n * Only consulted for grid-layout groups. Default: 2.\n */\n columns?: 2 | 3;\n /**\n * ContentRef.type values to exclude. Honored in ALL modes — controlled\n * mode post-filters (original behavior); suggestion mode ALSO forwards the\n * list verbatim as the API's `excludeTypes=` param so excluded types never\n * consume engine fill slots (`minResults` stays honored). The subtraction\n * happens SERVER-side — this component never mirrors the hub's candidate\n * list.\n */\n excludeTypes?: string[];\n /**\n * SUGGESTION-mode allow-list (rail vocabulary): which content types\n * participate in this rail. Sent verbatim as the API's `types=` param —\n * the SERVER intersects it with its own allowed candidate set, and\n * platform policy gates (e.g. internal-only types) ALWAYS win: the client\n * cannot request its way past them. Absent → all server-side candidates.\n */\n includeTypes?: string[];\n /** Fetch-URL prefix for third-party embeds / reverse proxies\n * ('' = same-origin). Applied to BOTH the suggestion fetch and the\n * default per-group list fetches. */\n apiBaseUrl?: string;\n /** Host injection bundle — REUSES the chat dispatcher's\n * `ChatCardDispatchExtras` (programConfigs, buildOgPlaceholderUrl,\n * buildProductReleaseCardProps override). Program groups render nothing\n * when their config is absent. */\n extras?: ChatCardDispatchExtras;\n /** Hub injects its `buildContentURL` recomposition; default uses the\n * ref's stored `url`/`targetPlatform` as the API composed them. */\n resolveHref?: (ref: ContentRef) => { href: string | null; targetPlatform: string | null };\n /** Hub injects its registry-driven entity-list-api builder; default = the\n * lib's `buildListUrl(type, ids, apiBaseUrl)`. */\n buildListUrl?: (type: string, ids: string[]) => string | null;\n /** Hub injects a `useNavLink`-backed render-prop provider; default = pure\n * anchor via `decideNewTab`. MUST be a module-scope component. */\n LinkProvider?: CardLinkProvider;\n /** Renderer pair for the admin-only `marketing_campaign` type. Absent →\n * the type renders nothing. */\n adminCampaignCard?: AdminCampaignCardSlot;\n}\n\nexport function RelatedContentSection({\n contentRefs,\n entityType,\n entityId,\n minResults,\n sameTypeMinResults,\n includeTypes,\n initialItems,\n title = 'Related Content',\n columns = 2,\n excludeTypes,\n apiBaseUrl = '',\n extras,\n resolveHref = defaultResolveHref,\n buildListUrl,\n LinkProvider = DefaultLinkPropsProvider,\n adminCampaignCard,\n}: RelatedContentSectionProps) {\n // ── Hooks above EVERY early return (the original `if (!contentRefs.length)\n // return null` guard moved below them). ──\n\n // Suggestion-mode fetch URL — null in controlled mode (contentRefs defined,\n // even []) or when the entity scope is incomplete.\n // `includeTypes: []` is an explicit \"nothing participates\" — skip the fetch\n // entirely (an empty-string `types=` param would be dropped by the URL\n // builder and read server-side as \"all candidates\") AND ignore SSR refs.\n const suggestionsDisabled = includeTypes?.length === 0;\n const suggestUrl =\n contentRefs === undefined &&\n entityType &&\n entityId !== undefined &&\n entityId !== null &&\n entityId !== '' &&\n !suggestionsDisabled\n ? buildSuggestionUrl('/api/related-content', {\n apiBaseUrl,\n entityType,\n entityId,\n count: minResults,\n extraParams: {\n sameTypeCount: sameTypeMinResults !== undefined ? String(sameTypeMinResults) : undefined,\n types: includeTypes !== undefined ? includeTypes.join(',') : undefined,\n excludeTypes: excludeTypes && excludeTypes.length > 0 ? excludeTypes.join(',') : undefined,\n },\n })\n : null;\n // Memoize the initialData wrapper — useSelfFetch re-syncs on [initialData],\n // and a fresh per-render object would loop setState under re-rendering\n // parents (the latent FaqSection bug, fixed there in the same change).\n const initialData = useMemo<RelatedContentResponse | undefined>(\n // An explicitly disabled rail (includeTypes: []) must ignore SSR-hydrated\n // refs too — otherwise useSelfFetch(null, {initialData}) keeps serving\n // initialItems and the \"nothing participates\" contract silently breaks.\n () => (!suggestionsDisabled && initialItems ? { refs: initialItems } : undefined),\n [initialItems, suggestionsDisabled],\n );\n const { data } = useSelfFetch<RelatedContentResponse>(suggestUrl, { initialData });\n\n // Default group fetcher: the lib's byte-parity-tested builder, prefixed for\n // embeds. Memoized so group-fetch URLs stay value-stable across renders.\n const effectiveBuildListUrl = useMemo(\n () => buildListUrl ?? ((type: string, ids: string[]) => libBuildListUrl(type, ids, apiBaseUrl)),\n [buildListUrl, apiBaseUrl],\n );\n\n const refs: ContentRef[] = contentRefs ?? data?.refs ?? [];\n\n // Per-consumer type gating — drops refs whose `type` is in the exclude\n // list. In suggestion mode the server already subtracted these (the param\n // is forwarded above); the client filter stays as an idempotent guard and\n // IS the mechanism in controlled mode (original behavior).\n const exclude = new Set(excludeTypes || []);\n const visibleRefs = exclude.size > 0 ? refs.filter((r) => !exclude.has(r.type)) : refs;\n // Zero refs (still loading in suggestion mode, or genuinely empty) → no\n // empty shell.\n if (!visibleRefs.length) return null;\n\n const grouped: Record<string, ContentRef[]> = {};\n for (const ref of visibleRefs) {\n if (!grouped[ref.type]) grouped[ref.type] = [];\n grouped[ref.type].push(ref);\n }\n\n // Registered types in CONTENT_REF_GROUPS order, then any unregistered\n // types appended (same shape the investor-email builder uses — both\n // consume `orderContentRefTypes` so cross-surface ordering matches).\n // SAME-TYPE FIRST: when a host entityType is known (suggestion / SSR\n // modes), its own content-type group is hoisted to the top — a blog\n // post's rail leads with blog posts. Rail group keys are compared via\n // the shared alias canonicalizer (blog_post_existing ↔ blog_post).\n let orderedTypes = orderContentRefTypes(Object.keys(grouped));\n if (entityType) {\n // Canonicalize BOTH sides — hosts pass registry vocab ('blog_post') but\n // rail-vocab aliases ('blog_post_existing') are also legal inputs; a raw\n // comparison would silently lose the same-type-first hoist for aliases.\n const canonicalEntityType = canonicalContentRefType(entityType);\n const sameType = orderedTypes.filter((t) => canonicalContentRefType(t) === canonicalEntityType);\n if (sameType.length > 0) {\n orderedTypes = [...sameType, ...orderedTypes.filter((t) => canonicalContentRefType(t) !== canonicalEntityType)];\n }\n }\n\n return (\n <div className=\"space-y-8\">\n <h2 className=\"text-2xl font-bold text-ods-text-primary\">{title}</h2>\n {orderedTypes.map((type) => (\n <ContentGroup\n key={type}\n type={type}\n refs={grouped[type]}\n columns={columns}\n buildUrl={effectiveBuildListUrl}\n resolveHref={resolveHref}\n LinkProvider={LinkProvider}\n extras={extras}\n adminCampaignCard={adminCampaignCard}\n heading={\n <h3 className=\"font-['Azeret_Mono'] text-[14px] font-semibold uppercase text-ods-text-secondary tracking-wider\">\n {getContentRefLabelOrTitleCase(type)}\n </h3>\n }\n />\n ))}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,eAAe;AAsGlB,cA2OP,YA3OO;AA1Cb,SAAS,yBAAyB,EAAE,MAAM,gBAAgB,SAAS,GAAqD;AACtH,MAAI,CAAC,KAAM,QAAO,SAAS,IAAI;AAC/B,QAAM,SAAS,aAAa,EAAE,MAAM,gBAAgB,eAAe,GAAG,CAAC;AACvE,SAAO;AAAA,IACL,SACI,EAAE,MAAM,QAAQ,UAAU,KAAK,sBAAsB,IACrD,E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C,CAAC;AAC/C,aAAW,OAAO,aAAa;AAC7B,QAAI,CAAC,QAAQ,IAAI,IAAI,EAAG,SAAQ,IAAI,IAAI,IAAI,CAAC;AAC7C,YAAQ,IAAI,IAAI,EAAE,KAAK,GAAG;AAAA,EAC5B;AASA,MAAI,eAAe,qBAAqB,OAAO,KAAK,OAAO,CAAC;AAC5D,MAAI,YAAY;AAId,UAAM,sBAAsB,wBAAwB,UAAU;AAC9D,UAAM,WAAW,aAAa,OAAO,CAAC,MAAM,wBAAwB,CAAC,MAAM,mBAAmB;AAC9F,QAAI,SAAS,SAAS,GAAG;AACvB,qBAAe,CAAC,GAAG,UAAU,GAAG,aAAa,OAAO,CAAC,MAAM,wBAAwB,CAAC,MAAM,mBAAmB,CAAC;AAAA,IAChH;AAAA,EACF;AAEA,SACE,qBAAC,SAAI,WAAU,aACb;AAAA,wBAAC,QAAG,WAAU,4CAA4C,iBAAM;AAAA,IAC/D,aAAa,IAAI,CAAC,SACjB;AAAA,MAAC;AAAA;AAAA,QAEC;AAAA,QACA,MAAM,QAAQ,IAAI;AAAA,QAClB;AAAA,QACA,UAAU;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,SACE,oBAAC,QAAG,WAAU,mGACX,wCAA8B,IAAI,GACrC;AAAA;AAAA,MAZG;AAAA,IAcP,CACD;AAAA,KACH;AAEJ;","names":["buildListUrl"]}
@@ -2924,12 +2924,15 @@ var ChatMessageList = forwardRef12(
2924
2924
  onLoadMoreRef.current = onLoadMore;
2925
2925
  const isFetchingRef = useRef3(isFetchingNextPage);
2926
2926
  isFetchingRef.current = isFetchingNextPage;
2927
+ const dialogIdRef = useRef3(dialogId);
2928
+ dialogIdRef.current = dialogId;
2927
2929
  const prevRenderRef = useRef3({ dialogId: void 0, messageCount: 0, lastMessageId: void 0 });
2928
- const prependRef = useRef3({ firstMessageId: void 0, firstMessageContent: void 0, scrollHeight: 0 });
2930
+ const loadOlderAnchorRef = useRef3(null);
2929
2931
  useEffect3(() => {
2930
2932
  if (!autoScroll) return;
2931
2933
  const dialogChanged = dialogId !== prevRenderRef.current.dialogId;
2932
2934
  const prevCount = prevRenderRef.current.messageCount;
2935
+ const prevLastId = prevRenderRef.current.lastMessageId;
2933
2936
  const newCount = messages.length;
2934
2937
  const currentLastId = messages[messages.length - 1]?.id;
2935
2938
  prevRenderRef.current = { dialogId, messageCount: newCount, lastMessageId: currentLastId };
@@ -2942,7 +2945,8 @@ var ChatMessageList = forwardRef12(
2942
2945
  return;
2943
2946
  }
2944
2947
  if (newCount > prevCount) {
2945
- const newSlice = messages.slice(prevCount);
2948
+ const prevLastIdx = prevLastId ? messages.findIndex((m) => m.id === prevLastId) : -1;
2949
+ const newSlice = prevLastIdx >= 0 ? messages.slice(prevLastIdx + 1) : messages.slice(prevCount);
2946
2950
  const hasNewUser = newSlice.some((m) => m.role === "user");
2947
2951
  if (hasNewUser) {
2948
2952
  void scrollToBottom({ animation: "instant", ignoreEscapes: true });
@@ -2966,34 +2970,17 @@ var ChatMessageList = forwardRef12(
2966
2970
  }, [autoScroll, messages, dialogId, scrollToBottom, contentRef]);
2967
2971
  useLayoutEffect2(() => {
2968
2972
  const el = scrollRef.current;
2969
- if (!el) {
2970
- prependRef.current = { firstMessageId: void 0, firstMessageContent: void 0, scrollHeight: 0 };
2973
+ const anchor = loadOlderAnchorRef.current;
2974
+ if (!el || !anchor) return;
2975
+ if (anchor.dialogId !== dialogId) {
2976
+ loadOlderAnchorRef.current = null;
2971
2977
  return;
2972
2978
  }
2973
- const currentFirstId = messages[0]?.id;
2974
- const currentFirstContent = messages[0]?.content;
2975
- const prevFirstId = prependRef.current.firstMessageId;
2976
- const prevHeight = prependRef.current.scrollHeight;
2977
- if (currentFirstId !== prevFirstId) {
2978
- if (prevFirstId && prevHeight > 0) {
2979
- const prevIdx = messages.findIndex((m) => m.id === prevFirstId);
2980
- if (prevIdx > 0) {
2981
- const addedHeight = el.scrollHeight - prevHeight;
2982
- if (addedHeight > 0) el.scrollTop += addedHeight;
2983
- }
2984
- }
2985
- prependRef.current = {
2986
- firstMessageId: currentFirstId,
2987
- firstMessageContent: currentFirstContent,
2988
- scrollHeight: el.scrollHeight
2989
- };
2990
- return;
2991
- }
2992
- prependRef.current.scrollHeight = el.scrollHeight;
2993
- if (currentFirstContent !== prependRef.current.firstMessageContent) {
2994
- prependRef.current.firstMessageContent = currentFirstContent;
2995
- }
2996
- }, [messages, scrollRef]);
2979
+ const addedHeight = el.scrollHeight - anchor.scrollHeight;
2980
+ if (addedHeight <= 0) return;
2981
+ loadOlderAnchorRef.current = null;
2982
+ el.scrollTop = anchor.scrollTop + addedHeight;
2983
+ }, [messages, dialogId, scrollRef]);
2997
2984
  const messageElsRef = useRef3(/* @__PURE__ */ new Map());
2998
2985
  const refCallbacksRef = useRef3(/* @__PURE__ */ new Map());
2999
2986
  const getRegisterMessageEl = (id) => {
@@ -3065,6 +3052,14 @@ var ChatMessageList = forwardRef12(
3065
3052
  const entry = entries[0];
3066
3053
  if (!entry) return;
3067
3054
  if (entry.isIntersecting && !isFetchingRef.current) {
3055
+ const el = scrollRef.current;
3056
+ if (el) {
3057
+ loadOlderAnchorRef.current = {
3058
+ dialogId: dialogIdRef.current,
3059
+ scrollHeight: el.scrollHeight,
3060
+ scrollTop: el.scrollTop
3061
+ };
3062
+ }
3068
3063
  onLoadMoreRef.current?.();
3069
3064
  }
3070
3065
  },
@@ -3072,7 +3067,7 @@ var ChatMessageList = forwardRef12(
3072
3067
  );
3073
3068
  observer.observe(sentinelElement);
3074
3069
  return () => observer.disconnect();
3075
- }, [hasNextPage, scrollRef]);
3070
+ }, [hasNextPage, isFetchingNextPage, scrollRef]);
3076
3071
  useImperativeHandle2(ref, () => scrollRef.current, [scrollRef]);
3077
3072
  if (isLoading) {
3078
3073
  return /* @__PURE__ */ jsx22(
@@ -20247,6 +20242,7 @@ var CategorySection = ({
20247
20242
  /* @__PURE__ */ jsx175(
20248
20243
  Button,
20249
20244
  {
20245
+ type: "button",
20250
20246
  variant: "transparent",
20251
20247
  onClick: (e) => {
20252
20248
  e.stopPropagation();
@@ -37808,6 +37804,110 @@ function extractIncompleteMessageState(lastMessage) {
37808
37804
  };
37809
37805
  }
37810
37806
 
37807
+ // src/components/chat/utils/history-merge.ts
37808
+ var SYNTHETIC_REALTIME_ID_PREFIXES = ["assistant-", "user-", "error-"];
37809
+ function isSyntheticRealtimeId(id) {
37810
+ return SYNTHETIC_REALTIME_ID_PREFIXES.some((prefix) => id.startsWith(prefix));
37811
+ }
37812
+ function flattenMessagePagesChronological(pages) {
37813
+ if (!pages) return [];
37814
+ return [...pages].reverse().flatMap((page) => [...page.messages].reverse());
37815
+ }
37816
+ function maxPersistedStreamSeq(pages) {
37817
+ let max = 0;
37818
+ if (!pages) return max;
37819
+ for (const page of pages) {
37820
+ for (const msg of page.messages) {
37821
+ const seq = msg.lastChunkStreamSeq;
37822
+ if (typeof seq === "number" && seq > max) max = seq;
37823
+ }
37824
+ }
37825
+ return max;
37826
+ }
37827
+ function mergeHistoryWithRealtime(input) {
37828
+ const {
37829
+ processedHistory,
37830
+ rawHistoryIds,
37831
+ existingMessages,
37832
+ streamingMessageId,
37833
+ historyFetchedAt,
37834
+ historyMaxStreamSeq = 0,
37835
+ realtimeSeenStreamSeq = 0
37836
+ } = input;
37837
+ if (processedHistory.length === 0) return existingMessages;
37838
+ const processedIds = new Set(processedHistory.map((m) => m.id));
37839
+ const seqCoverageKnown = realtimeSeenStreamSeq > 0 && historyMaxStreamSeq > 0;
37840
+ const historyCoversRealtime = seqCoverageKnown ? historyMaxStreamSeq >= realtimeSeenStreamSeq : null;
37841
+ const trailing = processedHistory[processedHistory.length - 1];
37842
+ const historyTrailingAssistant = trailing?.role === "assistant" ? trailing : null;
37843
+ const historyBatchId = historyTrailingAssistant && Array.isArray(historyTrailingAssistant.content) ? historyTrailingAssistant.content.find((s) => s.type === "approval_batch")?.data?.approvalRequestId ?? null : null;
37844
+ let processedToUse = processedHistory;
37845
+ const pinnedSyntheticIds = /* @__PURE__ */ new Set();
37846
+ const droppedSyntheticIds = /* @__PURE__ */ new Set();
37847
+ if (historyBatchId) {
37848
+ const batchTwins = existingMessages.filter(
37849
+ (m) => m.role === "assistant" && Array.isArray(m.content) && m.content.some(
37850
+ (s) => s.type === "approval_batch" && s.data?.approvalRequestId === historyBatchId
37851
+ )
37852
+ );
37853
+ const existingWithSameBatch = batchTwins.find((m) => m.id === streamingMessageId) ?? batchTwins[batchTwins.length - 1];
37854
+ if (existingWithSameBatch && Array.isArray(existingWithSameBatch.content)) {
37855
+ const histSize = Array.isArray(historyTrailingAssistant?.content) ? historyTrailingAssistant.content.length : 0;
37856
+ const realtimeSize = existingWithSameBatch.content.length;
37857
+ if (existingWithSameBatch.id === streamingMessageId || realtimeSize > histSize) {
37858
+ processedToUse = processedHistory.slice(0, -1);
37859
+ pinnedSyntheticIds.add(existingWithSameBatch.id);
37860
+ } else {
37861
+ droppedSyntheticIds.add(existingWithSameBatch.id);
37862
+ }
37863
+ }
37864
+ }
37865
+ const realtimeMessages = existingMessages.filter((m) => {
37866
+ if (pinnedSyntheticIds.has(m.id)) return true;
37867
+ if (droppedSyntheticIds.has(m.id)) return false;
37868
+ if (processedIds.has(m.id)) return false;
37869
+ if (rawHistoryIds?.has(m.id)) return false;
37870
+ if (m.role === "user" && m.id.startsWith("optimistic-") && typeof m.content === "string") {
37871
+ const canBeInSnapshot = (m.timestamp?.getTime() ?? 0) <= historyFetchedAt;
37872
+ return !(canBeInSnapshot && processedToUse.some((pm) => pm.role === "user" && pm.content === m.content));
37873
+ }
37874
+ if (isSyntheticRealtimeId(m.id) && m.id !== streamingMessageId) {
37875
+ const covered = historyCoversRealtime !== null ? historyCoversRealtime : (m.timestamp?.getTime() ?? 0) <= historyFetchedAt;
37876
+ if (covered) return false;
37877
+ }
37878
+ return true;
37879
+ });
37880
+ return [...processedToUse, ...realtimeMessages];
37881
+ }
37882
+ function computeHistoryPrepend(processedHistory, existingMessages) {
37883
+ const existingIds = new Set(existingMessages.map((m) => m.id));
37884
+ const newMessages = [];
37885
+ let boundaryMessageIndex = -1;
37886
+ for (let i = 0; i < processedHistory.length; i++) {
37887
+ if (existingIds.has(processedHistory[i].id)) {
37888
+ boundaryMessageIndex = i;
37889
+ break;
37890
+ }
37891
+ newMessages.push(processedHistory[i]);
37892
+ }
37893
+ let boundaryMessageId;
37894
+ let boundaryUpdates;
37895
+ if (boundaryMessageIndex >= 0) {
37896
+ const boundaryMessage = processedHistory[boundaryMessageIndex];
37897
+ const existingBoundary = existingMessages.find((m) => m.id === boundaryMessage.id);
37898
+ if (existingBoundary) {
37899
+ const existingContent = JSON.stringify(existingBoundary.content);
37900
+ const newContent = JSON.stringify(boundaryMessage.content);
37901
+ if (existingContent !== newContent) {
37902
+ boundaryMessageId = boundaryMessage.id;
37903
+ boundaryUpdates = { content: boundaryMessage.content };
37904
+ }
37905
+ }
37906
+ }
37907
+ if (newMessages.length === 0 && !boundaryUpdates) return null;
37908
+ return { newMessages, boundaryMessageId, boundaryUpdates };
37909
+ }
37910
+
37811
37911
  // src/components/chat/utils/chip-action-class.ts
37812
37912
  var CHIP_ACTION_BUTTON_CLASS = "text-[11px] font-medium text-ods-text-secondary hover:text-ods-text-primary bg-transparent hover:bg-ods-card-hover border border-ods-border rounded-md px-2 py-1 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ods-focus";
37813
37913
 
@@ -39283,6 +39383,11 @@ export {
39283
39383
  useNatsChatAdapter,
39284
39384
  useUnifiedChat,
39285
39385
  extractIncompleteMessageState,
39386
+ SYNTHETIC_REALTIME_ID_PREFIXES,
39387
+ flattenMessagePagesChronological,
39388
+ maxPersistedStreamSeq,
39389
+ mergeHistoryWithRealtime,
39390
+ computeHistoryPrepend,
39286
39391
  CHIP_ACTION_BUTTON_CLASS,
39287
39392
  chatChipClass,
39288
39393
  clickupTaskUrl,
@@ -39610,4 +39715,4 @@ export {
39610
39715
  LogsList,
39611
39716
  assets
39612
39717
  };
39613
- //# sourceMappingURL=chunk-PCXI7ZB2.js.map
39718
+ //# sourceMappingURL=chunk-D2BC3NZ2.js.map