@athenaintel/react 0.42.2 → 0.43.0

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 (60) hide show
  1. package/README.md +10 -0
  2. package/dist/agent-runtime/src/conversation-list-groups.d.ts +74 -0
  3. package/dist/agent-runtime/src/index.d.ts +1 -0
  4. package/dist/agent-runtime/src/tool-metadata.cjs +0 -8
  5. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  6. package/dist/agent-runtime/src/tool-metadata.js +0 -8
  7. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  8. package/dist/agent-runtime/src/use-deep-agent-voice.cjs +30 -15
  9. package/dist/agent-runtime/src/use-deep-agent-voice.cjs.map +1 -1
  10. package/dist/agent-runtime/src/use-deep-agent-voice.d.ts +8 -0
  11. package/dist/agent-runtime/src/use-deep-agent-voice.js +30 -15
  12. package/dist/agent-runtime/src/use-deep-agent-voice.js.map +1 -1
  13. package/dist/chat/super-grouping/SuperGroupingCard.cjs +8 -2
  14. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  15. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +6 -1
  16. package/dist/chat/super-grouping/SuperGroupingCard.js +8 -2
  17. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  18. package/dist/chat/super-grouping/ToolTimeline.cjs +27 -0
  19. package/dist/chat/super-grouping/ToolTimeline.cjs.map +1 -1
  20. package/dist/chat/super-grouping/ToolTimeline.d.ts +5 -1
  21. package/dist/chat/super-grouping/ToolTimeline.js +27 -0
  22. package/dist/chat/super-grouping/ToolTimeline.js.map +1 -1
  23. package/dist/chat/super-grouping/index.d.ts +1 -0
  24. package/dist/chat/super-grouping/timeline-step.cjs +61 -2
  25. package/dist/chat/super-grouping/timeline-step.cjs.map +1 -1
  26. package/dist/chat/super-grouping/timeline-step.d.ts +13 -1
  27. package/dist/chat/super-grouping/timeline-step.js +61 -2
  28. package/dist/chat/super-grouping/timeline-step.js.map +1 -1
  29. package/dist/chat-ui/mentions/mention-chip.cjs +144 -35
  30. package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
  31. package/dist/chat-ui/mentions/mention-chip.d.ts +17 -1
  32. package/dist/chat-ui/mentions/mention-chip.js +146 -37
  33. package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
  34. package/dist/chat-ui/mentions/use-mention-asset.cjs +140 -0
  35. package/dist/chat-ui/mentions/use-mention-asset.cjs.map +1 -0
  36. package/dist/chat-ui/mentions/use-mention-asset.d.ts +16 -0
  37. package/dist/chat-ui/mentions/use-mention-asset.js +140 -0
  38. package/dist/chat-ui/mentions/use-mention-asset.js.map +1 -0
  39. package/dist/chat-ui/rich-text/chat-link.cjs +5 -4
  40. package/dist/chat-ui/rich-text/chat-link.cjs.map +1 -1
  41. package/dist/chat-ui/rich-text/chat-link.d.ts +2 -3
  42. package/dist/chat-ui/rich-text/chat-link.js +6 -5
  43. package/dist/chat-ui/rich-text/chat-link.js.map +1 -1
  44. package/dist/chat-ui/rich-text/chat-node-views.cjs +1 -0
  45. package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -1
  46. package/dist/chat-ui/rich-text/chat-node-views.js +1 -0
  47. package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -1
  48. package/dist/react/package.json.cjs +1 -1
  49. package/dist/react/package.json.js +1 -1
  50. package/dist/references/src/tool-option-schemas.d.ts +0 -34
  51. package/dist/styles.css +1 -1
  52. package/dist/threads/statewire-thread-list.cjs +6 -2
  53. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  54. package/dist/threads/statewire-thread-list.js +6 -2
  55. package/dist/threads/statewire-thread-list.js.map +1 -1
  56. package/dist/tools/tool-summary.cjs +0 -2
  57. package/dist/tools/tool-summary.cjs.map +1 -1
  58. package/dist/tools/tool-summary.js +0 -2
  59. package/dist/tools/tool-summary.js.map +1 -1
  60. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"mention-chip.js","sources":["../../../src/chat-ui/mentions/mention-chip.tsx"],"sourcesContent":["/**\n * Mention chip rendering for message display.\n *\n * Parses [@name](mention://type?...) markdown links and renders them\n * as styled inline chips matching the Olympus mention style.\n * Used in both user messages (inline text) and assistant messages (markdown links).\n */\n\nimport {\n useContext,\n useState,\n type FC,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport {\n formatScreenPoint,\n isScreenPointHref,\n parseScreenPointHref,\n} from \"@athenaintel/agent-runtime\";\nimport {\n type AssetReference,\n decodeFromAssetMentionUri,\n decodeFromAssetSpacesUrl,\n encodeToAssetSpacesUrl,\n formatReferenceAnchor,\n} from \"@athenaintel/references/asset-links\";\nimport {\n CrosshairIcon,\n DatabaseIcon,\n FileCodeIcon,\n FileIcon,\n FileTextIcon,\n FolderIcon,\n Globe2Icon,\n HeadphonesIcon,\n ImageIcon,\n type LucideIcon,\n MailIcon,\n MessageSquareIcon,\n MonitorIcon,\n PresentationIcon,\n SheetIcon,\n UserIcon,\n VideoIcon,\n} from \"lucide-react\";\nimport { cn } from \"../../lib/utils\";\nimport { createOlympusAssetUrl } from \"../lib/asset-urls\";\nimport { MentionAuthCtx } from \"./suggestions/data/api-client\";\nimport { assetTypeToThumb } from \"./suggestions/data/sources/asset-type-icons\";\nimport { useMemberAvatarUrl } from \"./use-member-avatar\";\n\nconst SPACES_MENTION_PATH = /\\/dashboard\\/spaces\\/?\\?/;\n\nfunction isSpacesMentionUrl(url: string): boolean {\n return SPACES_MENTION_PATH.test(url);\n}\n\nfunction getSpacesAssetType(url: URL): string | null {\n const assetType =\n url.searchParams.get(\"assetType\") ||\n url.searchParams.get(\"asset_type\") ||\n url.searchParams.get(\"type\");\n return assetType === \"sheet\" ? \"spreadsheet\" : assetType;\n}\n\n/**\n * Where in the asset a citation points, as its chip shows it. The anchor is\n * read and labelled by `@athenaintel/references` — the same parser and labels\n * Olympus's mention chips use — so a chip reads `jwt.py:12-25`, `p.5` or\n * `Slide 3` in every Athena chat.\n */\nexport interface MentionChipCitation {\n /** The anchor type (`page`, `file_line_range`, `slide`, …). */\n anchorType: string;\n /** The short label drawn after the name (`p.5`, `jwt.py:12-25`). */\n label: string;\n /**\n * The place spelled out (`Page 5`, `agora/…/jwt.py:12-25`), without the\n * excerpt: the tooltip when the link carries no excerpt, and part of the\n * chip's accessible name when it holds a word.\n */\n description: string;\n}\n\n/** The citation an asset link's anchor names, or undefined for a plain mention or an anchor nobody can read. */\nfunction citationOf(reference: AssetReference): MentionChipCitation | undefined {\n const { anchor, meta } = reference;\n if (!anchor) return undefined;\n const label = formatReferenceAnchor(anchor, \"short\", meta);\n if (!label) return undefined;\n const { excerpt: _excerpt, ...place } = meta ?? {};\n return {\n anchorType: anchor.type,\n label,\n description: formatReferenceAnchor(anchor, \"long\", place) ?? label,\n };\n}\n\n/**\n * The chip's icon for an asset type when the host serves no asset-type SVGs.\n * A compact set on purpose: the chip renders in every message (and Olympus's\n * main layout reaches it through the queued-message tray), so it carries a\n * dozen icons rather than the `@` menu's whole map.\n */\nconst ASSET_CHIP_ICONS: Record<string, LucideIcon> = {\n document: FileTextIcon,\n word_document: FileTextIcon,\n markdown: FileTextIcon,\n txt: FileTextIcon,\n pdf: FileTextIcon,\n spreadsheet: SheetIcon,\n table: SheetIcon,\n presentation: PresentationIcon,\n powerpoint_deck: PresentationIcon,\n presentation_pptx_studio: PresentationIcon,\n pptx: PresentationIcon,\n image: ImageIcon,\n figure: ImageIcon,\n canvas: ImageIcon,\n video: VideoIcon,\n meeting: VideoIcon,\n video_session: VideoIcon,\n audio: HeadphonesIcon,\n voice_memo: HeadphonesIcon,\n phone_call: HeadphonesIcon,\n email: MailIcon,\n email_message: MailIcon,\n live_email_thread: MailIcon,\n live_calendar_event: MailIcon,\n python: FileCodeIcon,\n javascript: FileCodeIcon,\n typescript: FileCodeIcon,\n json: FileCodeIcon,\n yaml: FileCodeIcon,\n database: DatabaseIcon,\n catalog: DatabaseIcon,\n drive: DatabaseIcon,\n dataset: DatabaseIcon,\n semantic_model: DatabaseIcon,\n query_snippet: DatabaseIcon,\n folder: FolderIcon,\n gdrive_folder: FolderIcon,\n project: FolderIcon,\n collection: FolderIcon,\n session: MessageSquareIcon,\n computer: MonitorIcon,\n desktop_session: MonitorIcon,\n user_interface: MonitorIcon,\n application: MonitorIcon,\n html: Globe2Icon,\n web_page: Globe2Icon,\n browse_session: Globe2Icon,\n};\n\n/** A repository file's lines read as a code file, whatever the catalog holding them. */\nfunction assetChipIcon(\n assetType: string | undefined,\n citation: MentionChipCitation | undefined,\n): LucideIcon {\n if (citation?.anchorType === \"file_line_range\") return FileCodeIcon;\n return (assetType && ASSET_CHIP_ICONS[assetType.toLowerCase()]) || FileIcon;\n}\n\n/** A label with a letter or digit in it; `§` or `•` alone says nothing read aloud. */\nconst SPEAKABLE = /[\\p{L}\\p{N}]/u;\n\n/** The asset reference an asset link decodes to, or null when it does not parse. */\nfunction decodeAssetLink(\n url: URL,\n decode: (url: URL) => AssetReference,\n): AssetReference | null {\n try {\n return decode(url);\n } catch {\n return null;\n }\n}\n\n// ── Mention link component for markdown renderer ──\n\n/**\n * Custom <a> renderer for MarkdownTextPrimitive.\n * Intercepts mention:// links and renders them as chips.\n * Falls through to a normal link for non-mention URLs.\n */\nfunction personEmailForMention(\n parsed: ReturnType<typeof parseMentionUrl>,\n): string | undefined {\n if (parsed.type !== \"person\") return undefined;\n return parsed.email || (parsed.id.includes(\"@\") ? parsed.id : undefined);\n}\n\nexport const MentionLink: FC<{\n href?: string;\n children?: ReactNode;\n interactive?: boolean;\n}> = ({ href, children, interactive = true }) => {\n if (\n href &&\n (href.startsWith(\"mention://\") || isSpacesMentionUrl(href))\n ) {\n const name = typeof children === \"string\"\n ? children.replace(/^@/, \"\")\n : Array.isArray(children)\n ? String(children[0] ?? \"\").replace(/^@/, \"\")\n : \"\";\n\n const parsed = parseMentionUrl(href);\n\n return (\n <MentionChip\n name={name || parsed.name}\n type={parsed.type}\n personEmail={personEmailForMention(parsed)}\n assetIds={parsed.assetIds}\n assetType={parsed.assetType}\n citation={parsed.citation}\n thumbnailUrl={parsed.thumbnailUrl}\n sourceHref={isSpacesMentionUrl(href) ? href : parsed.sourceHref}\n interactive={interactive}\n />\n );\n }\n\n if (href?.startsWith(\"chrome-extension://\")) {\n return <span>{children}</span>;\n }\n\n if (isScreenPointHref(href)) {\n return <ScreenPointChip href={href}>{children}</ScreenPointChip>;\n }\n\n // Normal link — render as-is\n return (\n <a href={href} target=\"_blank\" rel=\"noopener noreferrer\">\n {children}\n </a>\n );\n};\n\n// ── Inline screen-point chip ──\n\n/**\n * Renders an `athena-point://` link as a non-navigating coordinate chip.\n * Surfaces without screenshot context (extension side panel, SDK consumers)\n * get the label plus the coordinates; malformed points fall back to text.\n */\nexport const ScreenPointChip: FC<{\n href: string;\n children?: ReactNode;\n}> = ({ href, children }) => {\n const parsed = parseScreenPointHref(href);\n if (!parsed.ok) {\n return <span>{children}</span>;\n }\n const description = formatScreenPoint(parsed.point);\n return (\n <span\n className=\"not-prose inline-flex max-w-[260px] items-center gap-1 whitespace-nowrap rounded-md border border-slate-300 bg-white px-1.5 py-px align-middle text-[0.85em] font-medium leading-[1.4] text-slate-600\"\n title={description}\n aria-label={description}\n data-screen-point=\"valid\"\n >\n <CrosshairIcon className=\"size-3.5 shrink-0\" aria-hidden=\"true\" />\n <span className=\"max-w-[180px] overflow-hidden text-ellipsis\">\n {children}\n </span>\n <span className=\"font-normal text-slate-400\">\n {parsed.point.x}, {parsed.point.y}\n </span>\n </span>\n );\n};\n\n// ── Inline mention chip ──\n\nexport const MentionChip: FC<{\n name: string;\n type?: string;\n assetIds?: string[];\n /** The asset's type (`document`, `catalog`, …): picks the icon when the host bundles no SVG thumbnails. */\n assetType?: string;\n /** Where in the asset the link points: its label follows the name. */\n citation?: MentionChipCitation;\n personEmail?: string;\n thumbnailUrl?: string;\n sourceHref?: string;\n interactive?: boolean;\n}> = ({\n name,\n type,\n assetIds,\n assetType,\n citation,\n personEmail,\n thumbnailUrl,\n sourceHref,\n interactive = true,\n}) => {\n const auth = useContext(MentionAuthCtx);\n const memberAvatarUrl = useMemberAvatarUrl(personEmail);\n const [erroredAvatarUrl, setErroredAvatarUrl] = useState<string>();\n // A citation's excerpt (the passage the chip points at) is the tooltip, else\n // the cited place spelled out; the accessible name stays the action.\n const excerpt = sourceHref ? readSourceExcerpt(sourceHref) : null;\n const tooltip = excerpt ?? citation?.description ?? null;\n // A chip the model left unlabelled is already named by its place.\n const anchorLabel =\n citation && name !== citation.description && name !== citation.label\n ? citation.label\n : null;\n const assetRootHref =\n type === \"asset\" && assetIds?.length\n ? createOlympusAssetUrl({\n appUrl: auth?.appUrl,\n backendUrl: auth?.backendUrl,\n assetIds,\n })\n : null;\n const href = (() => {\n if (!assetRootHref || !sourceHref) return assetRootHref;\n try {\n const source = new URL(sourceHref, \"https://app.athenaintel.com\");\n const destination = new URL(assetRootHref);\n for (const [key, value] of source.searchParams) {\n destination.searchParams.set(key, value);\n }\n destination.searchParams.set(\"asset_ids\", assetIds?.join(\",\") ?? \"\");\n return destination.toString();\n } catch {\n return assetRootHref;\n }\n })();\n // `not-prose` matters: assistant messages render inside Tailwind\n // Typography's `prose`, whose zero-specificity `img` margins (~1.7em\n // top/bottom) would otherwise inflate the chip's icon into a tall card\n // that breaks the sentence flow around it.\n const className = cn(\n \"not-prose inline-flex max-w-[220px] items-center gap-1 whitespace-nowrap rounded-md border border-slate-300 bg-white px-1.5 py-px align-middle text-[0.85em] font-medium leading-[1.4] text-slate-600 no-underline\",\n // The cited place gets its own room after a name already at its cap.\n anchorLabel && \"max-w-[340px]\",\n href &&\n \"cursor-pointer transition-colors hover:border-slate-400 hover:bg-slate-50 hover:text-slate-800 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1\",\n );\n const AssetIcon = assetChipIcon(assetType, citation);\n const contents = (\n <>\n {thumbnailUrl && (\n <img\n src={thumbnailUrl}\n alt=\"\"\n className=\"size-3.5 shrink-0\"\n draggable={false}\n />\n )}\n {!thumbnailUrl && (type === \"asset\" || type === \"folder\") && (\n // A host that bundles no asset-type SVGs (computer apps, most SDK\n // apps) still gets the type's icon.\n <AssetIcon className=\"size-3.5 shrink-0\" aria-hidden=\"true\" />\n )}\n {!thumbnailUrl && type === \"webpage\" && (\n <Globe2Icon className=\"size-3.5 shrink-0\" aria-hidden=\"true\" />\n )}\n {!thumbnailUrl && type === \"person\" && (\n memberAvatarUrl && erroredAvatarUrl !== memberAvatarUrl ? (\n <img\n src={memberAvatarUrl}\n alt=\"\"\n className=\"size-3.5 shrink-0 rounded-full object-cover\"\n draggable={false}\n onError={() => setErroredAvatarUrl(memberAvatarUrl)}\n />\n ) : (\n <UserIcon className=\"size-3.5 shrink-0\" aria-hidden=\"true\" />\n )\n )}\n <span className=\"max-w-[180px] overflow-hidden text-ellipsis\">\n {name}\n </span>\n {citation && anchorLabel && (\n <>\n {/* Copied or read as text, the place stays a word apart from the name; a flex row draws no space. */}{\" \"}\n <span\n className=\"max-w-[140px] shrink-0 overflow-hidden text-ellipsis font-normal text-slate-400\"\n data-citation-anchor={citation.anchorType}\n >\n {anchorLabel}\n </span>\n </>\n )}\n </>\n );\n\n if (href && interactive) {\n return (\n <a\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={className}\n aria-label={\n anchorLabel && citation && SPEAKABLE.test(citation.description)\n ? `Open ${name} at ${citation.description} in Spaces`\n : `Open ${name} in Spaces`\n }\n title={tooltip ?? `Open ${name} in Spaces`}\n data-excerpt={excerpt ?? undefined}\n // The link's text without its place: what a click names the opened asset.\n data-mention-name={name}\n >\n {contents}\n </a>\n );\n }\n\n return (\n <span\n className={className}\n title={tooltip ?? undefined}\n data-excerpt={excerpt ?? undefined}\n >\n {contents}\n </span>\n );\n};\n\n/** The `excerpt` a Spaces citation URL carries, or null. */\nfunction readSourceExcerpt(href: string): string | null {\n try {\n const excerpt = new URL(href, \"https://app.athenaintel.com\").searchParams\n .get(\"excerpt\")\n ?.trim();\n return excerpt ? excerpt : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The label an asset citation chip falls back to when the model wrote none\n * (`[](…/spaces/?asset_ids=…&page=5)`): the cited location, else \"Asset\" — a\n * chip must never render as an empty box.\n */\nfunction citationFallbackLabel(params: URLSearchParams): string {\n const start = params.get(\"start_page\") ?? params.get(\"page\");\n const end = params.get(\"end_page\");\n if (start && end && end !== start) return `Pages ${start}–${end}`;\n if (start) return `Page ${start}`;\n return \"Asset\";\n}\n\n// ── Parse mention:// URLs ──\n\nexport function parseMentionUrl(url: string): {\n type: string;\n name: string;\n id: string;\n email?: string;\n assetIds?: string[];\n assetType?: string;\n citation?: MentionChipCitation;\n /**\n * For a `mention://asset` citation, the Spaces link to its place (anchor and\n * excerpt), so the chip opens there; a Spaces mention is its own link.\n */\n sourceHref?: string;\n thumbnailUrl?: string;\n} {\n try {\n if (isSpacesMentionUrl(url)) {\n const parsed = new URL(url, \"https://app.athenaintel.com\");\n const assetIds = (parsed.searchParams.get(\"asset_ids\") ?? \"\")\n .split(\",\")\n .map((id) => id.trim())\n .filter(Boolean);\n const id = assetIds[0] ?? \"\";\n const assetType = getSpacesAssetType(parsed);\n // A link to several assets names no one place in any of them.\n const reference =\n assetIds.length === 1\n ? decodeAssetLink(parsed, decodeFromAssetSpacesUrl)\n : null;\n const citation = reference ? citationOf(reference) : undefined;\n return {\n type: \"asset\",\n name:\n assetIds.length > 1\n ? `${assetIds.length} assets`\n : (citation?.description ??\n citationFallbackLabel(parsed.searchParams)),\n id,\n assetIds,\n assetType: assetType ?? undefined,\n citation,\n thumbnailUrl: assetTypeToThumb(assetType),\n };\n }\n // mention://tool?name=...&description=...\n // mention://asset?id=...&assetType=project&thumb=../icons/files/ic-project.svg\n const u = new URL(url);\n const type = u.hostname || u.pathname.replace(/^\\/\\//, \"\").split(\"?\")[0];\n const isWebpage = type === \"webpage\";\n const id = isWebpage\n ? u.searchParams.get(\"tab_id\") || \"\"\n : u.searchParams.get(\"id\") || u.searchParams.get(\"name\") || \"\";\n const name = isWebpage\n ? u.searchParams.get(\"title\") || \"This webpage\"\n : u.searchParams.get(\"name\") || id;\n\n // Get thumbnail: prefer explicit thumb param, then derive from assetType\n let thumbnailUrl = u.searchParams.get(\"thumb\") || undefined;\n if (!thumbnailUrl) {\n const assetType = u.searchParams.get(\"assetType\");\n if (assetType) {\n thumbnailUrl = assetTypeToThumb(assetType);\n } else if (type === \"asset\" || type === \"folder\") {\n thumbnailUrl = assetTypeToThumb(type === \"folder\" ? \"folder\" : null);\n }\n }\n\n const reference =\n type === \"asset\" ? decodeAssetLink(u, decodeFromAssetMentionUri) : null;\n\n return {\n type,\n name,\n id,\n email: type === \"person\" ? u.searchParams.get(\"email\") || undefined : undefined,\n assetIds: type === \"asset\" && id ? [id] : undefined,\n assetType:\n type === \"asset\" || type === \"folder\"\n ? u.searchParams.get(\"assetType\") ||\n reference?.meta?.assetType ||\n (type === \"folder\" ? \"folder\" : undefined)\n : undefined,\n citation: reference ? citationOf(reference) : undefined,\n sourceHref:\n reference && (reference.anchor || reference.meta?.excerpt)\n ? encodeToAssetSpacesUrl(reference)\n : undefined,\n thumbnailUrl,\n };\n } catch {\n return { type: \"unknown\", name: \"\", id: \"\" };\n }\n}\n\nfunction htmlAttribute(attributes: string, name: string): string | null {\n const escapedName = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = new RegExp(\n `(?:^|\\\\s)${escapedName}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`,\n \"i\",\n ).exec(attributes);\n return match?.[1] ?? match?.[2] ?? match?.[3] ?? null;\n}\n\nfunction decodeHtmlAttribute(value: string): string {\n return value\n .replace(/&amp;/gi, \"&\")\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;|&apos;/gi, \"'\")\n .replace(/&lt;/gi, \"<\")\n .replace(/&gt;/gi, \">\");\n}\n\n/** Turn complete model-emitted URL citation anchors into safe Markdown links. */\nexport function normalizeAthenaMentionHtml(text: string): string {\n return text.replace(\n /<a\\b([^>]*)>([\\s\\S]*?)<\\/a>/gi,\n (original, attributes: string, rawLabel: string) => {\n const className = htmlAttribute(attributes, \"class\") ?? \"\";\n const type = htmlAttribute(attributes, \"data-type\") ?? \"\";\n if (!className.split(/\\s+/).includes(\"mention\") || type !== \"url\") {\n return original;\n }\n\n const rawUrl =\n htmlAttribute(attributes, \"data-url\") ??\n htmlAttribute(attributes, \"href\");\n if (!rawUrl) return original;\n const url = decodeHtmlAttribute(rawUrl);\n let normalizedUrl: string;\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return original;\n }\n normalizedUrl = parsed.toString();\n } catch {\n return original;\n }\n\n const label = decodeHtmlAttribute(rawLabel.replace(/<[^>]*>/g, \"\"))\n .trim()\n .replace(/([\\\\[\\]])/g, \"\\\\$1\");\n return label ? `[${label}](<${normalizedUrl}>)` : original;\n },\n );\n}\n// ── Parse mention markdown in plain text ──\n\n// The label may hold balanced brackets one level deep (`[@Plan [Q3]](…)`) or a lone `[`.\nconst MENTION_RE =\n /\\[@((?:\\[[^[\\]]*\\](?!\\((?:[a-z][a-z0-9+.-]*:\\/\\/|\\/))|[^\\]])*)\\]\\(((?:mention:\\/\\/|(?:https?:\\/\\/[^)\\s]+)?\\/dashboard\\/spaces\\/?\\?)[^)]+)\\)/g;\n\n/**\n * Parse text containing [@name](mention://...) patterns into\n * an array of string segments and MentionChip elements.\n */\nexport function parseMentionsInText(text: string): (string | ReactElement)[] {\n const parts: (string | ReactElement)[] = [];\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n MENTION_RE.lastIndex = 0;\n\n while ((match = MENTION_RE.exec(text)) !== null) {\n if (match.index > lastIndex) {\n parts.push(text.slice(lastIndex, match.index));\n }\n\n const name = match[1];\n const url = match[2];\n const parsed = parseMentionUrl(url);\n\n parts.push(\n <MentionChip\n key={`mention-${match.index}`}\n name={name || parsed.name}\n type={parsed.type}\n personEmail={personEmailForMention(parsed)}\n assetIds={parsed.assetIds}\n assetType={parsed.assetType}\n citation={parsed.citation}\n thumbnailUrl={parsed.thumbnailUrl}\n sourceHref={isSpacesMentionUrl(url) ? url : parsed.sourceHref}\n />\n );\n\n lastIndex = match.index + match[0].length;\n }\n\n if (lastIndex < text.length) {\n parts.push(text.slice(lastIndex));\n }\n\n return parts.length > 0 ? parts : [text];\n}\n\n/** The text as a reader sees it: each `[@name](…)` mention becomes `@name`. */\nexport function mentionsToPlainText(text: string): string {\n return text.replace(MENTION_RE, (_match, name: string, url: string) => {\n return `@${name || parseMentionUrl(url).name}`;\n });\n}\n"],"names":["id","reference"],"mappings":";;;;;;;;;;;;AAoDA,MAAM,sBAAsB;AAE5B,SAAS,mBAAmB,KAAsB;AAChD,SAAO,oBAAoB,KAAK,GAAG;AACrC;AAEA,SAAS,mBAAmB,KAAyB;AACnD,QAAM,YACJ,IAAI,aAAa,IAAI,WAAW,KAChC,IAAI,aAAa,IAAI,YAAY,KACjC,IAAI,aAAa,IAAI,MAAM;AAC7B,SAAO,cAAc,UAAU,gBAAgB;AACjD;AAsBA,SAAS,WAAW,WAA4D;AAC9E,QAAM,EAAE,QAAQ,KAAA,IAAS;AACzB,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,QAAQ,sBAAsB,QAAQ,SAAS,IAAI;AACzD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,EAAE,SAAS,UAAU,GAAG,MAAA,IAAU,QAAQ,CAAA;AAChD,SAAO;AAAA,IACL,YAAY,OAAO;AAAA,IACnB;AAAA,IACA,aAAa,sBAAsB,QAAQ,QAAQ,KAAK,KAAK;AAAA,EAAA;AAEjE;AAQA,MAAM,mBAA+C;AAAA,EACnD,UAAU;AAAA,EACV,eAAe;AAAA,EACf,UAAU;AAAA,EACV,KAAK;AAAA,EACL,KAAK;AAAA,EACL,aAAa;AAAA,EACb,OAAO;AAAA,EACP,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,0BA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,aAAW,YAAY;AAEvB,UAAQ,QAAQ,WAAW,KAAK,IAAI,OAAO,MAAM;AAC/C,QAAI,MAAM,QAAQ,WAAW;AAC3B,YAAM,KAAK,KAAK,MAAM,WAAW,MAAM,KAAK,CAAC;AAAA,IAC/C;AAEA,UAAM,OAAO,MAAM,CAAC;AACpB,UAAM,MAAM,MAAM,CAAC;AACnB,UAAM,SAAS,gBAAgB,GAAG;AAElC,UAAM;AAAA,MACJ;AAAA,QAAC;AAAA,QAAA;AAAA,UAEC,MAAM,QAAQ,OAAO;AAAA,UACrB,MAAM,OAAO;AAAA,UACb,aAAa,sBAAsB,MAAM;AAAA,UACzC,UAAU,OAAO;AAAA,UACjB,WAAW,OAAO;AAAA,UAClB,UAAU,OAAO;AAAA,UACjB,cAAc,OAAO;AAAA,UACrB,YAAY,mBAAmB,GAAG,IAAI,MAAM,OAAO;AAAA,QAAA;AAAA,QAR9C,WAAW,MAAM,KAAK;AAAA,MAAA;AAAA,IAS7B;AAGF,gBAAY,MAAM,QAAQ,MAAM,CAAC,EAAE;AAAA,EACrC;AAEA,MAAI,YAAY,KAAK,QAAQ;AAC3B,UAAM,KAAK,KAAK,MAAM,SAAS,CAAC;AAAA,EAClC;AAEA,SAAO,MAAM,SAAS,IAAI,QAAQ,CAAC,IAAI;AACzC;AAGO,SAAS,oBAAoB,MAAsB;AACxD,SAAO,KAAK,QAAQ,YAAY,CAAC,QAAQ,MAAc,QAAgB;AACrE,WAAO,IAAI,QAAQ,gBAAgB,GAAG,EAAE,IAAI;AAAA,EAC9C,CAAC;AACH;"}
1
+ {"version":3,"file":"mention-chip.js","sources":["../../../src/chat-ui/mentions/mention-chip.tsx"],"sourcesContent":["/**\n * Mention chip rendering for message display.\n *\n * Parses [@name](mention://type?...) markdown links and renders them\n * as styled inline chips matching the Olympus mention style.\n * Used in both user messages (inline text) and assistant messages (markdown links).\n */\n\nimport {\n isValidElement,\n useContext,\n useState,\n type FC,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport {\n formatScreenPoint,\n isScreenPointHref,\n parseScreenPointHref,\n} from \"@athenaintel/agent-runtime\";\nimport {\n type AssetReference,\n decodeFromAssetMentionUri,\n decodeFromAssetSpacesUrl,\n encodeToAssetSpacesUrl,\n formatReferenceAnchor,\n} from \"@athenaintel/references/asset-links\";\nimport {\n CrosshairIcon,\n DatabaseIcon,\n FileCodeIcon,\n FileIcon,\n FileTextIcon,\n FolderIcon,\n Globe2Icon,\n HeadphonesIcon,\n ImageIcon,\n type LucideIcon,\n MailIcon,\n MessageSquareIcon,\n MonitorIcon,\n PresentationIcon,\n SheetIcon,\n UserIcon,\n VideoIcon,\n} from \"lucide-react\";\nimport { cn } from \"../../lib/utils\";\nimport { createOlympusAssetUrl } from \"../lib/asset-urls\";\nimport { MentionAuthCtx } from \"./suggestions/data/api-client\";\nimport { assetTypeToThumb } from \"./suggestions/data/sources/asset-type-icons\";\nimport { useMemberAvatarUrl } from \"./use-member-avatar\";\nimport { useMentionAsset } from \"./use-mention-asset\";\n\nconst SPACES_MENTION_PATH = /\\/dashboard\\/spaces\\/?\\?/;\n\nfunction isSpacesMentionUrl(url: string): boolean {\n return SPACES_MENTION_PATH.test(url);\n}\n\nfunction getSpacesAssetType(url: URL): string | null {\n const assetType =\n url.searchParams.get(\"assetType\") ||\n url.searchParams.get(\"asset_type\") ||\n url.searchParams.get(\"type\");\n return assetType === \"sheet\" ? \"spreadsheet\" : assetType;\n}\n\n/**\n * Where in the asset a citation points, as its chip shows it. The anchor is\n * read and labelled by `@athenaintel/references` — the same parser and labels\n * Olympus's mention chips use — so a chip reads `jwt.py:12-25`, `p.5` or\n * `Slide 3` in every Athena chat.\n */\nexport interface MentionChipCitation {\n /** The anchor type (`page`, `file_line_range`, `slide`, …). */\n anchorType: string;\n /** The short label drawn after the name (`p.5`, `jwt.py:12-25`). */\n label: string;\n /**\n * The place spelled out (`Page 5`, `agora/…/jwt.py:12-25`), without the\n * excerpt: the tooltip when the link carries no excerpt, and part of the\n * chip's accessible name when it holds a word.\n */\n description: string;\n}\n\n/** The citation an asset link's anchor names, or undefined for a plain mention or an anchor nobody can read. */\nfunction citationOf(reference: AssetReference): MentionChipCitation | undefined {\n const { anchor, meta } = reference;\n if (!anchor) return undefined;\n const label = formatReferenceAnchor(anchor, \"short\", meta);\n if (!label) return undefined;\n const { excerpt: _excerpt, ...place } = meta ?? {};\n return {\n anchorType: anchor.type,\n label,\n description: formatReferenceAnchor(anchor, \"long\", place) ?? label,\n };\n}\n\n/**\n * The chip's icon for an asset type when the host serves no asset-type SVGs.\n * A compact set on purpose: the chip renders in every message (and Olympus's\n * main layout reaches it through the queued-message tray), so it carries a\n * dozen icons rather than the `@` menu's whole map.\n */\nconst ASSET_CHIP_ICONS: Record<string, LucideIcon> = {\n document: FileTextIcon,\n word_document: FileTextIcon,\n markdown: FileTextIcon,\n txt: FileTextIcon,\n pdf: FileTextIcon,\n spreadsheet: SheetIcon,\n table: SheetIcon,\n presentation: PresentationIcon,\n powerpoint_deck: PresentationIcon,\n presentation_pptx_studio: PresentationIcon,\n pptx: PresentationIcon,\n image: ImageIcon,\n figure: ImageIcon,\n canvas: ImageIcon,\n video: VideoIcon,\n meeting: VideoIcon,\n video_session: VideoIcon,\n audio: HeadphonesIcon,\n voice_memo: HeadphonesIcon,\n phone_call: HeadphonesIcon,\n email: MailIcon,\n email_message: MailIcon,\n live_email_thread: MailIcon,\n live_calendar_event: MailIcon,\n python: FileCodeIcon,\n javascript: FileCodeIcon,\n typescript: FileCodeIcon,\n json: FileCodeIcon,\n yaml: FileCodeIcon,\n database: DatabaseIcon,\n catalog: DatabaseIcon,\n drive: DatabaseIcon,\n dataset: DatabaseIcon,\n semantic_model: DatabaseIcon,\n query_snippet: DatabaseIcon,\n folder: FolderIcon,\n gdrive_folder: FolderIcon,\n project: FolderIcon,\n collection: FolderIcon,\n session: MessageSquareIcon,\n computer: MonitorIcon,\n desktop_session: MonitorIcon,\n user_interface: MonitorIcon,\n application: MonitorIcon,\n html: Globe2Icon,\n web_page: Globe2Icon,\n browse_session: Globe2Icon,\n};\n\nfunction assetChipIcon(assetType: string | undefined): LucideIcon {\n return (assetType && ASSET_CHIP_ICONS[assetType.toLowerCase()]) || FileIcon;\n}\n\n/**\n * GitHub's mark (Octicons `mark-github`), drawn by a repository file's\n * citation. Lucide carries no brand icons and an SDK app serves none of\n * Olympus's, so the chip brings its own. Only a GitHub repository catalog\n * serves `file_line_range` anchors (`ASSET_ANCHOR_REGISTRY`; agora's\n * `_CATALOG_ANCHORS_BY_PROVIDER`), so the anchor alone names the provider.\n */\nfunction GitHubMarkIcon({ className }: { className?: string }) {\n return (\n <svg\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n className={className}\n data-chip-icon=\"github\"\n >\n <path d=\"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z\" />\n </svg>\n );\n}\n\n/** Anchors only a session holds: its messages, blocks and tool calls. */\nconst SESSION_ANCHORS: ReadonlySet<string> = new Set([\n \"msg\",\n \"msg_range\",\n \"msg_block\",\n \"msg_section\",\n \"msg_text\",\n \"tool_call\",\n]);\n\n/** Whether a link names a session (its type, or an anchor only a session holds). */\nfunction isSessionLink(\n assetType: string | undefined,\n citation: MentionChipCitation | undefined,\n): boolean {\n return (\n assetType?.toLowerCase() === \"session\" ||\n (citation !== undefined && SESSION_ANCHORS.has(citation.anchorType))\n );\n}\n\n/** Past this many characters a place may not show whole in the chip, so the tooltip spells it out. */\nconst PLACE_FITS_CHARS = 20;\n\n/** `route.ts:18-24` as the file's name and its lines, so a long name shortens while its lines stay. */\nfunction splitFileLines(label: string): { file: string; lines: string } {\n const colon = label.lastIndexOf(\":\");\n return colon > 0\n ? { file: label.slice(0, colon), lines: label.slice(colon) }\n : { file: label, lines: \"\" };\n}\n\n/**\n * Whether a name already says where its citation points: the place's label or\n * its spelled-out form, or a name ending in the label (`Q4 report p.5`,\n * `olympus/…/route.ts:18-24`). The chip then draws the place once.\n */\nfunction restatesPlace(name: string, citation: MentionChipCitation): boolean {\n const said = name.trim().toLowerCase();\n const label = citation.label.toLowerCase();\n return said === label || said === citation.description.toLowerCase() || said.endsWith(label);\n}\n\n/**\n * The link's own label when it tells the reader something the chip does not\n * already show: not the place again (a path, `file:lines`), not the asset's\n * name. The tooltip keeps it, since the chip shows the asset and the place.\n */\nfunction informativeLabel({\n label,\n shown,\n citation,\n}: {\n label: string;\n shown: readonly (string | null | undefined)[];\n citation: MentionChipCitation | undefined;\n}): string | null {\n const trimmed = label.trim();\n if (!trimmed || !SPEAKABLE.test(trimmed)) return null;\n if (PLACEHOLDER_LABELS.has(trimmed.toLowerCase())) return null;\n if (citation && restatesPlace(trimmed, citation)) return null;\n // Every word of it already shown (`Tesla Q3 report` beside `Tesla Q3\n // Earnings Report`, `demo-app-monorepo` beside the repository's title).\n const shownWords = new Set(\n [...shown, citation?.description].flatMap((text) => (text ? wordsOf(text) : [])),\n );\n return wordsOf(trimmed).every((word) => shownWords.has(word)) ? null : trimmed;\n}\n\nfunction wordsOf(text: string): string[] {\n return text.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [];\n}\n\n/** A label with a letter or digit in it; `§` or `•` alone says nothing read aloud. */\nconst SPEAKABLE = /[\\p{L}\\p{N}]/u;\n\n/** Labels that name nothing: agora's read_asset citations all read `Citation`. */\nconst PLACEHOLDER_LABELS: ReadonlySet<string> = new Set([\"citation\", \"source\", \"link\", \"here\"]);\n\n/** The asset reference an asset link decodes to, or null when it does not parse. */\nfunction decodeAssetLink(\n url: URL,\n decode: (url: URL) => AssetReference,\n): AssetReference | null {\n try {\n return decode(url);\n } catch {\n return null;\n }\n}\n\n// ── Mention link component for markdown renderer ──\n\n/**\n * Custom <a> renderer for MarkdownTextPrimitive.\n * Intercepts mention:// links and renders them as chips.\n * Falls through to a normal link for non-mention URLs.\n */\nfunction personEmailForMention(\n parsed: ReturnType<typeof parseMentionUrl>,\n): string | undefined {\n if (parsed.type !== \"person\") return undefined;\n return parsed.email || (parsed.id.includes(\"@\") ? parsed.id : undefined);\n}\n\n/**\n * The text a link's children read as. Markdown can hand a link several children, some of them\n * elements (an escaped `_` or a `*` in a URL splits its text), and stringifying an element gives\n * `[object Object]`.\n */\nfunction textOf(node: ReactNode): string {\n if (typeof node === \"string\" || typeof node === \"number\") return String(node);\n if (Array.isArray(node)) return node.map(textOf).join(\"\");\n if (isValidElement<{ children?: ReactNode }>(node)) return textOf(node.props.children);\n return \"\";\n}\n\nexport const MentionLink: FC<{\n href?: string;\n children?: ReactNode;\n interactive?: boolean;\n}> = ({ href, children, interactive = true }) => {\n if (\n href &&\n (href.startsWith(\"mention://\") || isSpacesMentionUrl(href))\n ) {\n const name = textOf(children).trim().replace(/^@/, \"\");\n\n const parsed = parseMentionUrl(href);\n\n return (\n <MentionChip\n name={name || parsed.name}\n type={parsed.type}\n personEmail={personEmailForMention(parsed)}\n assetIds={parsed.assetIds}\n assetType={parsed.assetType}\n citation={parsed.citation}\n thumbnailUrl={parsed.thumbnailUrl}\n sourceHref={isSpacesMentionUrl(href) ? href : parsed.sourceHref}\n interactive={interactive}\n />\n );\n }\n\n if (href?.startsWith(\"chrome-extension://\")) {\n return <span>{children}</span>;\n }\n\n if (isScreenPointHref(href)) {\n return <ScreenPointChip href={href}>{children}</ScreenPointChip>;\n }\n\n // Normal link — render as-is\n return (\n <a href={href} target=\"_blank\" rel=\"noopener noreferrer\">\n {children}\n </a>\n );\n};\n\n// ── The chip pill ──\n\n/**\n * Olympus's mention pill (`mentionPillClassName`: 20px high, 16px icon, the\n * place in `text-xs`) in the provider's theme tokens, so a dark theme keeps it\n * legible, and `box-border` so its height holds without a host's CSS reset.\n * Every chat chip draws it: an asset or citation chip, a web source, a screen\n * point. Only stock Tailwind sizes: Olympus renders these chips (the queued\n * message tray) with a stylesheet that does not scan this package, so an\n * arbitrary value would reach it unstyled. `not-prose` matters: assistant\n * messages render inside Tailwind Typography's `prose`, whose\n * zero-specificity `img` margins (~1.7em top/bottom) would otherwise inflate\n * the chip's icon into a tall card that breaks the sentence flow around it.\n */\nexport const CHIP_PILL_CLASS =\n \"not-prose box-border inline-flex h-5 items-center gap-1.5 whitespace-nowrap rounded-md border border-border bg-muted px-1 py-0.5 align-middle font-normal leading-none text-foreground no-underline\";\n/** A chip that opens something. */\nexport const CHIP_LINK_CLASS =\n \"cursor-pointer transition-colors hover:bg-accent hover:text-accent-foreground hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1\";\nexport const CHIP_ICON_CLASS = \"size-4 shrink-0\";\n\n// ── Inline screen-point chip ──\n\n/**\n * Renders an `athena-point://` link as a non-navigating coordinate chip.\n * Surfaces without screenshot context (extension side panel, SDK consumers)\n * get the label plus the coordinates; malformed points fall back to text.\n */\nexport const ScreenPointChip: FC<{\n href: string;\n children?: ReactNode;\n}> = ({ href, children }) => {\n const parsed = parseScreenPointHref(href);\n if (!parsed.ok) {\n return <span>{children}</span>;\n }\n const description = formatScreenPoint(parsed.point);\n return (\n <span\n className={cn(CHIP_PILL_CLASS, \"max-w-[260px]\")}\n title={description}\n aria-label={description}\n data-screen-point=\"valid\"\n >\n <CrosshairIcon className={CHIP_ICON_CLASS} aria-hidden=\"true\" />\n <span className=\"min-w-0 max-w-[180px] overflow-hidden text-ellipsis\">\n {children}\n </span>\n <span className=\"shrink-0 text-xs text-muted-foreground\">\n {parsed.point.x}, {parsed.point.y}\n </span>\n </span>\n );\n};\n\n// ── Inline mention chip ──\n\nexport const MentionChip: FC<{\n name: string;\n type?: string;\n assetIds?: string[];\n /** The asset's type (`document`, `catalog`, …): picks the icon until (or unless) the asset is looked up. */\n assetType?: string;\n /** Where in the asset the link points: its label follows the name. */\n citation?: MentionChipCitation;\n personEmail?: string;\n thumbnailUrl?: string;\n sourceHref?: string;\n interactive?: boolean;\n}> = ({\n name,\n type,\n assetIds,\n assetType,\n citation,\n personEmail,\n thumbnailUrl,\n sourceHref,\n interactive = true,\n}) => {\n const auth = useContext(MentionAuthCtx);\n const memberAvatarUrl = useMemberAvatarUrl(personEmail);\n const [erroredAvatarUrl, setErroredAvatarUrl] = useState<string>();\n const excerpt = sourceHref ? readSourceExcerpt(sourceHref) : null;\n // A repository file's lines read as the file (`route.ts:18-24`): the chip\n // opens that file, and every citation in a reply names the same repository,\n // whatever label the model wrote.\n const repositoryFile =\n citation?.anchorType === \"file_line_range\"\n ? { ...splitFileLines(citation.label), label: citation.label }\n : null;\n // The asset as agora has it, read the way Olympus's chips read it: its own\n // title and type. Until it answers, and for an asset the viewer cannot read,\n // the link's label and `type=` stand in. Asked only where it changes the\n // chip: a repository file reads as its file whatever the catalog is called,\n // and a session's row is too heavy to read for a name.\n const asset = useMentionAsset(\n type === \"asset\" &&\n assetIds?.length === 1 &&\n !repositoryFile &&\n !isSessionLink(assetType, citation)\n ? assetIds[0]\n : undefined,\n );\n const assetTitle = asset?.title || null;\n const chipName = repositoryFile?.label ?? assetTitle ?? name;\n // The place follows a name that does not already say it, as `[p.5]`.\n const placeLabel =\n citation && !repositoryFile && !restatesPlace(chipName, citation)\n ? citation.label\n : null;\n // The tooltip: what the model called it (when the chip does not show it),\n // the repository a file is in and the file's whole path, the cited passage.\n // The place spelled out stands in for a passage the citation does not carry,\n // and for a place too long to show whole (a long sheet name).\n const tooltip =\n citation || excerpt\n ? tooltipText({\n lines: [\n informativeLabel({ label: name, shown: [chipName, assetTitle], citation }),\n repositoryFile ? assetTitle : null,\n repositoryFile || !excerpt || (placeLabel?.length ?? 0) > PLACE_FITS_CHARS\n ? citation?.description\n : null,\n ],\n excerpt,\n })\n : null;\n const assetRootHref =\n type === \"asset\" && assetIds?.length\n ? createOlympusAssetUrl({\n appUrl: auth?.appUrl,\n backendUrl: auth?.backendUrl,\n assetIds,\n })\n : null;\n const href = (() => {\n if (!assetRootHref || !sourceHref) return assetRootHref;\n try {\n const source = new URL(sourceHref, \"https://app.athenaintel.com\");\n const destination = new URL(assetRootHref);\n for (const [key, value] of source.searchParams) {\n destination.searchParams.set(key, value);\n }\n destination.searchParams.set(\"asset_ids\", assetIds?.join(\",\") ?? \"\");\n return destination.toString();\n } catch {\n return assetRootHref;\n }\n })();\n const className = cn(CHIP_PILL_CLASS, \"max-w-[275px]\", href && CHIP_LINK_CLASS);\n // A host's asset-type SVG follows the looked-up type, when it serves them.\n const chipThumbnailUrl = repositoryFile\n ? undefined\n : (asset?.assetType && assetTypeToThumb(asset.assetType)) || thumbnailUrl;\n const AssetIcon = assetChipIcon(asset?.assetType || assetType);\n const contents = (\n <>\n {repositoryFile ? (\n <GitHubMarkIcon className={CHIP_ICON_CLASS} />\n ) : chipThumbnailUrl ? (\n <img\n src={chipThumbnailUrl}\n alt=\"\"\n className={CHIP_ICON_CLASS}\n draggable={false}\n />\n ) : type === \"asset\" || type === \"folder\" ? (\n // A host that bundles no asset-type SVGs (computer apps, most SDK\n // apps) still gets the type's icon.\n <AssetIcon className={CHIP_ICON_CLASS} aria-hidden=\"true\" />\n ) : type === \"webpage\" ? (\n <Globe2Icon className={CHIP_ICON_CLASS} aria-hidden=\"true\" />\n ) : type === \"person\" ? (\n memberAvatarUrl && erroredAvatarUrl !== memberAvatarUrl ? (\n <img\n src={memberAvatarUrl}\n alt=\"\"\n className={cn(CHIP_ICON_CLASS, \"rounded-full object-cover\")}\n draggable={false}\n onError={() => setErroredAvatarUrl(memberAvatarUrl)}\n />\n ) : (\n <UserIcon className={CHIP_ICON_CLASS} aria-hidden=\"true\" />\n )\n ) : null}\n {repositoryFile ? (\n <span\n className=\"flex min-w-0 items-center\"\n data-citation-anchor=\"file_line_range\"\n >\n <span className=\"min-w-0 overflow-hidden text-ellipsis\">\n {repositoryFile.file}\n </span>\n <span className=\"shrink-0 text-muted-foreground\">{repositoryFile.lines}</span>\n </span>\n ) : (\n <span\n className={cn(\n \"max-w-[180px] overflow-hidden text-ellipsis\",\n // A long place may shorten the name, never make it vanish.\n placeLabel && \"min-w-8\",\n )}\n >\n {chipName}\n </span>\n )}\n {citation && placeLabel && (\n <>\n {/* Copied or read as text, the place stays a word apart from the name; a flex row draws no space. */}{\" \"}\n <span\n className=\"flex min-w-0 items-center text-xs text-muted-foreground\"\n data-citation-anchor={citation.anchorType}\n >\n [<span className=\"min-w-0 overflow-hidden text-ellipsis\">{placeLabel}</span>]\n </span>\n </>\n )}\n </>\n );\n\n if (href && interactive) {\n const speakablePlace = citation && SPEAKABLE.test(citation.description);\n return (\n <a\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={className}\n aria-label={\n repositoryFile && citation\n ? `Open ${citation.description} in Spaces`\n : placeLabel && citation && speakablePlace\n ? `Open ${chipName} at ${citation.description} in Spaces`\n : `Open ${chipName} in Spaces`\n }\n title={tooltip ?? `Open ${chipName} in Spaces`}\n data-excerpt={excerpt ?? undefined}\n // The asset without its place: what a click names the opened asset.\n data-mention-name={repositoryFile ? (assetTitle ?? name) : chipName}\n >\n {contents}\n </a>\n );\n }\n\n return (\n <span\n className={className}\n title={tooltip ?? undefined}\n data-excerpt={excerpt ?? undefined}\n >\n {contents}\n </span>\n );\n};\n\n/**\n * A chip's tooltip: the lines that say something, each once, then the cited\n * passage, quoted when it shares the tooltip with other lines.\n */\nfunction tooltipText({\n lines,\n excerpt,\n}: {\n lines: readonly (string | null | undefined)[];\n excerpt: string | null;\n}): string | null {\n const kept: string[] = [];\n for (const line of lines) {\n const trimmed = line?.trim();\n if (trimmed && !kept.includes(trimmed)) kept.push(trimmed);\n }\n if (excerpt) kept.push(kept.length ? `“${excerpt}”` : excerpt);\n return kept.length ? kept.join(\"\\n\") : null;\n}\n\n/** The `excerpt` a Spaces citation URL carries, or null. */\nfunction readSourceExcerpt(href: string): string | null {\n try {\n const excerpt = new URL(href, \"https://app.athenaintel.com\").searchParams\n .get(\"excerpt\")\n ?.trim();\n return excerpt ? excerpt : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The label an asset citation chip falls back to when the model wrote none\n * (`[](…/spaces/?asset_ids=…&page=5)`): the cited location, else \"Asset\" — a\n * chip must never render as an empty box.\n */\nfunction citationFallbackLabel(params: URLSearchParams): string {\n const start = params.get(\"start_page\") ?? params.get(\"page\");\n const end = params.get(\"end_page\");\n if (start && end && end !== start) return `Pages ${start}–${end}`;\n if (start) return `Page ${start}`;\n return \"Asset\";\n}\n\n// ── Parse mention:// URLs ──\n\nexport function parseMentionUrl(url: string): {\n type: string;\n name: string;\n id: string;\n email?: string;\n assetIds?: string[];\n assetType?: string;\n citation?: MentionChipCitation;\n /**\n * For a `mention://asset` citation, the Spaces link to its place (anchor and\n * excerpt), so the chip opens there; a Spaces mention is its own link.\n */\n sourceHref?: string;\n thumbnailUrl?: string;\n} {\n try {\n if (isSpacesMentionUrl(url)) {\n const parsed = new URL(url, \"https://app.athenaintel.com\");\n const assetIds = (parsed.searchParams.get(\"asset_ids\") ?? \"\")\n .split(\",\")\n .map((id) => id.trim())\n .filter(Boolean);\n const id = assetIds[0] ?? \"\";\n const assetType = getSpacesAssetType(parsed);\n // A link to several assets names no one place in any of them.\n const reference =\n assetIds.length === 1\n ? decodeAssetLink(parsed, decodeFromAssetSpacesUrl)\n : null;\n const citation = reference ? citationOf(reference) : undefined;\n return {\n type: \"asset\",\n name:\n assetIds.length > 1\n ? `${assetIds.length} assets`\n : (citation?.description ??\n citationFallbackLabel(parsed.searchParams)),\n id,\n assetIds,\n assetType: assetType ?? undefined,\n citation,\n thumbnailUrl: assetTypeToThumb(assetType),\n };\n }\n // mention://tool?name=...&description=...\n // mention://asset?id=...&assetType=project&thumb=../icons/files/ic-project.svg\n const u = new URL(url);\n const type = u.hostname || u.pathname.replace(/^\\/\\//, \"\").split(\"?\")[0];\n const isWebpage = type === \"webpage\";\n const id = isWebpage\n ? u.searchParams.get(\"tab_id\") || \"\"\n : u.searchParams.get(\"id\") || u.searchParams.get(\"name\") || \"\";\n const name = isWebpage\n ? u.searchParams.get(\"title\") || \"This webpage\"\n : u.searchParams.get(\"name\") || id;\n\n // Get thumbnail: prefer explicit thumb param, then derive from assetType\n let thumbnailUrl = u.searchParams.get(\"thumb\") || undefined;\n if (!thumbnailUrl) {\n const assetType = u.searchParams.get(\"assetType\");\n if (assetType) {\n thumbnailUrl = assetTypeToThumb(assetType);\n } else if (type === \"asset\" || type === \"folder\") {\n thumbnailUrl = assetTypeToThumb(type === \"folder\" ? \"folder\" : null);\n }\n }\n\n const reference =\n type === \"asset\" ? decodeAssetLink(u, decodeFromAssetMentionUri) : null;\n\n return {\n type,\n name,\n id,\n email: type === \"person\" ? u.searchParams.get(\"email\") || undefined : undefined,\n assetIds: type === \"asset\" && id ? [id] : undefined,\n assetType:\n type === \"asset\" || type === \"folder\"\n ? u.searchParams.get(\"assetType\") ||\n reference?.meta?.assetType ||\n (type === \"folder\" ? \"folder\" : undefined)\n : undefined,\n citation: reference ? citationOf(reference) : undefined,\n sourceHref:\n reference && (reference.anchor || reference.meta?.excerpt)\n ? encodeToAssetSpacesUrl(reference)\n : undefined,\n thumbnailUrl,\n };\n } catch {\n return { type: \"unknown\", name: \"\", id: \"\" };\n }\n}\n\nfunction htmlAttribute(attributes: string, name: string): string | null {\n const escapedName = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = new RegExp(\n `(?:^|\\\\s)${escapedName}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`,\n \"i\",\n ).exec(attributes);\n return match?.[1] ?? match?.[2] ?? match?.[3] ?? null;\n}\n\nfunction decodeHtmlAttribute(value: string): string {\n return value\n .replace(/&amp;/gi, \"&\")\n .replace(/&quot;/gi, '\"')\n .replace(/&#39;|&apos;/gi, \"'\")\n .replace(/&lt;/gi, \"<\")\n .replace(/&gt;/gi, \">\");\n}\n\n/** Turn complete model-emitted URL citation anchors into safe Markdown links. */\nexport function normalizeAthenaMentionHtml(text: string): string {\n return text.replace(\n /<a\\b([^>]*)>([\\s\\S]*?)<\\/a>/gi,\n (original, attributes: string, rawLabel: string) => {\n const className = htmlAttribute(attributes, \"class\") ?? \"\";\n const type = htmlAttribute(attributes, \"data-type\") ?? \"\";\n if (!className.split(/\\s+/).includes(\"mention\") || type !== \"url\") {\n return original;\n }\n\n const rawUrl =\n htmlAttribute(attributes, \"data-url\") ??\n htmlAttribute(attributes, \"href\");\n if (!rawUrl) return original;\n const url = decodeHtmlAttribute(rawUrl);\n let normalizedUrl: string;\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return original;\n }\n normalizedUrl = parsed.toString();\n } catch {\n return original;\n }\n\n const label = decodeHtmlAttribute(rawLabel.replace(/<[^>]*>/g, \"\"))\n .trim()\n .replace(/([\\\\[\\]])/g, \"\\\\$1\");\n return label ? `[${label}](<${normalizedUrl}>)` : original;\n },\n );\n}\n// ── Parse mention markdown in plain text ──\n\n// The label may hold balanced brackets one level deep (`[@Plan [Q3]](…)`) or a lone `[`.\nconst MENTION_RE =\n /\\[@((?:\\[[^[\\]]*\\](?!\\((?:[a-z][a-z0-9+.-]*:\\/\\/|\\/))|[^\\]])*)\\]\\(((?:mention:\\/\\/|(?:https?:\\/\\/[^)\\s]+)?\\/dashboard\\/spaces\\/?\\?)[^)]+)\\)/g;\n\n/**\n * Parse text containing [@name](mention://...) patterns into\n * an array of string segments and MentionChip elements.\n */\nexport function parseMentionsInText(text: string): (string | ReactElement)[] {\n const parts: (string | ReactElement)[] = [];\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n MENTION_RE.lastIndex = 0;\n\n while ((match = MENTION_RE.exec(text)) !== null) {\n if (match.index > lastIndex) {\n parts.push(text.slice(lastIndex, match.index));\n }\n\n const name = match[1];\n const url = match[2];\n const parsed = parseMentionUrl(url);\n\n parts.push(\n <MentionChip\n key={`mention-${match.index}`}\n name={name || parsed.name}\n type={parsed.type}\n personEmail={personEmailForMention(parsed)}\n assetIds={parsed.assetIds}\n assetType={parsed.assetType}\n citation={parsed.citation}\n thumbnailUrl={parsed.thumbnailUrl}\n sourceHref={isSpacesMentionUrl(url) ? url : parsed.sourceHref}\n />\n );\n\n lastIndex = match.index + match[0].length;\n }\n\n if (lastIndex < text.length) {\n parts.push(text.slice(lastIndex));\n }\n\n return parts.length > 0 ? parts : [text];\n}\n\n/** The text as a reader sees it: each `[@name](…)` mention becomes `@name`. */\nexport function mentionsToPlainText(text: string): string {\n return text.replace(MENTION_RE, (_match, name: string, url: string) => {\n return `@${name || parseMentionUrl(url).name}`;\n });\n}\n"],"names":["id","reference"],"mappings":";;;;;;;;;;;;;AAsDA,MAAM,sBAAsB;AAE5B,SAAS,mBAAmB,KAAsB;AAChD,SAAO,oBAAoB,KAAK,GAAG;AACrC;AAEA,SAAS,mBAAmB,KAAyB;AACnD,QAAM,YACJ,IAAI,aAAa,IAAI,WAAW,KAChC,IAAI,aAAa,IAAI,YAAY,KACjC,IAAI,aAAa,IAAI,MAAM;AAC7B,SAAO,cAAc,UAAU,gBAAgB;AACjD;AAsBA,SAAS,WAAW,WAA4D;AAC9E,QAAM,EAAE,QAAQ,KAAA,IAAS;AACzB,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,QAAQ,sBAAsB,QAAQ,SAAS,IAAI;AACzD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,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CAAC;AAAA,IAC/C;AAEA,UAAM,OAAO,MAAM,CAAC;AACpB,UAAM,MAAM,MAAM,CAAC;AACnB,UAAM,SAAS,gBAAgB,GAAG;AAElC,UAAM;AAAA,MACJ;AAAA,QAAC;AAAA,QAAA;AAAA,UAEC,MAAM,QAAQ,OAAO;AAAA,UACrB,MAAM,OAAO;AAAA,UACb,aAAa,sBAAsB,MAAM;AAAA,UACzC,UAAU,OAAO;AAAA,UACjB,WAAW,OAAO;AAAA,UAClB,UAAU,OAAO;AAAA,UACjB,cAAc,OAAO;AAAA,UACrB,YAAY,mBAAmB,GAAG,IAAI,MAAM,OAAO;AAAA,QAAA;AAAA,QAR9C,WAAW,MAAM,KAAK;AAAA,MAAA;AAAA,IAS7B;AAGF,gBAAY,MAAM,QAAQ,MAAM,CAAC,EAAE;AAAA,EACrC;AAEA,MAAI,YAAY,KAAK,QAAQ;AAC3B,UAAM,KAAK,KAAK,MAAM,SAAS,CAAC;AAAA,EAClC;AAEA,SAAO,MAAM,SAAS,IAAI,QAAQ,CAAC,IAAI;AACzC;AAGO,SAAS,oBAAoB,MAAsB;AACxD,SAAO,KAAK,QAAQ,YAAY,CAAC,QAAQ,MAAc,QAAgB;AACrE,WAAO,IAAI,QAAQ,gBAAgB,GAAG,EAAE,IAAI;AAAA,EAC9C,CAAC;AACH;"}
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const reactQuery = require("@tanstack/react-query");
4
+ const react = require("react");
5
+ const apiClient = require("./suggestions/data/api-client.cjs");
6
+ const MENTION_ASSET_BATCH_SIZE = 50;
7
+ const MENTION_ASSET_BATCH_WINDOW_MS = 16;
8
+ const MENTION_ASSET_STALE_TIME_MS = 6e4;
9
+ const MENTION_ASSETS_QUERY = `
10
+ query MentionChipAssets($assetIds: [String!]!) {
11
+ getAssetsByIds(assetIds: $assetIds) {
12
+ id
13
+ title
14
+ athenaOriginalType
15
+ }
16
+ }
17
+ `;
18
+ const LOOKUP_ID = /^asset_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
+ function mentionAssetLookupId(assetId) {
20
+ const baseId = (assetId == null ? void 0 : assetId.trim().split("@")[0]) ?? "";
21
+ return LOOKUP_ID.test(baseId) ? baseId : null;
22
+ }
23
+ function canAuthenticate(auth) {
24
+ return Boolean(auth.accessToken || auth.apiKey || auth.credentials || auth.getAccessToken);
25
+ }
26
+ function fingerprint(credential) {
27
+ let hash = 2166136261;
28
+ for (let index = 0; index < credential.length; index += 1) {
29
+ hash ^= credential.charCodeAt(index);
30
+ hash = Math.imul(hash, 16777619) >>> 0;
31
+ }
32
+ return hash.toString(16).padStart(8, "0");
33
+ }
34
+ const authScopes = /* @__PURE__ */ new WeakMap();
35
+ let authScopeCount = 0;
36
+ function principalOf(auth) {
37
+ const scope = [];
38
+ if (auth.userId) scope.push(`user:${auth.userId}`);
39
+ if (auth.apiKey) scope.push(`key:${fingerprint(auth.apiKey)}`);
40
+ if (scope.length) return scope.join("|");
41
+ let own = authScopes.get(auth);
42
+ if (!own) {
43
+ authScopeCount += 1;
44
+ own = `auth:${authScopeCount}`;
45
+ authScopes.set(auth, own);
46
+ }
47
+ const token = auth.accessToken;
48
+ return token ? `${own}|token:${fingerprint(token)}` : own;
49
+ }
50
+ const pendingBatches = /* @__PURE__ */ new Map();
51
+ function settle(waiters, asset) {
52
+ for (const waiter of waiters ?? []) waiter.resolve(asset);
53
+ }
54
+ function fail(waiters, error) {
55
+ for (const waiter of waiters ?? []) waiter.reject(error);
56
+ }
57
+ function sendBatch(batchKey) {
58
+ const batch = pendingBatches.get(batchKey);
59
+ if (!batch) return;
60
+ pendingBatches.delete(batchKey);
61
+ const ids = [...batch.waiters.keys()];
62
+ for (let start = 0; start < ids.length; start += MENTION_ASSET_BATCH_SIZE) {
63
+ const chunk = ids.slice(start, start + MENTION_ASSET_BATCH_SIZE);
64
+ apiClient.fetchGraphQL(batch.auth, MENTION_ASSETS_QUERY, {
65
+ assetIds: chunk
66
+ }).then(
67
+ (data) => {
68
+ var _a, _b;
69
+ const found = new Map((data.getAssetsByIds ?? []).map((asset) => [asset.id, asset]));
70
+ for (const id of chunk) {
71
+ const asset = found.get(id);
72
+ settle(
73
+ batch.waiters.get(id),
74
+ asset ? {
75
+ id,
76
+ title: ((_a = asset.title) == null ? void 0 : _a.trim()) ?? "",
77
+ assetType: ((_b = asset.athenaOriginalType) == null ? void 0 : _b.trim()) ?? ""
78
+ } : null
79
+ );
80
+ }
81
+ },
82
+ (error) => {
83
+ for (const id of chunk) fail(batch.waiters.get(id), error);
84
+ }
85
+ );
86
+ }
87
+ }
88
+ function loadMentionAsset({
89
+ auth,
90
+ batchKey,
91
+ assetId
92
+ }) {
93
+ return new Promise((resolve, reject) => {
94
+ let batch = pendingBatches.get(batchKey);
95
+ if (!batch) {
96
+ batch = { auth, waiters: /* @__PURE__ */ new Map() };
97
+ pendingBatches.set(batchKey, batch);
98
+ setTimeout(() => sendBatch(batchKey), MENTION_ASSET_BATCH_WINDOW_MS);
99
+ }
100
+ const waiters = batch.waiters.get(assetId) ?? [];
101
+ waiters.push({ resolve, reject });
102
+ batch.waiters.set(assetId, waiters);
103
+ });
104
+ }
105
+ const chipQueryClient = new reactQuery.QueryClient();
106
+ function useMentionAsset(assetId) {
107
+ const auth = react.useContext(apiClient.MentionAuthCtx);
108
+ const hostQueryClient = react.useContext(reactQuery.QueryClientContext);
109
+ const lookupId = mentionAssetLookupId(assetId);
110
+ const enabled = Boolean(auth && lookupId && canAuthenticate(auth));
111
+ const backendUrl = (auth == null ? void 0 : auth.backendUrl) ?? "";
112
+ const principal = auth ? principalOf(auth) : "";
113
+ const { data } = reactQuery.useQuery(
114
+ {
115
+ queryKey: ["athena-sdk", "mention-asset", backendUrl, principal, lookupId ?? ""],
116
+ queryFn: () => {
117
+ if (!auth || !lookupId) return null;
118
+ return loadMentionAsset({
119
+ auth,
120
+ batchKey: `${backendUrl}|${principal}`,
121
+ assetId: lookupId
122
+ });
123
+ },
124
+ enabled,
125
+ staleTime: MENTION_ASSET_STALE_TIME_MS,
126
+ // Kept no longer than it is fresh: a title is shown again only after
127
+ // agora answers again, never from a cache a minute past its check.
128
+ gcTime: MENTION_ASSET_STALE_TIME_MS,
129
+ retry: false,
130
+ refetchOnWindowFocus: false
131
+ },
132
+ hostQueryClient ?? chipQueryClient
133
+ );
134
+ return enabled ? data : void 0;
135
+ }
136
+ exports.MENTION_ASSET_BATCH_SIZE = MENTION_ASSET_BATCH_SIZE;
137
+ exports.MENTION_ASSET_BATCH_WINDOW_MS = MENTION_ASSET_BATCH_WINDOW_MS;
138
+ exports.mentionAssetLookupId = mentionAssetLookupId;
139
+ exports.useMentionAsset = useMentionAsset;
140
+ //# sourceMappingURL=use-mention-asset.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-mention-asset.cjs","sources":["../../../src/chat-ui/mentions/use-mention-asset.ts"],"sourcesContent":["/**\n * The asset an asset chip names, read the way Olympus's chips read it: its\n * title and type from agora's `getAssetsByIds`, which returns only the assets\n * the caller may read (an id they cannot read is left out of the answer, as is\n * another workspace's). A chip then shows the asset's own name and icon\n * instead of whatever label and `type=` its link carried.\n *\n * Chips that mount together ask together: one GraphQL request per batch of up\n * to {@link MENTION_ASSET_BATCH_SIZE} ids, gathered over\n * {@link MENTION_ASSET_BATCH_WINDOW_MS}. Each answer is a TanStack query keyed\n * by backend, the person asking and the id, fresh for a minute, so a\n * transcript full of citations to one repository asks for it once.\n */\nimport { QueryClient, QueryClientContext, useQuery } from \"@tanstack/react-query\";\nimport { useContext } from \"react\";\nimport {\n fetchGraphQL,\n type MentionAuthContext,\n MentionAuthCtx,\n} from \"./suggestions/data/api-client\";\n\n/** What a chip draws from the asset: its current title and its type. */\nexport interface MentionAsset {\n id: string;\n title: string;\n assetType: string;\n}\n\nexport const MENTION_ASSET_BATCH_SIZE = 50;\nexport const MENTION_ASSET_BATCH_WINDOW_MS = 16;\nconst MENTION_ASSET_STALE_TIME_MS = 60_000;\n\n/** No metadata: a session's carries its token ledgers, and a chip needs a name and a type. */\nconst MENTION_ASSETS_QUERY = `\n query MentionChipAssets($assetIds: [String!]!) {\n getAssetsByIds(assetIds: $assetIds) {\n id\n title\n athenaOriginalType\n }\n }\n`;\n\ninterface MentionAssetsResponse {\n getAssetsByIds?: Array<{\n id: string;\n title: string | null;\n athenaOriginalType: string | null;\n }> | null;\n}\n\n/**\n * The ids a lookup asks about: a stored asset. A versioned id (`asset_x@3`)\n * asks about its asset. A live provider file (`asset_<catalog>_<file>`) is not\n * a row `getAssetsByIds` holds, and a session (`asset_thread_<uuid>`) is never\n * asked about: agora reads the whole row, and a session's metadata carries\n * its transcript's ledgers (megabytes on a long session) — too much for a name.\n */\nconst LOOKUP_ID = /^asset_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function mentionAssetLookupId(assetId: string | undefined): string | null {\n const baseId = assetId?.trim().split(\"@\")[0] ?? \"\";\n return LOOKUP_ID.test(baseId) ? baseId : null;\n}\n\n/** Whether a request can carry a credential (`mentionRequestInit` refuses one that cannot). */\nfunction canAuthenticate(auth: MentionAuthContext): boolean {\n return Boolean(auth.accessToken || auth.apiKey || auth.credentials || auth.getAccessToken);\n}\n\n/** A short, stable stand-in for a credential in a cache key; never the credential itself. */\nfunction fingerprint(credential: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < credential.length; index += 1) {\n hash ^= credential.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n/** The scope each credential with no stable identity of its own gets: its own auth object. */\nconst authScopes = new WeakMap<MentionAuthContext, string>();\nlet authScopeCount = 0;\n\n/**\n * Who is asking, as narrowly as the credential says: what `getAssetsByIds`\n * answers differs per person and per API key, and an answer (or a batch's\n * request) is only ever shared within one scope. A person's id and an API key\n * scope the cache across token rotations. A credential that names neither (a\n * session cookie, a token callback) shares nothing beyond its own auth object\n * and its current token, so a token swapped on the same object asks again.\n */\nfunction principalOf(auth: MentionAuthContext): string {\n const scope: string[] = [];\n if (auth.userId) scope.push(`user:${auth.userId}`);\n if (auth.apiKey) scope.push(`key:${fingerprint(auth.apiKey)}`);\n if (scope.length) return scope.join(\"|\");\n let own = authScopes.get(auth);\n if (!own) {\n authScopeCount += 1;\n own = `auth:${authScopeCount}`;\n authScopes.set(auth, own);\n }\n const token = auth.accessToken;\n return token ? `${own}|token:${fingerprint(token)}` : own;\n}\n\ninterface Waiter {\n resolve: (asset: MentionAsset | null) => void;\n reject: (error: unknown) => void;\n}\n\ninterface PendingBatch {\n auth: MentionAuthContext;\n waiters: Map<string, Waiter[]>;\n}\n\n/** The batch each backend and principal is gathering, until its window closes. */\nconst pendingBatches = new Map<string, PendingBatch>();\n\nfunction settle(waiters: Waiter[] | undefined, asset: MentionAsset | null): void {\n for (const waiter of waiters ?? []) waiter.resolve(asset);\n}\n\nfunction fail(waiters: Waiter[] | undefined, error: unknown): void {\n for (const waiter of waiters ?? []) waiter.reject(error);\n}\n\nfunction sendBatch(batchKey: string): void {\n const batch = pendingBatches.get(batchKey);\n if (!batch) return;\n pendingBatches.delete(batchKey);\n const ids = [...batch.waiters.keys()];\n for (let start = 0; start < ids.length; start += MENTION_ASSET_BATCH_SIZE) {\n const chunk = ids.slice(start, start + MENTION_ASSET_BATCH_SIZE);\n fetchGraphQL<MentionAssetsResponse>(batch.auth, MENTION_ASSETS_QUERY, {\n assetIds: chunk,\n }).then(\n (data) => {\n const found = new Map((data.getAssetsByIds ?? []).map((asset) => [asset.id, asset]));\n for (const id of chunk) {\n const asset = found.get(id);\n settle(\n batch.waiters.get(id),\n asset\n ? {\n id,\n title: asset.title?.trim() ?? \"\",\n assetType: asset.athenaOriginalType?.trim() ?? \"\",\n }\n : null,\n );\n }\n },\n (error: unknown) => {\n for (const id of chunk) fail(batch.waiters.get(id), error);\n },\n );\n }\n}\n\nfunction loadMentionAsset({\n auth,\n batchKey,\n assetId,\n}: {\n auth: MentionAuthContext;\n batchKey: string;\n assetId: string;\n}): Promise<MentionAsset | null> {\n return new Promise((resolve, reject) => {\n let batch = pendingBatches.get(batchKey);\n if (!batch) {\n batch = { auth, waiters: new Map() };\n pendingBatches.set(batchKey, batch);\n setTimeout(() => sendBatch(batchKey), MENTION_ASSET_BATCH_WINDOW_MS);\n }\n const waiters = batch.waiters.get(assetId) ?? [];\n waiters.push({ resolve, reject });\n batch.waiters.set(assetId, waiters);\n });\n}\n\n/** Chips rendered outside any query client (a host's own tray) still share one cache. */\nconst chipQueryClient = new QueryClient();\n\n/**\n * The asset an asset chip names: `undefined` while unknown (no lookup, still\n * loading, or the lookup failed), `null` when agora returned no asset the\n * viewer may read under that id, else its title and type.\n */\nexport function useMentionAsset(assetId: string | undefined): MentionAsset | null | undefined {\n const auth = useContext(MentionAuthCtx);\n const hostQueryClient = useContext(QueryClientContext);\n const lookupId = mentionAssetLookupId(assetId);\n const enabled = Boolean(auth && lookupId && canAuthenticate(auth));\n const backendUrl = auth?.backendUrl ?? \"\";\n const principal = auth ? principalOf(auth) : \"\";\n const { data } = useQuery(\n {\n queryKey: [\"athena-sdk\", \"mention-asset\", backendUrl, principal, lookupId ?? \"\"],\n queryFn: () => {\n if (!auth || !lookupId) return null;\n return loadMentionAsset({\n auth,\n batchKey: `${backendUrl}|${principal}`,\n assetId: lookupId,\n });\n },\n enabled,\n staleTime: MENTION_ASSET_STALE_TIME_MS,\n // Kept no longer than it is fresh: a title is shown again only after\n // agora answers again, never from a cache a minute past its check.\n gcTime: MENTION_ASSET_STALE_TIME_MS,\n retry: false,\n refetchOnWindowFocus: false,\n },\n hostQueryClient ?? chipQueryClient,\n );\n return enabled ? data : undefined;\n}\n\nexport function resetMentionAssetsForTests(): void {\n pendingBatches.clear();\n chipQueryClient.clear();\n}\n"],"names":["fetchGraphQL","QueryClient","useContext","MentionAuthCtx","QueryClient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AAO;AACV,cAAQ,EAAE,MAAM,SAAS,oBAAI,MAAI;AACjC,qBAAe,IAAI,UAAU,KAAK;AAClC,iBAAW,MAAM,UAAU,QAAQ,GAAG,6BAA6B;AAAA,IACrE;AACA,UAAM,UAAU,MAAM,QAAQ,IAAI,OAAO,KAAK,CAAA;AAC9C,YAAQ,KAAK,EAAE,SAAS,OAAA,CAAQ;AAChC,UAAM,QAAQ,IAAI,SAAS,OAAO;AAAA,EACpC,CAAC;AACH;AAGA,MAAM,kBAAkB,IAAIC,WAAAA,YAAA;AAOrB,SAAS,gBAAgB,SAA8D;AAC5F,QAAM,OAAOC,MAAAA,WAAWC,wBAAc;AACtC,QAAM,kBAAkBD,MAAAA,WAAWE,6BAAkB;AACrD,QAAM,WAAW,qBAAqB,OAAO;AAC7C,QAAM,UAAU,QAAQ,QAAQ,YAAY,gBAAgB,IAAI,CAAC;AACjE,QAAM,cAAa,6BAAM,eAAc;AACvC,QAAM,YAAY,OAAO,YAAY,IAAI,IAAI;AAC7C,QAAM,EAAE,SAASC,WAAAA;AAAAA,IACf;AAAA,MACE,UAAU,CAAC,cAAc,iBAAiB,YAAY,WAAW,YAAY,EAAE;AAAA,MAC/E,SAAS,MAAM;AACb,YAAI,CAAC,QAAQ,CAAC,SAAU,QAAO;AAC/B,eAAO,iBAAiB;AAAA,UACtB;AAAA,UACA,UAAU,GAAG,UAAU,IAAI,SAAS;AAAA,UACpC,SAAS;AAAA,QAAA,CACV;AAAA,MACH;AAAA,MACA;AAAA,MACA,WAAW;AAAA;AAAA;AAAA,MAGX,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,sBAAsB;AAAA,IAAA;AAAA,IAExB,mBAAmB;AAAA,EAAA;AAErB,SAAO,UAAU,OAAO;AAC1B;;;;;"}
@@ -0,0 +1,16 @@
1
+ /** What a chip draws from the asset: its current title and its type. */
2
+ export interface MentionAsset {
3
+ id: string;
4
+ title: string;
5
+ assetType: string;
6
+ }
7
+ export declare const MENTION_ASSET_BATCH_SIZE = 50;
8
+ export declare const MENTION_ASSET_BATCH_WINDOW_MS = 16;
9
+ export declare function mentionAssetLookupId(assetId: string | undefined): string | null;
10
+ /**
11
+ * The asset an asset chip names: `undefined` while unknown (no lookup, still
12
+ * loading, or the lookup failed), `null` when agora returned no asset the
13
+ * viewer may read under that id, else its title and type.
14
+ */
15
+ export declare function useMentionAsset(assetId: string | undefined): MentionAsset | null | undefined;
16
+ export declare function resetMentionAssetsForTests(): void;
@@ -0,0 +1,140 @@
1
+ import { QueryClientContext, useQuery, QueryClient } from "@tanstack/react-query";
2
+ import { useContext } from "react";
3
+ import { MentionAuthCtx, fetchGraphQL } from "./suggestions/data/api-client.js";
4
+ const MENTION_ASSET_BATCH_SIZE = 50;
5
+ const MENTION_ASSET_BATCH_WINDOW_MS = 16;
6
+ const MENTION_ASSET_STALE_TIME_MS = 6e4;
7
+ const MENTION_ASSETS_QUERY = `
8
+ query MentionChipAssets($assetIds: [String!]!) {
9
+ getAssetsByIds(assetIds: $assetIds) {
10
+ id
11
+ title
12
+ athenaOriginalType
13
+ }
14
+ }
15
+ `;
16
+ const LOOKUP_ID = /^asset_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+ function mentionAssetLookupId(assetId) {
18
+ const baseId = (assetId == null ? void 0 : assetId.trim().split("@")[0]) ?? "";
19
+ return LOOKUP_ID.test(baseId) ? baseId : null;
20
+ }
21
+ function canAuthenticate(auth) {
22
+ return Boolean(auth.accessToken || auth.apiKey || auth.credentials || auth.getAccessToken);
23
+ }
24
+ function fingerprint(credential) {
25
+ let hash = 2166136261;
26
+ for (let index = 0; index < credential.length; index += 1) {
27
+ hash ^= credential.charCodeAt(index);
28
+ hash = Math.imul(hash, 16777619) >>> 0;
29
+ }
30
+ return hash.toString(16).padStart(8, "0");
31
+ }
32
+ const authScopes = /* @__PURE__ */ new WeakMap();
33
+ let authScopeCount = 0;
34
+ function principalOf(auth) {
35
+ const scope = [];
36
+ if (auth.userId) scope.push(`user:${auth.userId}`);
37
+ if (auth.apiKey) scope.push(`key:${fingerprint(auth.apiKey)}`);
38
+ if (scope.length) return scope.join("|");
39
+ let own = authScopes.get(auth);
40
+ if (!own) {
41
+ authScopeCount += 1;
42
+ own = `auth:${authScopeCount}`;
43
+ authScopes.set(auth, own);
44
+ }
45
+ const token = auth.accessToken;
46
+ return token ? `${own}|token:${fingerprint(token)}` : own;
47
+ }
48
+ const pendingBatches = /* @__PURE__ */ new Map();
49
+ function settle(waiters, asset) {
50
+ for (const waiter of waiters ?? []) waiter.resolve(asset);
51
+ }
52
+ function fail(waiters, error) {
53
+ for (const waiter of waiters ?? []) waiter.reject(error);
54
+ }
55
+ function sendBatch(batchKey) {
56
+ const batch = pendingBatches.get(batchKey);
57
+ if (!batch) return;
58
+ pendingBatches.delete(batchKey);
59
+ const ids = [...batch.waiters.keys()];
60
+ for (let start = 0; start < ids.length; start += MENTION_ASSET_BATCH_SIZE) {
61
+ const chunk = ids.slice(start, start + MENTION_ASSET_BATCH_SIZE);
62
+ fetchGraphQL(batch.auth, MENTION_ASSETS_QUERY, {
63
+ assetIds: chunk
64
+ }).then(
65
+ (data) => {
66
+ var _a, _b;
67
+ const found = new Map((data.getAssetsByIds ?? []).map((asset) => [asset.id, asset]));
68
+ for (const id of chunk) {
69
+ const asset = found.get(id);
70
+ settle(
71
+ batch.waiters.get(id),
72
+ asset ? {
73
+ id,
74
+ title: ((_a = asset.title) == null ? void 0 : _a.trim()) ?? "",
75
+ assetType: ((_b = asset.athenaOriginalType) == null ? void 0 : _b.trim()) ?? ""
76
+ } : null
77
+ );
78
+ }
79
+ },
80
+ (error) => {
81
+ for (const id of chunk) fail(batch.waiters.get(id), error);
82
+ }
83
+ );
84
+ }
85
+ }
86
+ function loadMentionAsset({
87
+ auth,
88
+ batchKey,
89
+ assetId
90
+ }) {
91
+ return new Promise((resolve, reject) => {
92
+ let batch = pendingBatches.get(batchKey);
93
+ if (!batch) {
94
+ batch = { auth, waiters: /* @__PURE__ */ new Map() };
95
+ pendingBatches.set(batchKey, batch);
96
+ setTimeout(() => sendBatch(batchKey), MENTION_ASSET_BATCH_WINDOW_MS);
97
+ }
98
+ const waiters = batch.waiters.get(assetId) ?? [];
99
+ waiters.push({ resolve, reject });
100
+ batch.waiters.set(assetId, waiters);
101
+ });
102
+ }
103
+ const chipQueryClient = new QueryClient();
104
+ function useMentionAsset(assetId) {
105
+ const auth = useContext(MentionAuthCtx);
106
+ const hostQueryClient = useContext(QueryClientContext);
107
+ const lookupId = mentionAssetLookupId(assetId);
108
+ const enabled = Boolean(auth && lookupId && canAuthenticate(auth));
109
+ const backendUrl = (auth == null ? void 0 : auth.backendUrl) ?? "";
110
+ const principal = auth ? principalOf(auth) : "";
111
+ const { data } = useQuery(
112
+ {
113
+ queryKey: ["athena-sdk", "mention-asset", backendUrl, principal, lookupId ?? ""],
114
+ queryFn: () => {
115
+ if (!auth || !lookupId) return null;
116
+ return loadMentionAsset({
117
+ auth,
118
+ batchKey: `${backendUrl}|${principal}`,
119
+ assetId: lookupId
120
+ });
121
+ },
122
+ enabled,
123
+ staleTime: MENTION_ASSET_STALE_TIME_MS,
124
+ // Kept no longer than it is fresh: a title is shown again only after
125
+ // agora answers again, never from a cache a minute past its check.
126
+ gcTime: MENTION_ASSET_STALE_TIME_MS,
127
+ retry: false,
128
+ refetchOnWindowFocus: false
129
+ },
130
+ hostQueryClient ?? chipQueryClient
131
+ );
132
+ return enabled ? data : void 0;
133
+ }
134
+ export {
135
+ MENTION_ASSET_BATCH_SIZE,
136
+ MENTION_ASSET_BATCH_WINDOW_MS,
137
+ mentionAssetLookupId,
138
+ useMentionAsset
139
+ };
140
+ //# sourceMappingURL=use-mention-asset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-mention-asset.js","sources":["../../../src/chat-ui/mentions/use-mention-asset.ts"],"sourcesContent":["/**\n * The asset an asset chip names, read the way Olympus's chips read it: its\n * title and type from agora's `getAssetsByIds`, which returns only the assets\n * the caller may read (an id they cannot read is left out of the answer, as is\n * another workspace's). A chip then shows the asset's own name and icon\n * instead of whatever label and `type=` its link carried.\n *\n * Chips that mount together ask together: one GraphQL request per batch of up\n * to {@link MENTION_ASSET_BATCH_SIZE} ids, gathered over\n * {@link MENTION_ASSET_BATCH_WINDOW_MS}. Each answer is a TanStack query keyed\n * by backend, the person asking and the id, fresh for a minute, so a\n * transcript full of citations to one repository asks for it once.\n */\nimport { QueryClient, QueryClientContext, useQuery } from \"@tanstack/react-query\";\nimport { useContext } from \"react\";\nimport {\n fetchGraphQL,\n type MentionAuthContext,\n MentionAuthCtx,\n} from \"./suggestions/data/api-client\";\n\n/** What a chip draws from the asset: its current title and its type. */\nexport interface MentionAsset {\n id: string;\n title: string;\n assetType: string;\n}\n\nexport const MENTION_ASSET_BATCH_SIZE = 50;\nexport const MENTION_ASSET_BATCH_WINDOW_MS = 16;\nconst MENTION_ASSET_STALE_TIME_MS = 60_000;\n\n/** No metadata: a session's carries its token ledgers, and a chip needs a name and a type. */\nconst MENTION_ASSETS_QUERY = `\n query MentionChipAssets($assetIds: [String!]!) {\n getAssetsByIds(assetIds: $assetIds) {\n id\n title\n athenaOriginalType\n }\n }\n`;\n\ninterface MentionAssetsResponse {\n getAssetsByIds?: Array<{\n id: string;\n title: string | null;\n athenaOriginalType: string | null;\n }> | null;\n}\n\n/**\n * The ids a lookup asks about: a stored asset. A versioned id (`asset_x@3`)\n * asks about its asset. A live provider file (`asset_<catalog>_<file>`) is not\n * a row `getAssetsByIds` holds, and a session (`asset_thread_<uuid>`) is never\n * asked about: agora reads the whole row, and a session's metadata carries\n * its transcript's ledgers (megabytes on a long session) — too much for a name.\n */\nconst LOOKUP_ID = /^asset_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function mentionAssetLookupId(assetId: string | undefined): string | null {\n const baseId = assetId?.trim().split(\"@\")[0] ?? \"\";\n return LOOKUP_ID.test(baseId) ? baseId : null;\n}\n\n/** Whether a request can carry a credential (`mentionRequestInit` refuses one that cannot). */\nfunction canAuthenticate(auth: MentionAuthContext): boolean {\n return Boolean(auth.accessToken || auth.apiKey || auth.credentials || auth.getAccessToken);\n}\n\n/** A short, stable stand-in for a credential in a cache key; never the credential itself. */\nfunction fingerprint(credential: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < credential.length; index += 1) {\n hash ^= credential.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n/** The scope each credential with no stable identity of its own gets: its own auth object. */\nconst authScopes = new WeakMap<MentionAuthContext, string>();\nlet authScopeCount = 0;\n\n/**\n * Who is asking, as narrowly as the credential says: what `getAssetsByIds`\n * answers differs per person and per API key, and an answer (or a batch's\n * request) is only ever shared within one scope. A person's id and an API key\n * scope the cache across token rotations. A credential that names neither (a\n * session cookie, a token callback) shares nothing beyond its own auth object\n * and its current token, so a token swapped on the same object asks again.\n */\nfunction principalOf(auth: MentionAuthContext): string {\n const scope: string[] = [];\n if (auth.userId) scope.push(`user:${auth.userId}`);\n if (auth.apiKey) scope.push(`key:${fingerprint(auth.apiKey)}`);\n if (scope.length) return scope.join(\"|\");\n let own = authScopes.get(auth);\n if (!own) {\n authScopeCount += 1;\n own = `auth:${authScopeCount}`;\n authScopes.set(auth, own);\n }\n const token = auth.accessToken;\n return token ? `${own}|token:${fingerprint(token)}` : own;\n}\n\ninterface Waiter {\n resolve: (asset: MentionAsset | null) => void;\n reject: (error: unknown) => void;\n}\n\ninterface PendingBatch {\n auth: MentionAuthContext;\n waiters: Map<string, Waiter[]>;\n}\n\n/** The batch each backend and principal is gathering, until its window closes. */\nconst pendingBatches = new Map<string, PendingBatch>();\n\nfunction settle(waiters: Waiter[] | undefined, asset: MentionAsset | null): void {\n for (const waiter of waiters ?? []) waiter.resolve(asset);\n}\n\nfunction fail(waiters: Waiter[] | undefined, error: unknown): void {\n for (const waiter of waiters ?? []) waiter.reject(error);\n}\n\nfunction sendBatch(batchKey: string): void {\n const batch = pendingBatches.get(batchKey);\n if (!batch) return;\n pendingBatches.delete(batchKey);\n const ids = [...batch.waiters.keys()];\n for (let start = 0; start < ids.length; start += MENTION_ASSET_BATCH_SIZE) {\n const chunk = ids.slice(start, start + MENTION_ASSET_BATCH_SIZE);\n fetchGraphQL<MentionAssetsResponse>(batch.auth, MENTION_ASSETS_QUERY, {\n assetIds: chunk,\n }).then(\n (data) => {\n const found = new Map((data.getAssetsByIds ?? []).map((asset) => [asset.id, asset]));\n for (const id of chunk) {\n const asset = found.get(id);\n settle(\n batch.waiters.get(id),\n asset\n ? {\n id,\n title: asset.title?.trim() ?? \"\",\n assetType: asset.athenaOriginalType?.trim() ?? \"\",\n }\n : null,\n );\n }\n },\n (error: unknown) => {\n for (const id of chunk) fail(batch.waiters.get(id), error);\n },\n );\n }\n}\n\nfunction loadMentionAsset({\n auth,\n batchKey,\n assetId,\n}: {\n auth: MentionAuthContext;\n batchKey: string;\n assetId: string;\n}): Promise<MentionAsset | null> {\n return new Promise((resolve, reject) => {\n let batch = pendingBatches.get(batchKey);\n if (!batch) {\n batch = { auth, waiters: new Map() };\n pendingBatches.set(batchKey, batch);\n setTimeout(() => sendBatch(batchKey), MENTION_ASSET_BATCH_WINDOW_MS);\n }\n const waiters = batch.waiters.get(assetId) ?? [];\n waiters.push({ resolve, reject });\n batch.waiters.set(assetId, waiters);\n });\n}\n\n/** Chips rendered outside any query client (a host's own tray) still share one cache. */\nconst chipQueryClient = new QueryClient();\n\n/**\n * The asset an asset chip names: `undefined` while unknown (no lookup, still\n * loading, or the lookup failed), `null` when agora returned no asset the\n * viewer may read under that id, else its title and type.\n */\nexport function useMentionAsset(assetId: string | undefined): MentionAsset | null | undefined {\n const auth = useContext(MentionAuthCtx);\n const hostQueryClient = useContext(QueryClientContext);\n const lookupId = mentionAssetLookupId(assetId);\n const enabled = Boolean(auth && lookupId && canAuthenticate(auth));\n const backendUrl = auth?.backendUrl ?? \"\";\n const principal = auth ? principalOf(auth) : \"\";\n const { data } = useQuery(\n {\n queryKey: [\"athena-sdk\", \"mention-asset\", backendUrl, principal, lookupId ?? \"\"],\n queryFn: () => {\n if (!auth || !lookupId) return null;\n return loadMentionAsset({\n auth,\n batchKey: `${backendUrl}|${principal}`,\n assetId: lookupId,\n });\n },\n enabled,\n staleTime: MENTION_ASSET_STALE_TIME_MS,\n // Kept no longer than it is fresh: a title is shown again only after\n // agora answers again, never from a cache a minute past its check.\n gcTime: MENTION_ASSET_STALE_TIME_MS,\n retry: false,\n refetchOnWindowFocus: false,\n },\n hostQueryClient ?? chipQueryClient,\n );\n return enabled ? data : undefined;\n}\n\nexport function resetMentionAssetsForTests(): void {\n pendingBatches.clear();\n chipQueryClient.clear();\n}\n"],"names":[],"mappings":";;;AA4BO,MAAM,2BAA2B;AACjC,MAAM,gCAAgC;AAC7C,MAAM,8BAA8B;AAGpC,MAAM,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyB7B,MAAM,YAAY;AAEX,SAAS,qBAAqB,SAA4C;AAC/E,QAAM,UAAS,mCAAS,OAAO,MAAM,KAAK,OAAM;AAChD,SAAO,UAAU,KAAK,MAAM,IAAI,SAAS;AAC3C;AAGA,SAAS,gBAAgB,MAAmC;AAC1D,SAAO,QAAQ,KAAK,eAAe,KAAK,UAAU,KAAK,eAAe,KAAK,cAAc;AAC3F;AAGA,SAAS,YAAY,YAA4B;AAC/C,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS,GAAG;AACzD,YAAQ,WAAW,WAAW,KAAK;AACnC,WAAO,KAAK,KAAK,MAAM,QAAU,MAAM;AAAA,EACzC;AACA,SAAO,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAC1C;AAGA,MAAM,iCAAiB,QAAA;AACvB,IAAI,iBAAiB;AAUrB,SAAS,YAAY,MAAkC;A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,QAAQ,CAAC,SAAU,QAAO;AAC/B,eAAO,iBAAiB;AAAA,UACtB;AAAA,UACA,UAAU,GAAG,UAAU,IAAI,SAAS;AAAA,UACpC,SAAS;AAAA,QAAA,CACV;AAAA,MACH;AAAA,MACA;AAAA,MACA,WAAW;AAAA;AAAA;AAAA,MAGX,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,sBAAsB;AAAA,IAAA;AAAA,IAExB,mBAAmB;AAAA,EAAA;AAErB,SAAO,UAAU,OAAO;AAC1B;"}
@@ -5,6 +5,7 @@ const lucideReact = require("lucide-react");
5
5
  const react = require("react");
6
6
  const mentionChip = require("../mentions/mention-chip.cjs");
7
7
  const citationAnchors = require("./citation-anchors.cjs");
8
+ const cnfast = require("cnfast");
8
9
  function ChatLink({
9
10
  href,
10
11
  excerpt,
@@ -29,10 +30,10 @@ function SourceChip({
29
30
  title: excerpt,
30
31
  "data-chat-source": "",
31
32
  "data-excerpt": excerpt,
32
- className: "not-prose inline-flex max-w-[240px] items-center gap-1 whitespace-nowrap rounded-md border border-slate-300 bg-white px-1.5 py-px align-middle text-[0.85em] font-medium leading-[1.4] text-slate-600 no-underline transition-colors hover:border-slate-400 hover:bg-slate-50 hover:text-slate-800 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1",
33
+ className: cnfast.cn(mentionChip.CHIP_PILL_CLASS, "max-w-[240px]", mentionChip.CHIP_LINK_CLASS),
33
34
  children: [
34
35
  /* @__PURE__ */ jsxRuntime.jsx(SourceFavicon, { href }),
35
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "max-w-[200px] overflow-hidden text-ellipsis", children })
36
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "min-w-0 max-w-[200px] overflow-hidden text-ellipsis", children })
36
37
  ]
37
38
  }
38
39
  );
@@ -44,7 +45,7 @@ function SourceFavicon({ href }) {
44
45
  return /* @__PURE__ */ jsxRuntime.jsx(
45
46
  lucideReact.Globe2Icon,
46
47
  {
47
- className: "size-3.5 shrink-0 text-slate-400",
48
+ className: cnfast.cn(mentionChip.CHIP_ICON_CLASS, "text-muted-foreground"),
48
49
  "aria-hidden": "true"
49
50
  }
50
51
  );
@@ -56,7 +57,7 @@ function SourceFavicon({ href }) {
56
57
  alt: "",
57
58
  width: 14,
58
59
  height: 14,
59
- className: "size-3.5 shrink-0 rounded-[3px]",
60
+ className: cnfast.cn(mentionChip.CHIP_ICON_CLASS, "rounded-[3px]"),
60
61
  loading: "lazy",
61
62
  referrerPolicy: "no-referrer",
62
63
  draggable: false,
@@ -1 +1 @@
1
- {"version":3,"file":"chat-link.cjs","sources":["../../../src/chat-ui/rich-text/chat-link.tsx"],"sourcesContent":["import { Globe2Icon } from \"lucide-react\";\nimport { type ReactNode, useState } from \"react\";\nimport { MentionLink } from \"../mentions/mention-chip\";\nimport {\n buildScrollToTextUrl,\n isWebHref,\n sourceFaviconUrl,\n} from \"./citation-anchors\";\n\n/**\n * A link mark of the static message body. A web source the model cited with\n * an excerpt renders as a source chip; everything else goes through\n * `MentionLink`, which draws mention and Spaces hrefs as asset chips,\n * screen points as coordinate chips, and the rest as a plain link.\n */\nexport function ChatLink({\n href,\n excerpt,\n children,\n}: {\n href: string | null | undefined;\n excerpt?: string | null;\n children: ReactNode;\n}) {\n if (href && excerpt && isWebHref(href)) {\n return (\n <SourceChip href={href} excerpt={excerpt}>\n {children}\n </SourceChip>\n );\n }\n return <MentionLink href={href ?? undefined}>{children}</MentionLink>;\n}\n\n/**\n * A cited web page: the site's favicon, the model's label, the excerpt as\n * the tooltip, opening the page at the excerpt (scroll-to-text) in a new tab.\n * Same geometry as the asset mention chip so a sentence that cites a PDF and\n * a web page reads as one row of sources. `not-prose` keeps Tailwind\n * Typography's `img` margins off the favicon.\n */\nexport function SourceChip({\n href,\n excerpt,\n children,\n}: {\n href: string;\n excerpt: string;\n children: ReactNode;\n}) {\n return (\n <a\n href={buildScrollToTextUrl(href, excerpt)}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n title={excerpt}\n data-chat-source=\"\"\n data-excerpt={excerpt}\n className=\"not-prose inline-flex max-w-[240px] items-center gap-1 whitespace-nowrap rounded-md border border-slate-300 bg-white px-1.5 py-px align-middle text-[0.85em] font-medium leading-[1.4] text-slate-600 no-underline transition-colors hover:border-slate-400 hover:bg-slate-50 hover:text-slate-800 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1\"\n >\n <SourceFavicon href={href} />\n <span className=\"max-w-[200px] overflow-hidden text-ellipsis\">\n {children}\n </span>\n </a>\n );\n}\n\n/** The site's favicon; a globe once the favicon service has no icon for the host. */\nfunction SourceFavicon({ href }: { href: string }) {\n const [failed, setFailed] = useState(false);\n const src = failed ? null : sourceFaviconUrl(href);\n if (!src) {\n return (\n <Globe2Icon\n className=\"size-3.5 shrink-0 text-slate-400\"\n aria-hidden=\"true\"\n />\n );\n }\n return (\n <img\n src={src}\n alt=\"\"\n width={14}\n height={14}\n className=\"size-3.5 shrink-0 rounded-[3px]\"\n loading=\"lazy\"\n referrerPolicy=\"no-referrer\"\n draggable={false}\n onError={() => setFailed(true)}\n />\n );\n}\n"],"names":["isWebHref","jsx","MentionLink","jsxs","buildScrollToTextUrl","useState","sourceFaviconUrl","Globe2Icon"],"mappings":";;;;;;;AAeO,SAAS,SAAS;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,MAAI,QAAQ,WAAWA,gBAAAA,UAAU,IAAI,GAAG;AACtC,WACEC,2BAAAA,IAAC,YAAA,EAAW,MAAY,SACrB,SAAA,CACH;AAAA,EAEJ;AACA,SAAOA,2BAAAA,IAACC,YAAAA,aAAA,EAAY,MAAM,QAAQ,QAAY,UAAS;AACzD;AASO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SACEC,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC,MAAMC,gBAAAA,qBAAqB,MAAM,OAAO;AAAA,MACxC,QAAO;AAAA,MACP,KAAI;AAAA,MACJ,OAAO;AAAA,MACP,oBAAiB;AAAA,MACjB,gBAAc;AAAA,MACd,WAAU;AAAA,MAEV,UAAA;AAAA,QAAAH,+BAAC,iBAAc,MAAY;AAAA,QAC3BA,2BAAAA,IAAC,QAAA,EAAK,WAAU,+CACb,SAAA,CACH;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGN;AAGA,SAAS,cAAc,EAAE,QAA0B;AACjD,QAAM,CAAC,QAAQ,SAAS,IAAII,MAAAA,SAAS,KAAK;AAC1C,QAAM,MAAM,SAAS,OAAOC,gBAAAA,iBAAiB,IAAI;AACjD,MAAI,CAAC,KAAK;AACR,WACEL,2BAAAA;AAAAA,MAACM,YAAAA;AAAAA,MAAA;AAAA,QACC,WAAU;AAAA,QACV,eAAY;AAAA,MAAA;AAAA,IAAA;AAAA,EAGlB;AACA,SACEN,2BAAAA;AAAAA,IAAC;AAAA,IAAA;AAAA,MACC;AAAA,MACA,KAAI;AAAA,MACJ,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,WAAU;AAAA,MACV,SAAQ;AAAA,MACR,gBAAe;AAAA,MACf,WAAW;AAAA,MACX,SAAS,MAAM,UAAU,IAAI;AAAA,IAAA;AAAA,EAAA;AAGnC;;;"}
1
+ {"version":3,"file":"chat-link.cjs","sources":["../../../src/chat-ui/rich-text/chat-link.tsx"],"sourcesContent":["import { Globe2Icon } from \"lucide-react\";\nimport { type ReactNode, useState } from \"react\";\nimport { CHIP_ICON_CLASS, CHIP_LINK_CLASS, CHIP_PILL_CLASS, MentionLink } from \"../mentions/mention-chip\";\nimport { cn } from \"../../lib/utils\";\nimport {\n buildScrollToTextUrl,\n isWebHref,\n sourceFaviconUrl,\n} from \"./citation-anchors\";\n\n/**\n * A link mark of the static message body. A web source the model cited with\n * an excerpt renders as a source chip; everything else goes through\n * `MentionLink`, which draws mention and Spaces hrefs as asset chips,\n * screen points as coordinate chips, and the rest as a plain link.\n */\nexport function ChatLink({\n href,\n excerpt,\n children,\n}: {\n href: string | null | undefined;\n excerpt?: string | null;\n children: ReactNode;\n}) {\n if (href && excerpt && isWebHref(href)) {\n return (\n <SourceChip href={href} excerpt={excerpt}>\n {children}\n </SourceChip>\n );\n }\n return <MentionLink href={href ?? undefined}>{children}</MentionLink>;\n}\n\n/**\n * A cited web page: the site's favicon, the model's label, the excerpt as\n * the tooltip, opening the page at the excerpt (scroll-to-text) in a new tab.\n * The asset mention chip's pill (`CHIP_PILL_CLASS`), so a sentence that cites\n * a PDF and a web page reads as one row of sources.\n */\nexport function SourceChip({\n href,\n excerpt,\n children,\n}: {\n href: string;\n excerpt: string;\n children: ReactNode;\n}) {\n return (\n <a\n href={buildScrollToTextUrl(href, excerpt)}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n title={excerpt}\n data-chat-source=\"\"\n data-excerpt={excerpt}\n className={cn(CHIP_PILL_CLASS, \"max-w-[240px]\", CHIP_LINK_CLASS)}\n >\n <SourceFavicon href={href} />\n <span className=\"min-w-0 max-w-[200px] overflow-hidden text-ellipsis\">\n {children}\n </span>\n </a>\n );\n}\n\n/** The site's favicon; a globe once the favicon service has no icon for the host. */\nfunction SourceFavicon({ href }: { href: string }) {\n const [failed, setFailed] = useState(false);\n const src = failed ? null : sourceFaviconUrl(href);\n if (!src) {\n return (\n <Globe2Icon\n className={cn(CHIP_ICON_CLASS, \"text-muted-foreground\")}\n aria-hidden=\"true\"\n />\n );\n }\n return (\n <img\n src={src}\n alt=\"\"\n width={14}\n height={14}\n className={cn(CHIP_ICON_CLASS, \"rounded-[3px]\")}\n loading=\"lazy\"\n referrerPolicy=\"no-referrer\"\n draggable={false}\n onError={() => setFailed(true)}\n />\n );\n}\n"],"names":["isWebHref","jsx","MentionLink","jsxs","buildScrollToTextUrl","cn","CHIP_PILL_CLASS","CHIP_LINK_CLASS","useState","sourceFaviconUrl","Globe2Icon","CHIP_ICON_CLASS"],"mappings":";;;;;;;;AAgBO,SA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,SAAQ;AAAA,MACR,gBAAe;AAAA,MACf,WAAW;AAAA,MACX,SAAS,MAAM,UAAU,IAAI;AAAA,IAAA;AAAA,EAAA;AAGnC;;;"}
@@ -13,9 +13,8 @@ export declare function ChatLink({ href, excerpt, children, }: {
13
13
  /**
14
14
  * A cited web page: the site's favicon, the model's label, the excerpt as
15
15
  * the tooltip, opening the page at the excerpt (scroll-to-text) in a new tab.
16
- * Same geometry as the asset mention chip so a sentence that cites a PDF and
17
- * a web page reads as one row of sources. `not-prose` keeps Tailwind
18
- * Typography's `img` margins off the favicon.
16
+ * The asset mention chip's pill (`CHIP_PILL_CLASS`), so a sentence that cites
17
+ * a PDF and a web page reads as one row of sources.
19
18
  */
20
19
  export declare function SourceChip({ href, excerpt, children, }: {
21
20
  href: string;