@arbidocs/react 0.4.5 → 0.4.6

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.
@@ -23,6 +23,7 @@ var arbiQueryKeys = {
23
23
  workspaces: () => ["arbi", "workspaces"],
24
24
  documents: (workspaceId) => ["arbi", "documents", workspaceId],
25
25
  conversations: (workspaceId) => ["arbi", "conversations", workspaceId],
26
+ conversationThreads: (workspaceId, conversationId) => ["arbi", "conversations", workspaceId, "threads", conversationId],
26
27
  tags: (workspaceId) => ["arbi", "tags", workspaceId],
27
28
  thumbnails: (docIds) => ["arbi", "thumbnails", [...docIds].sort().join(",")],
28
29
  parsedDoc: (docId, stage) => ["arbi", "parsedDoc", docId, stage],
@@ -43,7 +44,11 @@ var arbiQueryKeys = {
43
44
  /** An agent's pinned config; `undefined` = the library default config. */
44
45
  agentConfig: (agentExtId) => ["arbi", "agentConfig", agentExtId ?? "default"],
45
46
  agentWorkspaces: (agentExtId) => ["arbi", "agentWorkspaces", agentExtId],
46
- models: () => ["arbi", "models"]
47
+ models: () => ["arbi", "models"],
48
+ /** The signed-in user's own profile (name, picture, email). */
49
+ profile: () => ["arbi", "profile"],
50
+ /** The signed-in user's settings record (notification preferences, flags). */
51
+ userSettings: () => ["arbi", "userSettings"]
47
52
  };
48
53
  function useWorkspaces(options) {
49
54
  const arbi = chunkZMTLGO3K_cjs.useArbi();
@@ -69,6 +74,15 @@ function useConversations(workspaceId, options) {
69
74
  enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace
70
75
  });
71
76
  }
77
+ function useConversationThreads(workspaceId, conversationId, options) {
78
+ const arbi = chunkZMTLGO3K_cjs.useArbi();
79
+ return reactQuery.useQuery({
80
+ queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? "", conversationId ?? ""),
81
+ queryFn: () => arbi.conversations.getThreads(conversationId),
82
+ enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,
83
+ gcTime: 0
84
+ });
85
+ }
72
86
  function useTags(workspaceId, options) {
73
87
  const arbi = chunkZMTLGO3K_cjs.useArbi();
74
88
  return reactQuery.useQuery({
@@ -282,6 +296,7 @@ exports.useActivity = useActivity;
282
296
  exports.useAgents = useAgents;
283
297
  exports.useAssistantQuery = useAssistantQuery;
284
298
  exports.useConfigs = useConfigs;
299
+ exports.useConversationThreads = useConversationThreads;
285
300
  exports.useConversations = useConversations;
286
301
  exports.useDeleteAgents = useDeleteAgents;
287
302
  exports.useDocuments = useDocuments;
@@ -298,5 +313,5 @@ exports.useTasks = useTasks;
298
313
  exports.useThumbnails = useThumbnails;
299
314
  exports.useUserUsageToday = useUserUsageToday;
300
315
  exports.useWorkspaces = useWorkspaces;
301
- //# sourceMappingURL=chunk-2DXS7L7M.cjs.map
302
- //# sourceMappingURL=chunk-2DXS7L7M.cjs.map
316
+ //# sourceMappingURL=chunk-CBJ3WOGD.cjs.map
317
+ //# sourceMappingURL=chunk-CBJ3WOGD.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/credits.ts","../src/hooks.ts"],"names":["useArbi","useQuery","useMutation","useQueries","useMemo"],"mappings":";;;;;;;AAWO,IAAM,sBAAA,GAAyB;AAU/B,SAAS,aAAA,CAAc,OAAA,EAAiB,OAAA,GAAgC,EAAC,EAAW;AACzF,EAAA,MAAM,EAAE,IAAA,GAAO,IAAA,EAAM,MAAA,GAAS,SAAQ,GAAI,OAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,KAAK,KAAA,CAAM,MAAA,CAAO,SAAS,OAAO,CAAA,GAAI,UAAU,CAAC,CAAA;AAC/D,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,cAAA,CAAe,MAAM,CAAA;AAC1C,EAAA,OAAO,IAAA,GAAO,GAAG,MAAM,CAAA,CAAA,EAAI,UAAU,CAAA,GAAI,QAAA,GAAW,SAAS,CAAA,CAAA,GAAK,MAAA;AACpE;AAGO,SAAS,YAAA,CACd,OAAA,EACA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AQ,IAAA,CAAK,CAAC,CAAA,KAAM,EAAE,SAAS,CAAA;AAAA,MAC1C,SAAS,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,EAAE,OAAO;AAAA,KACxC;AAAA,EACF,CAAA,EAAG,CAAC,SAAS,CAAC,CAAA;AAChB;AAGO,SAAS,kBAAA,CACd,cACA,OAAA,EACA;AACA,EAAA,MAAM,OAAOJ,yBAAA,EAAQ;AACrB,EAAA,OAAOC,mBAAA,CAAS;AAAA,IACd,QAAA,EAAU,aAAA,CAAc,eAAA,CAAgB,YAAA,IAAgB,EAAE,CAAA;AAAA,IAC1D,OAAA,EAAS,MAAM,IAAA,CAAK,QAAA,CAAS,SAAS,YAAsB,CAAA;AAAA,IAC5D,UAAU,OAAA,EAAS,OAAA,IAAW,SAAS,CAAC,CAAC,gBAAgB,IAAA,CAAK;AAAA,GAC/D,CAAA;AACH;AAGO,SAAS,kBAAkB,OAAA,EAAiC;AACjE,EAAA,MAAM,OAAOD,yBAAA,EAAQ;AACrB,EAAA,OAAOC,mBAAA,CAAS;AAAA,IACd,QAAA,EAAU,cAAc,cAAA,EAAe;AAAA,IACvC,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,CAAK,UAAA,EAAW;AAAA,IACpC,OAAA,EAAS,OAAA,EAAS,OAAA,IAAW,IAAA,CAAK;AAAA,GACnC,CAAA;AACH","file":"chunk-CBJ3WOGD.cjs","sourcesContent":["/**\n * Credits: the unit the ARBI backend reports AI usage in.\n *\n * The usage endpoints (`/v1/user/projects/{id}/usage`, `/me/usage/today`) convert the metered USD\n * spend into whole credits at the API boundary: 1 credit = `CREDITS_TO_AI_USD`, which is $0.01 on\n * a default deployment. The fields are still named `spend` / `total_spend` in the schema, but they\n * hold CREDITS, never dollars. Label them as credits; use {@link creditsToUsd} only when a\n * dollar figure is genuinely wanted, with the deployment's own rate.\n */\n\n/** Dollars per credit on a default deployment (`CREDITS_TO_AI_USD`). */\nexport const DEFAULT_USD_PER_CREDIT = 0.01\n\nexport interface FormatCreditsOptions {\n /** Append the unit (\"12 credits\"). Default true; pass false inside a column headed \"Credits\". */\n unit?: boolean\n /** BCP 47 locale for the digit grouping. Default `en-US`. */\n locale?: string\n}\n\n/** \"1,234 credits\" / \"1 credit\". The backend reports whole credits; this rounds away float dust. */\nexport function formatCredits(credits: number, options: FormatCreditsOptions = {}): string {\n const { unit = true, locale = 'en-US' } = options\n const whole = Math.round(Number.isFinite(credits) ? credits : 0)\n const digits = whole.toLocaleString(locale)\n return unit ? `${digits} ${whole === 1 ? 'credit' : 'credits'}` : digits\n}\n\n/** The dollar value of an amount of credits. `usdPerCredit` defaults to {@link DEFAULT_USD_PER_CREDIT}. */\nexport function creditsToUsd(\n credits: number,\n usdPerCredit: number = DEFAULT_USD_PER_CREDIT\n): number {\n return credits * usdPerCredit\n}\n\n/** The slice of a usage response that tells whether anything was recorded. */\nexport interface UsageTotals {\n total_spend: number\n total_tokens: number\n total_requests: number\n}\n\n/**\n * Was this usage actually metered? A project on the `dev` plan belongs to a deployment with\n * billing switched off: the backend only records AI usage per project when billing is enabled, so\n * an all-zero response there means \"not metered\", not \"nothing happened\". Show a note instead of\n * silent zeros.\n */\nexport function isUsageMetered(\n usage: UsageTotals,\n subscription: string | null | undefined\n): boolean {\n const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0\n return !(empty && subscription === 'dev')\n}\n","/**\n * React Query hooks that use the Arbi instance from context.\n */\n\nimport { useMemo } from 'react'\nimport { useQuery, useQueries, useMutation } from '@tanstack/react-query'\nimport type {\n SSEStreamResult,\n SSEStreamStartData,\n ResponseOutputItemDoneEvent,\n ArtifactEvent,\n UserMessageEvent,\n MessageMetadataPayload,\n} from '@arbidocs/sdk/browser'\nimport { useArbi } from './useArbi'\nimport type { ParsedDocument } from './documents/parsed-types'\nimport { isUsageMetered } from './credits'\n\n// ── Query keys ──────────────────────────────────────────────────────────────\n\nexport const arbiQueryKeys = {\n workspaces: () => ['arbi', 'workspaces'] as const,\n documents: (workspaceId: string) => ['arbi', 'documents', workspaceId] as const,\n conversations: (workspaceId: string) => ['arbi', 'conversations', workspaceId] as const,\n conversationThreads: (workspaceId: string, conversationId: string) =>\n ['arbi', 'conversations', workspaceId, 'threads', conversationId] as const,\n tags: (workspaceId: string) => ['arbi', 'tags', workspaceId] as const,\n thumbnails: (docIds: string[]) => ['arbi', 'thumbnails', [...docIds].sort().join(',')] as const,\n parsedDoc: (docId: string, stage: string) => ['arbi', 'parsedDoc', docId, stage] as const,\n agents: () => ['arbi', 'agents'] as const,\n sessions: () => ['arbi', 'sessions'] as const,\n health: () => ['arbi', 'health'] as const,\n tasks: () => ['arbi', 'tasks'] as const,\n facts: (workspaceId: string) => ['arbi', 'facts', workspaceId] as const,\n configs: () => ['arbi', 'configs'] as const,\n activity: () => ['arbi', 'activity'] as const,\n projects: () => ['arbi', 'projects'] as const,\n projectUsage: (projectExtId: string, monthsBack: number) =>\n ['arbi', 'projectUsage', projectExtId, monthsBack] as const,\n projectInvoices: (projectExtId: string) => ['arbi', 'projectInvoices', projectExtId] as const,\n userUsageToday: () => ['arbi', 'userUsageToday'] as const,\n contacts: () => ['arbi', 'contacts'] as const,\n skills: () => ['arbi', 'skills'] as const,\n taskRuns: (taskId: string) => ['arbi', 'taskRuns', taskId] as const,\n /** An agent's pinned config; `undefined` = the library default config. */\n agentConfig: (agentExtId?: string) => ['arbi', 'agentConfig', agentExtId ?? 'default'] as const,\n agentWorkspaces: (agentExtId: string) => ['arbi', 'agentWorkspaces', agentExtId] as const,\n models: () => ['arbi', 'models'] as const,\n /** The signed-in user's own profile (name, picture, email). */\n profile: () => ['arbi', 'profile'] as const,\n /** The signed-in user's settings record (notification preferences, flags). */\n userSettings: () => ['arbi', 'userSettings'] as const,\n}\n\n// ── Hooks ───────────────────────────────────────────────────────────────────\n\n/** List the logged-in user's workspaces. */\nexport function useWorkspaces(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** List documents in a workspace. */\nexport function useDocuments(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.documents(workspaceId ?? ''),\n queryFn: () => arbi.documents.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/** List conversations in a workspace. */\nexport function useConversations(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.conversations(workspaceId ?? ''),\n queryFn: () => arbi.conversations.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/**\n * A conversation's stored threads (each with its message history, citations data included).\n * Always refetched on mount: a conversation that was open before may have new turns.\n */\nexport function useConversationThreads(\n workspaceId: string | undefined,\n conversationId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? '', conversationId ?? ''),\n queryFn: () => arbi.conversations.getThreads(conversationId as string),\n enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,\n gcTime: 0,\n })\n}\n\n/** List tags in a workspace. */\nexport function useTags(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.tags(workspaceId ?? ''),\n queryFn: () => arbi.tags.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/**\n * Batch-fetch first-page thumbnails for a set of documents. Returns a map of\n * doc external id → `data:image/webp` URI (or `null` when no thumbnail exists).\n * Cached for a few minutes since thumbnails are effectively immutable per doc.\n */\nexport function useThumbnails(docIds: string[], options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.thumbnails(docIds),\n queryFn: () => arbi.documents.getThumbnails(docIds),\n enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,\n staleTime: 5 * 60_000,\n })\n}\n\n/**\n * Fetch a document's parsed content (chunks grouped by page) for the review\n * viewer. `stage` defaults to `final` (fully processed); `marker`/`subchunk`\n * expose earlier pipeline stages.\n */\nexport function useParsedDocument(\n docId: string | undefined,\n stage: string = 'final',\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.parsedDoc(docId ?? '', stage),\n queryFn: () =>\n arbi.documents.getParsedContent(docId as string, stage) as unknown as Promise<ParsedDocument>,\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/** Send a streaming query to the RAG assistant. Returns a mutation. */\nexport function useAssistantQuery() {\n const arbi = useArbi()\n\n return useMutation<\n SSEStreamResult,\n Error,\n {\n question: string\n docIds: string[]\n previousResponseId?: string | null\n model?: string\n onToken?: (content: string) => void\n /** Aborts the request and the stream; the mutation then rejects with an `AbortError`. */\n signal?: AbortSignal\n onStreamStart?: (data: SSEStreamStartData) => void\n onUserMessage?: (data: UserMessageEvent) => void\n onMetadata?: (data: MessageMetadataPayload) => void\n onOutputItemDone?: (data: ResponseOutputItemDoneEvent) => void\n onArtifact?: (data: ArtifactEvent) => void\n onError?: (message: string) => void\n onComplete?: () => void\n }\n >({\n mutationFn: ({ question, ...options }) => arbi.assistant.query(question, options),\n })\n}\n\n/** List agents owned by the current user. */\nexport function useAgents(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.agents(),\n queryFn: () => arbi.agents.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** Delete agents. Returns a mutation. */\nexport function useDeleteAgents() {\n const arbi = useArbi()\n return useMutation<unknown, Error, { agentExtIds: string[] }>({\n mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),\n })\n}\n\n/** List active sessions. */\nexport function useSessions(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.sessions(),\n queryFn: () => arbi.sessions.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** Authorize a delegated session (generates claim code). Returns a mutation. */\n\n/** Check backend health. */\nexport function useHealth(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.health(),\n queryFn: () => arbi.health.check(),\n enabled: options?.enabled,\n })\n}\n\n// ── Scheduled tasks ──────────────────────────────────────────────────────────\n\n/** List the caller's scheduled agent tasks. */\nexport function useTasks(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.tasks(),\n queryFn: () => arbi.tasks.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Workspace notes ──────────────────────────────────────────────────────────\n\n/** List the open workspace's facts. */\nexport function useFacts(\n workspaceId: string | undefined,\n options?: { enabled?: boolean; pinnedOnly?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.facts(workspaceId ?? ''),\n queryFn: () => arbi.facts.list({ pinnedOnly: options?.pinnedOnly }),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n// ── Behaviour-template configs ───────────────────────────────────────────────\n\n/** List the caller's saved agent configurations (behaviour templates). */\nexport function useConfigs(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.configs(),\n queryFn: () => arbi.agentConfig.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Activity feed ─────────────────────────────────────────────────────────────\n\n/**\n * List the caller's durable activity feed, newest first.\n *\n * Activity entries are backend-originated, to-self log lines that are always\n * read — they are deliberately kept out of the normal notifications/DM feed and\n * never affect the unread badge, so this is a separate, opt-in query.\n */\nexport function useActivity(options?: { enabled?: boolean; limit?: number; offset?: number }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.activity(),\n queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Projects, usage & spend ───────────────────────────────────────────────────\n\n/** List the logged-in user's projects (billing accounts). */\nexport function useProjects(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projects(),\n queryFn: () => arbi.projects.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * AI usage breakdown for a project's billing period. `monthsBack` selects the period (0 =\n * current, 1 = previous month, …).\n *\n * The response's `total_spend` / `spend` fields are CREDITS, not dollars (see `formatCredits`).\n * `metered` is `false` when the deployment does not record usage (a `dev`-plan project with all\n * zeros): show \"usage is not metered here\" instead of zeros. It is `undefined` until the usage\n * has loaded.\n */\nexport function useProjectUsage(\n projectExtId: string | undefined,\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n const usage = useQuery({\n queryKey: arbiQueryKeys.projectUsage(projectExtId ?? '', monthsBack),\n queryFn: () => arbi.projects.usage(projectExtId as string, monthsBack),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) })\n const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription\n const metered = usage.data ? isUsageMetered(usage.data, subscription) : undefined\n return { ...usage, metered }\n}\n\n/** One day of aggregated usage across projects (for a spend/token trend). */\nexport interface AggregatedDailyUsage {\n date: string\n /** Credits used that day (not dollars). */\n credits: number\n totalTokens: number\n apiRequests: number\n}\n\n/** One model group's aggregated usage across projects (for a breakdown). */\nexport interface AggregatedModelGroupUsage {\n model: string\n /** Credits used by this model group (not dollars). */\n credits: number\n totalTokens: number\n promptTokens: number\n completionTokens: number\n successfulRequests: number\n}\n\n/** Aggregated AI usage + spend across several projects. */\nexport interface ProjectsUsageAggregate {\n /** Summed usage across the projects, in CREDITS (1 credit = $0.01 by default), not dollars. */\n totalCredits: number\n /** Summed token count across the projects. */\n totalTokens: number\n /** Summed API request count across the projects. */\n totalRequests: number\n /** Per-day totals merged across every project, oldest first. */\n daily: AggregatedDailyUsage[]\n /** Per-model-group totals merged across every project, most credits first. */\n modelGroups: AggregatedModelGroupUsage[]\n /**\n * False when none of the loaded projects records usage (billing is off on this deployment), so\n * zeros mean \"not metered\". True while anything real was recorded, or before data arrived.\n */\n metered: boolean\n /** True while any per-project query is still loading. */\n isLoading: boolean\n /** True if any per-project query errored. */\n isError: boolean\n}\n\n/**\n * Firm-wide AI usage + spend: aggregates {@link useProjectUsage} across several\n * projects (e.g. all of a firm's matters) in parallel and merges the real totals,\n * the daily trend, and the per-model breakdown. Shares the per-project query\n * cache, so it costs nothing extra where a project's usage is already loaded.\n * Numbers are genuine — zero projects (or zero billed work) yields zero totals;\n * callers render that honestly.\n */\nexport function useProjectsUsage(\n projectExtIds: string[],\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n): ProjectsUsageAggregate {\n const arbi = useArbi()\n const enabled = (options?.enabled ?? true) && arbi.isLoggedIn\n const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 })\n const results = useQueries({\n queries: projectExtIds.map((id) => ({\n queryKey: arbiQueryKeys.projectUsage(id, monthsBack),\n queryFn: () => arbi.projects.usage(id, monthsBack),\n enabled: enabled && !!id,\n })),\n })\n\n // Recompute only when a query's data actually changes (not on every parent\n // render — the dashboard re-renders often while a digest streams).\n const signature =\n results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join('|') +\n `#${projects.dataUpdatedAt}`\n\n return useMemo(() => {\n const dailyMap = new Map<string, AggregatedDailyUsage>()\n const modelMap = new Map<string, AggregatedModelGroupUsage>()\n let totalCredits = 0\n let anyData = false\n let anyMetered = false\n let totalTokens = 0\n let totalRequests = 0\n\n results.forEach((r, i) => {\n const d = r.data\n if (!d) return\n anyData = true\n const subscription = projects.data?.find(\n (p) => p.external_id === projectExtIds[i]\n )?.subscription\n if (isUsageMetered(d, subscription)) anyMetered = true\n totalCredits += d.total_spend ?? 0\n totalTokens += d.total_tokens ?? 0\n totalRequests += d.total_requests ?? 0\n\n for (const day of d.daily ?? []) {\n const cur = dailyMap.get(day.date) ?? {\n date: day.date,\n credits: 0,\n totalTokens: 0,\n apiRequests: 0,\n }\n cur.credits += day.spend ?? 0\n cur.totalTokens += day.total_tokens ?? 0\n cur.apiRequests += day.api_requests ?? 0\n dailyMap.set(day.date, cur)\n }\n\n for (const [model, mg] of Object.entries(d.model_groups ?? {})) {\n const cur = modelMap.get(model) ?? {\n model,\n credits: 0,\n totalTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n successfulRequests: 0,\n }\n cur.credits += mg.spend ?? 0\n cur.totalTokens += mg.total_tokens ?? 0\n cur.promptTokens += mg.prompt_tokens ?? 0\n cur.completionTokens += mg.completion_tokens ?? 0\n cur.successfulRequests += mg.successful_requests ?? 0\n modelMap.set(model, cur)\n }\n })\n\n return {\n totalCredits,\n totalTokens,\n totalRequests,\n daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),\n modelGroups: [...modelMap.values()].sort(\n (a, b) => b.credits - a.credits || b.totalTokens - a.totalTokens\n ),\n metered: !anyData || anyMetered,\n isLoading: results.some((r) => r.isLoading),\n isError: results.some((r) => r.isError),\n }\n }, [signature])\n}\n\n/** List the Stripe invoices for a project's subscription. */\nexport function useProjectInvoices(\n projectExtId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ''),\n queryFn: () => arbi.projects.invoices(projectExtId as string),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n}\n\n/** Today's deployment-wide credit use for the current user (`credits_used`, in credits). */\nexport function useUserUsageToday(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.userUsageToday(),\n queryFn: () => arbi.user.usageToday(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n"]}
@@ -21,6 +21,7 @@ var arbiQueryKeys = {
21
21
  workspaces: () => ["arbi", "workspaces"],
22
22
  documents: (workspaceId) => ["arbi", "documents", workspaceId],
23
23
  conversations: (workspaceId) => ["arbi", "conversations", workspaceId],
24
+ conversationThreads: (workspaceId, conversationId) => ["arbi", "conversations", workspaceId, "threads", conversationId],
24
25
  tags: (workspaceId) => ["arbi", "tags", workspaceId],
25
26
  thumbnails: (docIds) => ["arbi", "thumbnails", [...docIds].sort().join(",")],
26
27
  parsedDoc: (docId, stage) => ["arbi", "parsedDoc", docId, stage],
@@ -41,7 +42,11 @@ var arbiQueryKeys = {
41
42
  /** An agent's pinned config; `undefined` = the library default config. */
42
43
  agentConfig: (agentExtId) => ["arbi", "agentConfig", agentExtId ?? "default"],
43
44
  agentWorkspaces: (agentExtId) => ["arbi", "agentWorkspaces", agentExtId],
44
- models: () => ["arbi", "models"]
45
+ models: () => ["arbi", "models"],
46
+ /** The signed-in user's own profile (name, picture, email). */
47
+ profile: () => ["arbi", "profile"],
48
+ /** The signed-in user's settings record (notification preferences, flags). */
49
+ userSettings: () => ["arbi", "userSettings"]
45
50
  };
46
51
  function useWorkspaces(options) {
47
52
  const arbi = useArbi();
@@ -67,6 +72,15 @@ function useConversations(workspaceId, options) {
67
72
  enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace
68
73
  });
69
74
  }
75
+ function useConversationThreads(workspaceId, conversationId, options) {
76
+ const arbi = useArbi();
77
+ return useQuery({
78
+ queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? "", conversationId ?? ""),
79
+ queryFn: () => arbi.conversations.getThreads(conversationId),
80
+ enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,
81
+ gcTime: 0
82
+ });
83
+ }
70
84
  function useTags(workspaceId, options) {
71
85
  const arbi = useArbi();
72
86
  return useQuery({
@@ -271,6 +285,6 @@ function useUserUsageToday(options) {
271
285
  });
272
286
  }
273
287
 
274
- export { DEFAULT_USD_PER_CREDIT, arbiQueryKeys, creditsToUsd, formatCredits, isUsageMetered, useActivity, useAgents, useAssistantQuery, useConfigs, useConversations, useDeleteAgents, useDocuments, useFacts, useHealth, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSessions, useTags, useTasks, useThumbnails, useUserUsageToday, useWorkspaces };
275
- //# sourceMappingURL=chunk-ZY53R6I4.js.map
276
- //# sourceMappingURL=chunk-ZY53R6I4.js.map
288
+ export { DEFAULT_USD_PER_CREDIT, arbiQueryKeys, creditsToUsd, formatCredits, isUsageMetered, useActivity, useAgents, useAssistantQuery, useConfigs, useConversationThreads, useConversations, useDeleteAgents, useDocuments, useFacts, useHealth, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSessions, useTags, useTasks, useThumbnails, useUserUsageToday, useWorkspaces };
289
+ //# sourceMappingURL=chunk-KWCHIAQ5.js.map
290
+ //# sourceMappingURL=chunk-KWCHIAQ5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/credits.ts","../src/hooks.ts"],"names":[],"mappings":";;;;;AAWO,IAAM,sBAAA,GAAyB;AAU/B,SAAS,aAAA,CAAc,OAAA,EAAiB,OAAA,GAAgC,EAAC,EAAW;AACzF,EAAA,MAAM,EAAE,IAAA,GAAO,IAAA,EAAM,MAAA,GAAS,SAAQ,GAAI,OAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,KAAK,KAAA,CAAM,MAAA,CAAO,SAAS,OAAO,CAAA,GAAI,UAAU,CAAC,CAAA;AAC/D,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,cAAA,CAAe,MAAM,CAAA;AAC1C,EAAA,OAAO,IAAA,GAAO,GAAG,MAAM,CAAA,CAAA,EAAI,UAAU,CAAA,GAAI,QAAA,GAAW,SAAS,CAAA,CAAA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,SAAS,CAAA;AAAA,MAC1C,SAAS,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,EAAE,OAAO;AAAA,KACxC;AAAA,EACF,CAAA,EAAG,CAAC,SAAS,CAAC,CAAA;AAChB;AAGO,SAAS,kBAAA,CACd,cACA,OAAA,EACA;AACA,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,OAAO,QAAA,CAAS;AAAA,IACd,QAAA,EAAU,aAAA,CAAc,eAAA,CAAgB,YAAA,IAAgB,EAAE,CAAA;AAAA,IAC1D,OAAA,EAAS,MAAM,IAAA,CAAK,QAAA,CAAS,SAAS,YAAsB,CAAA;AAAA,IAC5D,UAAU,OAAA,EAAS,OAAA,IAAW,SAAS,CAAC,CAAC,gBAAgB,IAAA,CAAK;AAAA,GAC/D,CAAA;AACH;AAGO,SAAS,kBAAkB,OAAA,EAAiC;AACjE,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,OAAO,QAAA,CAAS;AAAA,IACd,QAAA,EAAU,cAAc,cAAA,EAAe;AAAA,IACvC,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,CAAK,UAAA,EAAW;AAAA,IACpC,OAAA,EAAS,OAAA,EAAS,OAAA,IAAW,IAAA,CAAK;AAAA,GACnC,CAAA;AACH","file":"chunk-KWCHIAQ5.js","sourcesContent":["/**\n * Credits: the unit the ARBI backend reports AI usage in.\n *\n * The usage endpoints (`/v1/user/projects/{id}/usage`, `/me/usage/today`) convert the metered USD\n * spend into whole credits at the API boundary: 1 credit = `CREDITS_TO_AI_USD`, which is $0.01 on\n * a default deployment. The fields are still named `spend` / `total_spend` in the schema, but they\n * hold CREDITS, never dollars. Label them as credits; use {@link creditsToUsd} only when a\n * dollar figure is genuinely wanted, with the deployment's own rate.\n */\n\n/** Dollars per credit on a default deployment (`CREDITS_TO_AI_USD`). */\nexport const DEFAULT_USD_PER_CREDIT = 0.01\n\nexport interface FormatCreditsOptions {\n /** Append the unit (\"12 credits\"). Default true; pass false inside a column headed \"Credits\". */\n unit?: boolean\n /** BCP 47 locale for the digit grouping. Default `en-US`. */\n locale?: string\n}\n\n/** \"1,234 credits\" / \"1 credit\". The backend reports whole credits; this rounds away float dust. */\nexport function formatCredits(credits: number, options: FormatCreditsOptions = {}): string {\n const { unit = true, locale = 'en-US' } = options\n const whole = Math.round(Number.isFinite(credits) ? credits : 0)\n const digits = whole.toLocaleString(locale)\n return unit ? `${digits} ${whole === 1 ? 'credit' : 'credits'}` : digits\n}\n\n/** The dollar value of an amount of credits. `usdPerCredit` defaults to {@link DEFAULT_USD_PER_CREDIT}. */\nexport function creditsToUsd(\n credits: number,\n usdPerCredit: number = DEFAULT_USD_PER_CREDIT\n): number {\n return credits * usdPerCredit\n}\n\n/** The slice of a usage response that tells whether anything was recorded. */\nexport interface UsageTotals {\n total_spend: number\n total_tokens: number\n total_requests: number\n}\n\n/**\n * Was this usage actually metered? A project on the `dev` plan belongs to a deployment with\n * billing switched off: the backend only records AI usage per project when billing is enabled, so\n * an all-zero response there means \"not metered\", not \"nothing happened\". Show a note instead of\n * silent zeros.\n */\nexport function isUsageMetered(\n usage: UsageTotals,\n subscription: string | null | undefined\n): boolean {\n const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0\n return !(empty && subscription === 'dev')\n}\n","/**\n * React Query hooks that use the Arbi instance from context.\n */\n\nimport { useMemo } from 'react'\nimport { useQuery, useQueries, useMutation } from '@tanstack/react-query'\nimport type {\n SSEStreamResult,\n SSEStreamStartData,\n ResponseOutputItemDoneEvent,\n ArtifactEvent,\n UserMessageEvent,\n MessageMetadataPayload,\n} from '@arbidocs/sdk/browser'\nimport { useArbi } from './useArbi'\nimport type { ParsedDocument } from './documents/parsed-types'\nimport { isUsageMetered } from './credits'\n\n// ── Query keys ──────────────────────────────────────────────────────────────\n\nexport const arbiQueryKeys = {\n workspaces: () => ['arbi', 'workspaces'] as const,\n documents: (workspaceId: string) => ['arbi', 'documents', workspaceId] as const,\n conversations: (workspaceId: string) => ['arbi', 'conversations', workspaceId] as const,\n conversationThreads: (workspaceId: string, conversationId: string) =>\n ['arbi', 'conversations', workspaceId, 'threads', conversationId] as const,\n tags: (workspaceId: string) => ['arbi', 'tags', workspaceId] as const,\n thumbnails: (docIds: string[]) => ['arbi', 'thumbnails', [...docIds].sort().join(',')] as const,\n parsedDoc: (docId: string, stage: string) => ['arbi', 'parsedDoc', docId, stage] as const,\n agents: () => ['arbi', 'agents'] as const,\n sessions: () => ['arbi', 'sessions'] as const,\n health: () => ['arbi', 'health'] as const,\n tasks: () => ['arbi', 'tasks'] as const,\n facts: (workspaceId: string) => ['arbi', 'facts', workspaceId] as const,\n configs: () => ['arbi', 'configs'] as const,\n activity: () => ['arbi', 'activity'] as const,\n projects: () => ['arbi', 'projects'] as const,\n projectUsage: (projectExtId: string, monthsBack: number) =>\n ['arbi', 'projectUsage', projectExtId, monthsBack] as const,\n projectInvoices: (projectExtId: string) => ['arbi', 'projectInvoices', projectExtId] as const,\n userUsageToday: () => ['arbi', 'userUsageToday'] as const,\n contacts: () => ['arbi', 'contacts'] as const,\n skills: () => ['arbi', 'skills'] as const,\n taskRuns: (taskId: string) => ['arbi', 'taskRuns', taskId] as const,\n /** An agent's pinned config; `undefined` = the library default config. */\n agentConfig: (agentExtId?: string) => ['arbi', 'agentConfig', agentExtId ?? 'default'] as const,\n agentWorkspaces: (agentExtId: string) => ['arbi', 'agentWorkspaces', agentExtId] as const,\n models: () => ['arbi', 'models'] as const,\n /** The signed-in user's own profile (name, picture, email). */\n profile: () => ['arbi', 'profile'] as const,\n /** The signed-in user's settings record (notification preferences, flags). */\n userSettings: () => ['arbi', 'userSettings'] as const,\n}\n\n// ── Hooks ───────────────────────────────────────────────────────────────────\n\n/** List the logged-in user's workspaces. */\nexport function useWorkspaces(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** List documents in a workspace. */\nexport function useDocuments(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.documents(workspaceId ?? ''),\n queryFn: () => arbi.documents.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/** List conversations in a workspace. */\nexport function useConversations(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.conversations(workspaceId ?? ''),\n queryFn: () => arbi.conversations.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/**\n * A conversation's stored threads (each with its message history, citations data included).\n * Always refetched on mount: a conversation that was open before may have new turns.\n */\nexport function useConversationThreads(\n workspaceId: string | undefined,\n conversationId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.conversationThreads(workspaceId ?? '', conversationId ?? ''),\n queryFn: () => arbi.conversations.getThreads(conversationId as string),\n enabled: (options?.enabled ?? true) && !!workspaceId && !!conversationId && arbi.hasWorkspace,\n gcTime: 0,\n })\n}\n\n/** List tags in a workspace. */\nexport function useTags(workspaceId: string | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.tags(workspaceId ?? ''),\n queryFn: () => arbi.tags.list(),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n/**\n * Batch-fetch first-page thumbnails for a set of documents. Returns a map of\n * doc external id → `data:image/webp` URI (or `null` when no thumbnail exists).\n * Cached for a few minutes since thumbnails are effectively immutable per doc.\n */\nexport function useThumbnails(docIds: string[], options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.thumbnails(docIds),\n queryFn: () => arbi.documents.getThumbnails(docIds),\n enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,\n staleTime: 5 * 60_000,\n })\n}\n\n/**\n * Fetch a document's parsed content (chunks grouped by page) for the review\n * viewer. `stage` defaults to `final` (fully processed); `marker`/`subchunk`\n * expose earlier pipeline stages.\n */\nexport function useParsedDocument(\n docId: string | undefined,\n stage: string = 'final',\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.parsedDoc(docId ?? '', stage),\n queryFn: () =>\n arbi.documents.getParsedContent(docId as string, stage) as unknown as Promise<ParsedDocument>,\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/** Send a streaming query to the RAG assistant. Returns a mutation. */\nexport function useAssistantQuery() {\n const arbi = useArbi()\n\n return useMutation<\n SSEStreamResult,\n Error,\n {\n question: string\n docIds: string[]\n previousResponseId?: string | null\n model?: string\n onToken?: (content: string) => void\n /** Aborts the request and the stream; the mutation then rejects with an `AbortError`. */\n signal?: AbortSignal\n onStreamStart?: (data: SSEStreamStartData) => void\n onUserMessage?: (data: UserMessageEvent) => void\n onMetadata?: (data: MessageMetadataPayload) => void\n onOutputItemDone?: (data: ResponseOutputItemDoneEvent) => void\n onArtifact?: (data: ArtifactEvent) => void\n onError?: (message: string) => void\n onComplete?: () => void\n }\n >({\n mutationFn: ({ question, ...options }) => arbi.assistant.query(question, options),\n })\n}\n\n/** List agents owned by the current user. */\nexport function useAgents(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.agents(),\n queryFn: () => arbi.agents.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** Delete agents. Returns a mutation. */\nexport function useDeleteAgents() {\n const arbi = useArbi()\n return useMutation<unknown, Error, { agentExtIds: string[] }>({\n mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),\n })\n}\n\n/** List active sessions. */\nexport function useSessions(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.sessions(),\n queryFn: () => arbi.sessions.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** Authorize a delegated session (generates claim code). Returns a mutation. */\n\n/** Check backend health. */\nexport function useHealth(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.health(),\n queryFn: () => arbi.health.check(),\n enabled: options?.enabled,\n })\n}\n\n// ── Scheduled tasks ──────────────────────────────────────────────────────────\n\n/** List the caller's scheduled agent tasks. */\nexport function useTasks(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.tasks(),\n queryFn: () => arbi.tasks.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Workspace notes ──────────────────────────────────────────────────────────\n\n/** List the open workspace's facts. */\nexport function useFacts(\n workspaceId: string | undefined,\n options?: { enabled?: boolean; pinnedOnly?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.facts(workspaceId ?? ''),\n queryFn: () => arbi.facts.list({ pinnedOnly: options?.pinnedOnly }),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n })\n}\n\n// ── Behaviour-template configs ───────────────────────────────────────────────\n\n/** List the caller's saved agent configurations (behaviour templates). */\nexport function useConfigs(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.configs(),\n queryFn: () => arbi.agentConfig.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Activity feed ─────────────────────────────────────────────────────────────\n\n/**\n * List the caller's durable activity feed, newest first.\n *\n * Activity entries are backend-originated, to-self log lines that are always\n * read — they are deliberately kept out of the normal notifications/DM feed and\n * never affect the unread badge, so this is a separate, opt-in query.\n */\nexport function useActivity(options?: { enabled?: boolean; limit?: number; offset?: number }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.activity(),\n queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n// ── Projects, usage & spend ───────────────────────────────────────────────────\n\n/** List the logged-in user's projects (billing accounts). */\nexport function useProjects(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projects(),\n queryFn: () => arbi.projects.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * AI usage breakdown for a project's billing period. `monthsBack` selects the period (0 =\n * current, 1 = previous month, …).\n *\n * The response's `total_spend` / `spend` fields are CREDITS, not dollars (see `formatCredits`).\n * `metered` is `false` when the deployment does not record usage (a `dev`-plan project with all\n * zeros): show \"usage is not metered here\" instead of zeros. It is `undefined` until the usage\n * has loaded.\n */\nexport function useProjectUsage(\n projectExtId: string | undefined,\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n const usage = useQuery({\n queryKey: arbiQueryKeys.projectUsage(projectExtId ?? '', monthsBack),\n queryFn: () => arbi.projects.usage(projectExtId as string, monthsBack),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) })\n const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription\n const metered = usage.data ? isUsageMetered(usage.data, subscription) : undefined\n return { ...usage, metered }\n}\n\n/** One day of aggregated usage across projects (for a spend/token trend). */\nexport interface AggregatedDailyUsage {\n date: string\n /** Credits used that day (not dollars). */\n credits: number\n totalTokens: number\n apiRequests: number\n}\n\n/** One model group's aggregated usage across projects (for a breakdown). */\nexport interface AggregatedModelGroupUsage {\n model: string\n /** Credits used by this model group (not dollars). */\n credits: number\n totalTokens: number\n promptTokens: number\n completionTokens: number\n successfulRequests: number\n}\n\n/** Aggregated AI usage + spend across several projects. */\nexport interface ProjectsUsageAggregate {\n /** Summed usage across the projects, in CREDITS (1 credit = $0.01 by default), not dollars. */\n totalCredits: number\n /** Summed token count across the projects. */\n totalTokens: number\n /** Summed API request count across the projects. */\n totalRequests: number\n /** Per-day totals merged across every project, oldest first. */\n daily: AggregatedDailyUsage[]\n /** Per-model-group totals merged across every project, most credits first. */\n modelGroups: AggregatedModelGroupUsage[]\n /**\n * False when none of the loaded projects records usage (billing is off on this deployment), so\n * zeros mean \"not metered\". True while anything real was recorded, or before data arrived.\n */\n metered: boolean\n /** True while any per-project query is still loading. */\n isLoading: boolean\n /** True if any per-project query errored. */\n isError: boolean\n}\n\n/**\n * Firm-wide AI usage + spend: aggregates {@link useProjectUsage} across several\n * projects (e.g. all of a firm's matters) in parallel and merges the real totals,\n * the daily trend, and the per-model breakdown. Shares the per-project query\n * cache, so it costs nothing extra where a project's usage is already loaded.\n * Numbers are genuine — zero projects (or zero billed work) yields zero totals;\n * callers render that honestly.\n */\nexport function useProjectsUsage(\n projectExtIds: string[],\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n): ProjectsUsageAggregate {\n const arbi = useArbi()\n const enabled = (options?.enabled ?? true) && arbi.isLoggedIn\n const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 })\n const results = useQueries({\n queries: projectExtIds.map((id) => ({\n queryKey: arbiQueryKeys.projectUsage(id, monthsBack),\n queryFn: () => arbi.projects.usage(id, monthsBack),\n enabled: enabled && !!id,\n })),\n })\n\n // Recompute only when a query's data actually changes (not on every parent\n // render — the dashboard re-renders often while a digest streams).\n const signature =\n results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join('|') +\n `#${projects.dataUpdatedAt}`\n\n return useMemo(() => {\n const dailyMap = new Map<string, AggregatedDailyUsage>()\n const modelMap = new Map<string, AggregatedModelGroupUsage>()\n let totalCredits = 0\n let anyData = false\n let anyMetered = false\n let totalTokens = 0\n let totalRequests = 0\n\n results.forEach((r, i) => {\n const d = r.data\n if (!d) return\n anyData = true\n const subscription = projects.data?.find(\n (p) => p.external_id === projectExtIds[i]\n )?.subscription\n if (isUsageMetered(d, subscription)) anyMetered = true\n totalCredits += d.total_spend ?? 0\n totalTokens += d.total_tokens ?? 0\n totalRequests += d.total_requests ?? 0\n\n for (const day of d.daily ?? []) {\n const cur = dailyMap.get(day.date) ?? {\n date: day.date,\n credits: 0,\n totalTokens: 0,\n apiRequests: 0,\n }\n cur.credits += day.spend ?? 0\n cur.totalTokens += day.total_tokens ?? 0\n cur.apiRequests += day.api_requests ?? 0\n dailyMap.set(day.date, cur)\n }\n\n for (const [model, mg] of Object.entries(d.model_groups ?? {})) {\n const cur = modelMap.get(model) ?? {\n model,\n credits: 0,\n totalTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n successfulRequests: 0,\n }\n cur.credits += mg.spend ?? 0\n cur.totalTokens += mg.total_tokens ?? 0\n cur.promptTokens += mg.prompt_tokens ?? 0\n cur.completionTokens += mg.completion_tokens ?? 0\n cur.successfulRequests += mg.successful_requests ?? 0\n modelMap.set(model, cur)\n }\n })\n\n return {\n totalCredits,\n totalTokens,\n totalRequests,\n daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),\n modelGroups: [...modelMap.values()].sort(\n (a, b) => b.credits - a.credits || b.totalTokens - a.totalTokens\n ),\n metered: !anyData || anyMetered,\n isLoading: results.some((r) => r.isLoading),\n isError: results.some((r) => r.isError),\n }\n }, [signature])\n}\n\n/** List the Stripe invoices for a project's subscription. */\nexport function useProjectInvoices(\n projectExtId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ''),\n queryFn: () => arbi.projects.invoices(projectExtId as string),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n}\n\n/** Today's deployment-wide credit use for the current user (`credits_used`, in credits). */\nexport function useUserUsageToday(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.userUsageToday(),\n queryFn: () => arbi.user.usageToday(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n"]}
@@ -88,6 +88,7 @@ function splitMarkdownBlocks(content) {
88
88
  }
89
89
 
90
90
  // src/ai/normalize-citations.ts
91
+ var SOURCE_RESIDUE = /\(\*+\s*(Sources?\s*:[^\n]*?)\s*\*+\)/g;
91
92
  var CITE_LINK = /\[([^\]\n]+)\]\((#cite-[\w-]+)\)/g;
92
93
  var BLOCK_MARKER = /^(?:[-*+]|\d{1,9}[.)]|#{1,6})[ \t]+/;
93
94
  var LEADING_EMPHASIS = /^(?:\*\*|__|\*|_)+/;
@@ -157,17 +158,24 @@ function normalizeLine(line) {
157
158
  return `${prefix}[${body}](${href})${suffix}`;
158
159
  });
159
160
  }
161
+ function normalizeSourceResidue(line) {
162
+ return line.includes("(*") ? line.replace(SOURCE_RESIDUE, "*($1)*") : line;
163
+ }
160
164
  function normalizeCitationMarkup(markdown) {
161
- if (!markdown.includes("](#cite-")) return markdown;
165
+ if (!markdown.includes("](#cite-") && !markdown.includes("(*")) return markdown;
162
166
  let inFence = false;
163
167
  return markdown.split("\n").map((line) => {
164
168
  if (/^\s*(```|~~~)/.test(line)) {
165
169
  inFence = !inFence;
166
170
  return line;
167
171
  }
168
- return inFence ? line : normalizeLine(line);
172
+ return inFence ? line : normalizeSourceResidue(normalizeLine(line));
169
173
  }).join("\n");
170
174
  }
175
+ var OPEN_CITATION_TAIL = /\[[^\]\n]*(?:\](?:\((?:#(?:c(?:i(?:t(?:e(?:-[\w-]*)?)?)?)?)?)?)?)?$/;
176
+ function trimOpenCitation(markdown) {
177
+ return markdown.replace(OPEN_CITATION_TAIL, "");
178
+ }
171
179
  function CodeBlock({ language, code }) {
172
180
  const [copied, setCopied] = React.useState(false);
173
181
  const handleCopy = async () => {
@@ -205,31 +213,32 @@ function CodeBlock({ language, code }) {
205
213
  }
206
214
  );
207
215
  }
208
- var defaultComponents = {
209
- ...markdownBaseComponents,
210
- a: ({ href, children, ...props }) => {
211
- if (href?.startsWith("#cite-")) {
212
- return /* @__PURE__ */ jsxRuntime.jsx(
213
- "span",
214
- {
215
- className: "cited-text underline decoration-dotted underline-offset-4",
216
- "data-cite": href.slice(6),
217
- children
218
- }
219
- );
220
- }
221
- const isInternal = !href || href.startsWith("#") || href.startsWith("cite:");
216
+ function MarkdownLink({ href, children, ...props }) {
217
+ if (href?.startsWith("#cite-")) {
222
218
  return /* @__PURE__ */ jsxRuntime.jsx(
223
- "a",
219
+ "span",
224
220
  {
225
- className: "text-primary underline underline-offset-2",
226
- href,
227
- ...isInternal ? {} : { target: "_blank", rel: "noopener noreferrer" },
228
- ...props,
221
+ className: "cited-text after:ml-px after:align-super after:text-[0.7em] after:font-medium after:text-muted-foreground after:content-[attr(data-cite)]",
222
+ "data-cite": href.slice(6),
229
223
  children
230
224
  }
231
225
  );
232
- },
226
+ }
227
+ const isInternal = !href || href.startsWith("#") || href.startsWith("cite:");
228
+ return /* @__PURE__ */ jsxRuntime.jsx(
229
+ "a",
230
+ {
231
+ className: "text-primary underline underline-offset-2",
232
+ href,
233
+ ...isInternal ? {} : { target: "_blank", rel: "noopener noreferrer" },
234
+ ...props,
235
+ children
236
+ }
237
+ );
238
+ }
239
+ var defaultComponents = {
240
+ ...markdownBaseComponents,
241
+ a: MarkdownLink,
233
242
  em: ({ children, ...props }) => /* @__PURE__ */ jsxRuntime.jsx("em", { className: "italic", ...props, children }),
234
243
  code: function MarkdownCode({
235
244
  className,
@@ -283,14 +292,20 @@ var MarkdownErrorBoundary = class extends React__default.default.Component {
283
292
  function MarkdownRendererComponent({
284
293
  children,
285
294
  components: customComponents,
295
+ renderCitation,
286
296
  isStreaming = false,
287
297
  className,
288
298
  testId = "markdown-renderer"
289
299
  }) {
290
- const components = React.useMemo(
291
- () => customComponents ? { ...defaultComponents, ...customComponents } : defaultComponents,
292
- [customComponents]
293
- );
300
+ const components = React.useMemo(() => {
301
+ const base = customComponents ? { ...defaultComponents, ...customComponents } : defaultComponents;
302
+ if (!renderCitation) return base;
303
+ const Link = base.a ?? MarkdownLink;
304
+ return {
305
+ ...base,
306
+ a: (props) => props.href?.startsWith("#cite-") ? renderCitation({ num: props.href.slice(6), children: props.children }) : React__default.default.createElement(Link, props)
307
+ };
308
+ }, [customComponents, renderCitation]);
294
309
  const blocks = React.useMemo(() => splitMarkdownBlocks(normalizeCitationMarkup(children)), [children]);
295
310
  return /* @__PURE__ */ jsxRuntime.jsx(
296
311
  MarkdownErrorBoundary,
@@ -314,5 +329,6 @@ exports.MarkdownStreamingContext = MarkdownStreamingContext;
314
329
  exports.markdownBaseComponents = markdownBaseComponents;
315
330
  exports.normalizeCitationMarkup = normalizeCitationMarkup;
316
331
  exports.splitMarkdownBlocks = splitMarkdownBlocks;
317
- //# sourceMappingURL=chunk-7V7B7OEM.cjs.map
318
- //# sourceMappingURL=chunk-7V7B7OEM.cjs.map
332
+ exports.trimOpenCitation = trimOpenCitation;
333
+ //# sourceMappingURL=chunk-OI55JRKT.cjs.map
334
+ //# sourceMappingURL=chunk-OI55JRKT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai/markdown-base-components.tsx","../src/ai/markdown-streaming-context.ts","../src/ai/split-markdown-blocks.ts","../src/ai/normalize-citations.ts","../src/ai/MarkdownRenderer.tsx"],"names":["jsx","createContext","useState","jsxs","Check","Copy","cn","Fragment","remarkGfm","rehypeRaw","React","Markdown","useMemo"],"mappings":";;;;;;;;;;;;;;;;;AAeO,IAAM,sBAAA,GAA8C;AAAA,EACzD,EAAA,EAAI,CAAC,EAAE,QAAA,EAAU,GAAG,KAAA,EAAM,qBACxBA,cAAA,CAAC,IAAA,EAAA,EAAG,WAAU,uBAAA,EAAwB,aAAA,EAAY,oBAAA,EAAsB,GAAG,OACxE,QAAA,EACH,CAAA;AAAA,EAEF,EAAA,EAAI,CAAC,EAAE,QAAA,EAAU,GAAG,KAAA,EAAM,qBACxBA,cAAA,CAAC,IAAA,EAAA,EAAG,WAAU,yBAAA,EAA0B,aAAA,EAAY,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,CACpE;AAAA;AAAA,OACH,EACF;AAAA;AAAA,GACF;AAEJ;AAOO,IAAM,gBAAA,GAAmBU,sBAAA,CAAM,IAAA,CAAK,yBAAyB","file":"chunk-OI55JRKT.cjs","sourcesContent":["import React from 'react'\nimport type { Components } from 'react-markdown'\n\n/**\n * Brand-neutral presentational component overrides for react-markdown, shared by\n * every markdown surface in the workspace (the monolith's `MarkdownRenderer` and\n * the AI kit's `AiMarkdown`). One house style for headings, lists, tables and the\n * inline text elements — token-based, so it themes per app.\n *\n * Deliberately excluded (kept per-consumer): `a` (external-link confirm vs\n * plain), `code`/`pre` (rich CodeBlock + Mermaid vs inline), `span` (doc-entity\n * pills), and `del`/`ins`/`mark` (general emphasis vs redline tracked-changes) —\n * these differ by intent or carry heavy/coupled behaviour, so each renderer owns\n * them and spreads this base underneath.\n */\nexport const markdownBaseComponents: Partial<Components> = {\n h1: ({ children, ...props }: React.ComponentPropsWithoutRef<'h1'>) => (\n <h1 className=\"text-lg font-semibold\" data-testid=\"markdown-heading-1\" {...props}>\n {children}\n </h1>\n ),\n h2: ({ children, ...props }: React.ComponentPropsWithoutRef<'h2'>) => (\n <h2 className=\"font-semibold text-base\" data-testid=\"markdown-heading-2\" {...props}>\n {children}\n </h2>\n ),\n h3: ({ children, ...props }: React.ComponentPropsWithoutRef<'h3'>) => (\n <h3 className=\"font-semibold text-base\" data-testid=\"markdown-heading-3\" {...props}>\n {children}\n </h3>\n ),\n h4: ({ children, ...props }: React.ComponentPropsWithoutRef<'h4'>) => (\n <h4 className=\"font-semibold text-base\" {...props}>\n {children}\n </h4>\n ),\n h5: ({ children, ...props }: React.ComponentPropsWithoutRef<'h5'>) => (\n <h5 className=\"font-medium\" {...props}>\n {children}\n </h5>\n ),\n strong: ({ children, ...props }: React.ComponentPropsWithoutRef<'strong'>) => (\n <strong className=\"font-semibold\" {...props}>\n {children}\n </strong>\n ),\n blockquote: ({ children, ...props }: React.ComponentPropsWithoutRef<'blockquote'>) => (\n <blockquote className=\"border-l-2 border-primary pl-4\" {...props}>\n {children}\n </blockquote>\n ),\n ol: ({ children, ...props }: React.ComponentPropsWithoutRef<'ol'>) => (\n <ol className=\"list-decimal space-y-2 pl-6\" data-testid=\"markdown-ordered-list\" {...props}>\n {children}\n </ol>\n ),\n ul: ({ children, ...props }: React.ComponentPropsWithoutRef<'ul'>) => (\n <ul className=\"list-none space-y-2 pl-6\" data-testid=\"markdown-unordered-list\" {...props}>\n {children}\n </ul>\n ),\n li: ({ children, ...props }: React.ComponentPropsWithoutRef<'li'>) => (\n <li className=\"my-1.5\" {...props}>\n {children}\n </li>\n ),\n table: ({ children, ...props }: React.ComponentPropsWithoutRef<'table'>) => (\n <table data-testid=\"markdown-table\" {...props}>\n {children}\n </table>\n ),\n th: ({ children, ...props }: React.ComponentPropsWithoutRef<'th'>) => (\n <th {...props}>{children}</th>\n ),\n td: ({ children, ...props }: React.ComponentPropsWithoutRef<'td'>) => (\n <td {...props}>{children}</td>\n ),\n tr: ({ children, ...props }: React.ComponentPropsWithoutRef<'tr'>) => (\n <tr {...props}>{children}</tr>\n ),\n p: ({ children, ...props }: React.ComponentPropsWithoutRef<'p'>) => (\n <p className=\"whitespace-pre-wrap\" {...props}>\n {children}\n </p>\n ),\n hr: (props: React.ComponentPropsWithoutRef<'hr'>) => (\n <hr className=\"border-foreground/20\" {...props} />\n ),\n sup: ({ children, ...props }: React.ComponentPropsWithoutRef<'sup'>) => (\n <sup className=\"text-xs\" {...props}>\n {children}\n </sup>\n ),\n sub: ({ children, ...props }: React.ComponentPropsWithoutRef<'sub'>) => (\n <sub className=\"text-xs\" {...props}>\n {children}\n </sub>\n ),\n div: ({ children, className, ...props }: React.ComponentPropsWithoutRef<'div'>) => (\n <div className={className} {...props}>\n {children}\n </div>\n ),\n br: (props: React.ComponentPropsWithoutRef<'br'>) => <br {...props} />,\n kbd: ({ children, ...props }: React.ComponentPropsWithoutRef<'kbd'>) => (\n <kbd\n className=\"px-1.5 py-0.5 text-xs font-mono bg-muted border border-border rounded\"\n {...props}\n >\n {children}\n </kbd>\n ),\n abbr: ({ children, title, ...props }: React.ComponentPropsWithoutRef<'abbr'>) => (\n <abbr title={title} className=\"underline decoration-dotted cursor-help\" {...props}>\n {children}\n </abbr>\n ),\n cite: ({ children, ...props }: React.ComponentPropsWithoutRef<'cite'>) => (\n <cite className=\"italic\" {...props}>\n {children}\n </cite>\n ),\n}\n","import { createContext } from 'react'\n\n/**\n * Signals to `MarkdownRenderer`'s component overrides that the surrounding\n * message is still streaming tokens. Heavy renderers can defer their work while\n * this is true to avoid burning CPU on partially complete fences and to keep the\n * UI responsive during long generations.\n *\n * Default `false` means non-streaming usages (parsed documents, static answers,\n * DM bubbles) get the full rendering with no behaviour change.\n */\nexport const MarkdownStreamingContext = createContext(false)\n","/**\n * Splits a markdown string into top-level blocks at `\\n\\n` boundaries.\n *\n * Streaming AI responses arrive token-by-token; passing the full string to\n * react-markdown re-parses the entire AST on every flush. By splitting into\n * blocks and memoizing each, only the trailing (still-growing) block re-parses\n * — completed blocks stay frozen in the DOM.\n *\n * The split avoids three correctness pitfalls:\n * - never splits inside an open ``` code fence (would corrupt the language)\n * - never splits between two adjacent list items (would render as two lists)\n * - never splits between two blockquote lines (would render as two quotes)\n */\nconst LIST_ITEM_RE = /^\\s*([-*+]|\\d+[.)])\\s/\nconst BLOCKQUOTE_RE = /^\\s*>/\n\nexport function splitMarkdownBlocks(content: string): string[] {\n if (!content) return []\n const blocks: string[] = []\n let start = 0\n let inFence = false\n let i = 0\n while (i < content.length) {\n if (content.startsWith('```', i)) {\n inFence = !inFence\n i += 3\n continue\n }\n if (!inFence && content[i] === '\\n' && content[i + 1] === '\\n') {\n const before = content.slice(start, i)\n const lastLine = before.slice(before.lastIndexOf('\\n') + 1)\n const afterStart = i + 2\n const nextNewline = content.indexOf('\\n', afterStart)\n const nextLine = content.slice(afterStart, nextNewline === -1 ? undefined : nextNewline)\n const bothListItems = LIST_ITEM_RE.test(lastLine) && LIST_ITEM_RE.test(nextLine)\n const bothBlockquotes = BLOCKQUOTE_RE.test(lastLine) && BLOCKQUOTE_RE.test(nextLine)\n if (bothListItems || bothBlockquotes) {\n i += 2\n continue\n }\n blocks.push(content.slice(start, afterStart))\n start = afterStart\n i = afterStart\n continue\n }\n i++\n }\n if (start < content.length) blocks.push(content.slice(start))\n return blocks\n}\n","/**\n * Citation markup normaliser.\n *\n * The backend marks a cited statement as a markdown link, `[statement](#cite-N)`, and the\n * statement can include the markdown that surrounds it: a list marker, a heading marker or the\n * opener of a bold/italic span whose closer sits after the link. Inside link text those tokens\n * are not parsed as block or inline syntax, so they show literally and break lists and bold:\n *\n * [- **Claimed quantum (by Claimant)](#cite-1):** **USD 47 million**\n *\n * `normalizeCitationMarkup` hoists the leading tokens out of the link text (and a trailing\n * emphasis closer after it), so the link only wraps the words:\n *\n * - **[Claimed quantum (by Claimant)](#cite-1):** **USD 47 million**\n *\n * It is conservative: emphasis that opens and closes inside the link text is valid markdown and\n * is left alone, an opener is only hoisted when its closer follows on the same line, and fenced\n * code blocks are never touched. The result is idempotent.\n *\n * It also tidies the residue the model leaves when it cites in prose as well: a literal\n * `(*Source: Award.pdf, p. 12*)` shows its asterisks, because `(*` does not open emphasis. It\n * becomes the italic note `*(Source: Award.pdf, p. 12)*`.\n */\n\nconst SOURCE_RESIDUE = /\\(\\*+\\s*(Sources?\\s*:[^\\n]*?)\\s*\\*+\\)/g\n\nconst CITE_LINK = /\\[([^\\]\\n]+)\\]\\((#cite-[\\w-]+)\\)/g\nconst BLOCK_MARKER = /^(?:[-*+]|\\d{1,9}[.)]|#{1,6})[ \\t]+/\nconst LEADING_EMPHASIS = /^(?:\\*\\*|__|\\*|_)+/\nconst TRAILING_EMPHASIS = /(\\*\\*|__|\\*|_)(:?)$/\n\n/** Occurrences of `token` in `text`; a single `*` is counted outside any `**` pair. */\nfunction countToken(text: string, token: string): number {\n const double = token + token\n if (token.length === 2) return text.split(token).length - 1\n const withoutDouble = text.split(double).join('')\n return withoutDouble.split(token).length - 1\n}\n\n/** Split a run of emphasis characters (`***`, `**`, `*`...) into its parser-level tokens. */\nfunction emphasisTokens(run: string): string[] {\n const char = run[0]\n const tokens: string[] = []\n let rest = run\n while (rest.length > 0) {\n const size = rest.length >= 2 ? 2 : 1\n tokens.push(char.repeat(size))\n rest = rest.slice(size)\n }\n return tokens\n}\n\nfunction hoistFromLink(text: string, before: string, after: string): [string, string, string] {\n let body = text\n let prefix = ''\n let suffix = ''\n\n if (before.trim() === '') {\n const marker = BLOCK_MARKER.exec(body)\n if (marker) {\n prefix += marker[0]\n body = body.slice(marker[0].length)\n }\n }\n\n const leading = LEADING_EMPHASIS.exec(body)\n if (leading) {\n let kept = ''\n let rest = body.slice(leading[0].length)\n for (const token of emphasisTokens(leading[0]).reverse()) {\n // Balanced inside the link text: valid as written.\n if (countToken(rest, token) % 2 === 1) {\n kept = token + kept\n continue\n }\n // Unmatched here: hoist only if the line closes it after the link.\n if (countToken(after, token) % 2 === 1) prefix += token\n else kept = token + kept\n }\n body = kept + rest\n rest = ''\n }\n\n const trailing = TRAILING_EMPHASIS.exec(body)\n if (trailing) {\n const token = trailing[1]\n const inner = body.slice(0, body.length - trailing[0].length)\n const openedBefore = countToken(before + prefix, token) % 2 === 1\n if (countToken(inner, token) % 2 === 0 && openedBefore) {\n body = inner\n suffix = trailing[0]\n }\n }\n\n return [prefix, body, suffix]\n}\n\nfunction normalizeLine(line: string): string {\n if (!line.includes('](#cite-')) return line\n return line.replace(CITE_LINK, (match, text: string, href: string, offset: number) => {\n const before = line.slice(0, offset)\n const after = line.slice(offset + match.length)\n const [prefix, body, suffix] = hoistFromLink(text, before, after)\n if (!prefix && !suffix && body === text) return match\n return `${prefix}[${body}](${href})${suffix}`\n })\n}\n\nfunction normalizeSourceResidue(line: string): string {\n return line.includes('(*') ? line.replace(SOURCE_RESIDUE, '*($1)*') : line\n}\n\nexport function normalizeCitationMarkup(markdown: string): string {\n if (!markdown.includes('](#cite-') && !markdown.includes('(*')) return markdown\n let inFence = false\n return markdown\n .split('\\n')\n .map((line) => {\n if (/^\\s*(```|~~~)/.test(line)) {\n inFence = !inFence\n return line\n }\n return inFence ? line : normalizeSourceResidue(normalizeLine(line))\n })\n .join('\\n')\n}\n\n/** A trailing, still-open `[words](#cite-N` marker (or an unclosed `[words`) on the last line. */\nconst OPEN_CITATION_TAIL = /\\[[^\\]\\n]*(?:\\](?:\\((?:#(?:c(?:i(?:t(?:e(?:-[\\w-]*)?)?)?)?)?)?)?)?$/\n\n/**\n * Drops an unfinished citation marker from the end of text that is still streaming (or was\n * stopped mid-marker), so `[Change of control](#cite-` never shows as raw markup: the words appear\n * once the marker is complete. Complete markers and everything else are left alone.\n */\nexport function trimOpenCitation(markdown: string): string {\n return markdown.replace(OPEN_CITATION_TAIL, '')\n}\n","import React, { useMemo, useState } from 'react'\nimport Markdown, { type Components } from 'react-markdown'\nimport remarkGfm from 'remark-gfm'\nimport rehypeRaw from 'rehype-raw'\nimport { Copy, Check } from 'lucide-react'\nimport { cn } from '../lib/utils'\nimport { markdownBaseComponents } from './markdown-base-components'\nimport { MarkdownStreamingContext } from './markdown-streaming-context'\nimport { splitMarkdownBlocks } from './split-markdown-blocks'\nimport { normalizeCitationMarkup } from './normalize-citations'\n\n/**\n * MarkdownRenderer — the single, full-featured markdown surface for the kit.\n *\n * Renders AI answers, chat/DM messages and parsed-document panes with one house\n * style: headings, paragraphs, bold/italic, ordered/unordered lists, GFM tables,\n * fenced code blocks (monospace + copy button), inline code, blockquotes, safe\n * links (`rel=\"noopener\"`, new tab) and horizontal rules.\n *\n * Styling is 100% semantic Tailwind tokens (`text-foreground`,\n * `text-muted-foreground`, `border-border`, `bg-muted`, `text-primary`) so it\n * themes per firm — no hardcoded brand colours. It sizes to its container, so it\n * looks right in a compact chat bubble and in a full-width document pane alike.\n *\n * Streaming: the content is split into block-level chunks (see\n * `splitMarkdownBlocks`) and each chunk is memoised, so streaming token updates\n * only re-parse the trailing block instead of the whole message. Pass\n * `isStreaming` to let heavy custom components defer via `MarkdownStreamingContext`.\n *\n * Extending: pass `components` to override any element (the kit's `AiMarkdown`\n * and `CitationRenderer` layer their accent links / citation popovers on top).\n */\n\n/** Fenced code block with a language label and copy-to-clipboard button. */\nfunction CodeBlock({ language, code }: { language: string; code: string }) {\n const [copied, setCopied] = useState(false)\n\n const handleCopy = async () => {\n try {\n await navigator.clipboard.writeText(code)\n setCopied(true)\n setTimeout(() => setCopied(false), 2000)\n } catch {\n // Clipboard unavailable (insecure context / permissions) — no-op.\n }\n }\n\n return (\n <div\n className=\"code-block relative my-3 overflow-hidden rounded-md border border-current/20 bg-current/5\"\n data-testid=\"markdown-code-block\"\n >\n <div className=\"flex items-center justify-between border-b border-current/20 px-3 py-1.5\">\n <span className=\"font-mono text-xs text-muted-foreground\">{language || 'code'}</span>\n <button\n type=\"button\"\n onClick={handleCopy}\n className=\"flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground\"\n title={copied ? 'Copied!' : 'Copy code'}\n >\n {copied ? <Check size={12} /> : <Copy size={12} />}\n <span>{copied ? 'Copied' : 'Copy'}</span>\n </button>\n </div>\n <pre className=\"overflow-x-auto p-3 text-sm leading-relaxed\">\n <code className={cn('font-mono', language && `language-${language}`)}>{code}</code>\n </pre>\n </div>\n )\n}\n\n/**\n * Links. Internal hash/anchor links stay in-page; everything else opens safely in a new tab\n * (`rel=\"noopener noreferrer\"` prevents reverse-tabnabbing). A backend citation marker\n * (`#cite-N`) has no popover here: the cited words stay in the surface's own colour with a quiet\n * superscript number after them (no underline, so a cited sentence does not read as a link).\n * Pass `renderCitation` to `MarkdownRenderer` to swap in a real source popover.\n */\nfunction MarkdownLink({ href, children, ...props }: React.ComponentPropsWithoutRef<'a'>) {\n if (href?.startsWith('#cite-')) {\n return (\n <span\n className=\"cited-text after:ml-px after:align-super after:text-[0.7em] after:font-medium after:text-muted-foreground after:content-[attr(data-cite)]\"\n data-cite={href.slice(6)}\n >\n {children}\n </span>\n )\n }\n const isInternal = !href || href.startsWith('#') || href.startsWith('cite:')\n return (\n <a\n className=\"text-primary underline underline-offset-2\"\n href={href}\n {...(isInternal ? {} : { target: '_blank', rel: 'noopener noreferrer' })}\n {...props}\n >\n {children}\n </a>\n )\n}\n\n/**\n * Default component overrides. Spreads the shared brand-neutral base\n * (`markdownBaseComponents`: headings, lists, paragraphs, emphasis, hr…) and adds\n * the elements that carry behaviour or need self-contained styling: safe links,\n * code (inline + fenced), bordered tables and blockquotes. Module-scoped so the\n * reference is stable across renders and react-markdown can skip re-parsing.\n */\nconst defaultComponents: Partial<Components> = {\n ...markdownBaseComponents,\n a: MarkdownLink,\n em: ({ children, ...props }: React.ComponentPropsWithoutRef<'em'>) => (\n <em className=\"italic\" {...props}>\n {children}\n </em>\n ),\n code: function MarkdownCode({\n className,\n children,\n ...props\n }: React.ComponentPropsWithoutRef<'code'>) {\n const match = /language-(\\w+)/.exec(className || '')\n if (!match) {\n return (\n <code\n className=\"rounded bg-current/10 px-1 py-0.5 font-mono text-[0.9em]\"\n data-testid=\"markdown-inline-code\"\n {...props}\n >\n {children}\n </code>\n )\n }\n return <CodeBlock language={match[1]} code={String(children).replace(/\\n$/, '')} />\n },\n // The CodeBlock renders its own <pre>; unwrap react-markdown's wrapper so we\n // don't nest <pre><pre>.\n pre: ({ children }: React.ComponentPropsWithoutRef<'pre'>) => <>{children}</>,\n blockquote: ({ children, ...props }: React.ComponentPropsWithoutRef<'blockquote'>) => (\n <blockquote className=\"border-l-2 border-border pl-4 italic text-muted-foreground\" {...props}>\n {children}\n </blockquote>\n ),\n table: ({ children, ...props }: React.ComponentPropsWithoutRef<'table'>) => (\n <div className=\"my-3 overflow-x-auto rounded-lg border border-border\">\n <table data-testid=\"markdown-table\" className=\"w-full border-collapse text-sm\" {...props}>\n {children}\n </table>\n </div>\n ),\n thead: ({ children, ...props }: React.ComponentPropsWithoutRef<'thead'>) => (\n <thead className=\"bg-current/10\" {...props}>\n {children}\n </thead>\n ),\n th: ({ children, ...props }: React.ComponentPropsWithoutRef<'th'>) => (\n <th className=\"border-b border-border px-3 py-2 text-left font-semibold\" {...props}>\n {children}\n </th>\n ),\n td: ({ children, ...props }: React.ComponentPropsWithoutRef<'td'>) => (\n <td className=\"border-b border-border px-3 py-2 align-top\" {...props}>\n {children}\n </td>\n ),\n // General emphasis marks (GFM `~~strikethrough~~` → <del>, raw <ins>/<mark>).\n del: ({ children, ...props }: React.ComponentPropsWithoutRef<'del'>) => (\n <del className=\"text-muted-foreground line-through\" {...props}>\n {children}\n </del>\n ),\n ins: ({ children, ...props }: React.ComponentPropsWithoutRef<'ins'>) => (\n <ins className=\"underline decoration-primary/60\" {...props}>\n {children}\n </ins>\n ),\n mark: ({ children, ...props }: React.ComponentPropsWithoutRef<'mark'>) => (\n <mark className=\"rounded bg-primary/15 px-0.5 text-inherit\" {...props}>\n {children}\n </mark>\n ),\n}\n\n// Stable module-scope plugin arrays so react-markdown compares them by reference\n// and skips re-running the remark/rehype pipeline when nothing else changed.\n// `rehype-raw` enables inline HTML (e.g. redline <del>/<ins>); no math/mermaid\n// plugins are bundled to keep the kit light.\nconst remarkPlugins = [remarkGfm]\nconst rehypePlugins = [rehypeRaw]\n\n/**\n * One parsed markdown block, memoised on (content, components) so already-rendered\n * blocks don't re-parse when a later block streams new tokens. This is the core\n * of the streaming-rendering optimisation.\n */\nconst MemoizedBlock = React.memo(function MarkdownBlock({\n content,\n components,\n}: {\n content: string\n components: Partial<Components>\n}) {\n return (\n <Markdown remarkPlugins={remarkPlugins} rehypePlugins={rehypePlugins} components={components}>\n {content}\n </Markdown>\n )\n})\n\n/** Prevents a malformed-markdown render error from crashing the whole surface. */\nclass MarkdownErrorBoundary extends React.Component<\n { fallback: React.ReactNode; children: React.ReactNode },\n { hasError: boolean }\n> {\n state = { hasError: false }\n static getDerivedStateFromError() {\n return { hasError: true }\n }\n render() {\n return this.state.hasError ? this.props.fallback : this.props.children\n }\n}\n\nexport interface MarkdownRendererProps {\n /** Markdown content to render. */\n children: string\n /** Custom component overrides merged on top of the defaults. */\n components?: Partial<Components>\n /**\n * When true, signals heavy custom components (via `MarkdownStreamingContext`)\n * to defer their work while tokens are still arriving. Defaults to false.\n */\n isStreaming?: boolean\n /**\n * Renders a citation marker `[words](#cite-N)`: `children` are the cited words, `num` the N.\n * Keep it referentially stable (`useCallback`/`useMemo`), or every block re-parses.\n */\n renderCitation?: (citation: { num: string; children: React.ReactNode }) => React.ReactNode\n /** Extra classes on the wrapper (font-size, prose width, etc.). */\n className?: string\n /** Overrides the `data-testid` on the wrapper (default `markdown-renderer`). */\n testId?: string\n}\n\nfunction MarkdownRendererComponent({\n children,\n components: customComponents,\n renderCitation,\n isStreaming = false,\n className,\n testId = 'markdown-renderer',\n}: MarkdownRendererProps) {\n const components = useMemo(() => {\n const base = customComponents\n ? { ...defaultComponents, ...customComponents }\n : defaultComponents\n if (!renderCitation) return base\n const Link = base.a ?? MarkdownLink\n return {\n ...base,\n a: (props: React.ComponentPropsWithoutRef<'a'>) =>\n props.href?.startsWith('#cite-')\n ? renderCitation({ num: props.href.slice(6), children: props.children })\n : React.createElement(Link as React.ElementType, props),\n }\n }, [customComponents, renderCitation])\n\n const blocks = useMemo(() => splitMarkdownBlocks(normalizeCitationMarkup(children)), [children])\n\n return (\n <MarkdownErrorBoundary\n fallback={<div className={cn('whitespace-pre-wrap break-words', className)}>{children}</div>}\n >\n <MarkdownStreamingContext.Provider value={isStreaming}>\n <div\n className={cn('markdown-content space-y-3 break-words leading-relaxed', className)}\n data-testid={testId}\n >\n {blocks.map((block, index) => (\n <MemoizedBlock key={index} content={block} components={components} />\n ))}\n </div>\n </MarkdownStreamingContext.Provider>\n </MarkdownErrorBoundary>\n )\n}\n\n/**\n * Memoised so a stable message in a long thread doesn't re-parse when unrelated\n * tokens arrive elsewhere; a streaming message gets a fresh `children` each flush\n * and re-renders (only its trailing block re-parses, thanks to `MemoizedBlock`).\n */\nexport const MarkdownRenderer = React.memo(MarkdownRendererComponent)\n"]}
@@ -79,6 +79,7 @@ function splitMarkdownBlocks(content) {
79
79
  }
80
80
 
81
81
  // src/ai/normalize-citations.ts
82
+ var SOURCE_RESIDUE = /\(\*+\s*(Sources?\s*:[^\n]*?)\s*\*+\)/g;
82
83
  var CITE_LINK = /\[([^\]\n]+)\]\((#cite-[\w-]+)\)/g;
83
84
  var BLOCK_MARKER = /^(?:[-*+]|\d{1,9}[.)]|#{1,6})[ \t]+/;
84
85
  var LEADING_EMPHASIS = /^(?:\*\*|__|\*|_)+/;
@@ -148,17 +149,24 @@ function normalizeLine(line) {
148
149
  return `${prefix}[${body}](${href})${suffix}`;
149
150
  });
150
151
  }
152
+ function normalizeSourceResidue(line) {
153
+ return line.includes("(*") ? line.replace(SOURCE_RESIDUE, "*($1)*") : line;
154
+ }
151
155
  function normalizeCitationMarkup(markdown) {
152
- if (!markdown.includes("](#cite-")) return markdown;
156
+ if (!markdown.includes("](#cite-") && !markdown.includes("(*")) return markdown;
153
157
  let inFence = false;
154
158
  return markdown.split("\n").map((line) => {
155
159
  if (/^\s*(```|~~~)/.test(line)) {
156
160
  inFence = !inFence;
157
161
  return line;
158
162
  }
159
- return inFence ? line : normalizeLine(line);
163
+ return inFence ? line : normalizeSourceResidue(normalizeLine(line));
160
164
  }).join("\n");
161
165
  }
166
+ var OPEN_CITATION_TAIL = /\[[^\]\n]*(?:\](?:\((?:#(?:c(?:i(?:t(?:e(?:-[\w-]*)?)?)?)?)?)?)?)?$/;
167
+ function trimOpenCitation(markdown) {
168
+ return markdown.replace(OPEN_CITATION_TAIL, "");
169
+ }
162
170
  function CodeBlock({ language, code }) {
163
171
  const [copied, setCopied] = useState(false);
164
172
  const handleCopy = async () => {
@@ -196,31 +204,32 @@ function CodeBlock({ language, code }) {
196
204
  }
197
205
  );
198
206
  }
199
- var defaultComponents = {
200
- ...markdownBaseComponents,
201
- a: ({ href, children, ...props }) => {
202
- if (href?.startsWith("#cite-")) {
203
- return /* @__PURE__ */ jsx(
204
- "span",
205
- {
206
- className: "cited-text underline decoration-dotted underline-offset-4",
207
- "data-cite": href.slice(6),
208
- children
209
- }
210
- );
211
- }
212
- const isInternal = !href || href.startsWith("#") || href.startsWith("cite:");
207
+ function MarkdownLink({ href, children, ...props }) {
208
+ if (href?.startsWith("#cite-")) {
213
209
  return /* @__PURE__ */ jsx(
214
- "a",
210
+ "span",
215
211
  {
216
- className: "text-primary underline underline-offset-2",
217
- href,
218
- ...isInternal ? {} : { target: "_blank", rel: "noopener noreferrer" },
219
- ...props,
212
+ className: "cited-text after:ml-px after:align-super after:text-[0.7em] after:font-medium after:text-muted-foreground after:content-[attr(data-cite)]",
213
+ "data-cite": href.slice(6),
220
214
  children
221
215
  }
222
216
  );
223
- },
217
+ }
218
+ const isInternal = !href || href.startsWith("#") || href.startsWith("cite:");
219
+ return /* @__PURE__ */ jsx(
220
+ "a",
221
+ {
222
+ className: "text-primary underline underline-offset-2",
223
+ href,
224
+ ...isInternal ? {} : { target: "_blank", rel: "noopener noreferrer" },
225
+ ...props,
226
+ children
227
+ }
228
+ );
229
+ }
230
+ var defaultComponents = {
231
+ ...markdownBaseComponents,
232
+ a: MarkdownLink,
224
233
  em: ({ children, ...props }) => /* @__PURE__ */ jsx("em", { className: "italic", ...props, children }),
225
234
  code: function MarkdownCode({
226
235
  className,
@@ -274,14 +283,20 @@ var MarkdownErrorBoundary = class extends React.Component {
274
283
  function MarkdownRendererComponent({
275
284
  children,
276
285
  components: customComponents,
286
+ renderCitation,
277
287
  isStreaming = false,
278
288
  className,
279
289
  testId = "markdown-renderer"
280
290
  }) {
281
- const components = useMemo(
282
- () => customComponents ? { ...defaultComponents, ...customComponents } : defaultComponents,
283
- [customComponents]
284
- );
291
+ const components = useMemo(() => {
292
+ const base = customComponents ? { ...defaultComponents, ...customComponents } : defaultComponents;
293
+ if (!renderCitation) return base;
294
+ const Link = base.a ?? MarkdownLink;
295
+ return {
296
+ ...base,
297
+ a: (props) => props.href?.startsWith("#cite-") ? renderCitation({ num: props.href.slice(6), children: props.children }) : React.createElement(Link, props)
298
+ };
299
+ }, [customComponents, renderCitation]);
285
300
  const blocks = useMemo(() => splitMarkdownBlocks(normalizeCitationMarkup(children)), [children]);
286
301
  return /* @__PURE__ */ jsx(
287
302
  MarkdownErrorBoundary,
@@ -300,6 +315,6 @@ function MarkdownRendererComponent({
300
315
  }
301
316
  var MarkdownRenderer = React.memo(MarkdownRendererComponent);
302
317
 
303
- export { MarkdownRenderer, MarkdownStreamingContext, markdownBaseComponents, normalizeCitationMarkup, splitMarkdownBlocks };
304
- //# sourceMappingURL=chunk-H7ZZQ4ZV.js.map
305
- //# sourceMappingURL=chunk-H7ZZQ4ZV.js.map
318
+ export { MarkdownRenderer, MarkdownStreamingContext, markdownBaseComponents, normalizeCitationMarkup, splitMarkdownBlocks, trimOpenCitation };
319
+ //# sourceMappingURL=chunk-RIHMIEXM.js.map
320
+ //# sourceMappingURL=chunk-RIHMIEXM.js.map